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
|
---|---|---|---|---|---|---|---|---|---|
a17f76fb2e10e874ed376ae59f165dda0437fc7e
|
src/el-functions-default.adb
|
src/el-functions-default.adb
|
-----------------------------------------------------------------------
-- EL.Functions -- Default function mapper
-- 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.
-----------------------------------------------------------------------
-- The default function mapper allows to register
-- The expression context provides information to resolve runtime
-- information when evaluating an expression. The context provides
-- a resolver whose role is to find variables given their name.
package body EL.Functions.Default is
-- ------------------------------
-- Default Function mapper
-- ------------------------------
--
use Function_Maps;
-- ------------------------------
-- Find the function knowing its name.
-- ------------------------------
function Get_Function (Mapper : Default_Function_Mapper;
Namespace : String;
Name : String) return Function_Access is
Full_Name : constant String := Namespace & ":" & Name;
C : constant Cursor := Mapper.Map.Find (Key => To_Unbounded_String (Full_Name));
begin
if Has_Element (C) then
return Element (C);
end if;
raise No_Function;
end Get_Function;
-- ------------------------------
-- Bind a name to a function.
-- ------------------------------
procedure Set_Function (Mapper : in out Default_Function_Mapper;
Namespace : in String;
Name : in String;
Func : in Function_Access) is
Full_Name : constant String := Namespace & ":" & Name;
begin
Mapper.Map.Include (Key => To_Unbounded_String (Full_Name), New_Item => Func);
end Set_Function;
-- ------------------------------
-- Truncate the string representation represented by <b>Value</b> to
-- the length specified by <b>Size</b>.
-- ------------------------------
function Truncate (Value : EL.Objects.Object;
Size : EL.Objects.Object) return EL.Objects.Object is
Cnt : constant Integer := To_Integer (Size);
begin
if Cnt <= 0 then
return To_Object (String '(""));
end if;
if Get_Type (Value) = TYPE_WIDE_STRING then
declare
S : constant Wide_Wide_String := To_Wide_Wide_String (Value);
begin
return To_Object (S (1 .. Cnt));
end;
else
-- Optimized case: use a String if we can.
declare
S : constant String := To_String (Value);
begin
return To_Object (S (1 .. Cnt));
end;
end if;
end Truncate;
end EL.Functions.Default;
|
-----------------------------------------------------------------------
-- EL.Functions -- Default function mapper
-- 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.
-----------------------------------------------------------------------
-- The default function mapper allows to register
-- The expression context provides information to resolve runtime
-- information when evaluating an expression. The context provides
-- a resolver whose role is to find variables given their name.
package body EL.Functions.Default is
-- ------------------------------
-- Default Function mapper
-- ------------------------------
--
use Function_Maps;
-- ------------------------------
-- Find the function knowing its name.
-- ------------------------------
function Get_Function (Mapper : Default_Function_Mapper;
Namespace : String;
Name : String) return Function_Access is
Full_Name : constant String := Namespace & ":" & Name;
C : constant Cursor := Mapper.Map.Find (Key => To_Unbounded_String (Full_Name));
begin
if Has_Element (C) then
return Element (C);
end if;
raise No_Function with "Function '" & Full_Name & "' not found";
end Get_Function;
-- ------------------------------
-- Bind a name to a function.
-- ------------------------------
procedure Set_Function (Mapper : in out Default_Function_Mapper;
Namespace : in String;
Name : in String;
Func : in Function_Access) is
Full_Name : constant String := Namespace & ":" & Name;
begin
Mapper.Map.Include (Key => To_Unbounded_String (Full_Name), New_Item => Func);
end Set_Function;
-- ------------------------------
-- Truncate the string representation represented by <b>Value</b> to
-- the length specified by <b>Size</b>.
-- ------------------------------
function Truncate (Value : EL.Objects.Object;
Size : EL.Objects.Object) return EL.Objects.Object is
Cnt : constant Integer := To_Integer (Size);
begin
if Cnt <= 0 then
return To_Object (String '(""));
end if;
if Get_Type (Value) = TYPE_WIDE_STRING then
declare
S : constant Wide_Wide_String := To_Wide_Wide_String (Value);
begin
return To_Object (S (1 .. Cnt));
end;
else
-- Optimized case: use a String if we can.
declare
S : constant String := To_String (Value);
begin
return To_Object (S (1 .. Cnt));
end;
end if;
end Truncate;
end EL.Functions.Default;
|
Add a message in the Not_Found exception
|
Add a message in the Not_Found exception
|
Ada
|
apache-2.0
|
Letractively/ada-el
|
fca29040d899ffe8078b4d8a03c109b90d285a42
|
src/gen-commands-docs.adb
|
src/gen-commands-docs.adb
|
-----------------------------------------------------------------------
-- gen-commands-docs -- Extract and generate documentation for the project
-- 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 GNAT.Command_Line;
with Ada.Text_IO;
package body Gen.Commands.Docs is
use GNAT.Command_Line;
-- ------------------------------
-- Execute the command with the arguments.
-- ------------------------------
procedure Execute (Cmd : in Command;
Generator : in out Gen.Generator.Handler) is
pragma Unreferenced (Cmd);
begin
Generator.Read_Project ("dynamo.xml", True);
-- Setup the target directory where the distribution is created.
declare
Target_Dir : constant String := Get_Argument;
begin
if Target_Dir'Length = 0 then
Generator.Error ("Missing target directory");
return;
end if;
Generator.Set_Result_Directory (Target_Dir);
end;
-- Read the package description.
declare
Package_File : constant String := Get_Argument;
begin
if Package_File'Length > 0 then
Gen.Generator.Read_Package (Generator, Package_File);
else
Gen.Generator.Read_Package (Generator, "package.xml");
end if;
end;
-- Run the generation.
Gen.Generator.Prepare (Generator);
Gen.Generator.Generate_All (Generator);
Gen.Generator.Finish (Generator);
end Execute;
-- ------------------------------
-- Write the help associated with the command.
-- ------------------------------
procedure Help (Cmd : in Command;
Generator : in out Gen.Generator.Handler) is
pragma Unreferenced (Cmd, Generator);
use Ada.Text_IO;
begin
Put_Line ("build-doc: Extract and generate the project documentation");
Put_Line ("Usage: build-doc");
New_Line;
Put_Line (" Extract the documentation from the project source files and generate the");
Put_Line (" project documentation. The following files are scanned:");
Put_Line (" - Ada specifications (src/*.ads)");
Put_Line (" - XML configuration files (config/*.xml)");
Put_Line (" - XML database model files (db/*.xml)");
end Help;
end Gen.Commands.Docs;
|
-----------------------------------------------------------------------
-- gen-commands-docs -- Extract and generate documentation for the project
-- Copyright (C) 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with GNAT.Command_Line;
with Ada.Text_IO;
with Gen.Artifacts.Docs;
with Gen.Model.Packages;
package body Gen.Commands.Docs is
use GNAT.Command_Line;
-- ------------------------------
-- Execute the command with the arguments.
-- ------------------------------
procedure Execute (Cmd : in Command;
Generator : in out Gen.Generator.Handler) is
pragma Unreferenced (Cmd);
Doc : Gen.Artifacts.Docs.Artifact;
M : Gen.Model.Packages.Model_Definition;
begin
Generator.Read_Project ("dynamo.xml", False);
-- Setup the target directory where the distribution is created.
declare
Target_Dir : constant String := Get_Argument;
begin
if Target_Dir'Length = 0 then
Generator.Error ("Missing target directory");
return;
end if;
Generator.Set_Result_Directory (Target_Dir);
end;
--
-- -- Read the package description.
-- declare
-- Package_File : constant String := Get_Argument;
-- begin
-- if Package_File'Length > 0 then
-- Gen.Generator.Read_Package (Generator, Package_File);
-- else
-- Gen.Generator.Read_Package (Generator, "package.xml");
-- end if;
-- end;
Doc.Prepare (M, Generator);
-- -- Run the generation.
-- Gen.Generator.Prepare (Generator);
-- Gen.Generator.Generate_All (Generator);
-- Gen.Generator.Finish (Generator);
end Execute;
-- ------------------------------
-- Write the help associated with the command.
-- ------------------------------
procedure Help (Cmd : in Command;
Generator : in out Gen.Generator.Handler) is
pragma Unreferenced (Cmd, Generator);
use Ada.Text_IO;
begin
Put_Line ("build-doc: Extract and generate the project documentation");
Put_Line ("Usage: build-doc");
New_Line;
Put_Line (" Extract the documentation from the project source files and generate the");
Put_Line (" project documentation. The following files are scanned:");
Put_Line (" - Ada specifications (src/*.ads)");
Put_Line (" - XML configuration files (config/*.xml)");
Put_Line (" - XML database model files (db/*.xml)");
end Help;
end Gen.Commands.Docs;
|
Create the documentation artifact and invoke it for the build-doc command
|
Create the documentation artifact and invoke it for the build-doc command
|
Ada
|
apache-2.0
|
Letractively/ada-gen,Letractively/ada-gen,Letractively/ada-gen,Letractively/ada-gen
|
e891e7b36939613980e14b55671089d05a702fac
|
src/security-policies-urls.adb
|
src/security-policies-urls.adb
|
-----------------------------------------------------------------------
-- security-policies-urls -- URL security policy
-- 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 Ada.Strings.Unbounded;
with Util.Refs;
with Util.Beans.Objects;
with Util.Beans.Objects.Vectors;
with Util.Serialize.Mappers;
with Util.Serialize.Mappers.Record_Mapper;
with GNAT.Regexp;
with Security.Controllers;
package body Security.Policies.Urls is
-- ------------------------------
-- URL policy
-- ------------------------------
-- ------------------------------
-- Get the policy name.
-- ------------------------------
overriding
function Get_Name (From : in URL_Policy) return String is
pragma Unreferenced (From);
begin
return NAME;
end Get_Name;
-- Returns True if the user has the permission to access the given URI permission.
function Has_Permission (Manager : in URL_Policy;
Context : in Security_Context_Access;
Permission : in URI_Permission'Class) return Boolean is
Name : constant String_Ref := To_String_Ref (Permission.URI);
Ref : constant Rules_Ref.Ref := Manager.Cache.Get;
Rules : constant Rules_Access := Ref.Value;
Pos : constant Rules_Maps.Cursor := Rules.Map.Find (Name);
Rule : Access_Rule_Ref;
begin
-- If the rule is not in the cache, search for the access rule that
-- matches our URI. Update the cache. This cache update is thread-safe
-- as the cache map is never modified: a new cache map is installed.
if not Rules_Maps.Has_Element (Pos) then
declare
New_Ref : constant Rules_Ref.Ref := Rules_Ref.Create;
begin
Rule := Manager.Find_Access_Rule (Permission.URI);
New_Ref.Value.all.Map := Rules.Map;
New_Ref.Value.all.Map.Insert (Name, Rule);
Manager.Cache.Set (New_Ref);
end;
else
Rule := Rules_Maps.Element (Pos);
end if;
-- Check if the user has one of the required permission.
declare
P : constant Access_Rule_Access := Rule.Value;
Granted : Boolean;
begin
if P /= null then
for I in P.Permissions'Range loop
-- Context.Has_Permission (P.Permissions (I), Granted);
if Granted then
return True;
end if;
end loop;
end if;
end;
return False;
end Has_Permission;
-- Grant the permission to access to the given <b>URI</b> to users having the <b>To</b>
-- permissions.
procedure Grant_URI_Permission (Manager : in out URL_Policy;
URI : in String;
To : in String) is
begin
null;
end Grant_URI_Permission;
-- ------------------------------
-- Policy Configuration
-- ------------------------------
type Policy_Config is record
Id : Natural := 0;
Permissions : Util.Beans.Objects.Vectors.Vector;
Patterns : Util.Beans.Objects.Vectors.Vector;
Manager : URL_Policy_Access;
end record;
type Policy_Config_Access is access all Policy_Config;
-- Setup the XML parser to read the <b>policy</b> description. For example:
-- Find the access rule of the policy that matches the given URI.
-- Returns the No_Rule value (disable access) if no rule is found.
function Find_Access_Rule (Manager : in URL_Policy;
URI : in String) return Access_Rule_Ref is
Matched : Boolean := False;
Result : Access_Rule_Ref;
procedure Match (P : in Policy);
procedure Match (P : in Policy) is
begin
if GNAT.Regexp.Match (URI, P.Pattern) then
Matched := True;
Result := P.Rule;
end if;
end Match;
Last : constant Natural := Manager.Policies.Last_Index;
begin
for I in 1 .. Last loop
Manager.Policies.Query_Element (I, Match'Access);
if Matched then
return Result;
end if;
end loop;
return Result;
end Find_Access_Rule;
-- ------------------------------
-- Initialize the permission manager.
-- ------------------------------
overriding
procedure Initialize (Manager : in out URL_Policy) is
begin
Manager.Cache := new Rules_Ref.Atomic_Ref;
Manager.Cache.Set (Rules_Ref.Create);
end Initialize;
-- ------------------------------
-- Finalize the permission manager.
-- ------------------------------
overriding
procedure Finalize (Manager : in out URL_Policy) is
use Ada.Strings.Unbounded;
use Security.Controllers;
procedure Free is
new Ada.Unchecked_Deallocation (Rules_Ref.Atomic_Ref,
Rules_Ref_Access);
procedure Free is
new Ada.Unchecked_Deallocation (Security.Controllers.Controller'Class,
Security.Controllers.Controller_Access);
procedure Free is
new Ada.Unchecked_Deallocation (Controller_Access_Array,
Controller_Access_Array_Access);
begin
Free (Manager.Cache);
-- for I in Manager.Names'Range loop
-- exit when Manager.Names (I) = null;
-- Ada.Strings.Unbounded.Free (Manager.Names (I));
-- end loop;
end Finalize;
type Policy_Fields is (FIELD_ID, FIELD_PERMISSION, FIELD_URL_PATTERN, FIELD_POLICY);
procedure Set_Member (P : in out Policy_Config;
Field : in Policy_Fields;
Value : in Util.Beans.Objects.Object);
procedure Process (Policy : in Policy_Config);
procedure Set_Member (P : in out Policy_Config;
Field : in Policy_Fields;
Value : in Util.Beans.Objects.Object) is
begin
case Field is
when FIELD_ID =>
P.Id := Util.Beans.Objects.To_Integer (Value);
when FIELD_PERMISSION =>
P.Permissions.Append (Value);
when FIELD_URL_PATTERN =>
P.Patterns.Append (Value);
when FIELD_POLICY =>
Process (P);
P.Id := 0;
P.Permissions.Clear;
P.Patterns.Clear;
end case;
end Set_Member;
procedure Process (Policy : in Policy_Config) is
Pol : Security.Policies.URLs.Policy;
Count : constant Natural := Natural (Policy.Permissions.Length);
Rule : constant Access_Rule_Ref := Access_Rule_Refs.Create (new Access_Rule (Count));
Iter : Util.Beans.Objects.Vectors.Cursor := Policy.Permissions.First;
Pos : Positive := 1;
begin
Pol.Rule := Rule;
-- Step 1: Initialize the list of permission index in Access_Rule from the permission names.
while Util.Beans.Objects.Vectors.Has_Element (Iter) loop
declare
Perm : constant Util.Beans.Objects.Object := Util.Beans.Objects.Vectors.Element (Iter);
Name : constant String := Util.Beans.Objects.To_String (Perm);
begin
Rule.Value.all.Permissions (Pos) := Permissions.Get_Permission_Index (Name);
Pos := Pos + 1;
exception
when Invalid_Name =>
raise Util.Serialize.Mappers.Field_Error with "Invalid permission: " & Name;
end;
Util.Beans.Objects.Vectors.Next (Iter);
end loop;
-- Step 2: Create one policy for each URL pattern
Iter := Policy.Patterns.First;
while Util.Beans.Objects.Vectors.Has_Element (Iter) loop
declare
Pattern : constant Util.Beans.Objects.Object
:= Util.Beans.Objects.Vectors.Element (Iter);
begin
Pol.Id := Policy.Id;
Pol.Pattern := GNAT.Regexp.Compile (Util.Beans.Objects.To_String (Pattern));
Policy.Manager.Policies.Append (Pol);
end;
Util.Beans.Objects.Vectors.Next (Iter);
end loop;
end Process;
package Policy_Mapper is
new Util.Serialize.Mappers.Record_Mapper (Element_Type => Policy_Config,
Element_Type_Access => Policy_Config_Access,
Fields => Policy_Fields,
Set_Member => Set_Member);
Policy_Mapping : aliased Policy_Mapper.Mapper;
-- Setup the XML parser to read the <b>policy</b> description.
overriding
procedure Set_Reader_Config (Policy : in out URL_Policy;
Reader : in out Util.Serialize.IO.XML.Parser) is
-- Policy_Mapping : aliased Policy_Mapper.Mapper;
Config : Policy_Config_Access := new Policy_Config;
begin
Reader.Add_Mapping ("policy-rules", Policy_Mapping'Access);
Reader.Add_Mapping ("module", Policy_Mapping'Access);
Config.Manager := Policy'Unchecked_Access;
Policy_Mapper.Set_Context (Reader, Config);
end Set_Reader_Config;
begin
Policy_Mapping.Add_Mapping ("policy", FIELD_POLICY);
Policy_Mapping.Add_Mapping ("policy/@id", FIELD_ID);
Policy_Mapping.Add_Mapping ("policy/permission", FIELD_PERMISSION);
Policy_Mapping.Add_Mapping ("policy/url-pattern", FIELD_URL_PATTERN);
end Security.Policies.Urls;
|
-----------------------------------------------------------------------
-- security-policies-urls -- URL security policy
-- 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 Ada.Strings.Unbounded;
with Util.Refs;
with Util.Beans.Objects;
with Util.Beans.Objects.Vectors;
with Util.Serialize.Mappers;
with Util.Serialize.Mappers.Record_Mapper;
with GNAT.Regexp;
with Security.Controllers;
package body Security.Policies.Urls is
-- ------------------------------
-- URL policy
-- ------------------------------
-- ------------------------------
-- Get the policy name.
-- ------------------------------
overriding
function Get_Name (From : in URL_Policy) return String is
pragma Unreferenced (From);
begin
return NAME;
end Get_Name;
-- Returns True if the user has the permission to access the given URI permission.
function Has_Permission (Manager : in URL_Policy;
Context : in Security_Context_Access;
Permission : in URI_Permission'Class) return Boolean is
Name : constant String_Ref := To_String_Ref (Permission.URI);
Ref : constant Rules_Ref.Ref := Manager.Cache.Get;
Rules : constant Rules_Access := Ref.Value;
Pos : constant Rules_Maps.Cursor := Rules.Map.Find (Name);
Rule : Access_Rule_Ref;
begin
-- If the rule is not in the cache, search for the access rule that
-- matches our URI. Update the cache. This cache update is thread-safe
-- as the cache map is never modified: a new cache map is installed.
if not Rules_Maps.Has_Element (Pos) then
declare
New_Ref : constant Rules_Ref.Ref := Rules_Ref.Create;
begin
Rule := Manager.Find_Access_Rule (Permission.URI);
New_Ref.Value.all.Map := Rules.Map;
New_Ref.Value.all.Map.Insert (Name, Rule);
Manager.Cache.Set (New_Ref);
end;
else
Rule := Rules_Maps.Element (Pos);
end if;
-- Check if the user has one of the required permission.
declare
P : constant Access_Rule_Access := Rule.Value;
Granted : Boolean;
begin
if P /= null then
for I in P.Permissions'Range loop
-- Context.Has_Permission (P.Permissions (I), Granted);
if Granted then
return True;
end if;
end loop;
end if;
end;
return False;
end Has_Permission;
-- Grant the permission to access to the given <b>URI</b> to users having the <b>To</b>
-- permissions.
procedure Grant_URI_Permission (Manager : in out URL_Policy;
URI : in String;
To : in String) is
begin
null;
end Grant_URI_Permission;
-- ------------------------------
-- Policy Configuration
-- ------------------------------
type Policy_Config is record
Id : Natural := 0;
Permissions : Util.Beans.Objects.Vectors.Vector;
Patterns : Util.Beans.Objects.Vectors.Vector;
Manager : URL_Policy_Access;
end record;
type Policy_Config_Access is access all Policy_Config;
-- Setup the XML parser to read the <b>policy</b> description. For example:
-- Find the access rule of the policy that matches the given URI.
-- Returns the No_Rule value (disable access) if no rule is found.
function Find_Access_Rule (Manager : in URL_Policy;
URI : in String) return Access_Rule_Ref is
Matched : Boolean := False;
Result : Access_Rule_Ref;
procedure Match (P : in Policy);
procedure Match (P : in Policy) is
begin
if GNAT.Regexp.Match (URI, P.Pattern) then
Matched := True;
Result := P.Rule;
end if;
end Match;
Last : constant Natural := Manager.Policies.Last_Index;
begin
for I in 1 .. Last loop
Manager.Policies.Query_Element (I, Match'Access);
if Matched then
return Result;
end if;
end loop;
return Result;
end Find_Access_Rule;
-- ------------------------------
-- Initialize the permission manager.
-- ------------------------------
overriding
procedure Initialize (Manager : in out URL_Policy) is
begin
Manager.Cache := new Rules_Ref.Atomic_Ref;
Manager.Cache.Set (Rules_Ref.Create);
end Initialize;
-- ------------------------------
-- Finalize the permission manager.
-- ------------------------------
overriding
procedure Finalize (Manager : in out URL_Policy) is
use Ada.Strings.Unbounded;
use Security.Controllers;
procedure Free is
new Ada.Unchecked_Deallocation (Rules_Ref.Atomic_Ref,
Rules_Ref_Access);
procedure Free is
new Ada.Unchecked_Deallocation (Security.Controllers.Controller'Class,
Security.Controllers.Controller_Access);
procedure Free is
new Ada.Unchecked_Deallocation (Controller_Access_Array,
Controller_Access_Array_Access);
begin
Free (Manager.Cache);
-- for I in Manager.Names'Range loop
-- exit when Manager.Names (I) = null;
-- Ada.Strings.Unbounded.Free (Manager.Names (I));
-- end loop;
end Finalize;
type Policy_Fields is (FIELD_ID, FIELD_PERMISSION, FIELD_URL_PATTERN, FIELD_POLICY);
procedure Set_Member (P : in out Policy_Config;
Field : in Policy_Fields;
Value : in Util.Beans.Objects.Object);
procedure Process (Policy : in Policy_Config);
procedure Set_Member (P : in out Policy_Config;
Field : in Policy_Fields;
Value : in Util.Beans.Objects.Object) is
begin
case Field is
when FIELD_ID =>
P.Id := Util.Beans.Objects.To_Integer (Value);
when FIELD_PERMISSION =>
P.Permissions.Append (Value);
when FIELD_URL_PATTERN =>
P.Patterns.Append (Value);
when FIELD_POLICY =>
Process (P);
P.Id := 0;
P.Permissions.Clear;
P.Patterns.Clear;
end case;
end Set_Member;
procedure Process (Policy : in Policy_Config) is
Pol : Security.Policies.URLs.Policy;
Count : constant Natural := Natural (Policy.Permissions.Length);
Rule : constant Access_Rule_Ref := Access_Rule_Refs.Create (new Access_Rule (Count));
Iter : Util.Beans.Objects.Vectors.Cursor := Policy.Permissions.First;
Pos : Positive := 1;
begin
Pol.Rule := Rule;
-- Step 1: Initialize the list of permission index in Access_Rule from the permission names.
while Util.Beans.Objects.Vectors.Has_Element (Iter) loop
declare
Perm : constant Util.Beans.Objects.Object := Util.Beans.Objects.Vectors.Element (Iter);
Name : constant String := Util.Beans.Objects.To_String (Perm);
begin
Rule.Value.all.Permissions (Pos) := Permissions.Get_Permission_Index (Name);
Pos := Pos + 1;
exception
when Invalid_Name =>
raise Util.Serialize.Mappers.Field_Error with "Invalid permission: " & Name;
end;
Util.Beans.Objects.Vectors.Next (Iter);
end loop;
-- Step 2: Create one policy for each URL pattern
Iter := Policy.Patterns.First;
while Util.Beans.Objects.Vectors.Has_Element (Iter) loop
declare
Pattern : constant Util.Beans.Objects.Object
:= Util.Beans.Objects.Vectors.Element (Iter);
begin
Pol.Id := Policy.Id;
Pol.Pattern := GNAT.Regexp.Compile (Util.Beans.Objects.To_String (Pattern));
Policy.Manager.Policies.Append (Pol);
end;
Util.Beans.Objects.Vectors.Next (Iter);
end loop;
end Process;
package Policy_Mapper is
new Util.Serialize.Mappers.Record_Mapper (Element_Type => Policy_Config,
Element_Type_Access => Policy_Config_Access,
Fields => Policy_Fields,
Set_Member => Set_Member);
Policy_Mapping : aliased Policy_Mapper.Mapper;
-- ------------------------------
-- Setup the XML parser to read the <b>policy</b> description.
-- ------------------------------
overriding
procedure Prepare_Config (Policy : in out URL_Policy;
Reader : in out Util.Serialize.IO.XML.Parser) is
Config : Policy_Config_Access := new Policy_Config;
begin
Reader.Add_Mapping ("policy-rules", Policy_Mapping'Access);
Reader.Add_Mapping ("module", Policy_Mapping'Access);
Config.Manager := Policy'Unchecked_Access;
Policy_Mapper.Set_Context (Reader, Config);
end Prepare_Config;
-- ------------------------------
-- Finish reading the XML policy configuration. The security policy implementation can use
-- this procedure to perform any configuration setup after the configuration is parsed.
-- ------------------------------
overriding
procedure Finish_Config (Into : in out URL_Policy;
Reader : in out Util.Serialize.IO.XML.Parser) is
begin
null;
end Finish_Config;
begin
Policy_Mapping.Add_Mapping ("policy", FIELD_POLICY);
Policy_Mapping.Add_Mapping ("policy/@id", FIELD_ID);
Policy_Mapping.Add_Mapping ("policy/permission", FIELD_PERMISSION);
Policy_Mapping.Add_Mapping ("policy/url-pattern", FIELD_URL_PATTERN);
end Security.Policies.Urls;
|
Implement the Finish_Config operation
|
Implement the Finish_Config operation
|
Ada
|
apache-2.0
|
Letractively/ada-security
|
07d65153ac49c929b5e4714bb2978314c06856c7
|
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, 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 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;
-- Rename the old name into a new name.
procedure Rename (Old_Name, New_Name : in String);
end Util.Files;
|
Declare new procedure Rename to rename a file using rename(2)
|
Declare new procedure Rename to rename a file using rename(2)
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
af2fa8dbbbfd08f239aad82ae26dabe8b69bb381
|
src/security-policies.adb
|
src/security-policies.adb
|
-----------------------------------------------------------------------
-- security-policies -- Security Policies
-- Copyright (C) 2010, 2011, 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Unchecked_Deallocation;
with Util.Log.Loggers;
with Security.Controllers;
with Security.Contexts;
package body Security.Policies is
use type Permissions.Permission_Index;
-- The logger
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Security.Policies");
procedure Free is
new Ada.Unchecked_Deallocation (Security.Controllers.Controller'Class,
Security.Controllers.Controller_Access);
-- ------------------------------
-- Get the policy index.
-- ------------------------------
function Get_Policy_Index (From : in Policy'Class) return Policy_Index is
begin
return From.Index;
end Get_Policy_Index;
-- ------------------------------
-- Add a permission under the given permission name and associated with the controller.
-- To verify the permission, the controller will be called.
-- ------------------------------
procedure Add_Permission (Manager : in out Policy;
Name : in String;
Permission : in Controller_Access) is
begin
Manager.Manager.Add_Permission (Name, Permission);
end Add_Permission;
-- ------------------------------
-- Get the policy with the name <b>Name</b> registered in the policy manager.
-- Returns null if there is no such policy.
-- ------------------------------
function Get_Policy (Manager : in Policy_Manager;
Name : in String) return Policy_Access is
begin
for I in Manager.Policies'Range loop
if Manager.Policies (I) = null then
return null;
elsif Manager.Policies (I).Get_Name = Name then
return Manager.Policies (I);
end if;
end loop;
return null;
end Get_Policy;
-- ------------------------------
-- Add the policy to the policy manager. After a policy is added in the manager,
-- it can participate in the security policy.
-- Raises Policy_Error if the policy table is full.
-- ------------------------------
procedure Add_Policy (Manager : in out Policy_Manager;
Policy : in Policy_Access) is
Name : constant String := Policy.Get_Name;
begin
Log.Info ("Adding policy {0}", Name);
for I in Manager.Policies'Range loop
if Manager.Policies (I) = null then
Manager.Policies (I) := Policy;
Policy.Manager := Manager'Unchecked_Access;
Policy.Index := I;
return;
end if;
end loop;
Log.Error ("Policy table is full, increase policy manager table to {0} to add policy {1}",
Policy_Index'Image (Manager.Max_Policies + 1), Name);
raise Policy_Error;
end Add_Policy;
-- ------------------------------
-- Add a permission under the given permission name and associated with the controller.
-- To verify the permission, the controller will be called.
-- ------------------------------
procedure Add_Permission (Manager : in out Policy_Manager;
Name : in String;
Permission : in Controller_Access) is
Index : Permission_Index;
begin
Log.Info ("Adding permission {0}", Name);
Permissions.Add_Permission (Name, Index);
if Index >= Manager.Last_Index then
declare
Count : constant Permission_Index := Index + 32;
Perms : constant Controller_Access_Array_Access
:= new Controller_Access_Array (0 .. Count);
begin
if Manager.Permissions /= null then
Perms (Manager.Permissions'Range) := Manager.Permissions.all;
end if;
Manager.Permissions := Perms;
Manager.Last_Index := Count;
end;
end if;
-- If the permission has a controller, release it.
if Manager.Permissions (Index) /= null then
Log.Warn ("Permission {0} is redefined", Name);
-- SCz 2011-12-03: GNAT 2011 reports a compilation error:
-- 'missing "with" clause on package "Security.Controllers"'
-- if we use the 'Security.Controller_Access' type, even if this "with"
-- clause exist.
-- gcc 4.4.3 under Ubuntu does not have this issue.
-- We use the 'Security.Controllers.Controller_Access' type to avoid the compiler
-- bug but we have to use a temporary variable and do some type conversion...
declare
P : Security.Controllers.Controller_Access := Manager.Permissions (Index).all'Access;
begin
Free (P);
end;
end if;
Manager.Permissions (Index) := Permission;
end Add_Permission;
-- ------------------------------
-- Checks whether the permission defined by the <b>Permission</b> is granted
-- for the security context passed in <b>Context</b>.
-- Returns true if such permission is granted.
-- ------------------------------
function Has_Permission (Manager : in Policy_Manager;
Context : in Security.Contexts.Security_Context'Class;
Permission : in Security.Permissions.Permission'Class)
return Boolean is
begin
if Permission.Id >= Manager.Last_Index then
return False;
end if;
declare
C : constant Controller_Access := Manager.Permissions (Permission.Id);
begin
if C = null then
return False;
else
return C.Has_Permission (Context, Permission);
end if;
end;
end Has_Permission;
-- ------------------------------
-- Returns True if the security controller is defined for the given permission index.
-- ------------------------------
function Has_Controller (Manager : in Policy_Manager;
Index : in Permissions.Permission_Index) return Boolean is
begin
return Index < Manager.Last_Index and then Manager.Permissions (Index) /= null;
end Has_Controller;
-- ------------------------------
-- Create the policy contexts to be associated with the security context.
-- ------------------------------
function Create_Policy_Contexts (Manager : in Policy_Manager)
return Policy_Context_Array_Access is
begin
return new Policy_Context_Array (1 .. Manager.Max_Policies);
end Create_Policy_Contexts;
-- ------------------------------
-- Prepare the XML parser to read the policy configuration.
-- ------------------------------
procedure Prepare_Config (Manager : in out Policy_Manager;
Reader : in out Util.Serialize.IO.XML.Parser) is
begin
-- Prepare the reader to parse the policy configuration.
for I in Manager.Policies'Range loop
exit when Manager.Policies (I) = null;
Manager.Policies (I).Prepare_Config (Reader);
end loop;
end Prepare_Config;
-- ------------------------------
-- Finish reading the XML policy configuration. The security policy implementation can use
-- this procedure to perform any configuration setup after the configuration is parsed.
-- ------------------------------
procedure Finish_Config (Manager : in out Policy_Manager;
Reader : in out Util.Serialize.IO.XML.Parser) is
begin
-- Finish the policy configuration.
for I in Manager.Policies'Range loop
exit when Manager.Policies (I) = null;
Manager.Policies (I).Finish_Config (Reader);
end loop;
end Finish_Config;
-- Read the policy file
procedure Read_Policy (Manager : in out Policy_Manager;
File : in String) is
use Util;
Reader : Util.Serialize.IO.XML.Parser;
package Policy_Config is
new Reader_Config (Reader, Manager'Unchecked_Access);
pragma Warnings (Off, Policy_Config);
begin
Log.Info ("Reading policy file {0}", File);
Manager.Prepare_Config (Reader);
-- Read the configuration file.
Reader.Parse (File);
Manager.Finish_Config (Reader);
end Read_Policy;
-- ------------------------------
-- Initialize the policy manager.
-- ------------------------------
overriding
procedure Initialize (Manager : in out Policy_Manager) is
begin
null;
end Initialize;
-- ------------------------------
-- Finalize the policy manager.
-- ------------------------------
overriding
procedure Finalize (Manager : in out Policy_Manager) is
procedure Free is
new Ada.Unchecked_Deallocation (Controller_Access_Array,
Controller_Access_Array_Access);
procedure Free is
new Ada.Unchecked_Deallocation (Policy'Class,
Policy_Access);
begin
-- Release the security controllers.
if Manager.Permissions /= null then
for I in Manager.Permissions.all'Range loop
if Manager.Permissions (I) /= null then
-- SCz 2011-12-03: GNAT 2011 reports a compilation error:
-- 'missing "with" clause on package "Security.Controllers"'
-- if we use the 'Security.Controller_Access' type, even if this "with"
-- clause exist.
-- gcc 4.4.3 under Ubuntu does not have this issue.
-- We use the 'Security.Controllers.Controller_Access' type to avoid the compiler
-- bug but we have to use a temporary variable and do some type conversion...
declare
P : Security.Controllers.Controller_Access := Manager.Permissions (I).all'Access;
begin
Free (P);
Manager.Permissions (I) := null;
end;
end if;
end loop;
Free (Manager.Permissions);
end if;
-- Release the policy instances.
for I in Manager.Policies'Range loop
exit when Manager.Policies (I) = null;
Free (Manager.Policies (I));
end loop;
end Finalize;
end Security.Policies;
|
-----------------------------------------------------------------------
-- security-policies -- Security Policies
-- Copyright (C) 2010, 2011, 2012, 2013 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Unchecked_Deallocation;
with Util.Log.Loggers;
with Util.Serialize.Mappers;
with Util.Serialize.Mappers.Record_Mapper;
with Security.Controllers;
with Security.Contexts;
package body Security.Policies is
use type Permissions.Permission_Index;
-- The logger
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Security.Policies");
procedure Free is
new Ada.Unchecked_Deallocation (Security.Controllers.Controller'Class,
Security.Controllers.Controller_Access);
-- ------------------------------
-- Default Security Controllers
-- ------------------------------
-- The <b>Auth_Controller</b> grants the permission if there is a principal.
type Auth_Controller is limited new Security.Controllers.Controller with null record;
-- Returns true if the user associated with the security context <b>Context</b> was
-- authentified (ie, it has a principal).
overriding
function Has_Permission (Handler : in Auth_Controller;
Context : in Security.Contexts.Security_Context'Class;
Permission : in Security.Permissions.Permission'Class)
return Boolean;
-- The <b>Pass_Through_Controller</b> grants access to anybody.
type Pass_Through_Controller is limited new Security.Controllers.Controller with null record;
-- Returns true if the user associated with the security context <b>Context</b> has
-- the permission to access the URL defined in <b>Permission</b>.
overriding
function Has_Permission (Handler : in Pass_Through_Controller;
Context : in Security.Contexts.Security_Context'Class;
Permission : in Security.Permissions.Permission'Class)
return Boolean;
-- ------------------------------
-- Returns true if the user associated with the security context <b>Context</b> was
-- authentified (ie, it has a principal).
-- ------------------------------
overriding
function Has_Permission (Handler : in Auth_Controller;
Context : in Security.Contexts.Security_Context'Class;
Permission : in Security.Permissions.Permission'Class)
return Boolean is
pragma Unreferenced (Handler, Permission);
use type Security.Principal_Access;
P : constant Security.Principal_Access := Context.Get_User_Principal;
begin
if P /= null then
Log.Debug ("Grant permission because a principal exists");
return True;
else
return False;
end if;
end Has_Permission;
-- ------------------------------
-- Returns true if the user associated with the security context <b>Context</b> has
-- the permission to access the URL defined in <b>Permission</b>.
-- ------------------------------
overriding
function Has_Permission (Handler : in Pass_Through_Controller;
Context : in Security.Contexts.Security_Context'Class;
Permission : in Security.Permissions.Permission'Class)
return Boolean is
pragma Unreferenced (Handler, Context, Permission);
begin
Log.Debug ("Pass through controller grants the permission");
return True;
end Has_Permission;
-- ------------------------------
-- Get the policy index.
-- ------------------------------
function Get_Policy_Index (From : in Policy'Class) return Policy_Index is
begin
return From.Index;
end Get_Policy_Index;
-- ------------------------------
-- Add a permission under the given permission name and associated with the controller.
-- To verify the permission, the controller will be called.
-- ------------------------------
procedure Add_Permission (Manager : in out Policy;
Name : in String;
Permission : in Controller_Access) is
begin
Manager.Manager.Add_Permission (Name, Permission);
end Add_Permission;
-- ------------------------------
-- Get the policy with the name <b>Name</b> registered in the policy manager.
-- Returns null if there is no such policy.
-- ------------------------------
function Get_Policy (Manager : in Policy_Manager;
Name : in String) return Policy_Access is
begin
for I in Manager.Policies'Range loop
if Manager.Policies (I) = null then
return null;
elsif Manager.Policies (I).Get_Name = Name then
return Manager.Policies (I);
end if;
end loop;
return null;
end Get_Policy;
-- ------------------------------
-- Add the policy to the policy manager. After a policy is added in the manager,
-- it can participate in the security policy.
-- Raises Policy_Error if the policy table is full.
-- ------------------------------
procedure Add_Policy (Manager : in out Policy_Manager;
Policy : in Policy_Access) is
Name : constant String := Policy.Get_Name;
begin
Log.Info ("Adding policy {0}", Name);
for I in Manager.Policies'Range loop
if Manager.Policies (I) = null then
Manager.Policies (I) := Policy;
Policy.Manager := Manager'Unchecked_Access;
Policy.Index := I;
return;
end if;
end loop;
Log.Error ("Policy table is full, increase policy manager table to {0} to add policy {1}",
Policy_Index'Image (Manager.Max_Policies + 1), Name);
raise Policy_Error;
end Add_Policy;
-- ------------------------------
-- Add a permission under the given permission name and associated with the controller.
-- To verify the permission, the controller will be called.
-- ------------------------------
procedure Add_Permission (Manager : in out Policy_Manager;
Name : in String;
Permission : in Controller_Access) is
Index : Permission_Index;
begin
Log.Info ("Adding permission {0}", Name);
Permissions.Add_Permission (Name, Index);
if Index >= Manager.Last_Index then
declare
Count : constant Permission_Index := Index + 32;
Perms : constant Controller_Access_Array_Access
:= new Controller_Access_Array (0 .. Count);
begin
if Manager.Permissions /= null then
Perms (Manager.Permissions'Range) := Manager.Permissions.all;
end if;
Manager.Permissions := Perms;
Manager.Last_Index := Count;
end;
end if;
-- If the permission has a controller, release it.
if Manager.Permissions (Index) /= null then
Log.Warn ("Permission {0} is redefined", Name);
-- SCz 2011-12-03: GNAT 2011 reports a compilation error:
-- 'missing "with" clause on package "Security.Controllers"'
-- if we use the 'Security.Controller_Access' type, even if this "with"
-- clause exist.
-- gcc 4.4.3 under Ubuntu does not have this issue.
-- We use the 'Security.Controllers.Controller_Access' type to avoid the compiler
-- bug but we have to use a temporary variable and do some type conversion...
declare
P : Security.Controllers.Controller_Access := Manager.Permissions (Index).all'Access;
begin
Free (P);
end;
end if;
Manager.Permissions (Index) := Permission;
end Add_Permission;
-- ------------------------------
-- Checks whether the permission defined by the <b>Permission</b> is granted
-- for the security context passed in <b>Context</b>.
-- Returns true if such permission is granted.
-- ------------------------------
function Has_Permission (Manager : in Policy_Manager;
Context : in Security.Contexts.Security_Context'Class;
Permission : in Security.Permissions.Permission'Class)
return Boolean is
begin
if Permission.Id >= Manager.Last_Index then
return False;
end if;
declare
C : constant Controller_Access := Manager.Permissions (Permission.Id);
begin
if C = null then
return False;
else
return C.Has_Permission (Context, Permission);
end if;
end;
end Has_Permission;
-- ------------------------------
-- Returns True if the security controller is defined for the given permission index.
-- ------------------------------
function Has_Controller (Manager : in Policy_Manager;
Index : in Permissions.Permission_Index) return Boolean is
begin
return Index < Manager.Last_Index and then Manager.Permissions (Index) /= null;
end Has_Controller;
-- ------------------------------
-- Create the policy contexts to be associated with the security context.
-- ------------------------------
function Create_Policy_Contexts (Manager : in Policy_Manager)
return Policy_Context_Array_Access is
begin
return new Policy_Context_Array (1 .. Manager.Max_Policies);
end Create_Policy_Contexts;
-- ------------------------------
-- Prepare the XML parser to read the policy configuration.
-- ------------------------------
procedure Prepare_Config (Manager : in out Policy_Manager;
Reader : in out Util.Serialize.IO.XML.Parser) is
begin
-- Prepare the reader to parse the policy configuration.
for I in Manager.Policies'Range loop
exit when Manager.Policies (I) = null;
Manager.Policies (I).Prepare_Config (Reader);
end loop;
end Prepare_Config;
-- ------------------------------
-- Finish reading the XML policy configuration. The security policy implementation can use
-- this procedure to perform any configuration setup after the configuration is parsed.
-- ------------------------------
procedure Finish_Config (Manager : in out Policy_Manager;
Reader : in out Util.Serialize.IO.XML.Parser) is
begin
-- Finish the policy configuration.
for I in Manager.Policies'Range loop
exit when Manager.Policies (I) = null;
Manager.Policies (I).Finish_Config (Reader);
end loop;
end Finish_Config;
type Policy_Fields is (FIELD_ALL_PERMISSION, FIELD_AUTH_PERMISSION);
procedure Set_Member (P : in out Policy_Manager'Class;
Field : in Policy_Fields;
Value : in Util.Beans.Objects.Object);
procedure Set_Member (P : in out Policy_Manager'Class;
Field : in Policy_Fields;
Value : in Util.Beans.Objects.Object) is
Name : constant String := Util.Beans.Objects.To_String (Value);
begin
case Field is
when FIELD_ALL_PERMISSION =>
P.Add_Permission (Name, new Pass_Through_Controller);
when FIELD_AUTH_PERMISSION =>
P.Add_Permission (Name, new Auth_Controller);
end case;
end Set_Member;
package Policy_Mapper is
new Util.Serialize.Mappers.Record_Mapper (Element_Type => Policy_Manager'Class,
Element_Type_Access => Policy_Manager_Access,
Fields => Policy_Fields,
Set_Member => Set_Member);
Policy_Mapping : aliased Policy_Mapper.Mapper;
-- Read the policy file
procedure Read_Policy (Manager : in out Policy_Manager;
File : in String) is
use Util;
Reader : Util.Serialize.IO.XML.Parser;
package Policy_Config is
new Reader_Config (Reader, Manager'Unchecked_Access);
pragma Warnings (Off, Policy_Config);
begin
Log.Info ("Reading policy file {0}", File);
Reader.Add_Mapping ("policy-rules", Policy_Mapping'Access);
Policy_Mapper.Set_Context (Reader, Manager'Unchecked_Access);
Manager.Prepare_Config (Reader);
-- Read the configuration file.
Reader.Parse (File);
Manager.Finish_Config (Reader);
end Read_Policy;
-- ------------------------------
-- Initialize the policy manager.
-- ------------------------------
overriding
procedure Initialize (Manager : in out Policy_Manager) is
begin
null;
end Initialize;
-- ------------------------------
-- Finalize the policy manager.
-- ------------------------------
overriding
procedure Finalize (Manager : in out Policy_Manager) is
procedure Free is
new Ada.Unchecked_Deallocation (Controller_Access_Array,
Controller_Access_Array_Access);
procedure Free is
new Ada.Unchecked_Deallocation (Policy'Class,
Policy_Access);
begin
-- Release the security controllers.
if Manager.Permissions /= null then
for I in Manager.Permissions.all'Range loop
if Manager.Permissions (I) /= null then
-- SCz 2011-12-03: GNAT 2011 reports a compilation error:
-- 'missing "with" clause on package "Security.Controllers"'
-- if we use the 'Security.Controller_Access' type, even if this "with"
-- clause exist.
-- gcc 4.4.3 under Ubuntu does not have this issue.
-- We use the 'Security.Controllers.Controller_Access' type to avoid the compiler
-- bug but we have to use a temporary variable and do some type conversion...
declare
P : Security.Controllers.Controller_Access := Manager.Permissions (I).all'Access;
begin
Free (P);
Manager.Permissions (I) := null;
end;
end if;
end loop;
Free (Manager.Permissions);
end if;
-- Release the policy instances.
for I in Manager.Policies'Range loop
exit when Manager.Policies (I) = null;
Free (Manager.Policies (I));
end loop;
end Finalize;
begin
Policy_Mapping.Add_Mapping ("all-permission/name", FIELD_ALL_PERMISSION);
Policy_Mapping.Add_Mapping ("auth-permission/name", FIELD_AUTH_PERMISSION);
end Security.Policies;
|
Add two default security controllers that can be installed to - grant the permission if the security context has a user principal - always grant the permission
|
Add two default security controllers that can be installed to
- grant the permission if the security context has a user principal
- always grant the permission
|
Ada
|
apache-2.0
|
stcarrez/ada-security
|
0f7f668d46fb5e53cfa9749ef286a3fb5b16a377
|
src/wiki-parsers-textile.ads
|
src/wiki-parsers-textile.ads
|
-----------------------------------------------------------------------
-- wiki-parsers-textile -- Textile parser operations
-- Copyright (C) 2022 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Wiki.Parsers.Html;
with Wiki.Parsers.Common;
private package Wiki.Parsers.Textile is
pragma Preelaborate;
-- Parse a textile wiki heading in the form 'h<N>.'.
-- Example:
-- h1. Level 1
-- h2. Level 2
procedure Parse_Header (P : in out Parser;
Token : in Wiki.Strings.WChar);
-- Parse a textile image.
-- Example:
-- !image-link!
-- !image-link(title)!
-- !image-path|:http-link
procedure Parse_Image (P : in out Parser;
Token : in Wiki.Strings.WChar);
-- Parse an external link:
-- Example:
-- "title":http-link
procedure Parse_Link (P : in out Parser;
Token : in Wiki.Strings.WChar);
-- Parse an italic or bold sequence or a list.
-- Example:
-- *name* (italic)
-- **name** (bold)
-- * item (list)
procedure Parse_Bold_Or_List (P : in out Parser;
Token : in Wiki.Strings.WChar);
-- Parse a markdown table/column.
-- Example:
-- | col1 | col2 | ... | colN |
procedure Parse_Table (P : in out Parser;
Token : in Wiki.Strings.WChar);
procedure Parse_Deleted_Or_Horizontal_Rule (P : in out Parser;
Token : in Wiki.Strings.WChar);
Wiki_Table : aliased constant Parser_Table
:= (
16#0A# => Parse_End_Line'Access,
16#0D# => Parse_End_Line'Access,
Character'Pos (' ') => Parse_Space'Access,
Character'Pos ('[') => Common.Parse_Link'Access,
Character'Pos ('#') => Common.Parse_List'Access,
Character'Pos ('*') => Parse_Bold_Or_List'Access,
Character'Pos ('<') => Parse_Maybe_Html'Access,
Character'Pos ('&') => Html.Parse_Entity'Access,
Character'Pos ('-') => Parse_Deleted_Or_Horizontal_Rule'Access,
Character'Pos ('!') => Parse_Image'Access,
Character'Pos ('"') => Parse_Link'Access,
Character'Pos ('@') => Common.Parse_Single_Code'Access,
Character'Pos ('_') => Common.Parse_Single_Italic'Access,
Character'Pos ('|') => Parse_Table'Access,
Character'Pos ('h') => Parse_Header'Access,
others => Parse_Text'Access
);
end Wiki.Parsers.Textile;
|
-----------------------------------------------------------------------
-- wiki-parsers-textile -- Textile parser operations
-- Copyright (C) 2022 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Wiki.Parsers.Html;
with Wiki.Parsers.Common;
private package Wiki.Parsers.Textile is
pragma Preelaborate;
-- Parse a textile wiki heading in the form 'h<N>.'.
-- Example:
-- h1. Level 1
-- h2. Level 2
procedure Parse_Header (P : in out Parser;
Token : in Wiki.Strings.WChar);
-- Parse a textile image.
-- Example:
-- !image-link!
-- !image-link(title)!
-- !image-path!:http-link
procedure Parse_Image (P : in out Parser;
Token : in Wiki.Strings.WChar);
-- Parse an external link:
-- Example:
-- "title":http-link
procedure Parse_Link (P : in out Parser;
Token : in Wiki.Strings.WChar);
-- Parse a bold sequence or a list.
-- Example:
-- *name* (bold)
-- * item (list)
procedure Parse_Bold_Or_List (P : in out Parser;
Token : in Wiki.Strings.WChar);
-- Parse a markdown table/column.
-- Example:
-- | col1 | col2 | ... | colN |
procedure Parse_Table (P : in out Parser;
Token : in Wiki.Strings.WChar);
procedure Parse_Deleted_Or_Horizontal_Rule (P : in out Parser;
Token : in Wiki.Strings.WChar);
Wiki_Table : aliased constant Parser_Table
:= (
16#0A# => Parse_End_Line'Access,
16#0D# => Parse_End_Line'Access,
Character'Pos (' ') => Parse_Space'Access,
Character'Pos ('[') => Common.Parse_Link'Access,
Character'Pos ('#') => Common.Parse_List'Access,
Character'Pos ('*') => Parse_Bold_Or_List'Access,
Character'Pos ('<') => Parse_Maybe_Html'Access,
Character'Pos ('&') => Html.Parse_Entity'Access,
Character'Pos ('-') => Parse_Deleted_Or_Horizontal_Rule'Access,
Character'Pos ('!') => Parse_Image'Access,
Character'Pos ('"') => Parse_Link'Access,
Character'Pos ('@') => Common.Parse_Single_Code'Access,
Character'Pos ('_') => Common.Parse_Single_Italic'Access,
Character'Pos ('|') => Parse_Table'Access,
Character'Pos ('h') => Parse_Header'Access,
others => Parse_Text'Access
);
end Wiki.Parsers.Textile;
|
Update the comments
|
Update the comments
|
Ada
|
apache-2.0
|
stcarrez/ada-wiki,stcarrez/ada-wiki
|
05bc756df234ddbf45c800d504694454e4f39f59
|
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.Schemas.Entities;
with ADO.Sequences;
with ADO.Caches;
with ADO.Sessions.Sources;
-- === Session Factory ===
-- The session factory is the entry point to obtain a database session.
-- The <b>ADO.Sessions.Factory</b> package defines the factory for creating
-- sessions.
--
-- with ADO.Sessions.Factory;
-- ...
-- Sess_Factory : ADO.Sessions.Factory;
--
-- The session factory can be initialized by using the <tt>Create</tt> operation and
-- by giving a URI string that identifies the driver and the information to connect
-- to the database. The session factory is created only once when the application starts.
--
-- ADO.Sessions.Factory.Create (Sess_Factory, "mysql://localhost:3306/ado_test?user=test");
--
-- Having a session factory, one can get a database by using the <tt>Get_Session</tt> or
-- <tt>Get_Master_Session</tt> function. Each time this operation is called, a new session
-- is returned. The session is released when the session variable is finalized.
--
-- DB : ADO.Sessions.Session := Sess_Factory.Get_Session;
--
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.Schemas.Entities;
with ADO.Sequences;
with ADO.Caches;
with ADO.Sessions.Sources;
-- === Session Factory ===
-- The session factory is the entry point to obtain a database session.
-- The <b>ADO.Sessions.Factory</b> package defines the factory for creating
-- sessions.
--
-- with ADO.Sessions.Factory;
-- ...
-- Sess_Factory : ADO.Sessions.Factory;
--
-- The session factory can be initialized by using the <tt>Create</tt> operation and
-- by giving a URI string that identifies the driver and the information to connect
-- to the database. The session factory is created only once when the application starts.
--
-- ADO.Sessions.Factory.Create (Sess_Factory, "mysql://localhost:3306/ado_test?user=test");
--
-- Having a session factory, one can get a database by using the <tt>Get_Session</tt> or
-- <tt>Get_Master_Session</tt> function. Each time this operation is called, a new session
-- is returned. The session is released when the session variable is finalized.
--
-- DB : ADO.Sessions.Session := Sess_Factory.Get_Session;
--
-- The session factory is also responsible for maintaining some data that is shared by
-- all the database connections. This includes:
--
-- o the sequence generators used to allocate unique identifiers for database tables,
-- o the entity cache,
-- o some application specific global cache.
--
package ADO.Sessions.Factory is
pragma Elaborate_Body;
ENTITY_CACHE_NAME : constant String := "entity_type";
-- ------------------------------
-- Session factory
-- ------------------------------
type Session_Factory is tagged limited private;
type Session_Factory_Access is access all Session_Factory'Class;
-- Get a read-only session from the factory.
function Get_Session (Factory : in Session_Factory) return Session;
-- Get a read-write session from the factory.
function Get_Master_Session (Factory : in Session_Factory) return Master_Session;
-- Open a session
procedure Open_Session (Factory : in out Session_Factory;
Database : out Session);
-- Open a session
procedure Open_Session (Factory : in Session_Factory;
Database : out Master_Session);
-- Create the session factory to connect to the database represented
-- by the data source.
procedure Create (Factory : out Session_Factory;
Source : in ADO.Sessions.Sources.Data_Source);
-- Create the session factory to connect to the database identified
-- by the URI.
procedure Create (Factory : out Session_Factory;
URI : in String);
-- Get a read-only session from the session proxy.
-- If the session has been invalidated, raise the SESSION_EXPIRED exception.
function Get_Session (Proxy : in Session_Record_Access) return Session;
private
-- The session factory holds the necessary information to obtain a master or slave
-- database connection. The sequence factory is shared by all sessions of the same
-- factory (implementation is thread-safe). The factory also contains the entity type
-- cache which is initialized when the factory is created.
type Session_Factory is tagged limited record
Source : ADO.Sessions.Sources.Data_Source;
Sequences : Factory_Access := null;
Seq_Factory : aliased ADO.Sequences.Factory;
-- Entity_Cache : aliased ADO.Schemas.Entities.Entity_Cache;
Entities : ADO.Sessions.Entity_Cache_Access := null;
Cache : aliased ADO.Caches.Cache_Manager;
Cache_Values : ADO.Caches.Cache_Manager_Access;
end record;
-- Initialize the sequence factory associated with the session factory.
procedure Initialize_Sequences (Factory : in out Session_Factory);
end ADO.Sessions.Factory;
|
Add some documentation
|
Add some documentation
|
Ada
|
apache-2.0
|
stcarrez/ada-ado
|
0d388997b5315f6759e0564c5b78f4552bea41e9
|
src/ado-utils.adb
|
src/ado-utils.adb
|
-----------------------------------------------------------------------
-- ado-utils -- Utility operations for ADO
-- 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.
-----------------------------------------------------------------------
package body ADO.Utils is
-- ------------------------------
-- Build a bean object from the identifier.
-- ------------------------------
function To_Object (Id : in ADO.Identifier) return Util.Beans.Objects.Object is
begin
if Id = ADO.NO_IDENTIFIER then
return Util.Beans.Objects.Null_Object;
else
return Util.Beans.Objects.To_Object (Long_Long_Integer (Id));
end if;
end To_Object;
-- ------------------------------
-- Build the identifier from the bean object.
-- ------------------------------
function To_Identifier (Value : in Util.Beans.Objects.Object) return ADO.Identifier is
begin
if Util.Beans.Objects.Is_Null (Value) then
return ADO.NO_IDENTIFIER;
else
return ADO.Identifier (Util.Beans.Objects.To_Long_Long_Integer (Value));
end if;
end To_Identifier;
-- ------------------------------
-- Compute the hash of the identifier.
-- ------------------------------
function Hash (Key : in ADO.Identifier) return Ada.Containers.Hash_Type is
use Ada.Containers;
begin
if Key < 0 then
return Hash_Type (-Key);
else
return Hash_Type (Key);
end if;
end Hash;
end ADO.Utils;
|
-----------------------------------------------------------------------
-- ado-utils -- Utility operations for ADO
-- 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.
-----------------------------------------------------------------------
package body ADO.Utils is
-- ------------------------------
-- Build a bean object from the identifier.
-- ------------------------------
function To_Object (Id : in ADO.Identifier) return Util.Beans.Objects.Object is
begin
if Id = ADO.NO_IDENTIFIER then
return Util.Beans.Objects.Null_Object;
else
return Util.Beans.Objects.To_Object (Long_Long_Integer (Id));
end if;
end To_Object;
-- ------------------------------
-- Build the identifier from the bean object.
-- ------------------------------
function To_Identifier (Value : in Util.Beans.Objects.Object) return ADO.Identifier is
begin
if Util.Beans.Objects.Is_Null (Value) then
return ADO.NO_IDENTIFIER;
else
return ADO.Identifier (Util.Beans.Objects.To_Long_Long_Integer (Value));
end if;
end To_Identifier;
-- ------------------------------
-- Compute the hash of the identifier.
-- ------------------------------
function Hash (Key : in ADO.Identifier) return Ada.Containers.Hash_Type is
use Ada.Containers;
begin
if Key < 0 then
return Hash_Type (-Key);
else
return Hash_Type (Key);
end if;
end Hash;
-- ------------------------------
-- Return the identifier list as a comma separated list of identifiers.
-- ------------------------------
function To_Parameter_List (List : in Identifier_Vector) return String is
use Identifier_Vectors;
Result : Ada.Strings.Unbounded.Unbounded_String;
Pos : Identifier_Cursor := List.First;
Need_Comma : Boolean := False;
begin
while Identifier_Vectors.Has_Element (Pos) loop
if Need_Comma then
Ada.Strings.Unbounded.Append (Result, ",");
end if;
Ada.Strings.Unbounded.Append (Result, ADO.Identifier'Image (Element (Pos)));
Need_Comma := True;
Next (Pos);
end loop;
return Ada.Strings.Unbounded.To_String (Result);
end To_Parameter_List;
end ADO.Utils;
|
Implement the To_Parameter_List operation
|
Implement the To_Parameter_List operation
|
Ada
|
apache-2.0
|
Letractively/ada-ado
|
7d83bbb4414f4bb91da45d8ff8744401f70a6ce8
|
regtests/ado-schemas-tests.ads
|
regtests/ado-schemas-tests.ads
|
-----------------------------------------------------------------------
-- schemas Tests -- Test loading of database schema
-- Copyright (C) 2009, 2010, 2011, 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Tests;
package ADO.Schemas.Tests is
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite);
type Test is new Util.Tests.Test with null record;
-- Test reading the entity cache and the Find_Entity_Type operation
procedure Test_Find_Entity_Type (T : in out Test);
-- Test calling Find_Entity_Type with an invalid table.
procedure Test_Find_Entity_Type_Error (T : in out Test);
-- Test the Load_Schema operation and check the result schema.
procedure Test_Load_Schema (T : in out Test);
-- Test the Table_Cursor operations and check the result schema.
procedure Test_Table_Iterator (T : in out Test);
end ADO.Schemas.Tests;
|
-----------------------------------------------------------------------
-- schemas Tests -- Test loading of database schema
-- Copyright (C) 2009, 2010, 2011, 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Tests;
package ADO.Schemas.Tests is
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite);
type Test is new Util.Tests.Test with null record;
-- Test reading the entity cache and the Find_Entity_Type operation
procedure Test_Find_Entity_Type (T : in out Test);
-- Test calling Find_Entity_Type with an invalid table.
procedure Test_Find_Entity_Type_Error (T : in out Test);
-- Test the Load_Schema operation and check the result schema.
procedure Test_Load_Schema (T : in out Test);
-- Test the Table_Cursor operations and check the result schema.
procedure Test_Table_Iterator (T : in out Test);
-- Test the Table_Cursor operations on an empty schema.
procedure Test_Empty_Schema (T : in out Test);
end ADO.Schemas.Tests;
|
Declare the Test_Empty_Schema procedure
|
Declare the Test_Empty_Schema procedure
|
Ada
|
apache-2.0
|
stcarrez/ada-ado
|
1b3f07354ea880173af5bd68a0aa791edc54199d
|
regtests/asf-cookies-tests.adb
|
regtests/asf-cookies-tests.adb
|
-----------------------------------------------------------------------
-- asf-cookies-tests - Unit tests for Cookies
-- Copyright (C) 2011 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Tests;
with Util.Test_Caller;
with Util.Log.Loggers;
with Util.Measures;
with Ada.Strings.Fixed;
with Ada.Unchecked_Deallocation;
package body ASF.Cookies.Tests is
use Ada.Strings.Fixed;
use Util.Tests;
use Util.Log;
-- The logger
Log : constant Loggers.Logger := Loggers.Create ("ASF.Cookies.Tests");
procedure Free is new Ada.Unchecked_Deallocation (Cookie_Array, Cookie_Array_Access);
package Caller is new Util.Test_Caller (Test);
procedure Add_Tests (Suite : AUnit.Test_Suites.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test ASF.Cookies.Create_Cookie",
Test_Create_Cookie'Access);
Caller.Add_Test (Suite, "Test ASF.Cookies.To_Http_Header",
Test_To_Http_Header'Access);
Caller.Add_Test (Suite, "Test ASF.Cookies.Get_Cookies",
Test_Parse_Http_Header'Access);
end Add_Tests;
-- ------------------------------
-- Test creation of cookie
-- ------------------------------
procedure Test_Create_Cookie (T : in out Test) is
C : constant Cookie := Create ("cookie", "value");
begin
T.Assert_Equals ("cookie", Get_Name (C), "Invalid name");
T.Assert_Equals ("value", Get_Value (C), "Invalid value");
T.Assert (not Is_Secure (C), "Invalid is_secure");
end Test_Create_Cookie;
-- ------------------------------
-- Test conversion of cookie for HTTP header
-- ------------------------------
procedure Test_To_Http_Header (T : in out Test) is
procedure Test_Cookie (C : in Cookie) is
S : constant String := To_Http_Header (C);
begin
Log.Info ("Cookie {0}: {1}", Get_Name (C), S);
T.Assert (S'Length > 0, "Invalid cookie length for: " & S);
T.Assert (Index (S, "=") > 0, "Invalid cookie format; " & S);
end Test_Cookie;
procedure Test_Cookie (Name : in String; Value : in String) is
C : Cookie := Create (Name, Value);
begin
Test_Cookie (C);
for I in 1 .. 24 loop
Set_Max_Age (C, I * 3600 + I);
Test_Cookie (C);
end loop;
Set_Secure (C, True);
Test_Cookie (C);
Set_Http_Only (C, True);
Test_Cookie (C);
Set_Domain (C, "world.com");
Test_Cookie (C);
Set_Path (C, "/some-path");
Test_Cookie (C);
end Test_Cookie;
begin
Test_Cookie ("a", "b");
Test_Cookie ("session_id", "79e2317bcabe731e2f681f5725bbc621-&v=1");
Test_Cookie ("p_41_zy", "");
Test_Cookie ("p_34", """quoted\t""");
Test_Cookie ("d", "s");
declare
C : Cookie := Create ("cookie-name", "79e2317bcabe731e2f681f5725bbc621");
Start : Util.Measures.Stamp;
begin
Set_Path (C, "/home");
Set_Domain (C, ".mydomain.example.com");
Set_Max_Age (C, 1000);
Set_Http_Only (C, True);
Set_Secure (C, True);
Set_Comment (C, "some comment");
for I in 1 .. 1000 loop
declare
S : constant String := To_Http_Header (C);
begin
if S'Length < 10 then
T.Assert (S'Length > 10, "Invalid cookie generation");
end if;
end;
end loop;
Util.Measures.Report (S => Start,
Title => "Generation of 1000 cookies");
end;
end Test_To_Http_Header;
-- ------------------------------
-- Test parsing of client cookie to build a list of Cookie objects
-- ------------------------------
procedure Test_Parse_Http_Header (T : in out Test) is
-- ------------------------------
-- Parse the header and check for the expected cookie count and verify
-- the value of a specific cookie
-- ------------------------------
procedure Test_Parse (Header : in String;
Count : in Natural;
Name : in String;
Value : in String) is
Start : Util.Measures.Stamp;
C : Cookie_Array_Access := Get_Cookies (Header);
Found : Boolean := False;
begin
Util.Measures.Report (S => Start,
Title => "Parsing of cookie " & Name);
T.Assert (C /= null, "Null value returned by Get_Cookies");
T.Assert_Equals (Count, C'Length, "Invalid count in result array");
for I in C'Range loop
Log.Debug ("Cookie: {0}={1}", Get_Name (C (I)), Get_Value (C (I)));
if Name = Get_Name (C (I)) then
T.Assert_Equals (Value, Get_Value (C (I)), "Invalid cookie: " & Name);
Found := True;
end if;
end loop;
T.Assert (Found, "Cookie " & Name & " not found");
Free (C);
end Test_Parse;
begin
Test_Parse ("A=B", 1, "A", "B");
Test_Parse ("A=B=", 1, "A", "B=");
Test_Parse ("CONTEXTE=mar=101&nab=84fbbe2a81887732fe9c635d9ac319b5"
& "&pfl=afide0&typsrv=we&sc=1&soumar=1011&srcurlconfigchapeau"
& "=sous_ouv_formulaire_chapeau_dei_config&nag=550®=14505; "
& "xtvrn=$354249$354336$; CEPORM=321169600.8782.0000; SES=auth=0&"
& "cartridge_url=&return_url=; CEPORC=344500416.8782.0000", 5,
"SES", "auth=0&cartridge_url=&return_url=");
Test_Parse ("s_nr=1298652863627; s_sq=%5B%5BB%5D%5D; s_cc=true; oraclelicense="
& "accept-dbindex-cookie; gpv_p24=no%20value; gpw_e24=no%20value",
6, "gpw_e24", "no%20value");
-- Parse a set of cookies from microsoft.com
Test_Parse ("WT_FPC=id=00.06.036.020-2037773472.29989343:lv=1300442685103:ss=1300442685103; "
& "MC1=GUID=9d86c397c1a5ea4cab48d9fe19b76b4e&HASH=97c3&LV=20092&V=3; "
& "A=I&I=AxUFAAAAAABwBwAALSllub5HorZBtWWX8ZeXcQ!!&CS=114[3B002j2p[0302g3V309; "
& "WT_NVR_RU=0=technet|msdn:1=:2=; mcI=Fri, 31 Dec 2010 10:44:31 GMT; "
& "omniID=beb780dd_ab6d_4802_9f37_e33dde280adb; CodeSnippetContainerLang="
& "Visual Basic; MSID=Microsoft.CreationDate=11/09/2010 10:08:25&Microsoft."
& "LastVisitDate=03/01/2011 17:08:34&Microsoft.VisitStartDate=03/01/2011 "
& "17:08:34&Microsoft.CookieId=882efa27-ee6c-40c5-96ba-2297f985d9e3&Microsoft"
& ".TokenId=0c0a5e07-37a6-4ca3-afc0-0edf3de329f6&Microsoft.NumberOfVisits="
& "60&Microsoft.IdentityToken=RojEm8r/0KbCYeKasdfwekl3FtctotD5ocj7WVR72795"
& "dBj23rXVz5/xeldkkKHr/NtXFN3xAvczHlHQHKw14/9f/VAraQFIzEYpypGE24z1AuPCzVwU"
& "l4HZPnOFH+IA0u2oarcR1n3IMC4Gk8D1UOPBwGlYMB2Xl2W+Up8kJikc4qUxmFG+X5SRrZ3m7"
& "LntAv92B4v7c9FPewcQHDSAJAmTOuy7+sl6zEwW2fGWjqGe3G7bh+qqUWPs4LrvSyyi7T3UCW"
& "anSWn6jqJInP/MSeAxAvjbTrBwlJlE3AoUfXUJgL81boPYsIXZ30lPpqjMkyc0Jd70dffNNTo5"
& "qwkvfFhyOvnfYoQ7dZ0REw+TRA01xHyyUSPINOVgM5Vcu4SdvcUoIlMR3Y097nK+lvx8SqV4UU"
& "+QENW1wbBDa7/u6AQqUuk0616tWrBQMR9pYKwYsORUqLkQY5URzhVVA7Py28dLX002Nehqjbh68"
& "4xQv/gQYbPZMZUq/wgmPsqA5mJU/lki6A0S/H/ULGbrJE0PBQr8T+Hd+Op4HxEHvjvkTs=&Micr"
& "osoft.MicrosoftId=0004-1282-6244-7365; msresearch=%7B%22version%22%3A%224.6"
& "%22%2C%22state%22%3A%7B%22name%22%3A%22IDLE%22%2C%22url%22%3Aundefined%2C%2"
& "2timestamp%22%3A1296211850175%7D%2C%22lastinvited%22%3A1296211850175%2C%22u"
& "serid%22%3A%2212962118501758905232121057759%22%2C%22vendorid%22%3A1%2C%22su"
& "rveys%22%3A%5Bundefined%5D%7D; s_sq=%5B%5BB%5D%5D; s_cc=true; "
& "GsfxStatsLog=true; GsfxSessionCookie=231210164895294015; ADS=SN=175A21EF;"
& ".ASPXANONYMOUS=HJbsF8QczAEkAAAAMGU4YjY4YTctNDJhNy00NmQ3LWJmOWEtNjVjMzFmODY"
& "1ZTA5dhasChFIbRm1YpxPXPteSbwdTE01",
15, "s_sq", "%5B%5BB%5D%5D");
end Test_Parse_Http_Header;
end ASF.Cookies.Tests;
|
-----------------------------------------------------------------------
-- asf-cookies-tests - Unit tests for Cookies
-- Copyright (C) 2011 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Tests;
with Util.Test_Caller;
with Util.Log.Loggers;
with Util.Measures;
with Ada.Strings.Fixed;
with Ada.Unchecked_Deallocation;
package body ASF.Cookies.Tests is
use Ada.Strings.Fixed;
use Util.Tests;
use Util.Log;
-- The logger
Log : constant Loggers.Logger := Loggers.Create ("ASF.Cookies.Tests");
procedure Free is new Ada.Unchecked_Deallocation (Cookie_Array, Cookie_Array_Access);
package Caller is new Util.Test_Caller (Test);
procedure Add_Tests (Suite : AUnit.Test_Suites.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test ASF.Cookies.Create_Cookie",
Test_Create_Cookie'Access);
Caller.Add_Test (Suite, "Test ASF.Cookies.To_Http_Header",
Test_To_Http_Header'Access);
Caller.Add_Test (Suite, "Test ASF.Cookies.Get_Cookies",
Test_Parse_Http_Header'Access);
end Add_Tests;
-- ------------------------------
-- Test creation of cookie
-- ------------------------------
procedure Test_Create_Cookie (T : in out Test) is
C : constant Cookie := Create ("cookie", "value");
begin
T.Assert_Equals ("cookie", Get_Name (C), "Invalid name");
T.Assert_Equals ("value", Get_Value (C), "Invalid value");
T.Assert (not Is_Secure (C), "Invalid is_secure");
end Test_Create_Cookie;
-- ------------------------------
-- Test conversion of cookie for HTTP header
-- ------------------------------
procedure Test_To_Http_Header (T : in out Test) is
procedure Test_Cookie (C : in Cookie) is
S : constant String := To_Http_Header (C);
begin
Log.Info ("Cookie {0}: {1}", Get_Name (C), S);
T.Assert (S'Length > 0, "Invalid cookie length for: " & S);
T.Assert (Index (S, "=") > 0, "Invalid cookie format; " & S);
end Test_Cookie;
procedure Test_Cookie (Name : in String; Value : in String) is
C : Cookie := Create (Name, Value);
begin
Test_Cookie (C);
for I in 1 .. 24 loop
Set_Max_Age (C, I * 3600 + I);
Test_Cookie (C);
end loop;
Set_Secure (C, True);
Test_Cookie (C);
Set_Http_Only (C, True);
Test_Cookie (C);
Set_Domain (C, "world.com");
Test_Cookie (C);
Set_Path (C, "/some-path");
Test_Cookie (C);
end Test_Cookie;
begin
Test_Cookie ("a", "b");
Test_Cookie ("session_id", "79e2317bcabe731e2f681f5725bbc621-&v=1");
Test_Cookie ("p_41_zy", "");
Test_Cookie ("p_34", """quoted\t""");
Test_Cookie ("d", "s");
declare
C : Cookie := Create ("cookie-name", "79e2317bcabe731e2f681f5725bbc621");
Start : Util.Measures.Stamp;
begin
Set_Path (C, "/home");
Set_Domain (C, ".mydomain.example.com");
Set_Max_Age (C, 1000);
Set_Http_Only (C, True);
Set_Secure (C, True);
Set_Comment (C, "some comment");
for I in 1 .. 1000 loop
declare
S : constant String := To_Http_Header (C);
begin
if S'Length < 10 then
T.Assert (S'Length > 10, "Invalid cookie generation");
end if;
end;
end loop;
Util.Measures.Report (S => Start,
Title => "Generation of 1000 cookies");
end;
end Test_To_Http_Header;
-- ------------------------------
-- Test parsing of client cookie to build a list of Cookie objects
-- ------------------------------
procedure Test_Parse_Http_Header (T : in out Test) is
-- ------------------------------
-- Parse the header and check for the expected cookie count and verify
-- the value of a specific cookie
-- ------------------------------
procedure Test_Parse (Header : in String;
Count : in Natural;
Name : in String;
Value : in String) is
Start : Util.Measures.Stamp;
C : Cookie_Array_Access := Get_Cookies (Header);
Found : Boolean := False;
begin
Util.Measures.Report (S => Start,
Title => "Parsing of cookie " & Name);
T.Assert (C /= null, "Null value returned by Get_Cookies");
Assert_Equals (T, Count, C'Length, "Invalid count in result array");
for I in C'Range loop
Log.Debug ("Cookie: {0}={1}", Get_Name (C (I)), Get_Value (C (I)));
if Name = Get_Name (C (I)) then
Assert_Equals (T, Value, Get_Value (C (I)), "Invalid cookie: " & Name);
Found := True;
end if;
end loop;
T.Assert (Found, "Cookie " & Name & " not found");
Free (C);
end Test_Parse;
begin
Test_Parse ("A=B", 1, "A", "B");
Test_Parse ("A=B=", 1, "A", "B=");
Test_Parse ("CONTEXTE=mar=101&nab=84fbbe2a81887732fe9c635d9ac319b5"
& "&pfl=afide0&typsrv=we&sc=1&soumar=1011&srcurlconfigchapeau"
& "=sous_ouv_formulaire_chapeau_dei_config&nag=550®=14505; "
& "xtvrn=$354249$354336$; CEPORM=321169600.8782.0000; SES=auth=0&"
& "cartridge_url=&return_url=; CEPORC=344500416.8782.0000", 5,
"SES", "auth=0&cartridge_url=&return_url=");
Test_Parse ("s_nr=1298652863627; s_sq=%5B%5BB%5D%5D; s_cc=true; oraclelicense="
& "accept-dbindex-cookie; gpv_p24=no%20value; gpw_e24=no%20value",
6, "gpw_e24", "no%20value");
-- Parse a set of cookies from microsoft.com
Test_Parse ("WT_FPC=id=00.06.036.020-2037773472.29989343:lv=1300442685103:ss=1300442685103; "
& "MC1=GUID=9d86c397c1a5ea4cab48d9fe19b76b4e&HASH=97c3&LV=20092&V=3; "
& "A=I&I=AxUFAAAAAABwBwAALSllub5HorZBtWWX8ZeXcQ!!&CS=114[3B002j2p[0302g3V309; "
& "WT_NVR_RU=0=technet|msdn:1=:2=; mcI=Fri, 31 Dec 2010 10:44:31 GMT; "
& "omniID=beb780dd_ab6d_4802_9f37_e33dde280adb; CodeSnippetContainerLang="
& "Visual Basic; MSID=Microsoft.CreationDate=11/09/2010 10:08:25&Microsoft."
& "LastVisitDate=03/01/2011 17:08:34&Microsoft.VisitStartDate=03/01/2011 "
& "17:08:34&Microsoft.CookieId=882efa27-ee6c-40c5-96ba-2297f985d9e3&Microsoft"
& ".TokenId=0c0a5e07-37a6-4ca3-afc0-0edf3de329f6&Microsoft.NumberOfVisits="
& "60&Microsoft.IdentityToken=RojEm8r/0KbCYeKasdfwekl3FtctotD5ocj7WVR72795"
& "dBj23rXVz5/xeldkkKHr/NtXFN3xAvczHlHQHKw14/9f/VAraQFIzEYpypGE24z1AuPCzVwU"
& "l4HZPnOFH+IA0u2oarcR1n3IMC4Gk8D1UOPBwGlYMB2Xl2W+Up8kJikc4qUxmFG+X5SRrZ3m7"
& "LntAv92B4v7c9FPewcQHDSAJAmTOuy7+sl6zEwW2fGWjqGe3G7bh+qqUWPs4LrvSyyi7T3UCW"
& "anSWn6jqJInP/MSeAxAvjbTrBwlJlE3AoUfXUJgL81boPYsIXZ30lPpqjMkyc0Jd70dffNNTo5"
& "qwkvfFhyOvnfYoQ7dZ0REw+TRA01xHyyUSPINOVgM5Vcu4SdvcUoIlMR3Y097nK+lvx8SqV4UU"
& "+QENW1wbBDa7/u6AQqUuk0616tWrBQMR9pYKwYsORUqLkQY5URzhVVA7Py28dLX002Nehqjbh68"
& "4xQv/gQYbPZMZUq/wgmPsqA5mJU/lki6A0S/H/ULGbrJE0PBQr8T+Hd+Op4HxEHvjvkTs=&Micr"
& "osoft.MicrosoftId=0004-1282-6244-7365; msresearch=%7B%22version%22%3A%224.6"
& "%22%2C%22state%22%3A%7B%22name%22%3A%22IDLE%22%2C%22url%22%3Aundefined%2C%2"
& "2timestamp%22%3A1296211850175%7D%2C%22lastinvited%22%3A1296211850175%2C%22u"
& "serid%22%3A%2212962118501758905232121057759%22%2C%22vendorid%22%3A1%2C%22su"
& "rveys%22%3A%5Bundefined%5D%7D; s_sq=%5B%5BB%5D%5D; s_cc=true; "
& "GsfxStatsLog=true; GsfxSessionCookie=231210164895294015; ADS=SN=175A21EF;"
& ".ASPXANONYMOUS=HJbsF8QczAEkAAAAMGU4YjY4YTctNDJhNy00NmQ3LWJmOWEtNjVjMzFmODY"
& "1ZTA5dhasChFIbRm1YpxPXPteSbwdTE01",
15, "s_sq", "%5B%5BB%5D%5D");
end Test_Parse_Http_Header;
end ASF.Cookies.Tests;
|
Fix compilation
|
Fix compilation
|
Ada
|
apache-2.0
|
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
|
f3947c91d3ddf8d3477bdaec6c6fbe8da1b17860
|
src/util-encoders-sha256.adb
|
src/util-encoders-sha256.adb
|
-----------------------------------------------------------------------
-- util-encoders-sha256 -- Compute SHA-1 hash
-- 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.Encoders.Base64;
package body Util.Encoders.SHA256 is
-- ------------------------------
-- Computes the SHA256 hash and returns the raw binary hash in <b>Hash</b>.
-- ------------------------------
procedure Finish (E : in out Context;
Hash : out Hash_Array) is
begin
Hash := GNAT.SHA256.Digest (E);
E := GNAT.SHA256.Initial_Context;
end Finish;
-- ------------------------------
-- Computes the SHA256 hash and returns the hexadecimal hash in <b>Hash</b>.
-- ------------------------------
procedure Finish (E : in out Context;
Hash : out Digest) is
begin
Hash := GNAT.SHA256.Digest (E);
E := GNAT.SHA256.Initial_Context;
end Finish;
-- ------------------------------
-- Computes the SHA256 hash and returns the base64 hash in <b>Hash</b>.
-- ------------------------------
procedure Finish_Base64 (E : in out Context;
Hash : out Base64_Digest) is
Buf : Ada.Streams.Stream_Element_Array (1 .. Hash'Length);
for Buf'Address use Hash'Address;
pragma Import (Ada, Buf);
H : Hash_Array;
B : Util.Encoders.Base64.Encoder;
Last : Ada.Streams.Stream_Element_Offset;
Encoded : Ada.Streams.Stream_Element_Offset;
begin
Finish (E, H);
E := GNAT.SHA256.Initial_Context;
B.Transform (Data => H, Into => Buf, Last => Last, Encoded => Encoded);
end Finish_Base64;
end Util.Encoders.SHA256;
|
-----------------------------------------------------------------------
-- util-encoders-sha256 -- Compute SHA-256 hash
-- 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.Encoders.Base64;
package body Util.Encoders.SHA256 is
-- ------------------------------
-- Computes the SHA256 hash and returns the raw binary hash in <b>Hash</b>.
-- ------------------------------
procedure Finish (E : in out Context;
Hash : out Hash_Array) is
begin
Hash := GNAT.SHA256.Digest (E);
E := GNAT.SHA256.Initial_Context;
end Finish;
-- ------------------------------
-- Computes the SHA256 hash and returns the hexadecimal hash in <b>Hash</b>.
-- ------------------------------
procedure Finish (E : in out Context;
Hash : out Digest) is
begin
Hash := GNAT.SHA256.Digest (E);
E := GNAT.SHA256.Initial_Context;
end Finish;
-- ------------------------------
-- Computes the SHA256 hash and returns the base64 hash in <b>Hash</b>.
-- ------------------------------
procedure Finish_Base64 (E : in out Context;
Hash : out Base64_Digest) is
H : Hash_Array;
B : Util.Encoders.Base64.Encoder;
begin
Finish (E, H);
B.Convert (H, Hash);
E := GNAT.SHA256.Initial_Context;
end Finish_Base64;
end Util.Encoders.SHA256;
|
Refactor the encoders to use the Convert procedure to simplify the final SHA256 conversion
|
Refactor the encoders to use the Convert procedure to simplify the final SHA256 conversion
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
41d584a34dc1133b8ff772efa7aac769854b34c1
|
src/wiki-streams-text_io.adb
|
src/wiki-streams-text_io.adb
|
-----------------------------------------------------------------------
-- wiki-streams-text_io -- Text_IO input output streams
-- Copyright (C) 2016 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.IO_Exceptions;
with Wiki.Helpers;
package body Wiki.Streams.Text_IO is
-- ------------------------------
-- Open the file and prepare to read the input stream.
-- ------------------------------
procedure Open (Stream : in out File_Input_Stream;
Path : in String;
Form : in String := "") is
begin
Ada.Wide_Wide_Text_IO.Open (Stream.File, Ada.Wide_Wide_Text_IO.In_File, Path, Form);
end Open;
-- ------------------------------
-- Close the file.
-- ------------------------------
procedure Close (Stream : in out File_Input_Stream) is
begin
Ada.Wide_Wide_Text_IO.Close (Stream.File);
end Close;
-- ------------------------------
-- Read one character from the input stream and return False to the <tt>Eof</tt> indicator.
-- When there is no character to read, return True in the <tt>Eof</tt> indicator.
-- ------------------------------
overriding
procedure Read (Input : in out File_Input_Stream;
Char : out Wiki.Strings.WChar;
Eof : out Boolean) is
Available : Boolean;
begin
Eof := False;
Ada.Wide_Wide_Text_IO.Get_immediate (Input.File, Char, Available);
exception
when Ada.IO_Exceptions.End_Error =>
Char := Wiki.Helpers.LF;
Eof := True;
end Read;
-- ------------------------------
-- Open the file and prepare to write the output stream.
-- ------------------------------
procedure Open (Stream : in out File_Output_Stream;
Path : in String;
Form : in String := "") is
begin
Ada.Wide_Wide_Text_IO.Open (Stream.File, Ada.Wide_Wide_Text_IO.Out_File, Path, Form);
end Open;
-- ------------------------------
-- Create the file and prepare to write the output stream.
-- ------------------------------
procedure Create (Stream : in out File_Output_Stream;
Path : in String;
Form : in String := "") is
begin
Ada.Wide_Wide_Text_IO.Create (Stream.File, Ada.Wide_Wide_Text_IO.Out_File, Path, Form);
end Create;
-- ------------------------------
-- Write the string to the output stream.
-- ------------------------------
overriding
procedure Write (Stream : in out File_Output_Stream;
Content : in Wiki.Strings.WString) is
begin
Ada.Wide_Wide_Text_IO.Put (Stream.File, Content);
end Write;
-- ------------------------------
-- Write a single character to the output stream.
-- ------------------------------
overriding
procedure Write (Stream : in out File_Output_Stream;
Char : in Wiki.Strings.WChar) is
begin
Ada.Wide_Wide_Text_IO.Put (Stream.File, Char);
end Write;
end Wiki.Streams.Text_IO;
|
-----------------------------------------------------------------------
-- wiki-streams-text_io -- Text_IO input output streams
-- Copyright (C) 2016 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.IO_Exceptions;
with Wiki.Helpers;
package body Wiki.Streams.Text_IO is
-- ------------------------------
-- Open the file and prepare to read the input stream.
-- ------------------------------
procedure Open (Stream : in out File_Input_Stream;
Path : in String;
Form : in String := "") is
begin
Ada.Wide_Wide_Text_IO.Open (Stream.File, Ada.Wide_Wide_Text_IO.In_File, Path, Form);
end Open;
-- ------------------------------
-- Close the file.
-- ------------------------------
procedure Close (Stream : in out File_Input_Stream) is
begin
if Ada.Wide_Wide_Text_IO.Is_Open (Stream.File) then
Ada.Wide_Wide_Text_IO.Close (Stream.File);
end if;
end Close;
-- ------------------------------
-- Close the stream.
-- ------------------------------
overriding
procedure Finalize (Stream : in out File_Input_Stream) is
begin
Stream.Close;
end Finalize;
-- ------------------------------
-- Read one character from the input stream and return False to the <tt>Eof</tt> indicator.
-- When there is no character to read, return True in the <tt>Eof</tt> indicator.
-- ------------------------------
overriding
procedure Read (Input : in out File_Input_Stream;
Char : out Wiki.Strings.WChar;
Eof : out Boolean) is
Available : Boolean;
begin
Eof := False;
Ada.Wide_Wide_Text_IO.Get_immediate (Input.File, Char, Available);
exception
when Ada.IO_Exceptions.End_Error =>
Char := Wiki.Helpers.LF;
Eof := True;
end Read;
-- ------------------------------
-- Open the file and prepare to write the output stream.
-- ------------------------------
procedure Open (Stream : in out File_Output_Stream;
Path : in String;
Form : in String := "") is
begin
if Ada.Wide_Wide_Text_IO.Is_Open (Stream.File) then
Ada.Wide_Wide_Text_IO.Close (Stream.File);
end if;
Ada.Wide_Wide_Text_IO.Open (Stream.File, Ada.Wide_Wide_Text_IO.Out_File, Path, Form);
Stream.Stdout := False;
end Open;
-- ------------------------------
-- Create the file and prepare to write the output stream.
-- ------------------------------
procedure Create (Stream : in out File_Output_Stream;
Path : in String;
Form : in String := "") is
begin
Ada.Wide_Wide_Text_IO.Create (Stream.File, Ada.Wide_Wide_Text_IO.Out_File, Path, Form);
Stream.Stdout := False;
end Create;
-- ------------------------------
-- Close the file.
-- ------------------------------
procedure Close (Stream : in out File_Output_Stream) is
begin
if Ada.Wide_Wide_Text_IO.Is_Open (Stream.File) then
Ada.Wide_Wide_Text_IO.Close (Stream.File);
end if;
end Close;
-- ------------------------------
-- Write the string to the output stream.
-- ------------------------------
overriding
procedure Write (Stream : in out File_Output_Stream;
Content : in Wiki.Strings.WString) is
begin
if not Stream.Stdout then
Ada.Wide_Wide_Text_IO.Put (Stream.File, Content);
else
Ada.Wide_Wide_Text_IO.Put (Content);
end if;
end Write;
-- ------------------------------
-- Write a single character to the output stream.
-- ------------------------------
overriding
procedure Write (Stream : in out File_Output_Stream;
Char : in Wiki.Strings.WChar) is
begin
if not Stream.Stdout then
Ada.Wide_Wide_Text_IO.Put (Stream.File, Char);
else
Ada.Wide_Wide_Text_IO.Put (Char);
end if;
end Write;
-- ------------------------------
-- Close the stream.
-- ------------------------------
overriding
procedure Finalize (Stream : in out File_Output_Stream) is
begin
Stream.Close;
end Finalize;
end Wiki.Streams.Text_IO;
|
Implement the Finalize procedures to close the file Use the Stdout boolean to check if we must write on the console or not Clear the Stdout boolean when we open/create a file for writing
|
Implement the Finalize procedures to close the file
Use the Stdout boolean to check if we must write on the console or not
Clear the Stdout boolean when we open/create a file for writing
|
Ada
|
apache-2.0
|
stcarrez/ada-wiki,stcarrez/ada-wiki
|
e5685d29f1d4ccc5ef99ebd77fc1fdc5f6f80fff
|
src/gen-commands-templates.adb
|
src/gen-commands-templates.adb
|
-----------------------------------------------------------------------
-- gen-commands-templates -- Template based command
-- Copyright (C) 2011, 2012, 2013 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Text_IO;
with Ada.IO_Exceptions;
with Ada.Directories;
with Ada.Streams.Stream_IO;
with GNAT.Command_Line;
with Gen.Artifacts;
with EL.Contexts.Default;
with EL.Expressions;
with EL.Variables.Default;
with Util.Log.Loggers;
with Util.Files;
with Util.Streams.Files;
with Util.Streams.Texts;
with Util.Beans.Objects;
with Util.Serialize.Mappers.Record_Mapper;
with Util.Serialize.IO.XML;
package body Gen.Commands.Templates is
use Ada.Strings.Unbounded;
use GNAT.Command_Line;
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Gen.Commands.Templates");
-- Apply the patch instruction
procedure Patch_File (Generator : in out Gen.Generator.Handler;
Info : in Patch);
function Match_Line (Line : in String;
Pattern : in String) return Boolean;
-- ------------------------------
-- Check if the line matches the pseudo pattern.
-- ------------------------------
function Match_Line (Line : in String;
Pattern : in String) return Boolean is
L_Pos : Natural := Line'First;
P_Pos : Natural := Pattern'First;
begin
while P_Pos <= Pattern'Last loop
if L_Pos > Line'Last then
return False;
end if;
if Line (L_Pos) = Pattern (P_Pos) then
if Pattern (P_Pos) /= ' ' then
P_Pos := P_Pos + 1;
end if;
L_Pos := L_Pos + 1;
elsif Pattern (P_Pos) = ' ' and Line (L_Pos) = Pattern (P_Pos + 1) then
P_Pos := P_Pos + 2;
L_Pos := L_Pos + 1;
elsif Pattern (P_Pos) = ' ' and Pattern (P_Pos + 1) = '*' then
P_Pos := P_Pos + 1;
L_Pos := L_Pos + 1;
elsif Pattern (P_Pos) = '*' and Line (L_Pos) = Pattern (P_Pos + 1) then
P_Pos := P_Pos + 2;
L_Pos := L_Pos + 1;
elsif Pattern (P_Pos) = '*' and Line (L_Pos) /= ' ' then
L_Pos := L_Pos + 1;
else
return False;
end if;
end loop;
return True;
end Match_Line;
-- ------------------------------
-- Apply the patch instruction
-- ------------------------------
procedure Patch_File (Generator : in out Gen.Generator.Handler;
Info : in Patch) is
procedure Save_Output (H : in out Gen.Generator.Handler;
File : in String;
Content : in Ada.Strings.Unbounded.Unbounded_String);
Ctx : EL.Contexts.Default.Default_Context;
Variables : aliased EL.Variables.Default.Default_Variable_Mapper;
procedure Save_Output (H : in out Gen.Generator.Handler;
File : in String;
Content : in Ada.Strings.Unbounded.Unbounded_String) is
type State is (MATCH_AFTER, MATCH_BEFORE, MATCH_DONE);
Output_Dir : constant String := H.Get_Result_Directory;
Path : constant String := Util.Files.Compose (Output_Dir, File);
Tmp_File : constant String := Path & ".tmp";
Line_Number : Natural := 0;
After_Pos : Natural := 1;
Current_State : State := MATCH_AFTER;
Tmp_Output : aliased Util.Streams.Files.File_Stream;
Output : Util.Streams.Texts.Print_Stream;
procedure Process (Line : in String);
procedure Process (Line : in String) is
begin
Line_Number := Line_Number + 1;
case Current_State is
when MATCH_AFTER =>
if Match_Line (Line, Info.After.Element (After_Pos)) then
Log.Info ("Match after at line {0}", Natural'Image (Line_Number));
After_Pos := After_Pos + 1;
if After_Pos >= Natural (Info.After.Length) then
Current_State := MATCH_BEFORE;
end if;
end if;
when MATCH_BEFORE =>
if Match_Line (Line, To_String (Info.Before)) then
Log.Info ("Match before at line {0}", Natural'Image (Line_Number));
Log.Info ("Add content {0}", Content);
Output.Write (Content);
Current_State := MATCH_DONE;
end if;
when MATCH_DONE =>
null;
end case;
Output.Write (Line);
Output.Write (ASCII.LF);
end Process;
begin
Tmp_Output.Create (Name => Tmp_File, Mode => Ada.Streams.Stream_IO.Out_File);
Output.Initialize (Tmp_Output'Unchecked_Access);
Util.Files.Read_File (Path, Process'Access);
Output.Close;
if Current_State /= MATCH_DONE then
H.Error ("Patch {0} failed", Path);
Ada.Directories.Delete_File (Tmp_File);
else
Ada.Directories.Delete_File (Path);
Ada.Directories.Rename (Old_Name => Tmp_File,
New_Name => Path);
end if;
exception
when Ada.IO_Exceptions.Name_Error =>
H.Error ("Cannot patch file {0}", Path);
end Save_Output;
begin
Ctx.Set_Variable_Mapper (Variables'Unchecked_Access);
Gen.Generator.Generate (Generator, Gen.Artifacts.ITERATION_TABLE,
To_String (Info.Template), Save_Output'Access);
end Patch_File;
-- Execute the command with the arguments.
procedure Execute (Cmd : in Command;
Generator : in out Gen.Generator.Handler) is
function Get_Output_Dir return String;
function Get_Output_Dir return String is
Dir : constant String := Generator.Get_Result_Directory;
begin
if Length (Cmd.Base_Dir) = 0 then
return Dir;
else
return Util.Files.Compose (Dir, To_String (Cmd.Base_Dir));
end if;
end Get_Output_Dir;
Out_Dir : constant String := Get_Output_Dir;
Iter : Param_Vectors.Cursor := Cmd.Params.First;
begin
Generator.Read_Project ("dynamo.xml", False);
while Param_Vectors.Has_Element (Iter) loop
declare
P : constant Param := Param_Vectors.Element (Iter);
Value : constant String := Get_Argument;
begin
if not P.Is_Optional and Value'Length = 0 then
Generator.Error ("Missing argument for {0}", To_String (P.Argument));
return;
end if;
Generator.Set_Global (To_String (P.Name), Value);
end;
Param_Vectors.Next (Iter);
end loop;
Generator.Set_Force_Save (False);
Generator.Set_Result_Directory (Out_Dir);
declare
Iter : Util.Strings.Sets.Cursor := Cmd.Templates.First;
begin
while Util.Strings.Sets.Has_Element (Iter) loop
Gen.Generator.Generate (Generator, Gen.Artifacts.ITERATION_TABLE,
Util.Strings.Sets.Element (Iter),
Gen.Generator.Save_Content'Access);
Util.Strings.Sets.Next (Iter);
end loop;
end;
-- Apply the patch instructions defined for the command.
declare
Iter : Patch_Vectors.Cursor := Cmd.Patches.First;
begin
while Patch_Vectors.Has_Element (Iter) loop
Patch_File (Generator, Patch_Vectors.Element (Iter));
Patch_Vectors.Next (Iter);
end loop;
end;
end Execute;
-- ------------------------------
-- Write the help associated with the command.
-- ------------------------------
procedure Help (Cmd : in Command;
Generator : in out Gen.Generator.Handler) is
pragma Unreferenced (Generator);
use Ada.Text_IO;
begin
Put_Line (To_String (Cmd.Name) & ": " & To_String (Cmd.Title));
Put_Line ("Usage: " & To_String (Cmd.Usage));
New_Line;
Put_Line (To_String (Cmd.Help_Msg));
end Help;
type Command_Fields is (FIELD_NAME,
FIELD_HELP,
FIELD_USAGE,
FIELD_TITLE,
FIELD_BASEDIR,
FIELD_PARAM,
FIELD_PARAM_NAME,
FIELD_PARAM_OPTIONAL,
FIELD_PARAM_ARG,
FIELD_TEMPLATE,
FIELD_PATCH,
FIELD_AFTER,
FIELD_BEFORE,
FIELD_INSERT_TEMPLATE,
FIELD_COMMAND);
type Command_Loader is record
Command : Command_Access := null;
P : Param;
Info : Patch;
end record;
type Command_Loader_Access is access all Command_Loader;
procedure Set_Member (Closure : in out Command_Loader;
Field : in Command_Fields;
Value : in Util.Beans.Objects.Object);
function To_String (Value : in Util.Beans.Objects.Object) return Unbounded_String;
-- ------------------------------
-- Convert the object value into a string and trim any space/tab/newlines.
-- ------------------------------
function To_String (Value : in Util.Beans.Objects.Object) return Unbounded_String is
Result : constant String := Util.Beans.Objects.To_String (Value);
First_Pos : Natural := Result'First;
Last_Pos : Natural := Result'Last;
C : Character;
begin
while First_Pos <= Last_Pos loop
C := Result (First_Pos);
exit when C /= ' ' and C /= ASCII.LF and C /= ASCII.CR and C /= ASCII.HT;
First_Pos := First_Pos + 1;
end loop;
while Last_Pos >= First_Pos loop
C := Result (Last_Pos);
exit when C /= ' ' and C /= ASCII.LF and C /= ASCII.CR and C /= ASCII.HT;
Last_Pos := Last_Pos - 1;
end loop;
return To_Unbounded_String (Result (First_Pos .. Last_Pos));
end To_String;
procedure Set_Member (Closure : in out Command_Loader;
Field : in Command_Fields;
Value : in Util.Beans.Objects.Object) is
use Util.Beans.Objects;
begin
if Field = FIELD_COMMAND then
if Closure.Command /= null then
Log.Info ("Adding command {0}", Closure.Command.Name);
Add_Command (Name => To_String (Closure.Command.Name),
Cmd => Closure.Command.all'Access);
Closure.Command := null;
end if;
else
if Closure.Command = null then
Closure.Command := new Gen.Commands.Templates.Command;
end if;
case Field is
when FIELD_NAME =>
Closure.Command.Name := To_String (Value);
when FIELD_TITLE =>
Closure.Command.Title := To_String (Value);
when FIELD_USAGE =>
Closure.Command.Usage := To_String (Value);
when FIELD_HELP =>
Closure.Command.Help_Msg := To_String (Value);
when FIELD_TEMPLATE =>
Closure.Command.Templates.Include (To_String (Value));
when FIELD_PARAM_NAME =>
Closure.P.Name := To_Unbounded_String (Value);
when FIELD_PARAM_OPTIONAL =>
Closure.P.Is_Optional := To_Boolean (Value);
when FIELD_PARAM_ARG =>
Closure.P.Argument := To_Unbounded_String (Value);
when FIELD_PARAM =>
Closure.P.Value := To_Unbounded_String (Value);
Closure.Command.Params.Append (Closure.P);
Closure.P.Name := Ada.Strings.Unbounded.Null_Unbounded_String;
Closure.P.Argument := Ada.Strings.Unbounded.Null_Unbounded_String;
Closure.P.Is_Optional := False;
when FIELD_BASEDIR =>
Closure.Command.Base_Dir := To_Unbounded_String (Value);
when FIELD_COMMAND =>
null;
when FIELD_INSERT_TEMPLATE =>
Closure.Info.Template := To_Unbounded_String (Value);
when FIELD_AFTER =>
Closure.Info.After.Append (To_String (Value));
when FIELD_BEFORE =>
Closure.Info.Before := To_Unbounded_String (Value);
when FIELD_PATCH =>
Closure.Command.Patches.Append (Closure.Info);
Closure.Info.After.Clear;
Closure.Info.Before := To_Unbounded_String ("");
end case;
end if;
end Set_Member;
package Command_Mapper is
new Util.Serialize.Mappers.Record_Mapper (Element_Type => Command_Loader,
Element_Type_Access => Command_Loader_Access,
Fields => Command_Fields,
Set_Member => Set_Member);
Cmd_Mapper : aliased Command_Mapper.Mapper;
-- ------------------------------
-- Read the template commands defined in dynamo configuration directory.
-- ------------------------------
procedure Read_Commands (Generator : in out Gen.Generator.Handler) is
procedure Read_Command (Name : in String;
File_Path : in String;
Done : out Boolean);
-- ------------------------------
-- Read the XML command file.
-- ------------------------------
procedure Read_Command (Name : in String;
File_Path : in String;
Done : out Boolean) is
pragma Unreferenced (Name);
Loader : aliased Command_Loader;
Reader : Util.Serialize.IO.XML.Parser;
begin
Log.Info ("Reading command file '{0}'", File_Path);
Done := False;
-- Create the mapping to load the XML command file.
Reader.Add_Mapping ("commands", Cmd_Mapper'Access);
-- Set the context for Set_Member.
Command_Mapper.Set_Context (Reader, Loader'Unchecked_Access);
-- Read the XML command file.
Reader.Parse (File_Path);
exception
when Ada.IO_Exceptions.Name_Error =>
Generator.Error ("Command file {0} does not exist", File_Path);
end Read_Command;
Config_Dir : constant String := Generator.Get_Config_Directory;
Cmd_Dir : constant String := Generator.Get_Parameter ("generator.commands.dir");
Path : constant String := Util.Files.Compose (Config_Dir, Cmd_Dir);
begin
Log.Debug ("Checking commands in {0}", Path);
if Ada.Directories.Exists (Path) then
Util.Files.Iterate_Files_Path (Path => Path,
Pattern => "*.xml",
Process => Read_Command'Access);
end if;
end Read_Commands;
begin
-- Setup the mapper to load XML commands.
Cmd_Mapper.Add_Mapping ("command/name", FIELD_NAME);
Cmd_Mapper.Add_Mapping ("command/title", FIELD_TITLE);
Cmd_Mapper.Add_Mapping ("command/usage", FIELD_USAGE);
Cmd_Mapper.Add_Mapping ("command/help", FIELD_HELP);
Cmd_Mapper.Add_Mapping ("command/basedir", FIELD_BASEDIR);
Cmd_Mapper.Add_Mapping ("command/param", FIELD_PARAM);
Cmd_Mapper.Add_Mapping ("command/param/@name", FIELD_PARAM_NAME);
Cmd_Mapper.Add_Mapping ("command/param/@optional", FIELD_PARAM_OPTIONAL);
Cmd_Mapper.Add_Mapping ("command/param/@arg", FIELD_PARAM_ARG);
Cmd_Mapper.Add_Mapping ("command/patch/template", FIELD_INSERT_TEMPLATE);
Cmd_Mapper.Add_Mapping ("command/patch/after", FIELD_AFTER);
Cmd_Mapper.Add_Mapping ("command/patch/before", FIELD_BEFORE);
Cmd_Mapper.Add_Mapping ("command/template", FIELD_TEMPLATE);
Cmd_Mapper.Add_Mapping ("command/patch", FIELD_PATCH);
Cmd_Mapper.Add_Mapping ("command", FIELD_COMMAND);
end Gen.Commands.Templates;
|
-----------------------------------------------------------------------
-- gen-commands-templates -- Template based command
-- Copyright (C) 2011, 2012, 2013 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Text_IO;
with Ada.IO_Exceptions;
with Ada.Directories;
with Ada.Streams.Stream_IO;
with GNAT.Command_Line;
with Gen.Artifacts;
with EL.Contexts.Default;
with EL.Expressions;
with EL.Variables.Default;
with Util.Log.Loggers;
with Util.Files;
with Util.Streams.Files;
with Util.Streams.Texts;
with Util.Beans.Objects;
with Util.Serialize.Mappers.Record_Mapper;
with Util.Serialize.IO.XML;
package body Gen.Commands.Templates is
use Ada.Strings.Unbounded;
use GNAT.Command_Line;
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Gen.Commands.Templates");
-- Apply the patch instruction
procedure Patch_File (Generator : in out Gen.Generator.Handler;
Info : in Patch);
function Match_Line (Line : in String;
Pattern : in String) return Boolean;
-- ------------------------------
-- Check if the line matches the pseudo pattern.
-- ------------------------------
function Match_Line (Line : in String;
Pattern : in String) return Boolean is
L_Pos : Natural := Line'First;
P_Pos : Natural := Pattern'First;
begin
while P_Pos <= Pattern'Last loop
if L_Pos > Line'Last then
return False;
end if;
if Line (L_Pos) = Pattern (P_Pos) then
if Pattern (P_Pos) /= ' ' then
P_Pos := P_Pos + 1;
end if;
L_Pos := L_Pos + 1;
elsif Pattern (P_Pos) = ' ' and then Line (L_Pos) = Pattern (P_Pos + 1) then
P_Pos := P_Pos + 2;
L_Pos := L_Pos + 1;
elsif Pattern (P_Pos) = ' ' and then Pattern (P_Pos + 1) = '*' then
P_Pos := P_Pos + 1;
L_Pos := L_Pos + 1;
elsif Pattern (P_Pos) = '*' and then Line (L_Pos) = Pattern (P_Pos + 1) then
P_Pos := P_Pos + 2;
L_Pos := L_Pos + 1;
elsif Pattern (P_Pos) = '*' and Line (L_Pos) /= ' ' then
L_Pos := L_Pos + 1;
else
return False;
end if;
end loop;
return True;
end Match_Line;
-- ------------------------------
-- Apply the patch instruction
-- ------------------------------
procedure Patch_File (Generator : in out Gen.Generator.Handler;
Info : in Patch) is
procedure Save_Output (H : in out Gen.Generator.Handler;
File : in String;
Content : in Ada.Strings.Unbounded.Unbounded_String);
Ctx : EL.Contexts.Default.Default_Context;
Variables : aliased EL.Variables.Default.Default_Variable_Mapper;
procedure Save_Output (H : in out Gen.Generator.Handler;
File : in String;
Content : in Ada.Strings.Unbounded.Unbounded_String) is
type State is (MATCH_AFTER, MATCH_BEFORE, MATCH_DONE);
Output_Dir : constant String := H.Get_Result_Directory;
Path : constant String := Util.Files.Compose (Output_Dir, File);
Tmp_File : constant String := Path & ".tmp";
Line_Number : Natural := 0;
After_Pos : Natural := 1;
Current_State : State := MATCH_AFTER;
Tmp_Output : aliased Util.Streams.Files.File_Stream;
Output : Util.Streams.Texts.Print_Stream;
procedure Process (Line : in String);
procedure Process (Line : in String) is
begin
Line_Number := Line_Number + 1;
case Current_State is
when MATCH_AFTER =>
if Match_Line (Line, Info.After.Element (After_Pos)) then
Log.Info ("Match after at line {0}", Natural'Image (Line_Number));
After_Pos := After_Pos + 1;
if After_Pos > Natural (Info.After.Length) then
Current_State := MATCH_BEFORE;
end if;
end if;
when MATCH_BEFORE =>
if Match_Line (Line, To_String (Info.Before)) then
Log.Info ("Match before at line {0}", Natural'Image (Line_Number));
Log.Info ("Add content {0}", Content);
Output.Write (Content);
Current_State := MATCH_DONE;
end if;
when MATCH_DONE =>
null;
end case;
Output.Write (Line);
Output.Write (ASCII.LF);
end Process;
begin
Tmp_Output.Create (Name => Tmp_File, Mode => Ada.Streams.Stream_IO.Out_File);
Output.Initialize (Tmp_Output'Unchecked_Access);
Util.Files.Read_File (Path, Process'Access);
Output.Close;
if Current_State /= MATCH_DONE then
H.Error ("Patch {0} failed", Path);
Ada.Directories.Delete_File (Tmp_File);
else
Ada.Directories.Delete_File (Path);
Ada.Directories.Rename (Old_Name => Tmp_File,
New_Name => Path);
end if;
exception
when Ada.IO_Exceptions.Name_Error =>
H.Error ("Cannot patch file {0}", Path);
end Save_Output;
begin
Ctx.Set_Variable_Mapper (Variables'Unchecked_Access);
Gen.Generator.Generate (Generator, Gen.Artifacts.ITERATION_TABLE,
To_String (Info.Template), Save_Output'Access);
end Patch_File;
-- Execute the command with the arguments.
procedure Execute (Cmd : in Command;
Generator : in out Gen.Generator.Handler) is
function Get_Output_Dir return String;
function Get_Output_Dir return String is
Dir : constant String := Generator.Get_Result_Directory;
begin
if Length (Cmd.Base_Dir) = 0 then
return Dir;
else
return Util.Files.Compose (Dir, To_String (Cmd.Base_Dir));
end if;
end Get_Output_Dir;
Out_Dir : constant String := Get_Output_Dir;
Iter : Param_Vectors.Cursor := Cmd.Params.First;
begin
Generator.Read_Project ("dynamo.xml", False);
while Param_Vectors.Has_Element (Iter) loop
declare
P : constant Param := Param_Vectors.Element (Iter);
Value : constant String := Get_Argument;
begin
if not P.Is_Optional and Value'Length = 0 then
Generator.Error ("Missing argument for {0}", To_String (P.Argument));
return;
end if;
Generator.Set_Global (To_String (P.Name), Value);
end;
Param_Vectors.Next (Iter);
end loop;
Generator.Set_Force_Save (False);
Generator.Set_Result_Directory (Out_Dir);
declare
Iter : Util.Strings.Sets.Cursor := Cmd.Templates.First;
begin
while Util.Strings.Sets.Has_Element (Iter) loop
Gen.Generator.Generate (Generator, Gen.Artifacts.ITERATION_TABLE,
Util.Strings.Sets.Element (Iter),
Gen.Generator.Save_Content'Access);
Util.Strings.Sets.Next (Iter);
end loop;
end;
-- Apply the patch instructions defined for the command.
declare
Iter : Patch_Vectors.Cursor := Cmd.Patches.First;
begin
while Patch_Vectors.Has_Element (Iter) loop
Patch_File (Generator, Patch_Vectors.Element (Iter));
Patch_Vectors.Next (Iter);
end loop;
end;
end Execute;
-- ------------------------------
-- Write the help associated with the command.
-- ------------------------------
procedure Help (Cmd : in Command;
Generator : in out Gen.Generator.Handler) is
pragma Unreferenced (Generator);
use Ada.Text_IO;
begin
Put_Line (To_String (Cmd.Name) & ": " & To_String (Cmd.Title));
Put_Line ("Usage: " & To_String (Cmd.Usage));
New_Line;
Put_Line (To_String (Cmd.Help_Msg));
end Help;
type Command_Fields is (FIELD_NAME,
FIELD_HELP,
FIELD_USAGE,
FIELD_TITLE,
FIELD_BASEDIR,
FIELD_PARAM,
FIELD_PARAM_NAME,
FIELD_PARAM_OPTIONAL,
FIELD_PARAM_ARG,
FIELD_TEMPLATE,
FIELD_PATCH,
FIELD_AFTER,
FIELD_BEFORE,
FIELD_INSERT_TEMPLATE,
FIELD_COMMAND);
type Command_Loader is record
Command : Command_Access := null;
P : Param;
Info : Patch;
end record;
type Command_Loader_Access is access all Command_Loader;
procedure Set_Member (Closure : in out Command_Loader;
Field : in Command_Fields;
Value : in Util.Beans.Objects.Object);
function To_String (Value : in Util.Beans.Objects.Object) return Unbounded_String;
-- ------------------------------
-- Convert the object value into a string and trim any space/tab/newlines.
-- ------------------------------
function To_String (Value : in Util.Beans.Objects.Object) return Unbounded_String is
Result : constant String := Util.Beans.Objects.To_String (Value);
First_Pos : Natural := Result'First;
Last_Pos : Natural := Result'Last;
C : Character;
begin
while First_Pos <= Last_Pos loop
C := Result (First_Pos);
exit when C /= ' ' and C /= ASCII.LF and C /= ASCII.CR and C /= ASCII.HT;
First_Pos := First_Pos + 1;
end loop;
while Last_Pos >= First_Pos loop
C := Result (Last_Pos);
exit when C /= ' ' and C /= ASCII.LF and C /= ASCII.CR and C /= ASCII.HT;
Last_Pos := Last_Pos - 1;
end loop;
return To_Unbounded_String (Result (First_Pos .. Last_Pos));
end To_String;
procedure Set_Member (Closure : in out Command_Loader;
Field : in Command_Fields;
Value : in Util.Beans.Objects.Object) is
use Util.Beans.Objects;
begin
if Field = FIELD_COMMAND then
if Closure.Command /= null then
Log.Info ("Adding command {0}", Closure.Command.Name);
Add_Command (Name => To_String (Closure.Command.Name),
Cmd => Closure.Command.all'Access);
Closure.Command := null;
end if;
else
if Closure.Command = null then
Closure.Command := new Gen.Commands.Templates.Command;
end if;
case Field is
when FIELD_NAME =>
Closure.Command.Name := To_String (Value);
when FIELD_TITLE =>
Closure.Command.Title := To_String (Value);
when FIELD_USAGE =>
Closure.Command.Usage := To_String (Value);
when FIELD_HELP =>
Closure.Command.Help_Msg := To_String (Value);
when FIELD_TEMPLATE =>
Closure.Command.Templates.Include (To_String (Value));
when FIELD_PARAM_NAME =>
Closure.P.Name := To_Unbounded_String (Value);
when FIELD_PARAM_OPTIONAL =>
Closure.P.Is_Optional := To_Boolean (Value);
when FIELD_PARAM_ARG =>
Closure.P.Argument := To_Unbounded_String (Value);
when FIELD_PARAM =>
Closure.P.Value := To_Unbounded_String (Value);
Closure.Command.Params.Append (Closure.P);
Closure.P.Name := Ada.Strings.Unbounded.Null_Unbounded_String;
Closure.P.Argument := Ada.Strings.Unbounded.Null_Unbounded_String;
Closure.P.Is_Optional := False;
when FIELD_BASEDIR =>
Closure.Command.Base_Dir := To_Unbounded_String (Value);
when FIELD_COMMAND =>
null;
when FIELD_INSERT_TEMPLATE =>
Closure.Info.Template := To_Unbounded_String (Value);
when FIELD_AFTER =>
Closure.Info.After.Append (To_String (Value));
when FIELD_BEFORE =>
Closure.Info.Before := To_Unbounded_String (Value);
when FIELD_PATCH =>
Closure.Command.Patches.Append (Closure.Info);
Closure.Info.After.Clear;
Closure.Info.Before := To_Unbounded_String ("");
end case;
end if;
end Set_Member;
package Command_Mapper is
new Util.Serialize.Mappers.Record_Mapper (Element_Type => Command_Loader,
Element_Type_Access => Command_Loader_Access,
Fields => Command_Fields,
Set_Member => Set_Member);
Cmd_Mapper : aliased Command_Mapper.Mapper;
-- ------------------------------
-- Read the template commands defined in dynamo configuration directory.
-- ------------------------------
procedure Read_Commands (Generator : in out Gen.Generator.Handler) is
procedure Read_Command (Name : in String;
File_Path : in String;
Done : out Boolean);
-- ------------------------------
-- Read the XML command file.
-- ------------------------------
procedure Read_Command (Name : in String;
File_Path : in String;
Done : out Boolean) is
pragma Unreferenced (Name);
Loader : aliased Command_Loader;
Reader : Util.Serialize.IO.XML.Parser;
begin
Log.Info ("Reading command file '{0}'", File_Path);
Done := False;
-- Create the mapping to load the XML command file.
Reader.Add_Mapping ("commands", Cmd_Mapper'Access);
-- Set the context for Set_Member.
Command_Mapper.Set_Context (Reader, Loader'Unchecked_Access);
-- Read the XML command file.
Reader.Parse (File_Path);
exception
when Ada.IO_Exceptions.Name_Error =>
Generator.Error ("Command file {0} does not exist", File_Path);
end Read_Command;
Config_Dir : constant String := Generator.Get_Config_Directory;
Cmd_Dir : constant String := Generator.Get_Parameter ("generator.commands.dir");
Path : constant String := Util.Files.Compose (Config_Dir, Cmd_Dir);
begin
Log.Debug ("Checking commands in {0}", Path);
if Ada.Directories.Exists (Path) then
Util.Files.Iterate_Files_Path (Path => Path,
Pattern => "*.xml",
Process => Read_Command'Access);
end if;
end Read_Commands;
begin
-- Setup the mapper to load XML commands.
Cmd_Mapper.Add_Mapping ("command/name", FIELD_NAME);
Cmd_Mapper.Add_Mapping ("command/title", FIELD_TITLE);
Cmd_Mapper.Add_Mapping ("command/usage", FIELD_USAGE);
Cmd_Mapper.Add_Mapping ("command/help", FIELD_HELP);
Cmd_Mapper.Add_Mapping ("command/basedir", FIELD_BASEDIR);
Cmd_Mapper.Add_Mapping ("command/param", FIELD_PARAM);
Cmd_Mapper.Add_Mapping ("command/param/@name", FIELD_PARAM_NAME);
Cmd_Mapper.Add_Mapping ("command/param/@optional", FIELD_PARAM_OPTIONAL);
Cmd_Mapper.Add_Mapping ("command/param/@arg", FIELD_PARAM_ARG);
Cmd_Mapper.Add_Mapping ("command/patch/template", FIELD_INSERT_TEMPLATE);
Cmd_Mapper.Add_Mapping ("command/patch/after", FIELD_AFTER);
Cmd_Mapper.Add_Mapping ("command/patch/before", FIELD_BEFORE);
Cmd_Mapper.Add_Mapping ("command/template", FIELD_TEMPLATE);
Cmd_Mapper.Add_Mapping ("command/patch", FIELD_PATCH);
Cmd_Mapper.Add_Mapping ("command", FIELD_COMMAND);
end Gen.Commands.Templates;
|
Fix matching rules when executing a patch command
|
Fix matching rules when executing a patch command
|
Ada
|
apache-2.0
|
Letractively/ada-gen,Letractively/ada-gen,Letractively/ada-gen,Letractively/ada-gen
|
8f5b97c34ce558622fcf252c3e286e4688b0c8c8
|
src/security-policies-urls.adb
|
src/security-policies-urls.adb
|
-----------------------------------------------------------------------
-- security-policies-urls -- URL security policy
-- Copyright (C) 2010, 2011, 2012, 2016 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Unchecked_Deallocation;
with Util.Beans.Objects;
with Util.Beans.Objects.Vectors;
with Util.Serialize.Mappers;
with Util.Serialize.Mappers.Record_Mapper;
with Security.Controllers.URLs;
package body Security.Policies.URLs is
-- ------------------------------
-- Get the policy name.
-- ------------------------------
overriding
function Get_Name (From : in URL_Policy) return String is
pragma Unreferenced (From);
begin
return NAME;
end Get_Name;
-- ------------------------------
-- Returns True if the user has the permission to access the given URI permission.
-- ------------------------------
function Has_Permission (Manager : in URL_Policy;
Context : in Contexts.Security_Context'Class;
Permission : in URL_Permission'Class) return Boolean is
Name : constant String_Ref := To_String_Ref (Permission.URL);
Ref : constant Rules_Ref.Ref := Manager.Cache.Get;
Rules : constant Rules_Access := Ref.Value;
Pos : constant Rules_Maps.Cursor := Rules.Map.Find (Name);
Rule : Access_Rule_Ref;
begin
-- If the rule is not in the cache, search for the access rule that
-- matches our URI. Update the cache. This cache update is thread-safe
-- as the cache map is never modified: a new cache map is installed.
if not Rules_Maps.Has_Element (Pos) then
declare
New_Ref : constant Rules_Ref.Ref := Rules_Ref.Create;
begin
Rule := Manager.Find_Access_Rule (Permission.URL);
New_Ref.Value.all.Map := Rules.Map;
New_Ref.Value.all.Map.Insert (Name, Rule);
Manager.Cache.Set (New_Ref);
end;
else
Rule := Rules_Maps.Element (Pos);
end if;
-- Check if the user has one of the required permission.
declare
P : constant Access_Rule_Access := Rule.Value;
begin
if P /= null then
for I in P.Permissions'Range loop
if Context.Has_Permission (P.Permissions (I)) then
return True;
end if;
end loop;
end if;
end;
return False;
end Has_Permission;
-- Grant the permission to access to the given <b>URI</b> to users having the <b>To</b>
-- permissions.
procedure Grant_URI_Permission (Manager : in out URL_Policy;
URI : in String;
To : in String) is
begin
null;
end Grant_URI_Permission;
-- ------------------------------
-- Policy Configuration
-- ------------------------------
-- ------------------------------
-- Find the access rule of the policy that matches the given URI.
-- Returns the No_Rule value (disable access) if no rule is found.
-- ------------------------------
function Find_Access_Rule (Manager : in URL_Policy;
URI : in String) return Access_Rule_Ref is
Matched : Boolean := False;
Result : Access_Rule_Ref;
procedure Match (P : in Policy);
procedure Match (P : in Policy) is
begin
if GNAT.Regexp.Match (URI, P.Pattern) then
Matched := True;
Result := P.Rule;
end if;
end Match;
Last : constant Natural := Manager.Policies.Last_Index;
begin
for I in 1 .. Last loop
Manager.Policies.Query_Element (I, Match'Access);
if Matched then
return Result;
end if;
end loop;
return Result;
end Find_Access_Rule;
-- ------------------------------
-- Initialize the permission manager.
-- ------------------------------
overriding
procedure Initialize (Manager : in out URL_Policy) is
begin
Manager.Cache := new Rules_Ref.Atomic_Ref;
Manager.Cache.Set (Rules_Ref.Create);
end Initialize;
-- ------------------------------
-- Finalize the permission manager.
-- ------------------------------
overriding
procedure Finalize (Manager : in out URL_Policy) is
procedure Free is
new Ada.Unchecked_Deallocation (Rules_Ref.Atomic_Ref,
Rules_Ref_Access);
begin
Free (Manager.Cache);
end Finalize;
type Policy_Fields is (FIELD_ID, FIELD_PERMISSION, FIELD_URL_PATTERN, FIELD_POLICY);
procedure Set_Member (P : in out URL_Policy'Class;
Field : in Policy_Fields;
Value : in Util.Beans.Objects.Object);
procedure Process (Policy : in out URL_Policy'Class);
procedure Set_Member (P : in out URL_Policy'Class;
Field : in Policy_Fields;
Value : in Util.Beans.Objects.Object) is
begin
case Field is
when FIELD_ID =>
P.Id := Util.Beans.Objects.To_Integer (Value);
when FIELD_PERMISSION =>
P.Permissions.Append (Value);
when FIELD_URL_PATTERN =>
P.Patterns.Append (Value);
when FIELD_POLICY =>
Process (P);
P.Id := 0;
P.Permissions.Clear;
P.Patterns.Clear;
end case;
end Set_Member;
procedure Process (Policy : in out URL_Policy'Class) is
Pol : Security.Policies.URLs.Policy;
Count : constant Natural := Natural (Policy.Permissions.Length);
Rule : constant Access_Rule_Ref := Access_Rule_Refs.Create (new Access_Rule (Count));
Iter : Util.Beans.Objects.Vectors.Cursor := Policy.Permissions.First;
Pos : Positive := 1;
begin
Pol.Rule := Rule;
-- Step 1: Initialize the list of permission index in Access_Rule from the permission names.
while Util.Beans.Objects.Vectors.Has_Element (Iter) loop
declare
Perm : constant Util.Beans.Objects.Object := Util.Beans.Objects.Vectors.Element (Iter);
Name : constant String := Util.Beans.Objects.To_String (Perm);
begin
Rule.Value.all.Permissions (Pos) := Permissions.Get_Permission_Index (Name);
Pos := Pos + 1;
exception
when Invalid_Name =>
raise Util.Serialize.Mappers.Field_Error with "Invalid permission: " & Name;
end;
Util.Beans.Objects.Vectors.Next (Iter);
end loop;
-- Step 2: Create one policy for each URL pattern
Iter := Policy.Patterns.First;
while Util.Beans.Objects.Vectors.Has_Element (Iter) loop
declare
Pattern : constant Util.Beans.Objects.Object
:= Util.Beans.Objects.Vectors.Element (Iter);
begin
Pol.Id := Policy.Id;
Pol.Pattern := GNAT.Regexp.Compile (Util.Beans.Objects.To_String (Pattern));
Policy.Policies.Append (Pol);
end;
Util.Beans.Objects.Vectors.Next (Iter);
end loop;
end Process;
package Policy_Mapper is
new Util.Serialize.Mappers.Record_Mapper (Element_Type => URL_Policy'Class,
Element_Type_Access => URL_Policy_Access,
Fields => Policy_Fields,
Set_Member => Set_Member);
Policy_Mapping : aliased Policy_Mapper.Mapper;
-- ------------------------------
-- Setup the XML parser to read the <b>policy</b> description.
-- ------------------------------
overriding
procedure Prepare_Config (Policy : in out URL_Policy;
Reader : in out Util.Serialize.IO.XML.Parser) is
Perm : Security.Controllers.URLs.URL_Controller_Access;
begin
Reader.Add_Mapping ("policy-rules", Policy_Mapping'Access);
Reader.Add_Mapping ("module", Policy_Mapping'Access);
Policy_Mapper.Set_Context (Reader, Policy'Unchecked_Access);
if not Policy.Manager.Has_Controller (P_URL.Permission) then
Perm := new Security.Controllers.URLs.URL_Controller;
Perm.Manager := Policy'Unchecked_Access;
Policy.Manager.Add_Permission (Name => "url",
Permission => Perm.all'Access);
end if;
end Prepare_Config;
-- ------------------------------
-- Get the URL policy associated with the given policy manager.
-- Returns the URL policy instance or null if it was not registered in the policy manager.
-- ------------------------------
function Get_URL_Policy (Manager : in Security.Policies.Policy_Manager'Class)
return URL_Policy_Access is
Policy : constant Security.Policies.Policy_Access := Manager.Get_Policy (NAME);
begin
if Policy = null or else not (Policy.all in URL_Policy'Class) then
return null;
else
return URL_Policy'Class (Policy.all)'Access;
end if;
end Get_URL_Policy;
begin
Policy_Mapping.Add_Mapping ("url-policy", FIELD_POLICY);
Policy_Mapping.Add_Mapping ("url-policy/@id", FIELD_ID);
Policy_Mapping.Add_Mapping ("url-policy/permission", FIELD_PERMISSION);
Policy_Mapping.Add_Mapping ("url-policy/url-pattern", FIELD_URL_PATTERN);
end Security.Policies.URLs;
|
-----------------------------------------------------------------------
-- security-policies-urls -- URL security policy
-- Copyright (C) 2010, 2011, 2012, 2016 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Unchecked_Deallocation;
with Util.Beans.Objects;
with Util.Beans.Objects.Vectors;
with Util.Serialize.Mappers;
with Util.Serialize.Mappers.Record_Mapper;
with Security.Controllers.URLs;
package body Security.Policies.URLs is
-- ------------------------------
-- Get the policy name.
-- ------------------------------
overriding
function Get_Name (From : in URL_Policy) return String is
pragma Unreferenced (From);
begin
return NAME;
end Get_Name;
-- ------------------------------
-- Returns True if the user has the permission to access the given URI permission.
-- ------------------------------
function Has_Permission (Manager : in URL_Policy;
Context : in Contexts.Security_Context'Class;
Permission : in URL_Permission'Class) return Boolean is
Name : constant String_Ref := To_String_Ref (Permission.URL);
Ref : constant Rules_Ref.Ref := Manager.Cache.Get;
Rules : constant Rules_Access := Ref.Value;
Pos : constant Rules_Maps.Cursor := Rules.Map.Find (Name);
Rule : Access_Rule_Ref;
begin
-- If the rule is not in the cache, search for the access rule that
-- matches our URI. Update the cache. This cache update is thread-safe
-- as the cache map is never modified: a new cache map is installed.
if not Rules_Maps.Has_Element (Pos) then
declare
New_Ref : constant Rules_Ref.Ref := Rules_Ref.Create;
begin
Rule := Manager.Find_Access_Rule (Permission.URL);
New_Ref.Value.all.Map := Rules.Map;
New_Ref.Value.all.Map.Insert (Name, Rule);
Manager.Cache.Set (New_Ref);
end;
else
Rule := Rules_Maps.Element (Pos);
end if;
-- Check if the user has one of the required permission.
declare
P : constant Access_Rule_Access := Rule.Value;
begin
if P /= null then
for I in P.Permissions'Range loop
if Context.Has_Permission (P.Permissions (I)) then
return True;
end if;
end loop;
end if;
end;
return False;
end Has_Permission;
-- Grant the permission to access to the given <b>URI</b> to users having the <b>To</b>
-- permissions.
procedure Grant_URI_Permission (Manager : in out URL_Policy;
URI : in String;
To : in String) is
begin
null;
end Grant_URI_Permission;
-- ------------------------------
-- Policy Configuration
-- ------------------------------
-- ------------------------------
-- Find the access rule of the policy that matches the given URI.
-- Returns the No_Rule value (disable access) if no rule is found.
-- ------------------------------
function Find_Access_Rule (Manager : in URL_Policy;
URI : in String) return Access_Rule_Ref is
Matched : Boolean := False;
Result : Access_Rule_Ref;
procedure Match (P : in Policy);
procedure Match (P : in Policy) is
begin
if GNAT.Regexp.Match (URI, P.Pattern) then
Matched := True;
Result := P.Rule;
end if;
end Match;
Last : constant Natural := Manager.Policies.Last_Index;
begin
for I in 1 .. Last loop
Manager.Policies.Query_Element (I, Match'Access);
if Matched then
return Result;
end if;
end loop;
return Result;
end Find_Access_Rule;
-- ------------------------------
-- Initialize the permission manager.
-- ------------------------------
overriding
procedure Initialize (Manager : in out URL_Policy) is
begin
Manager.Cache := new Rules_Ref.Atomic_Ref;
Manager.Cache.Set (Rules_Ref.Create);
end Initialize;
-- ------------------------------
-- Finalize the permission manager.
-- ------------------------------
overriding
procedure Finalize (Manager : in out URL_Policy) is
procedure Free is
new Ada.Unchecked_Deallocation (Rules_Ref.Atomic_Ref,
Rules_Ref_Access);
begin
Free (Manager.Cache);
end Finalize;
type Policy_Fields is (FIELD_ID, FIELD_PERMISSION, FIELD_URL_PATTERN, FIELD_POLICY);
procedure Set_Member (P : in out URL_Policy'Class;
Field : in Policy_Fields;
Value : in Util.Beans.Objects.Object);
procedure Process (Policy : in out URL_Policy'Class);
procedure Set_Member (P : in out URL_Policy'Class;
Field : in Policy_Fields;
Value : in Util.Beans.Objects.Object) is
begin
case Field is
when FIELD_ID =>
P.Id := Util.Beans.Objects.To_Integer (Value);
when FIELD_PERMISSION =>
P.Permissions.Append (Value);
when FIELD_URL_PATTERN =>
P.Patterns.Append (Value);
when FIELD_POLICY =>
Process (P);
P.Id := 0;
P.Permissions.Clear;
P.Patterns.Clear;
end case;
end Set_Member;
procedure Process (Policy : in out URL_Policy'Class) is
Pol : Security.Policies.URLs.Policy;
Count : constant Natural := Natural (Policy.Permissions.Length);
Rule : constant Access_Rule_Ref := Access_Rule_Refs.Create (new Access_Rule (Count));
Iter : Util.Beans.Objects.Vectors.Cursor := Policy.Permissions.First;
Pos : Positive := 1;
begin
Pol.Rule := Rule;
-- Step 1: Initialize the list of permission index in Access_Rule from the permission names.
while Util.Beans.Objects.Vectors.Has_Element (Iter) loop
declare
Perm : constant Util.Beans.Objects.Object := Util.Beans.Objects.Vectors.Element (Iter);
Name : constant String := Util.Beans.Objects.To_String (Perm);
begin
Rule.Value.all.Permissions (Pos) := Permissions.Get_Permission_Index (Name);
Pos := Pos + 1;
exception
when Invalid_Name =>
raise Util.Serialize.Mappers.Field_Error with "Invalid permission: " & Name;
end;
Util.Beans.Objects.Vectors.Next (Iter);
end loop;
-- Step 2: Create one policy for each URL pattern
Iter := Policy.Patterns.First;
while Util.Beans.Objects.Vectors.Has_Element (Iter) loop
declare
Pattern : constant Util.Beans.Objects.Object
:= Util.Beans.Objects.Vectors.Element (Iter);
begin
Pol.Id := Policy.Id;
Pol.Pattern := GNAT.Regexp.Compile (Util.Beans.Objects.To_String (Pattern));
Policy.Policies.Append (Pol);
end;
Util.Beans.Objects.Vectors.Next (Iter);
end loop;
end Process;
package Policy_Mapper is
new Util.Serialize.Mappers.Record_Mapper (Element_Type => URL_Policy'Class,
Element_Type_Access => URL_Policy_Access,
Fields => Policy_Fields,
Set_Member => Set_Member);
Policy_Mapping : aliased Policy_Mapper.Mapper;
-- ------------------------------
-- Setup the XML parser to read the <b>policy</b> description.
-- ------------------------------
overriding
procedure Prepare_Config (Policy : in out URL_Policy;
Mapper : in out Util.Serialize.Mappers.Processing) is
Perm : Security.Controllers.URLs.URL_Controller_Access;
begin
Mapper.Add_Mapping ("policy-rules", Policy_Mapping'Access);
Mapper.Add_Mapping ("module", Policy_Mapping'Access);
Policy_Mapper.Set_Context (Mapper, Policy'Unchecked_Access);
if not Policy.Manager.Has_Controller (P_URL.Permission) then
Perm := new Security.Controllers.URLs.URL_Controller;
Perm.Manager := Policy'Unchecked_Access;
Policy.Manager.Add_Permission (Name => "url",
Permission => Perm.all'Access);
end if;
end Prepare_Config;
-- ------------------------------
-- Get the URL policy associated with the given policy manager.
-- Returns the URL policy instance or null if it was not registered in the policy manager.
-- ------------------------------
function Get_URL_Policy (Manager : in Security.Policies.Policy_Manager'Class)
return URL_Policy_Access is
Policy : constant Security.Policies.Policy_Access := Manager.Get_Policy (NAME);
begin
if Policy = null or else not (Policy.all in URL_Policy'Class) then
return null;
else
return URL_Policy'Class (Policy.all)'Access;
end if;
end Get_URL_Policy;
begin
Policy_Mapping.Add_Mapping ("url-policy", FIELD_POLICY);
Policy_Mapping.Add_Mapping ("url-policy/@id", FIELD_ID);
Policy_Mapping.Add_Mapping ("url-policy/permission", FIELD_PERMISSION);
Policy_Mapping.Add_Mapping ("url-policy/url-pattern", FIELD_URL_PATTERN);
end Security.Policies.URLs;
|
Update Prepare_Config to get a Mappers.Processing type as parameter
|
Update Prepare_Config to get a Mappers.Processing type as parameter
|
Ada
|
apache-2.0
|
stcarrez/ada-security
|
93ccc1d5caafd38b75148e41a75eaaca2f98deb5
|
src/security-policies-urls.ads
|
src/security-policies-urls.ads
|
-----------------------------------------------------------------------
-- security-policies-urls -- URL security policy
-- 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.Containers.Hashed_Maps;
with Ada.Containers.Vectors;
with Util.Refs;
with Util.Strings;
with Util.Serialize.IO.XML;
with GNAT.Regexp;
-- == URL Security Policy ==
-- The <tt>Security.Policies.Urls</tt> implements a security policy intended to be used
-- in web servers.
--
-- === Policy creation ===
-- An instance of the <tt>URL_Policy</tt> must be created and registered in the policy manager.
-- Get or declare the following variables:
--
-- Manager : Security.Policies.Policy_Manager;
-- Policy : Security.Policies.Urls.URL_Policy_Access;
--
-- Create the URL policy and register it in the policy manager as follows:
--
-- Policy := new URL_Policy;
-- Manager.Add_Policy (Policy.all'Access);
--
-- === Policy Configuration ===
-- Once the URL policy is registered, the policy manager can read and process the following
-- XML configuration:
--
-- <url-policy id='1'>
-- <permission>create-workspace</permission>
-- <permission>admin</permission>
-- <url-pattern>/workspace/create</url-pattern>
-- <url-pattern>/workspace/setup/*</url-pattern>
-- </url-policy>
--
-- This policy gives access to the URL that match one of the URL pattern if the
-- security context has the permission <b>create-workspace</b> or <b>admin</b>.
-- These two permissions are checked according to another security policy.
-- The XML configuration can define several <tt>url-policy</tt>. They are checked in
-- the order defined in the XML. In other words, the first <tt>url-policy</tt> that matches
-- the URL is used to verify the permission.
--
-- The <tt>url-policy</tt> definition can contain several <tt>permission</tt>.
--
-- === Checking for permission ===
-- To check a URL permission, you must declare a <tt>URI_Permission</tt> object with the URL.
--
-- URI : constant String := ...;
-- Perm : constant Policies.URLs.URI_Permission (1, URI'Length)
-- := URI_Permission '(1, Len => URI'Length, URI => URI);
-- Result : Boolean;
--
-- Having the security context, we can check the permission:
--
-- Context.Has_Permission (Perm, Result);
--
package Security.Policies.Urls is
NAME : constant String := "URL-Policy";
package P_URL is new Security.Permissions.Definition ("url");
-- ------------------------------
-- URI Permission
-- ------------------------------
-- Represents a permission to access a given URI.
type URI_Permission (Len : Natural) is new Permissions.Permission (P_URL.Permission) with record
URI : String (1 .. Len);
end record;
-- ------------------------------
-- URL policy
-- ------------------------------
type URL_Policy is new Policy with private;
type URL_Policy_Access is access all URL_Policy'Class;
Invalid_Name : exception;
-- Get the policy name.
overriding
function Get_Name (From : in URL_Policy) return String;
-- Returns True if the user has the permission to access the given URI permission.
function Has_Permission (Manager : in URL_Policy;
Context : in Security_Context_Access;
Permission : in URI_Permission'Class) return Boolean;
-- Grant the permission to access to the given <b>URI</b> to users having the <b>To</b>
-- permissions.
procedure Grant_URI_Permission (Manager : in out URL_Policy;
URI : in String;
To : in String);
-- Initialize the permission manager.
overriding
procedure Initialize (Manager : in out URL_Policy);
-- Finalize the permission manager.
overriding
procedure Finalize (Manager : in out URL_Policy);
-- Setup the XML parser to read the <b>policy</b> description.
overriding
procedure Prepare_Config (Policy : in out URL_Policy;
Reader : in out Util.Serialize.IO.XML.Parser);
-- Finish reading the XML policy configuration. The security policy implementation can use
-- this procedure to perform any configuration setup after the configuration is parsed.
overriding
procedure Finish_Config (Into : in out URL_Policy;
Reader : in out Util.Serialize.IO.XML.Parser);
-- Get the URL policy associated with the given policy manager.
-- Returns the URL policy instance or null if it was not registered in the policy manager.
function Get_URL_Policy (Manager : in Security.Policies.Policy_Manager'Class)
return URL_Policy_Access;
private
use Util.Strings;
-- The <b>Access_Rule</b> represents a list of permissions to verify to grant
-- access to the resource. To make it simple, the user must have one of the
-- permission from the list. Each permission will refer to a specific permission
-- controller.
type Access_Rule (Count : Natural) is new Util.Refs.Ref_Entity with record
Permissions : Permission_Index_Array (1 .. Count);
end record;
type Access_Rule_Access is access all Access_Rule;
package Access_Rule_Refs is
new Util.Refs.Indefinite_References (Element_Type => Access_Rule,
Element_Access => Access_Rule_Access);
subtype Access_Rule_Ref is Access_Rule_Refs.Ref;
-- Find the access rule of the policy that matches the given URI.
-- Returns the No_Rule value (disable access) if no rule is found.
function Find_Access_Rule (Manager : in URL_Policy;
URI : in String) return Access_Rule_Ref;
-- The <b>Policy</b> defines the access rules that are applied on a given
-- URL, set of URLs or files.
type Policy is record
Id : Natural;
Pattern : GNAT.Regexp.Regexp;
Rule : Access_Rule_Ref;
end record;
-- The <b>Policy_Vector</b> represents the whole permission policy. The order of
-- policy in the list is important as policies can override each other.
package Policy_Vector is new Ada.Containers.Vectors (Index_Type => Positive,
Element_Type => Policy);
package Rules_Maps is new Ada.Containers.Hashed_Maps (Key_Type => String_Ref,
Element_Type => Access_Rule_Ref,
Hash => Hash,
Equivalent_Keys => Equivalent_Keys,
"=" => Access_Rule_Refs."=");
type Rules is new Util.Refs.Ref_Entity with record
Map : Rules_Maps.Map;
end record;
type Rules_Access is access all Rules;
package Rules_Ref is new Util.Refs.References (Rules, Rules_Access);
type Rules_Ref_Access is access Rules_Ref.Atomic_Ref;
type Controller_Access_Array_Access is access all Controller_Access_Array;
type URL_Policy is new Security.Policies.Policy with record
Cache : Rules_Ref_Access;
Policies : Policy_Vector.Vector;
end record;
end Security.Policies.Urls;
|
-----------------------------------------------------------------------
-- security-policies-urls -- URL security policy
-- 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.Containers.Hashed_Maps;
with Ada.Containers.Vectors;
with Util.Refs;
with Util.Strings;
with Util.Serialize.IO.XML;
with GNAT.Regexp;
-- == URL Security Policy ==
-- The <tt>Security.Policies.Urls</tt> implements a security policy intended to be used
-- in web servers.
--
-- === Policy creation ===
-- An instance of the <tt>URL_Policy</tt> must be created and registered in the policy manager.
-- Get or declare the following variables:
--
-- Manager : Security.Policies.Policy_Manager;
-- Policy : Security.Policies.Urls.URL_Policy_Access;
--
-- Create the URL policy and register it in the policy manager as follows:
--
-- Policy := new URL_Policy;
-- Manager.Add_Policy (Policy.all'Access);
--
-- === Policy Configuration ===
-- Once the URL policy is registered, the policy manager can read and process the following
-- XML configuration:
--
-- <policy-rules>
-- <url-policy id='1'>
-- <permission>create-workspace</permission>
-- <permission>admin</permission>
-- <url-pattern>/workspace/create</url-pattern>
-- <url-pattern>/workspace/setup/*</url-pattern>
-- </url-policy>
-- ...
-- </policy-rules>
--
-- This policy gives access to the URL that match one of the URL pattern if the
-- security context has the permission <b>create-workspace</b> or <b>admin</b>.
-- These two permissions are checked according to another security policy.
-- The XML configuration can define several <tt>url-policy</tt>. They are checked in
-- the order defined in the XML. In other words, the first <tt>url-policy</tt> that matches
-- the URL is used to verify the permission.
--
-- The <tt>url-policy</tt> definition can contain several <tt>permission</tt>.
--
-- === Checking for permission ===
-- To check a URL permission, you must declare a <tt>URI_Permission</tt> object with the URL.
--
-- URI : constant String := ...;
-- Perm : constant Policies.URLs.URI_Permission (URI'Length)
-- := URI_Permission '(Len => URI'Length, URI => URI);
--
-- Then, we can check the permission:
--
-- Result : Boolean := Security.Contexts.Has_Permission (Perm);
--
package Security.Policies.Urls is
NAME : constant String := "URL-Policy";
package P_URL is new Security.Permissions.Definition ("url");
-- ------------------------------
-- URI Permission
-- ------------------------------
-- Represents a permission to access a given URI.
type URI_Permission (Len : Natural) is new Permissions.Permission (P_URL.Permission) with record
URI : String (1 .. Len);
end record;
-- ------------------------------
-- URL policy
-- ------------------------------
type URL_Policy is new Policy with private;
type URL_Policy_Access is access all URL_Policy'Class;
Invalid_Name : exception;
-- Get the policy name.
overriding
function Get_Name (From : in URL_Policy) return String;
-- Returns True if the user has the permission to access the given URI permission.
function Has_Permission (Manager : in URL_Policy;
Context : in Security_Context_Access;
Permission : in URI_Permission'Class) return Boolean;
-- Grant the permission to access to the given <b>URI</b> to users having the <b>To</b>
-- permissions.
procedure Grant_URI_Permission (Manager : in out URL_Policy;
URI : in String;
To : in String);
-- Initialize the permission manager.
overriding
procedure Initialize (Manager : in out URL_Policy);
-- Finalize the permission manager.
overriding
procedure Finalize (Manager : in out URL_Policy);
-- Setup the XML parser to read the <b>policy</b> description.
overriding
procedure Prepare_Config (Policy : in out URL_Policy;
Reader : in out Util.Serialize.IO.XML.Parser);
-- Finish reading the XML policy configuration. The security policy implementation can use
-- this procedure to perform any configuration setup after the configuration is parsed.
overriding
procedure Finish_Config (Into : in out URL_Policy;
Reader : in out Util.Serialize.IO.XML.Parser);
-- Get the URL policy associated with the given policy manager.
-- Returns the URL policy instance or null if it was not registered in the policy manager.
function Get_URL_Policy (Manager : in Security.Policies.Policy_Manager'Class)
return URL_Policy_Access;
private
use Util.Strings;
-- The <b>Access_Rule</b> represents a list of permissions to verify to grant
-- access to the resource. To make it simple, the user must have one of the
-- permission from the list. Each permission will refer to a specific permission
-- controller.
type Access_Rule (Count : Natural) is new Util.Refs.Ref_Entity with record
Permissions : Permission_Index_Array (1 .. Count);
end record;
type Access_Rule_Access is access all Access_Rule;
package Access_Rule_Refs is
new Util.Refs.Indefinite_References (Element_Type => Access_Rule,
Element_Access => Access_Rule_Access);
subtype Access_Rule_Ref is Access_Rule_Refs.Ref;
-- Find the access rule of the policy that matches the given URI.
-- Returns the No_Rule value (disable access) if no rule is found.
function Find_Access_Rule (Manager : in URL_Policy;
URI : in String) return Access_Rule_Ref;
-- The <b>Policy</b> defines the access rules that are applied on a given
-- URL, set of URLs or files.
type Policy is record
Id : Natural;
Pattern : GNAT.Regexp.Regexp;
Rule : Access_Rule_Ref;
end record;
-- The <b>Policy_Vector</b> represents the whole permission policy. The order of
-- policy in the list is important as policies can override each other.
package Policy_Vector is new Ada.Containers.Vectors (Index_Type => Positive,
Element_Type => Policy);
package Rules_Maps is new Ada.Containers.Hashed_Maps (Key_Type => String_Ref,
Element_Type => Access_Rule_Ref,
Hash => Hash,
Equivalent_Keys => Equivalent_Keys,
"=" => Access_Rule_Refs."=");
type Rules is new Util.Refs.Ref_Entity with record
Map : Rules_Maps.Map;
end record;
type Rules_Access is access all Rules;
package Rules_Ref is new Util.Refs.References (Rules, Rules_Access);
type Rules_Ref_Access is access Rules_Ref.Atomic_Ref;
type Controller_Access_Array_Access is access all Controller_Access_Array;
type URL_Policy is new Security.Policies.Policy with record
Cache : Rules_Ref_Access;
Policies : Policy_Vector.Vector;
end record;
end Security.Policies.Urls;
|
Fix the documentation
|
Fix the documentation
|
Ada
|
apache-2.0
|
stcarrez/ada-security
|
17fb418b883143f97f9721372fb1119099ec2d49
|
src/util-commands-consoles.adb
|
src/util-commands-consoles.adb
|
-----------------------------------------------------------------------
-- util-commands-consoles - Console interface
-- Copyright (C) 2014, 2015, 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Strings;
package body Util.Commands.Consoles is
-- ------------------------------
-- Print the title for the given field and setup the associated field size.
-- ------------------------------
procedure Print_Title (Console : in out Console_Type;
Field : in Field_Type;
Title : in String;
Length : in Positive) is
begin
Console.Sizes (Field) := Length;
if Console.Field_Count >= 1 then
Console.Cols (Field) := Console.Cols (Console.Fields (Console.Field_Count))
+ Console.Sizes (Console.Fields (Console.Field_Count));
else
Console.Cols (Field) := 1;
end if;
Console.Field_Count := Console.Field_Count + 1;
Console.Fields (Console.Field_Count) := Field;
Console_Type'Class (Console).Print_Title (Field, Title);
end Print_Title;
-- ------------------------------
-- Format the integer and print it for the given field.
-- ------------------------------
procedure Print_Field (Console : in out Console_Type;
Field : in Field_Type;
Value : in Integer;
Justify : in Justify_Type := J_LEFT) is
Val : constant String := Util.Strings.Image (Value);
begin
Console_Type'Class (Console).Print_Field (Field, Val, Justify);
end Print_Field;
-- ------------------------------
-- Format the integer and print it for the given field.
-- ------------------------------
procedure Print_Field (Console : in out Console_Type;
Field : in Field_Type;
Value : in Ada.Strings.Unbounded.Unbounded_String;
Justify : in Justify_Type := J_LEFT) is
Item : String := Ada.Strings.Unbounded.To_String (Value);
Size : constant Natural := Console.Sizes (Field);
begin
if Size <= Item'Length then
Item (Item'Last - Size + 2 .. Item'Last - Size + 4) := "...";
Console_Type'Class (Console).Print_Field (Field,
Item (Item'Last - Size + 2 .. Item'Last));
else
Console_Type'Class (Console).Print_Field (Field, Item, Justify);
end if;
end Print_Field;
-- ------------------------------
-- Get the field count that was setup through the Print_Title calls.
-- ------------------------------
function Get_Field_Count (Console : in Console_Type) return Natural is
begin
return Console.Field_Count;
end Get_Field_Count;
-- ------------------------------
-- Reset the field count.
-- ------------------------------
procedure Clear_Fields (Console : in out Console_Type) is
begin
Console.Field_Count := 0;
end Clear_Fields;
end Util.Commands.Consoles;
|
-----------------------------------------------------------------------
-- util-commands-consoles -- Console interface
-- Copyright (C) 2014, 2015, 2017, 2018 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Strings;
package body Util.Commands.Consoles is
-- ------------------------------
-- Print the title for the given field and setup the associated field size.
-- ------------------------------
procedure Print_Title (Console : in out Console_Type;
Field : in Field_Type;
Title : in String;
Length : in Positive) is
begin
Console.Sizes (Field) := Length;
if Console.Field_Count >= 1 then
Console.Cols (Field) := Console.Cols (Console.Fields (Console.Field_Count))
+ Console.Sizes (Console.Fields (Console.Field_Count));
else
Console.Cols (Field) := 1;
end if;
Console.Field_Count := Console.Field_Count + 1;
Console.Fields (Console.Field_Count) := Field;
Console_Type'Class (Console).Print_Title (Field, Title);
end Print_Title;
-- ------------------------------
-- Format the integer and print it for the given field.
-- ------------------------------
procedure Print_Field (Console : in out Console_Type;
Field : in Field_Type;
Value : in Integer;
Justify : in Justify_Type := J_LEFT) is
Val : constant String := Util.Strings.Image (Value);
begin
Console_Type'Class (Console).Print_Field (Field, Val, Justify);
end Print_Field;
-- ------------------------------
-- Format the integer and print it for the given field.
-- ------------------------------
procedure Print_Field (Console : in out Console_Type;
Field : in Field_Type;
Value : in Ada.Strings.Unbounded.Unbounded_String;
Justify : in Justify_Type := J_LEFT) is
Item : String := Ada.Strings.Unbounded.To_String (Value);
Size : constant Natural := Console.Sizes (Field);
begin
if Size <= Item'Length then
Item (Item'Last - Size + 2 .. Item'Last - Size + 4) := "...";
Console_Type'Class (Console).Print_Field (Field,
Item (Item'Last - Size + 2 .. Item'Last));
else
Console_Type'Class (Console).Print_Field (Field, Item, Justify);
end if;
end Print_Field;
-- ------------------------------
-- Get the field count that was setup through the Print_Title calls.
-- ------------------------------
function Get_Field_Count (Console : in Console_Type) return Natural is
begin
return Console.Field_Count;
end Get_Field_Count;
-- ------------------------------
-- Reset the field count.
-- ------------------------------
procedure Clear_Fields (Console : in out Console_Type) is
begin
Console.Field_Count := 0;
end Clear_Fields;
end Util.Commands.Consoles;
|
Fix header style
|
Fix header style
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
d9e56bb5c7903b95e8a3d5116b917406f7ca0514
|
src/util-serialize-io-json.adb
|
src/util-serialize-io-json.adb
|
-----------------------------------------------------------------------
-- util-serialize-io-json -- JSON Serialization Driver
-- 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.Characters.Latin_1;
with Ada.IO_Exceptions;
with Util.Strings;
with Util.Streams;
with Util.Streams.Buffered;
package body Util.Serialize.IO.JSON is
use Ada.Strings.Unbounded;
-- -----------------------
-- Write the string as a quoted JSON string
-- -----------------------
procedure Write_String (Stream : in out Output_Stream;
Value : in String) is
begin
Stream.Write ('"');
for I in Value'Range loop
declare
C : constant Character := Value (I);
begin
if C = '"' then
Stream.Write ("\""");
elsif C = '\' then
Stream.Write ("\\");
elsif Character'Pos (C) >= 16#20# then
Stream.Write (C);
else
case C is
when Ada.Characters.Latin_1.BS =>
Stream.Write ("\b");
when Ada.Characters.Latin_1.VT =>
Stream.Write ("\f");
when Ada.Characters.Latin_1.LF =>
Stream.Write ("\n");
when Ada.Characters.Latin_1.CR =>
Stream.Write ("\r");
when Ada.Characters.Latin_1.HT =>
Stream.Write ("\t");
when others =>
Util.Streams.Texts.TR.To_Hex (Streams.Buffered.Buffered_Stream (Stream), C);
end case;
end if;
end;
end loop;
Stream.Write ('"');
end Write_String;
-- -----------------------
-- Start writing an object identified by the given name
-- -----------------------
procedure Start_Entity (Stream : in out Output_Stream;
Name : in String) is
Current : access Node_Info := Node_Info_Stack.Current (Stream.Stack);
begin
if Current /= null then
if Current.Has_Fields then
Stream.Write (',');
else
Current.Has_Fields := True;
end if;
end if;
Node_Info_Stack.Push (Stream.Stack);
Current := Node_Info_Stack.Current (Stream.Stack);
Current.Has_Fields := False;
if Name'Length > 0 then
Stream.Write_String (Name);
Stream.Write (':');
end if;
Stream.Write ('{');
end Start_Entity;
-- -----------------------
-- Finish writing an object identified by the given name
-- -----------------------
procedure End_Entity (Stream : in out Output_Stream;
Name : in String) is
pragma Unreferenced (Name);
begin
Node_Info_Stack.Pop (Stream.Stack);
Stream.Write ('}');
end End_Entity;
-- -----------------------
-- Write an attribute member from the current object
-- -----------------------
procedure Write_Attribute (Stream : in out Output_Stream;
Name : in String;
Value : in Util.Beans.Objects.Object) is
use Util.Beans.Objects;
Current : constant access Node_Info := Node_Info_Stack.Current (Stream.Stack);
begin
if Current /= null then
if Current.Has_Fields then
Stream.Write (",");
else
Current.Has_Fields := True;
end if;
end if;
Stream.Write_String (Name);
Stream.Write (':');
case Util.Beans.Objects.Get_Type (Value) is
when TYPE_NULL =>
Stream.Write ("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;
end Write_Attribute;
-- -----------------------
-- Write an object value as an entity
-- -----------------------
procedure Write_Entity (Stream : in out Output_Stream;
Name : in String;
Value : in Util.Beans.Objects.Object) is
begin
Stream.Write_Attribute (Name, Value);
end Write_Entity;
-- -----------------------
-- Start an array that will contain the specified number of elements
-- -----------------------
procedure Start_Array (Stream : in out Output_Stream;
Length : in Ada.Containers.Count_Type) is
pragma Unreferenced (Length);
begin
Node_Info_Stack.Push (Stream.Stack);
Stream.Write ('[');
end Start_Array;
-- -----------------------
-- Finishes an array
-- -----------------------
procedure End_Array (Stream : in out Output_Stream) is
begin
Node_Info_Stack.Pop (Stream.Stack);
Stream.Write (']');
end End_Array;
-- -----------------------
-- Get the current location (file and line) to report an error message.
-- -----------------------
function Get_Location (Handler : in Parser) return String is
begin
return Util.Strings.Image (Handler.Line_Number);
end Get_Location;
procedure Parse (Handler : in out Parser;
Stream : in out Util.Streams.Buffered.Buffered_Stream'Class) is
-- Put back a token in the buffer.
procedure Put_Back (P : in out Parser'Class;
Token : in Token_Type);
-- Parse the expression buffer to find the next token.
procedure Peek (P : in out Parser'Class;
Token : out Token_Type);
-- Parse a list of members
-- members ::= pair | pair ',' members
-- pair ::= string ':' value
-- value ::= string | number | object | array | true | false | null
procedure Parse_Pairs (P : in out Parser'Class);
-- Parse a value
-- value ::= string | number | object | array | true | false | null
procedure Parse_Value (P : in out Parser'Class;
Name : in String);
procedure Parse (P : in out Parser'Class);
procedure Parse (P : in out Parser'Class) is
Token : Token_Type;
begin
Peek (P, Token);
if Token /= T_LEFT_BRACE then
P.Error ("Missing '{'");
end if;
Parse_Pairs (P);
Peek (P, Token);
if Token /= T_RIGHT_BRACE then
P.Error ("Missing '}'");
end if;
end Parse;
-- ------------------------------
-- Parse a list of members
-- members ::= pair | pair ',' members
-- pair ::= string ':' value
-- value ::= string | number | object | array | true | false | null
-- ------------------------------
procedure Parse_Pairs (P : in out Parser'Class) is
Current_Name : Unbounded_String;
Token : Token_Type;
begin
loop
Peek (P, Token);
if Token /= T_STRING then
Put_Back (P, Token);
return;
end if;
Current_Name := P.Token;
Peek (P, Token);
if Token /= T_COLON then
P.Error ("Missing ':'");
end if;
Parse_Value (P, To_String (Current_Name));
Peek (P, Token);
if Token /= T_COMMA then
Put_Back (P, Token);
return;
end if;
end loop;
end Parse_Pairs;
-- ------------------------------
-- Parse a value
-- value ::= string | number | object | array | true | false | null
-- ------------------------------
procedure Parse_Value (P : in out Parser'Class;
Name : in String) is
Token : Token_Type;
begin
Peek (P, Token);
case Token is
when T_LEFT_BRACE =>
P.Start_Object (Name);
Parse_Pairs (P);
Peek (P, Token);
if Token /= T_RIGHT_BRACE then
P.Error ("Missing '}'");
end if;
P.Finish_Object (Name);
--
when T_LEFT_BRACKET =>
P.Start_Array (Name);
Peek (P, Token);
if Token /= T_RIGHT_BRACKET then
Put_Back (P, Token);
loop
Parse_Value (P, Name);
Peek (P, Token);
exit when Token = T_RIGHT_BRACKET;
if Token /= T_COMMA then
P.Error ("Missing ']'");
end if;
end loop;
end if;
P.Finish_Array (Name);
when T_NULL =>
P.Set_Member (Name, Util.Beans.Objects.Null_Object);
when T_NUMBER =>
P.Set_Member (Name, Util.Beans.Objects.To_Object (P.Token));
when T_STRING =>
P.Set_Member (Name, Util.Beans.Objects.To_Object (P.Token));
when T_TRUE =>
P.Set_Member (Name, Util.Beans.Objects.To_Object (True));
when T_FALSE =>
P.Set_Member (Name, Util.Beans.Objects.To_Object (False));
when T_EOF =>
P.Error ("End of stream reached");
return;
when others =>
P.Error ("Invalid token");
end case;
end Parse_Value;
-- ------------------------------
-- Put back a token in the buffer.
-- ------------------------------
procedure Put_Back (P : in out Parser'Class;
Token : in Token_Type) is
begin
P.Pending_Token := Token;
end Put_Back;
-- ------------------------------
-- Parse the expression buffer to find the next token.
-- ------------------------------
procedure Peek (P : in out Parser'Class;
Token : out Token_Type) is
C, C1 : Character;
begin
-- If a token was put back, return it.
if P.Pending_Token /= T_EOF then
Token := P.Pending_Token;
P.Pending_Token := T_EOF;
return;
end if;
if P.Has_Pending_Char then
C := P.Pending_Char;
else
-- Skip white spaces
loop
Stream.Read (Char => C);
if C = Ada.Characters.Latin_1.LF then
P.Line_Number := P.Line_Number + 1;
else
exit when C /= ' '
and C /= Ada.Characters.Latin_1.CR and C /= Ada.Characters.Latin_1.HT;
end if;
end loop;
end if;
P.Has_Pending_Char := False;
-- See what we have and continue parsing.
case C is
-- Literal string using double quotes
-- Collect up to the end of the string and put
-- the result in the parser token result.
when '"' =>
Delete (P.Token, 1, Length (P.Token));
loop
Stream.Read (Char => C1);
if C1 = '\' then
Stream.Read (Char => C1);
case C1 is
when '"' | '\' | '/' =>
C := C1;
when 'b' =>
C1 := Ada.Characters.Latin_1.BS;
when 'f' =>
C1 := Ada.Characters.Latin_1.VT;
when 'n' =>
C1 := Ada.Characters.Latin_1.LF;
when 'r' =>
C1 := Ada.Characters.Latin_1.CR;
when 't' =>
C1 := Ada.Characters.Latin_1.HT;
when 'u' =>
null;
when others =>
P.Error ("Invalid character '" & C1 & "' in \x sequence");
end case;
elsif C1 = C then
Token := T_STRING;
return;
end if;
Append (P.Token, C1);
end loop;
-- Number
when '-' | '0' .. '9' =>
Delete (P.Token, 1, Length (P.Token));
Append (P.Token, C);
loop
Stream.Read (Char => C);
exit when C not in '0' .. '9';
Append (P.Token, C);
end loop;
if C = '.' then
Append (P.Token, C);
loop
Stream.Read (Char => C);
exit when C not in '0' .. '9';
Append (P.Token, C);
end loop;
end if;
if C = 'e' or C = 'E' then
Append (P.Token, C);
Stream.Read (Char => C);
if C = '+' or C = '-' then
Append (P.Token, C);
Stream.Read (Char => C);
end if;
loop
Stream.Read (Char => C);
exit when C not in '0' .. '9';
Append (P.Token, C);
end loop;
end if;
if C /= ' ' and C /= Ada.Characters.Latin_1.HT then
P.Has_Pending_Char := True;
P.Pending_Char := C;
end if;
Token := T_NUMBER;
return;
-- Parse a name composed of letters or digits.
when 'a' .. 'z' | 'A' .. 'Z' =>
Delete (P.Token, 1, Length (P.Token));
Append (P.Token, C);
loop
Stream.Read (Char => C);
exit when not (C in 'a' .. 'z' or C in 'A' .. 'Z'
or C in '0' .. '9' or C = '_');
Append (P.Token, C);
end loop;
-- Putback the last character unless we can ignore it.
if C /= ' ' and C /= Ada.Characters.Latin_1.HT then
P.Has_Pending_Char := True;
P.Pending_Char := C;
end if;
-- and empty eq false ge gt le lt ne not null true
case Element (P.Token, 1) is
when 'n' | 'N' =>
if P.Token = "null" then
Token := T_NULL;
return;
end if;
when 'f' | 'F' =>
if P.Token = "false" then
Token := T_FALSE;
return;
end if;
when 't' | 'T' =>
if P.Token = "true" then
Token := T_TRUE;
return;
end if;
when others =>
null;
end case;
Token := T_UNKNOWN;
return;
when '{' =>
Token := T_LEFT_BRACE;
return;
when '}' =>
Token := T_RIGHT_BRACE;
return;
when '[' =>
Token := T_LEFT_BRACKET;
return;
when ']' =>
Token := T_RIGHT_BRACKET;
return;
when ':' =>
Token := T_COLON;
return;
when ',' =>
Token := T_COMMA;
return;
when others =>
Token := T_UNKNOWN;
return;
end case;
exception
when Ada.IO_Exceptions.Data_Error =>
Token := T_EOF;
return;
end Peek;
begin
Parse (Handler);
end Parse;
end Util.Serialize.IO.JSON;
|
-----------------------------------------------------------------------
-- util-serialize-io-json -- JSON Serialization Driver
-- 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.Characters.Latin_1;
with Ada.IO_Exceptions;
with Util.Strings;
with Util.Streams;
with Util.Streams.Buffered;
package body Util.Serialize.IO.JSON is
use Ada.Strings.Unbounded;
-- -----------------------
-- Write the string as a quoted JSON string
-- -----------------------
procedure Write_String (Stream : in out Output_Stream;
Value : in String) is
begin
Stream.Write ('"');
for I in Value'Range loop
declare
C : constant Character := Value (I);
begin
if C = '"' then
Stream.Write ("\""");
elsif C = '\' then
Stream.Write ("\\");
elsif Character'Pos (C) >= 16#20# then
Stream.Write (C);
else
case C is
when Ada.Characters.Latin_1.BS =>
Stream.Write ("\b");
when Ada.Characters.Latin_1.VT =>
Stream.Write ("\f");
when Ada.Characters.Latin_1.LF =>
Stream.Write ("\n");
when Ada.Characters.Latin_1.CR =>
Stream.Write ("\r");
when Ada.Characters.Latin_1.HT =>
Stream.Write ("\t");
when others =>
Util.Streams.Texts.TR.To_Hex (Streams.Buffered.Buffered_Stream (Stream), C);
end case;
end if;
end;
end loop;
Stream.Write ('"');
end Write_String;
-- -----------------------
-- Start writing an object identified by the given name
-- -----------------------
procedure Start_Entity (Stream : in out Output_Stream;
Name : in String) is
Current : access Node_Info := Node_Info_Stack.Current (Stream.Stack);
begin
if Current /= null then
if Current.Has_Fields then
Stream.Write (',');
else
Current.Has_Fields := True;
end if;
end if;
Node_Info_Stack.Push (Stream.Stack);
Current := Node_Info_Stack.Current (Stream.Stack);
Current.Has_Fields := False;
if Name'Length > 0 then
Stream.Write_String (Name);
Stream.Write (':');
end if;
Stream.Write ('{');
end Start_Entity;
-- -----------------------
-- Finish writing an object identified by the given name
-- -----------------------
procedure End_Entity (Stream : in out Output_Stream;
Name : in String) is
pragma Unreferenced (Name);
begin
Node_Info_Stack.Pop (Stream.Stack);
Stream.Write ('}');
end End_Entity;
-- -----------------------
-- Write an attribute member from the current object
-- -----------------------
procedure Write_Attribute (Stream : in out Output_Stream;
Name : in String;
Value : in Util.Beans.Objects.Object) is
use Util.Beans.Objects;
Current : constant access Node_Info := Node_Info_Stack.Current (Stream.Stack);
begin
if Current /= null then
if Current.Has_Fields then
Stream.Write (",");
else
Current.Has_Fields := True;
end if;
end if;
Stream.Write_String (Name);
Stream.Write (':');
case Util.Beans.Objects.Get_Type (Value) is
when TYPE_NULL =>
Stream.Write ("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;
end Write_Attribute;
-- -----------------------
-- Write an object value as an entity
-- -----------------------
procedure Write_Entity (Stream : in out Output_Stream;
Name : in String;
Value : in Util.Beans.Objects.Object) is
begin
Stream.Write_Attribute (Name, Value);
end Write_Entity;
-- -----------------------
-- Start an array that will contain the specified number of elements
-- -----------------------
procedure Start_Array (Stream : in out Output_Stream;
Length : in Ada.Containers.Count_Type) is
pragma Unreferenced (Length);
begin
Node_Info_Stack.Push (Stream.Stack);
Stream.Write ('[');
end Start_Array;
-- -----------------------
-- Finishes an array
-- -----------------------
procedure End_Array (Stream : in out Output_Stream) is
begin
Node_Info_Stack.Pop (Stream.Stack);
Stream.Write (']');
end End_Array;
-- -----------------------
-- Get the current location (file and line) to report an error message.
-- -----------------------
function Get_Location (Handler : in Parser) return String is
begin
return Util.Strings.Image (Handler.Line_Number);
end Get_Location;
procedure Parse (Handler : in out Parser;
Stream : in out Util.Streams.Buffered.Buffered_Stream'Class) is
-- Put back a token in the buffer.
procedure Put_Back (P : in out Parser'Class;
Token : in Token_Type);
-- Parse the expression buffer to find the next token.
procedure Peek (P : in out Parser'Class;
Token : out Token_Type);
-- Parse a list of members
-- members ::= pair | pair ',' members
-- pair ::= string ':' value
-- value ::= string | number | object | array | true | false | null
procedure Parse_Pairs (P : in out Parser'Class);
-- Parse a value
-- value ::= string | number | object | array | true | false | null
procedure Parse_Value (P : in out Parser'Class;
Name : in String);
procedure Parse (P : in out Parser'Class);
procedure Parse (P : in out Parser'Class) is
Token : Token_Type;
begin
Peek (P, Token);
if Token /= T_LEFT_BRACE then
P.Error ("Missing '{'");
end if;
Parse_Pairs (P);
Peek (P, Token);
if Token /= T_RIGHT_BRACE then
P.Error ("Missing '}'");
end if;
end Parse;
-- ------------------------------
-- Parse a list of members
-- members ::= pair | pair ',' members
-- pair ::= string ':' value
-- value ::= string | number | object | array | true | false | null
-- ------------------------------
procedure Parse_Pairs (P : in out Parser'Class) is
Current_Name : Unbounded_String;
Token : Token_Type;
begin
loop
Peek (P, Token);
if Token /= T_STRING then
Put_Back (P, Token);
return;
end if;
Current_Name := P.Token;
Peek (P, Token);
if Token /= T_COLON then
P.Error ("Missing ':'");
end if;
Parse_Value (P, To_String (Current_Name));
Peek (P, Token);
if Token /= T_COMMA then
Put_Back (P, Token);
return;
end if;
end loop;
end Parse_Pairs;
-- ------------------------------
-- Parse a value
-- value ::= string | number | object | array | true | false | null
-- ------------------------------
procedure Parse_Value (P : in out Parser'Class;
Name : in String) is
Token : Token_Type;
begin
Peek (P, Token);
case Token is
when T_LEFT_BRACE =>
P.Start_Object (Name);
Parse_Pairs (P);
Peek (P, Token);
if Token /= T_RIGHT_BRACE then
P.Error ("Missing '}'");
end if;
P.Finish_Object (Name);
--
when T_LEFT_BRACKET =>
P.Start_Array (Name);
Peek (P, Token);
if Token /= T_RIGHT_BRACKET then
Put_Back (P, Token);
loop
Parse_Value (P, Name);
Peek (P, Token);
exit when Token = T_RIGHT_BRACKET;
if Token /= T_COMMA then
P.Error ("Missing ']'");
end if;
end loop;
end if;
P.Finish_Array (Name);
when T_NULL =>
P.Set_Member (Name, Util.Beans.Objects.Null_Object);
when T_NUMBER =>
P.Set_Member (Name, Util.Beans.Objects.To_Object (P.Token));
when T_STRING =>
P.Set_Member (Name, Util.Beans.Objects.To_Object (P.Token));
when T_TRUE =>
P.Set_Member (Name, Util.Beans.Objects.To_Object (True));
when T_FALSE =>
P.Set_Member (Name, Util.Beans.Objects.To_Object (False));
when T_EOF =>
P.Error ("End of stream reached");
return;
when others =>
P.Error ("Invalid token");
end case;
end Parse_Value;
-- ------------------------------
-- Put back a token in the buffer.
-- ------------------------------
procedure Put_Back (P : in out Parser'Class;
Token : in Token_Type) is
begin
P.Pending_Token := Token;
end Put_Back;
-- ------------------------------
-- Parse the expression buffer to find the next token.
-- ------------------------------
procedure Peek (P : in out Parser'Class;
Token : out Token_Type) is
C, C1 : Character;
begin
-- If a token was put back, return it.
if P.Pending_Token /= T_EOF then
Token := P.Pending_Token;
P.Pending_Token := T_EOF;
return;
end if;
if P.Has_Pending_Char then
C := P.Pending_Char;
else
-- Skip white spaces
loop
Stream.Read (Char => C);
if C = Ada.Characters.Latin_1.LF then
P.Line_Number := P.Line_Number + 1;
else
exit when C /= ' '
and C /= Ada.Characters.Latin_1.CR and C /= Ada.Characters.Latin_1.HT;
end if;
end loop;
end if;
P.Has_Pending_Char := False;
-- See what we have and continue parsing.
case C is
-- Literal string using double quotes
-- Collect up to the end of the string and put
-- the result in the parser token result.
when '"' =>
Delete (P.Token, 1, Length (P.Token));
loop
Stream.Read (Char => C1);
if C1 = '\' then
Stream.Read (Char => C1);
case C1 is
when '"' | '\' | '/' =>
null;
when 'b' =>
C1 := Ada.Characters.Latin_1.BS;
when 'f' =>
C1 := Ada.Characters.Latin_1.VT;
when 'n' =>
C1 := Ada.Characters.Latin_1.LF;
when 'r' =>
C1 := Ada.Characters.Latin_1.CR;
when 't' =>
C1 := Ada.Characters.Latin_1.HT;
when 'u' =>
null;
when others =>
P.Error ("Invalid character '" & C1 & "' in \x sequence");
end case;
elsif C1 = C then
Token := T_STRING;
return;
end if;
Append (P.Token, C1);
end loop;
-- Number
when '-' | '0' .. '9' =>
Delete (P.Token, 1, Length (P.Token));
Append (P.Token, C);
loop
Stream.Read (Char => C);
exit when C not in '0' .. '9';
Append (P.Token, C);
end loop;
if C = '.' then
Append (P.Token, C);
loop
Stream.Read (Char => C);
exit when C not in '0' .. '9';
Append (P.Token, C);
end loop;
end if;
if C = 'e' or C = 'E' then
Append (P.Token, C);
Stream.Read (Char => C);
if C = '+' or C = '-' then
Append (P.Token, C);
Stream.Read (Char => C);
end if;
loop
Stream.Read (Char => C);
exit when C not in '0' .. '9';
Append (P.Token, C);
end loop;
end if;
if C /= ' ' and C /= Ada.Characters.Latin_1.HT then
P.Has_Pending_Char := True;
P.Pending_Char := C;
end if;
Token := T_NUMBER;
return;
-- Parse a name composed of letters or digits.
when 'a' .. 'z' | 'A' .. 'Z' =>
Delete (P.Token, 1, Length (P.Token));
Append (P.Token, C);
loop
Stream.Read (Char => C);
exit when not (C in 'a' .. 'z' or C in 'A' .. 'Z'
or C in '0' .. '9' or C = '_');
Append (P.Token, C);
end loop;
-- Putback the last character unless we can ignore it.
if C /= ' ' and C /= Ada.Characters.Latin_1.HT then
P.Has_Pending_Char := True;
P.Pending_Char := C;
end if;
-- and empty eq false ge gt le lt ne not null true
case Element (P.Token, 1) is
when 'n' | 'N' =>
if P.Token = "null" then
Token := T_NULL;
return;
end if;
when 'f' | 'F' =>
if P.Token = "false" then
Token := T_FALSE;
return;
end if;
when 't' | 'T' =>
if P.Token = "true" then
Token := T_TRUE;
return;
end if;
when others =>
null;
end case;
Token := T_UNKNOWN;
return;
when '{' =>
Token := T_LEFT_BRACE;
return;
when '}' =>
Token := T_RIGHT_BRACE;
return;
when '[' =>
Token := T_LEFT_BRACKET;
return;
when ']' =>
Token := T_RIGHT_BRACKET;
return;
when ':' =>
Token := T_COLON;
return;
when ',' =>
Token := T_COMMA;
return;
when others =>
Token := T_UNKNOWN;
return;
end case;
exception
when Ada.IO_Exceptions.Data_Error =>
Token := T_EOF;
return;
end Peek;
begin
Parser'Class (Handler).Start_Object ("");
Parse (Handler);
Parser'Class (Handler).Finish_Object ("");
end Parse;
end Util.Serialize.IO.JSON;
|
Fix parsing and mapping of JSON
|
Fix parsing and mapping of JSON
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
36fd34a8a41f2aa099688422ab85971b109d0a01
|
regtests/util-streams-buffered-lzma-tests.adb
|
regtests/util-streams-buffered-lzma-tests.adb
|
-----------------------------------------------------------------------
-- util-streams-buffered-lzma-tests -- Unit tests for encoding buffered streams
-- Copyright (C) 2018 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Test_Caller;
with Util.Streams.Files;
with Util.Streams.Texts;
with Ada.Streams.Stream_IO;
package body Util.Streams.Buffered.Lzma.Tests is
use Util.Tests;
use Util.Streams.Files;
use Ada.Streams.Stream_IO;
package Caller is new Util.Test_Caller (Test, "Streams.Buffered.Lzma");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test Util.Streams.Buffered.Lzma.Write",
Test_Compress_Stream'Access);
end Add_Tests;
procedure Test_Compress_Stream (T : in out Test) is
Stream : aliased File_Stream;
Buffer : aliased Util.Streams.Buffered.Lzma.Compress_Stream;
Print : Util.Streams.Texts.Print_Stream;
Path : constant String := Util.Tests.Get_Test_Path ("regtests/result/test-stream.lzma");
Expect : constant String := Util.Tests.Get_Path ("regtests/expect/test-stream.lzma");
begin
Stream.Create (Mode => Out_File, Name => Path);
Buffer.Initialize (Output => Stream'Unchecked_Access,
Size => 1024,
Format => Util.Encoders.BASE_64);
Print.Initialize (Output => Buffer'Unchecked_Access, Size => 5);
for I in 1 .. 32 loop
Print.Write ("abcd");
Print.Write (" fghij");
Print.Write (ASCII.LF);
end loop;
Print.Flush;
Stream.Close;
Util.Tests.Assert_Equal_Files (T => T,
Expect => Expect,
Test => Path,
Message => "LZMA stream");
end Test_Compress_Stream;
end Util.Streams.Buffered.Lzma.Tests;
|
-----------------------------------------------------------------------
-- util-streams-buffered-lzma-tests -- Unit tests for encoding buffered streams
-- Copyright (C) 2018 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Test_Caller;
with Util.Streams.Files;
with Util.Streams.Texts;
with Ada.Streams.Stream_IO;
package body Util.Streams.Buffered.Lzma.Tests is
use Util.Tests;
use Util.Streams.Files;
use Ada.Streams.Stream_IO;
package Caller is new Util.Test_Caller (Test, "Streams.Buffered.Lzma");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test Util.Streams.Buffered.Lzma.Write",
Test_Compress_Stream'Access);
Caller.Add_Test (Suite, "Test Util.Streams.Buffered.Lzma.Write (2)",
Test_Compress_File_Stream'Access);
end Add_Tests;
procedure Test_Compress_Stream (T : in out Test) is
Stream : aliased File_Stream;
Buffer : aliased Util.Streams.Buffered.Lzma.Compress_Stream;
Print : Util.Streams.Texts.Print_Stream;
Path : constant String := Util.Tests.Get_Test_Path ("regtests/result/test-stream.lzma");
Expect : constant String := Util.Tests.Get_Path ("regtests/expect/test-stream.lzma");
begin
Stream.Create (Mode => Out_File, Name => Path);
Buffer.Initialize (Output => Stream'Unchecked_Access,
Size => 1024,
Format => Util.Encoders.BASE_64);
Print.Initialize (Output => Buffer'Unchecked_Access, Size => 5);
for I in 1 .. 32 loop
Print.Write ("abcd");
Print.Write (" fghij");
Print.Write (ASCII.LF);
end loop;
Print.Flush;
Stream.Close;
Util.Tests.Assert_Equal_Files (T => T,
Expect => Expect,
Test => Path,
Message => "LZMA stream");
end Test_Compress_Stream;
procedure Test_Compress_File_Stream (T : in out Test) is
Stream : aliased File_Stream;
In_Stream : aliased File_Stream;
Buffer : aliased Util.Streams.Buffered.Lzma.Compress_Stream;
Print : Util.Streams.Texts.Print_Stream;
Path : constant String := Util.Tests.Get_Test_Path ("regtests/result/test-big-stream.lzma");
Expect : constant String := Util.Tests.Get_Path ("regtests/expect/test-big-stream.lzma");
begin
In_Stream.Open (Ada.Streams.Stream_IO.In_File,
Util.Tests.Get_Path ("regtests/files/test-big-stream.bin"));
Stream.Create (Mode => Out_File, Name => Path);
Buffer.Initialize (Output => Stream'Unchecked_Access,
Size => 32768,
Format => Util.Encoders.BASE_64);
Util.Streams.Copy (From => In_Stream, Into => Buffer);
Buffer.Flush;
Buffer.Close;
Util.Tests.Assert_Equal_Files (T => T,
Expect => Expect,
Test => Path,
Message => "LZMA stream");
end Test_Compress_File_Stream;
end Util.Streams.Buffered.Lzma.Tests;
|
Implement the Test_Compress_File_Stream unit test and register it
|
Implement the Test_Compress_File_Stream unit test and register it
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
a66916341f53e0c795184d5f7613689a21971415
|
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
|
Letractively/ada-gen,Letractively/ada-gen,Letractively/ada-gen,Letractively/ada-gen
|
cd977034fc25f1cc71dbd4ccb652c49cd7a3f2af
|
src/tests/ahven/util-xunit.ads
|
src/tests/ahven/util-xunit.ads
|
-----------------------------------------------------------------------
-- util-xunit - Unit tests on top of AHven
-- Copyright (C) 2011, 2018 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ahven;
with Ahven.Framework;
with Ahven.Results;
with Ada.Strings.Unbounded;
with GNAT.Source_Info;
-- The <b>Util.XUnit</b> package exposes a common package definition used by the Ada testutil
-- library. This implementation exposes an implementation on top of Ahven.
--
-- Ahven is written by Tero Koskinen and licensed under permissive ISC license.
-- See http://ahven.stronglytyped.org/
package Util.XUnit is
type Status is (Success, Failure);
subtype Message_String is String;
subtype Test_Suite is Ahven.Framework.Test_Suite;
type Access_Test_Suite is access all Test_Suite;
type Test_Access is access all Ahven.Framework.Test_Case'Class;
type Test_Object;
type Test_Object_Access is access all Test_Object;
type Test_Object is record
Test : Test_Access;
Next : Test_Object_Access;
end record;
-- Register a test object in the test suite.
procedure Register (T : in Test_Object_Access);
-- Build a message from a string (Adaptation for AUnit API).
function Format (S : in String) return Message_String;
-- Build a message with the source and line number.
function Build_Message (Message : in String;
Source : in String;
Line : in Natural) return String;
-- ------------------------------
-- A simple test case
-- ------------------------------
type Test_Case is abstract new Ahven.Framework.Test_Case with null record;
overriding
procedure Initialize (T : in out Test_Case);
procedure Assert (T : in Test_Case;
Condition : in Boolean;
Message : in String := "Test failed";
Source : in String := GNAT.Source_Info.File;
Line : in Natural := GNAT.Source_Info.Line);
-- Return the name of the test case.
overriding
function Get_Name (T : Test_Case) return String;
-- Test case name (this is the AUnit function that must be implemented).
function Name (T : in Test_Case) return Message_String is abstract;
-- Perform the test (AUnit function to implement).
procedure Run_Test (T : in out Test_Case) is abstract;
-- ------------------------------
-- A test with fixture
-- ------------------------------
type Test is new Ahven.Framework.Test_Case with null record;
-- Check that the value matches what we expect.
procedure Assert (T : in Test;
Condition : in Boolean;
Message : in String := "Test failed";
Source : String := GNAT.Source_Info.File;
Line : Natural := GNAT.Source_Info.Line);
-- Report passes, skips, failures, and errors from the result collection.
procedure Report_Results (Result : in Ahven.Results.Result_Collection;
Time : in Duration);
-- The main testsuite program. This launches the tests, collects the
-- results, create performance logs and set the program exit status
-- according to the testsuite execution status.
generic
with function Suite return Access_Test_Suite;
procedure Harness (Output : in Ada.Strings.Unbounded.Unbounded_String;
XML : in Boolean;
Result : out Status);
end Util.XUnit;
|
-----------------------------------------------------------------------
-- util-xunit - Unit tests on top of AHven
-- Copyright (C) 2011, 2018, 2019 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ahven;
with Ahven.Framework;
with Ahven.Results;
with GNAT.Source_Info;
-- The <b>Util.XUnit</b> package exposes a common package definition used by the Ada testutil
-- library. This implementation exposes an implementation on top of Ahven.
--
-- Ahven is written by Tero Koskinen and licensed under permissive ISC license.
-- See http://ahven.stronglytyped.org/
package Util.XUnit is
type Status is (Success, Failure);
subtype Message_String is String;
subtype Test_Suite is Ahven.Framework.Test_Suite;
type Access_Test_Suite is access all Test_Suite;
type Test_Access is access all Ahven.Framework.Test_Case'Class;
type Test_Object;
type Test_Object_Access is access all Test_Object;
type Test_Object is record
Test : Test_Access;
Next : Test_Object_Access;
end record;
-- Register a test object in the test suite.
procedure Register (T : in Test_Object_Access);
-- Build a message from a string (Adaptation for AUnit API).
function Format (S : in String) return Message_String;
-- Build a message with the source and line number.
function Build_Message (Message : in String;
Source : in String;
Line : in Natural) return String;
-- ------------------------------
-- A simple test case
-- ------------------------------
type Test_Case is abstract new Ahven.Framework.Test_Case with null record;
overriding
procedure Initialize (T : in out Test_Case);
procedure Assert (T : in Test_Case;
Condition : in Boolean;
Message : in String := "Test failed";
Source : in String := GNAT.Source_Info.File;
Line : in Natural := GNAT.Source_Info.Line);
-- Return the name of the test case.
overriding
function Get_Name (T : Test_Case) return String;
-- Test case name (this is the AUnit function that must be implemented).
function Name (T : in Test_Case) return Message_String is abstract;
-- Perform the test (AUnit function to implement).
procedure Run_Test (T : in out Test_Case) is abstract;
-- ------------------------------
-- A test with fixture
-- ------------------------------
type Test is new Ahven.Framework.Test_Case with null record;
-- Check that the value matches what we expect.
procedure Assert (T : in Test;
Condition : in Boolean;
Message : in String := "Test failed";
Source : String := GNAT.Source_Info.File;
Line : Natural := GNAT.Source_Info.Line);
-- Report passes, skips, failures, and errors from the result collection.
procedure Report_Results (Result : in Ahven.Results.Result_Collection;
Label : in String;
Time : in Duration);
-- The main testsuite program. This launches the tests, collects the
-- results, create performance logs and set the program exit status
-- according to the testsuite execution status.
generic
with function Suite return Access_Test_Suite;
procedure Harness (Output : in String;
XML : in Boolean;
Label : in String;
Result : out Status);
end Util.XUnit;
|
Add Label parameter to Harness procedure
|
Add Label parameter to Harness procedure
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
9c165c2458476fc58b1502a52020adbfb239f820
|
samples/date.adb
|
samples/date.adb
|
-----------------------------------------------------------------------
-- date -- Print the date
-- 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.Calendar;
with Ada.Strings.Unbounded;
with GNAT.Command_Line;
with Util.Log.Loggers;
with Util.Dates.Formats;
with Util.Properties.Bundles;
procedure Date is
use Util.Log.Loggers;
use Ada.Strings.Unbounded;
use Util.Properties.Bundles;
use GNAT.Command_Line;
Log : constant Logger := Create ("log", "samples/log4j.properties");
Factory : Util.Properties.Bundles.Loader;
Bundle : Util.Properties.Bundles.Manager;
Locale : Unbounded_String := To_Unbounded_String ("en");
Result : Ada.Strings.Unbounded.Unbounded_String;
begin
-- Load the bundles from the current directory
Initialize (Factory, "samples/;bundles");
begin
Load_Bundle (Factory, "dates", To_String (Locale), Bundle);
exception
when NO_BUNDLE =>
Log.Error ("There is no bundle: {0}", "dates");
end;
loop
case Getopt ("h l: locale: help") is
when ASCII.NUL =>
exit;
when 'l' =>
Locale := To_Unbounded_String (Parameter);
when others =>
Log.Info ("Usage: date -l locale format");
return;
end case;
end loop;
loop
declare
Pattern : constant String := Get_Argument;
begin
exit when Pattern = "";
Util.Dates.Formats.Format (Pattern => Pattern,
Date => Ada.Calendar.Clock,
Bundle => Bundle,
Into => Result);
Ada.Text_IO.Put_Line (Ada.Strings.Unbounded.To_String (Result));
end;
end loop;
end Date;
|
-----------------------------------------------------------------------
-- date -- Print the date
-- 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.Calendar;
with Ada.Strings.Unbounded;
with GNAT.Command_Line;
with Util.Log.Loggers;
with Util.Dates.Formats;
with Util.Properties.Bundles;
procedure Date is
use type Ada.Calendar.Time;
use Util.Log.Loggers;
use Ada.Strings.Unbounded;
use Util.Properties.Bundles;
use GNAT.Command_Line;
Log : constant Logger := Create ("log", "samples/log4j.properties");
Factory : Util.Properties.Bundles.Loader;
Bundle : Util.Properties.Bundles.Manager;
Locale : Unbounded_String := To_Unbounded_String ("en");
Date : Ada.Calendar.Time := Ada.Calendar.Clock;
begin
-- Load the bundles from the current directory
Initialize (Factory, "samples/;bundles");
loop
case Getopt ("h l: locale: help") is
when ASCII.NUL =>
exit;
when 'l' =>
Locale := To_Unbounded_String (Parameter);
when others =>
Log.Info ("Usage: date -l locale format");
return;
end case;
end loop;
begin
Load_Bundle (Factory, "dates", To_String (Locale), Bundle);
exception
when NO_BUNDLE =>
Log.Error ("There is no bundle: {0}", "dates");
end;
loop
declare
Pattern : constant String := Get_Argument;
begin
exit when Pattern = "";
Ada.Text_IO.Put_Line (Util.Dates.Formats.Format (Pattern => Pattern,
Date => Date,
Bundle => Bundle));
end;
end loop;
end Date;
|
Update the date example so that -l option works
|
Update the date example so that -l option works
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
edb4576c9e0b25fca1c9aca0e5e30151bb326a81
|
src/util-commands-drivers.ads
|
src/util-commands-drivers.ads
|
-----------------------------------------------------------------------
-- util-commands-drivers -- Support to make command line tools
-- Copyright (C) 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Log;
private with Ada.Containers.Indefinite_Ordered_Maps;
-- == Command line driver ==
-- The <tt>Util.Commands.Drivers</tt> generic package provides a support to build command line
-- tools that have different commands identified by a name.
generic
-- The command execution context.
type Context_Type (<>) is limited private;
Driver_Name : String := "Drivers";
package Util.Commands.Drivers is
-- A simple command handler executed when the command with the given name is executed.
type Command_Handler is not null access procedure (Name : in String;
Args : in Argument_List'Class;
Context : in out Context_Type);
-- A more complex command handler that has a command instance as context.
type Command_Type is abstract tagged limited private;
type Command_Access is access all Command_Type'Class;
-- Execute the command with the arguments. The command name is passed with the command
-- arguments.
procedure Execute (Command : in Command_Type;
Name : in String;
Args : in Argument_List'Class;
Context : in out Context_Type) is abstract;
-- Write the help associated with the command.
procedure Help (Command : in Command_Type;
Context : in out Context_Type) is abstract;
-- Write the command usage.
procedure Usage (Command : in Command_Type);
-- Print a message for the command. The level indicates whether the message is an error,
-- warning or informational. The command name can be used to known the originator.
-- The <tt>Log</tt> operation is redirected to the driver's <tt>Log</tt> procedure.
procedure Log (Command : in Command_Type;
Level : in Util.Log.Level_Type;
Name : in String;
Message : in String);
type Help_Command_Type is new Command_Type with private;
-- Execute the help command with the arguments.
-- Print the help for every registered command.
overriding
procedure Execute (Command : in Help_Command_Type;
Name : in String;
Args : in Argument_List'Class;
Context : in out Context_Type);
-- Write the help associated with the command.
procedure Help (Command : in Help_Command_Type;
Context : in out Context_Type);
type Driver_Type is tagged limited private;
-- Register the command under the given name.
procedure Add_Command (Driver : in out Driver_Type;
Name : in String;
Command : in Command_Access);
-- Register the command under the given name.
procedure Add_Command (Driver : in out Driver_Type;
Name : in String;
Handler : in Command_Handler);
-- Find the command having the given name.
-- Returns null if the command was not found.
function Find_Command (Driver : in Driver_Type;
Name : in String) return Command_Access;
-- Execute the command registered under the given name.
procedure Execute (Driver : in Driver_Type;
Name : in String;
Args : in Argument_List'Class;
Context : in out Context_Type);
-- Print a message for the command. The level indicates whether the message is an error,
-- warning or informational. The command name can be used to known the originator.
procedure Log (Driver : in Driver_Type;
Level : in Util.Log.Level_Type;
Name : in String;
Message : in String);
private
package Command_Maps is
new Ada.Containers.Indefinite_Ordered_Maps (Key_Type => String,
Element_Type => Command_Access,
"<" => "<");
type Command_Type is abstract tagged limited record
Driver : access Driver_Type'Class;
end record;
type Help_Command_Type is new Command_Type with null record;
type Handler_Command_Type is new Command_Type with record
Handler : Command_Handler;
end record;
-- Execute the command with the arguments.
overriding
procedure Execute (Command : in Handler_Command_Type;
Name : in String;
Args : in Argument_List'Class;
Context : in out Context_Type);
-- Write the help associated with the command.
overriding
procedure Help (Command : in Handler_Command_Type;
Context : in out Context_Type);
type Driver_Type is tagged limited record
List : Command_Maps.Map;
end record;
end Util.Commands.Drivers;
|
-----------------------------------------------------------------------
-- util-commands-drivers -- Support to make command line tools
-- Copyright (C) 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Log;
private with Ada.Strings.Unbounded;
private with Ada.Containers.Indefinite_Ordered_Maps;
-- == Command line driver ==
-- The <tt>Util.Commands.Drivers</tt> generic package provides a support to build command line
-- tools that have different commands identified by a name.
generic
-- The command execution context.
type Context_Type (<>) is limited private;
Driver_Name : String := "Drivers";
package Util.Commands.Drivers is
-- A simple command handler executed when the command with the given name is executed.
type Command_Handler is not null access procedure (Name : in String;
Args : in Argument_List'Class;
Context : in out Context_Type);
-- A more complex command handler that has a command instance as context.
type Command_Type is abstract tagged limited private;
type Command_Access is access all Command_Type'Class;
-- Execute the command with the arguments. The command name is passed with the command
-- arguments.
procedure Execute (Command : in Command_Type;
Name : in String;
Args : in Argument_List'Class;
Context : in out Context_Type) is abstract;
-- Write the help associated with the command.
procedure Help (Command : in Command_Type;
Context : in out Context_Type) is abstract;
-- Write the command usage.
procedure Usage (Command : in Command_Type);
-- Print a message for the command. The level indicates whether the message is an error,
-- warning or informational. The command name can be used to known the originator.
-- The <tt>Log</tt> operation is redirected to the driver's <tt>Log</tt> procedure.
procedure Log (Command : in Command_Type;
Level : in Util.Log.Level_Type;
Name : in String;
Message : in String);
type Help_Command_Type is new Command_Type with private;
-- Execute the help command with the arguments.
-- Print the help for every registered command.
overriding
procedure Execute (Command : in Help_Command_Type;
Name : in String;
Args : in Argument_List'Class;
Context : in out Context_Type);
-- Write the help associated with the command.
procedure Help (Command : in Help_Command_Type;
Context : in out Context_Type);
type Driver_Type is tagged limited private;
-- Set the driver description printed in the usage.
procedure Set_Description (Driver : in out Driver_Type;
Description : in String);
-- Register the command under the given name.
procedure Add_Command (Driver : in out Driver_Type;
Name : in String;
Command : in Command_Access);
-- Register the command under the given name.
procedure Add_Command (Driver : in out Driver_Type;
Name : in String;
Handler : in Command_Handler);
-- Find the command having the given name.
-- Returns null if the command was not found.
function Find_Command (Driver : in Driver_Type;
Name : in String) return Command_Access;
-- Execute the command registered under the given name.
procedure Execute (Driver : in Driver_Type;
Name : in String;
Args : in Argument_List'Class;
Context : in out Context_Type);
-- Print a message for the command. The level indicates whether the message is an error,
-- warning or informational. The command name can be used to known the originator.
procedure Log (Driver : in Driver_Type;
Level : in Util.Log.Level_Type;
Name : in String;
Message : in String);
private
package Command_Maps is
new Ada.Containers.Indefinite_Ordered_Maps (Key_Type => String,
Element_Type => Command_Access,
"<" => "<");
type Command_Type is abstract tagged limited record
Driver : access Driver_Type'Class;
end record;
type Help_Command_Type is new Command_Type with null record;
type Handler_Command_Type is new Command_Type with record
Handler : Command_Handler;
end record;
-- Execute the command with the arguments.
overriding
procedure Execute (Command : in Handler_Command_Type;
Name : in String;
Args : in Argument_List'Class;
Context : in out Context_Type);
-- Write the help associated with the command.
overriding
procedure Help (Command : in Handler_Command_Type;
Context : in out Context_Type);
type Driver_Type is tagged limited record
List : Command_Maps.Map;
Desc : Ada.Strings.Unbounded.Unbounded_String;
end record;
end Util.Commands.Drivers;
|
Declare the Set_Description procedure to associate a description to the driver and have it printed in the usage
|
Declare the Set_Description procedure to associate a description to the driver and have it printed in the usage
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
bafdd21564a420f0465386036914828464913f83
|
src/util-texts-transforms.adb
|
src/util-texts-transforms.adb
|
-----------------------------------------------------------------------
-- Util-texts -- Various Text Transformation Utilities
-- Copyright (C) 2001, 2002, 2003, 2009, 2010, 2011, 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Interfaces;
package body Util.Texts.Transforms is
type Code is mod 2**32;
Conversion : constant String (1 .. 16) := "0123456789ABCDEF";
procedure Put_Dec (Into : in out Stream;
Value : in Code);
procedure To_Hex (Into : in out Stream;
Value : in Code);
procedure Put (Into : in out Stream;
Value : in String) is
begin
for I in Value'Range loop
Put (Into, Value (I));
end loop;
end Put;
-- ------------------------------
-- Write in the output stream the value as a \uNNNN encoding form.
-- ------------------------------
procedure To_Hex (Into : in out Stream;
Value : in Char) is
begin
To_Hex (Into, Code (Char'Pos (Value)));
end To_Hex;
-- ------------------------------
-- Write in the output stream the value as a \uNNNN encoding form.
-- ------------------------------
procedure To_Hex (Into : in out Stream;
Value : in Code) is
S : String (1 .. 6) := (1 => '\', 2 => 'u', others => '0');
P : Code := Value;
N : Code;
I : Positive := S'Last;
begin
while P /= 0 loop
N := P mod 16;
P := P / 16;
S (I) := Conversion (Positive'Val (N + 1));
exit when I = 1;
I := I - 1;
end loop;
Put (Into, S);
end To_Hex;
procedure Put_Dec (Into : in out Stream;
Value : in Code) is
S : String (1 .. 9) := (others => '0');
P : Code := Value;
N : Code;
I : Positive := S'Last;
begin
while P /= 0 loop
N := P mod 10;
P := P / 10;
S (I) := Conversion (Positive'Val (N + 1));
exit when P = 0;
I := I - 1;
end loop;
Put (Into, S (I .. S'Last));
end Put_Dec;
-- ------------------------------
-- Capitalize the string into the result stream.
-- ------------------------------
procedure Capitalize (Content : in Input;
Into : in out Stream) is
Upper : Boolean := True;
C : Code;
begin
for I in Content'Range loop
if Upper then
C := Char'Pos (To_Upper (Content (I)));
Upper := False;
else
C := Char'Pos (To_Lower (Content (I)));
if C = Character'Pos ('_') or C = Character'Pos ('.') or C = Character'Pos (':')
or C = Character'Pos (';') or C = Character'Pos (',') or C = Character'Pos (' ') then
Upper := True;
end if;
end if;
Put (Into, Character'Val (C));
end loop;
end Capitalize;
-- ------------------------------
-- Capitalize the string
-- ------------------------------
function Capitalize (Content : Input) return Input is
Result : Stream;
begin
Capitalize (Content, Result);
return To_Input (Result);
end Capitalize;
-- ------------------------------
-- Translate the input string into an upper case string in the result stream.
-- ------------------------------
procedure To_Upper_Case (Content : in Input;
Into : in out Stream) is
C : Code;
begin
for I in Content'Range loop
C := Char'Pos (To_Upper (Content (I)));
Put (Into, Character'Val (C));
end loop;
end To_Upper_Case;
-- ------------------------------
-- Translate the input string into an upper case string.
-- ------------------------------
function To_Upper_Case (Content : Input) return Input is
Result : Input (Content'Range);
begin
for I in Content'Range loop
Result (I) := To_Upper (Content (I));
end loop;
return Result;
end To_Upper_Case;
-- ------------------------------
-- Translate the input string into a lower case string in the result stream.
-- ------------------------------
procedure To_Lower_Case (Content : in Input;
Into : in out Stream) is
C : Code;
begin
for I in Content'Range loop
C := Char'Pos (To_Lower (Content (I)));
Put (Into, Character'Val (C));
end loop;
end To_Lower_Case;
-- ------------------------------
-- Translate the input string into a lower case string in the result stream.
-- ------------------------------
function To_Lower_Case (Content : Input) return Input is
Result : Input (Content'Range);
begin
for I in Content'Range loop
Result (I) := To_Lower (Content (I));
end loop;
return Result;
end To_Lower_Case;
procedure Escape_Java_Script (Content : in Input;
Into : in out Stream) is
begin
Escape_Java (Content => Content, Into => Into,
Escape_Single_Quote => True);
end Escape_Java_Script;
function Escape_Java_Script (Content : Input) return Input is
Result : Stream;
begin
Escape_Java (Content => Content,
Into => Result,
Escape_Single_Quote => True);
return To_Input (Result);
end Escape_Java_Script;
procedure Escape_Java (Content : in Input;
Into : in out Stream) is
begin
Escape_Java (Content => Content, Into => Into,
Escape_Single_Quote => False);
end Escape_Java;
function Escape_Java (Content : Input) return Input is
Result : Stream;
begin
Escape_Java (Content => Content,
Into => Result,
Escape_Single_Quote => False);
return To_Input (Result);
end Escape_Java;
procedure Escape_Java (Content : in Input;
Escape_Single_Quote : in Boolean;
Into : in out Stream) is
C : Code;
begin
for I in Content'Range loop
C := Char'Pos (Content (I));
if C < 16#20# then
if C = 16#0A# then
Put (Into, '\');
Put (Into, 'n');
elsif C = 16#0D# then
Put (Into, '\');
Put (Into, 'r');
elsif C = 16#08# then
Put (Into, '\');
Put (Into, 'b');
elsif C = 16#09# then
Put (Into, '\');
Put (Into, 't');
elsif C = 16#0C# then
Put (Into, '\');
Put (Into, 'f');
else
To_Hex (Into, C);
end if;
elsif C = 16#27# then
if Escape_Single_Quote then
Put (Into, '\');
end if;
Put (Into, Character'Val (C));
elsif C = 16#22# then
Put (Into, '\');
Put (Into, Character'Val (C));
elsif C = 16#5C# then
Put (Into, '\');
Put (Into, Character'Val (C));
elsif C >= 16#100# then
To_Hex (Into, C);
else
Put (Into, Character'Val (C));
end if;
end loop;
end Escape_Java;
function Escape_Xml (Content : Input) return Input is
Result : Stream;
begin
Escape_Xml (Content => Content,
Into => Result);
return To_Input (Result);
end Escape_Xml;
-- Escape the content into the result stream using the XML
-- escape rules:
-- '<' -> '<'
-- '>' -> '>'
-- ''' -> '''
-- '&' -> '&'
-- -> '&#nnn;' if Character'Pos >= 128
procedure Escape_Xml (Content : in Input;
Into : in out Stream) is
C : Code;
begin
for I in Content'Range loop
C := Char'Pos (Content (I));
if C = Character'Pos ('<') then
Put (Into, "<");
elsif C = Character'Pos ('>') then
Put (Into, ">");
elsif C = Character'Pos ('&') then
Put (Into, "&");
elsif C = Character'Pos (''') then
Put (Into, "'");
elsif C > 16#7F# then
Put (Into, '&');
Put (Into, '#');
Put_Dec (Into, C);
Put (Into, ';');
else
Put (Into, Character'Val (C));
end if;
end loop;
end Escape_Xml;
-- ------------------------------
-- Translate the XML entity represented by <tt>Entity</tt> into an UTF-8 sequence
-- in the output stream.
-- ------------------------------
procedure Translate_Xml_Entity (Entity : in Input;
Into : in out Stream) is
begin
if Entity (Entity'First) = Char'Val (Character'Pos ('&'))
and then Entity (Entity'Last) = Char'Val (Character'Pos (';')) then
case Char'Pos (Entity (Entity'First + 1)) is
when Character'Pos ('l') =>
if Entity'Length = 4
and then Entity (Entity'First + 2) = Char'Val (Character'Pos ('t')) then
Put (Into, '<');
return;
end if;
when Character'Pos ('g') =>
if Entity'Length = 4
and then Entity (Entity'First + 2) = Char'Val (Character'Pos ('t')) then
Put (Into, '>');
return;
end if;
when Character'Pos ('a') =>
if Entity'Length = 5
and then Entity (Entity'First + 2) = Char'Val (Character'Pos ('m'))
and then Entity (Entity'First + 3) = Char'Val (Character'Pos ('p')) then
Put (Into, '&');
return;
end if;
if Entity'Length = 6
and then Entity (Entity'First + 2) = Char'Val (Character'Pos ('p'))
and then Entity (Entity'First + 3) = Char'Val (Character'Pos ('o'))
and then Entity (Entity'First + 4) = Char'Val (Character'Pos ('s')) then
Put (Into, ''');
return;
end if;
when Character'Pos ('q') =>
if Entity'Length = 6
and then Entity (Entity'First + 2) = Char'Val (Character'Pos ('u'))
and then Entity (Entity'First + 3) = Char'Val (Character'Pos ('o'))
and then Entity (Entity'First + 4) = Char'Val (Character'Pos ('t')) then
Put (Into, '"');
return;
end if;
when Character'Pos ('#') =>
declare
use Interfaces;
V : Unsigned_32 := 0;
C : Code;
begin
if Entity (Entity'First + 2) = Char'Val (Character'Pos ('x')) then
for I in Entity'First + 3 .. Entity'Last - 1 loop
C := Char'Pos (Entity (I));
if C >= Character'Pos ('0') and C <= Character'Pos ('9') then
V := (V * 16) + Unsigned_32 (C - Character'Pos ('0'));
elsif C >= Character'Pos ('a') and C <= Character'Pos ('z') then
V := (V * 16) + 10 + Unsigned_32 (C - Character'Pos ('a'));
elsif C >= Character'Pos ('A') and C <= Character'Pos ('Z') then
V := (V * 16) + 10 + Unsigned_32 (C - Character'Pos ('A'));
end if;
end loop;
else
for I in Entity'First + 2 .. Entity'Last - 1 loop
C := Char'Pos (Entity (I));
if C >= Character'Pos ('0') and C <= Character'Pos ('9') then
V := (V * 10) + Unsigned_32 (C - Character'Pos ('0'));
end if;
end loop;
end if;
if V <= 16#007F# then
Put (Into, Character'Val (V));
return;
elsif V <= 16#07FF# then
Put (Into, Character'Val (16#C0# or Interfaces.Shift_Right (V, 6)));
Put (Into, Character'Val (16#80# or (V and 16#03F#)));
return;
elsif V <= 16#0FFFF# then
Put (Into, Character'Val (16#D0# or Shift_Right (V, 12)));
Put (Into, Character'Val (16#80# or (Shift_Right (V, 6) and 16#03F#)));
Put (Into, Character'Val (16#80# or (V and 16#03F#)));
return;
elsif V <= 16#10FFFF# then
Put (Into, Character'Val (16#E0# or Shift_Right (V, 18)));
Put (Into, Character'Val (16#80# or (Shift_Right (V, 12) and 16#03F#)));
Put (Into, Character'Val (16#80# or (Shift_Right (V, 6) and 16#03F#)));
Put (Into, Character'Val (16#80# or (V and 16#03F#)));
return;
end if;
end;
when others =>
null;
end case;
end if;
-- Invalid entity.
end Translate_Xml_Entity;
-- ------------------------------
-- Unescape the XML entities from the content into the result stream.
-- For each XML entity found, call the <tt>Translator</tt> procedure who is responsible
-- for writing the result in the stream. The XML entity starts with '&' and ends with ';'.
-- The '&' and ';' are part of the entity when given to the translator. If the trailing
-- ';' is not part of the entity, it means the entity was truncated or the end of input
-- stream is reached.
-- ------------------------------
procedure Unescape_Xml (Content : in Input;
Translator : not null access
procedure (Entity : in Input;
Into : in out Stream) := Translate_Xml_Entity'Access;
Into : in out Stream) is
MAX_ENTITY_LENGTH : constant Positive := 30;
Entity : Input (1 .. MAX_ENTITY_LENGTH);
C : Code;
Pos : Natural := Content'First;
Last : Natural;
begin
while Pos <= Content'Last loop
C := Char'Pos (Content (Pos));
Pos := Pos + 1;
if C = Character'Pos ('&') then
Entity (Entity'First) := Char'Val (C);
Last := Entity'First;
while Pos <= Content'Last loop
C := Char'Pos (Content (Pos));
Pos := Pos + 1;
if Last < Entity'Last then
Last := Last + 1;
Entity (Last) := Char'Val (C);
end if;
exit when C = Character'Pos (';');
end loop;
Translator (Entity (Entity'First .. Last), Into);
else
Put (Into, Character'Val (C));
end if;
end loop;
end Unescape_Xml;
end Util.Texts.Transforms;
|
-----------------------------------------------------------------------
-- Util-texts -- Various Text Transformation Utilities
-- Copyright (C) 2001, 2002, 2003, 2009, 2010, 2011, 2012, 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Interfaces;
package body Util.Texts.Transforms is
type Code is mod 2**32;
Conversion : constant String (1 .. 16) := "0123456789ABCDEF";
procedure Put_Dec (Into : in out Stream;
Value : in Code);
procedure To_Hex (Into : in out Stream;
Value : in Code);
procedure Put (Into : in out Stream;
Value : in String) is
begin
for I in Value'Range loop
Put (Into, Value (I));
end loop;
end Put;
-- ------------------------------
-- Write in the output stream the value as a \uNNNN encoding form.
-- ------------------------------
procedure To_Hex (Into : in out Stream;
Value : in Char) is
begin
To_Hex (Into, Code (Char'Pos (Value)));
end To_Hex;
-- ------------------------------
-- Write in the output stream the value as a \uNNNN encoding form.
-- ------------------------------
procedure To_Hex (Into : in out Stream;
Value : in Code) is
S : String (1 .. 6) := (1 => '\', 2 => 'u', others => '0');
P : Code := Value;
N : Code;
I : Positive := S'Last;
begin
while P /= 0 loop
N := P mod 16;
P := P / 16;
S (I) := Conversion (Positive'Val (N + 1));
exit when I = 1;
I := I - 1;
end loop;
Put (Into, S);
end To_Hex;
procedure Put_Dec (Into : in out Stream;
Value : in Code) is
S : String (1 .. 9) := (others => '0');
P : Code := Value;
N : Code;
I : Positive := S'Last;
begin
while P /= 0 loop
N := P mod 10;
P := P / 10;
S (I) := Conversion (Positive'Val (N + 1));
exit when P = 0;
I := I - 1;
end loop;
Put (Into, S (I .. S'Last));
end Put_Dec;
-- ------------------------------
-- Capitalize the string into the result stream.
-- ------------------------------
procedure Capitalize (Content : in Input;
Into : in out Stream) is
Upper : Boolean := True;
C : Code;
begin
for I in Content'Range loop
if Upper then
C := Char'Pos (To_Upper (Content (I)));
Upper := False;
else
C := Char'Pos (To_Lower (Content (I)));
if C = Character'Pos ('_') or C = Character'Pos ('.') or C = Character'Pos (':')
or C = Character'Pos (';') or C = Character'Pos (',') or C = Character'Pos (' ')
then
Upper := True;
end if;
end if;
Put (Into, Character'Val (C));
end loop;
end Capitalize;
-- ------------------------------
-- Capitalize the string
-- ------------------------------
function Capitalize (Content : Input) return Input is
Upper : Boolean := True;
C : Code;
Result : Input (Content'Range);
begin
for I in Content'Range loop
if Upper then
C := Char'Pos (To_Upper (Content (I)));
Upper := False;
else
C := Char'Pos (To_Lower (Content (I)));
if C = Character'Pos ('_') or C = Character'Pos ('.') or C = Character'Pos (':')
or C = Character'Pos (';') or C = Character'Pos (',') or C = Character'Pos (' ')
then
Upper := True;
end if;
end if;
Result (I) := Char'Val (C);
end loop;
return Result;
end Capitalize;
-- ------------------------------
-- Translate the input string into an upper case string in the result stream.
-- ------------------------------
procedure To_Upper_Case (Content : in Input;
Into : in out Stream) is
C : Code;
begin
for I in Content'Range loop
C := Char'Pos (To_Upper (Content (I)));
Put (Into, Character'Val (C));
end loop;
end To_Upper_Case;
-- ------------------------------
-- Translate the input string into an upper case string.
-- ------------------------------
function To_Upper_Case (Content : Input) return Input is
Result : Input (Content'Range);
begin
for I in Content'Range loop
Result (I) := To_Upper (Content (I));
end loop;
return Result;
end To_Upper_Case;
-- ------------------------------
-- Translate the input string into a lower case string in the result stream.
-- ------------------------------
procedure To_Lower_Case (Content : in Input;
Into : in out Stream) is
C : Code;
begin
for I in Content'Range loop
C := Char'Pos (To_Lower (Content (I)));
Put (Into, Character'Val (C));
end loop;
end To_Lower_Case;
-- ------------------------------
-- Translate the input string into a lower case string in the result stream.
-- ------------------------------
function To_Lower_Case (Content : Input) return Input is
Result : Input (Content'Range);
begin
for I in Content'Range loop
Result (I) := To_Lower (Content (I));
end loop;
return Result;
end To_Lower_Case;
procedure Escape_Java_Script (Content : in Input;
Into : in out Stream) is
begin
Escape_Java (Content => Content, Into => Into,
Escape_Single_Quote => True);
end Escape_Java_Script;
procedure Escape_Java (Content : in Input;
Into : in out Stream) is
begin
Escape_Java (Content => Content, Into => Into,
Escape_Single_Quote => False);
end Escape_Java;
procedure Escape_Java (Content : in Input;
Escape_Single_Quote : in Boolean;
Into : in out Stream) is
C : Code;
begin
for I in Content'Range loop
C := Char'Pos (Content (I));
if C < 16#20# then
if C = 16#0A# then
Put (Into, '\');
Put (Into, 'n');
elsif C = 16#0D# then
Put (Into, '\');
Put (Into, 'r');
elsif C = 16#08# then
Put (Into, '\');
Put (Into, 'b');
elsif C = 16#09# then
Put (Into, '\');
Put (Into, 't');
elsif C = 16#0C# then
Put (Into, '\');
Put (Into, 'f');
else
To_Hex (Into, C);
end if;
elsif C = 16#27# then
if Escape_Single_Quote then
Put (Into, '\');
end if;
Put (Into, Character'Val (C));
elsif C = 16#22# then
Put (Into, '\');
Put (Into, Character'Val (C));
elsif C = 16#5C# then
Put (Into, '\');
Put (Into, Character'Val (C));
elsif C >= 16#100# then
To_Hex (Into, C);
else
Put (Into, Character'Val (C));
end if;
end loop;
end Escape_Java;
-- ------------------------------
-- Escape the content into the result stream using the XML
-- escape rules:
-- '<' -> '<'
-- '>' -> '>'
-- ''' -> '''
-- '&' -> '&'
-- -> '&#nnn;' if Character'Pos >= 128
-- ------------------------------
procedure Escape_Xml (Content : in Input;
Into : in out Stream) is
C : Code;
begin
for I in Content'Range loop
C := Char'Pos (Content (I));
if C = Character'Pos ('<') then
Put (Into, "<");
elsif C = Character'Pos ('>') then
Put (Into, ">");
elsif C = Character'Pos ('&') then
Put (Into, "&");
elsif C = Character'Pos (''') then
Put (Into, "'");
elsif C > 16#7F# then
Put (Into, '&');
Put (Into, '#');
Put_Dec (Into, C);
Put (Into, ';');
else
Put (Into, Character'Val (C));
end if;
end loop;
end Escape_Xml;
-- ------------------------------
-- Translate the XML entity represented by <tt>Entity</tt> into an UTF-8 sequence
-- in the output stream.
-- ------------------------------
procedure Translate_Xml_Entity (Entity : in Input;
Into : in out Stream) is
begin
if Entity (Entity'First) = Char'Val (Character'Pos ('&'))
and then Entity (Entity'Last) = Char'Val (Character'Pos (';'))
then
case Char'Pos (Entity (Entity'First + 1)) is
when Character'Pos ('l') =>
if Entity'Length = 4
and then Entity (Entity'First + 2) = Char'Val (Character'Pos ('t'))
then
Put (Into, '<');
return;
end if;
when Character'Pos ('g') =>
if Entity'Length = 4
and then Entity (Entity'First + 2) = Char'Val (Character'Pos ('t'))
then
Put (Into, '>');
return;
end if;
when Character'Pos ('a') =>
if Entity'Length = 5
and then Entity (Entity'First + 2) = Char'Val (Character'Pos ('m'))
and then Entity (Entity'First + 3) = Char'Val (Character'Pos ('p'))
then
Put (Into, '&');
return;
end if;
if Entity'Length = 6
and then Entity (Entity'First + 2) = Char'Val (Character'Pos ('p'))
and then Entity (Entity'First + 3) = Char'Val (Character'Pos ('o'))
and then Entity (Entity'First + 4) = Char'Val (Character'Pos ('s'))
then
Put (Into, ''');
return;
end if;
when Character'Pos ('q') =>
if Entity'Length = 6
and then Entity (Entity'First + 2) = Char'Val (Character'Pos ('u'))
and then Entity (Entity'First + 3) = Char'Val (Character'Pos ('o'))
and then Entity (Entity'First + 4) = Char'Val (Character'Pos ('t'))
then
Put (Into, '"');
return;
end if;
when Character'Pos ('#') =>
declare
use Interfaces;
V : Unsigned_32 := 0;
C : Code;
begin
if Entity (Entity'First + 2) = Char'Val (Character'Pos ('x')) then
for I in Entity'First + 3 .. Entity'Last - 1 loop
C := Char'Pos (Entity (I));
if C >= Character'Pos ('0') and C <= Character'Pos ('9') then
V := (V * 16) + Unsigned_32 (C - Character'Pos ('0'));
elsif C >= Character'Pos ('a') and C <= Character'Pos ('z') then
V := (V * 16) + 10 + Unsigned_32 (C - Character'Pos ('a'));
elsif C >= Character'Pos ('A') and C <= Character'Pos ('Z') then
V := (V * 16) + 10 + Unsigned_32 (C - Character'Pos ('A'));
end if;
end loop;
else
for I in Entity'First + 2 .. Entity'Last - 1 loop
C := Char'Pos (Entity (I));
if C >= Character'Pos ('0') and C <= Character'Pos ('9') then
V := (V * 10) + Unsigned_32 (C - Character'Pos ('0'));
end if;
end loop;
end if;
if V <= 16#007F# then
Put (Into, Character'Val (V));
return;
elsif V <= 16#07FF# then
Put (Into, Character'Val (16#C0# or Interfaces.Shift_Right (V, 6)));
Put (Into, Character'Val (16#80# or (V and 16#03F#)));
return;
elsif V <= 16#0FFFF# then
Put (Into, Character'Val (16#D0# or Shift_Right (V, 12)));
Put (Into, Character'Val (16#80# or (Shift_Right (V, 6) and 16#03F#)));
Put (Into, Character'Val (16#80# or (V and 16#03F#)));
return;
elsif V <= 16#10FFFF# then
Put (Into, Character'Val (16#E0# or Shift_Right (V, 18)));
Put (Into, Character'Val (16#80# or (Shift_Right (V, 12) and 16#03F#)));
Put (Into, Character'Val (16#80# or (Shift_Right (V, 6) and 16#03F#)));
Put (Into, Character'Val (16#80# or (V and 16#03F#)));
return;
end if;
end;
when others =>
null;
end case;
end if;
-- Invalid entity.
end Translate_Xml_Entity;
-- ------------------------------
-- Unescape the XML entities from the content into the result stream.
-- For each XML entity found, call the <tt>Translator</tt> procedure who is responsible
-- for writing the result in the stream. The XML entity starts with '&' and ends with ';'.
-- The '&' and ';' are part of the entity when given to the translator. If the trailing
-- ';' is not part of the entity, it means the entity was truncated or the end of input
-- stream is reached.
-- ------------------------------
procedure Unescape_Xml (Content : in Input;
Translator : not null access
procedure (Entity : in Input;
Into : in out Stream) := Translate_Xml_Entity'Access;
Into : in out Stream) is
MAX_ENTITY_LENGTH : constant Positive := 30;
Entity : Input (1 .. MAX_ENTITY_LENGTH);
C : Code;
Pos : Natural := Content'First;
Last : Natural;
begin
while Pos <= Content'Last loop
C := Char'Pos (Content (Pos));
Pos := Pos + 1;
if C = Character'Pos ('&') then
Entity (Entity'First) := Char'Val (C);
Last := Entity'First;
while Pos <= Content'Last loop
C := Char'Pos (Content (Pos));
Pos := Pos + 1;
if Last < Entity'Last then
Last := Last + 1;
Entity (Last) := Char'Val (C);
end if;
exit when C = Character'Pos (';');
end loop;
Translator (Entity (Entity'First .. Last), Into);
else
Put (Into, Character'Val (C));
end if;
end loop;
end Unescape_Xml;
end Util.Texts.Transforms;
|
Remove the functions which cannot be implemented for a Stream undefinite type
|
Remove the functions which cannot be implemented for a Stream undefinite type
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
e7d53cd2bfc7b64cb43ed113d3a7bd36e390643d
|
src/asf-sessions-factory.adb
|
src/asf-sessions-factory.adb
|
-----------------------------------------------------------------------
-- asf.sessions.factory -- ASF Sessions factory
-- Copyright (C) 2010, 2011, 2012, 2014 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Encoders.Base64;
with Util.Log.Loggers;
-- The <b>ASF.Sessions.Factory</b> package is a factory for creating, searching
-- and deleting sessions.
package body ASF.Sessions.Factory is
use Ada.Finalization;
use Ada.Strings.Unbounded;
-- The logger
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("ASF.Sessions.Factory");
-- ------------------------------
-- Allocate a unique and random session identifier. The default implementation
-- generates a 256 bit random number that it serializes as base64 in the string.
-- Upon successful completion, the sequence string buffer is allocated and
-- returned in <b>Id</b>. The buffer will be freed when the session is removed.
-- ------------------------------
procedure Allocate_Session_Id (Factory : in out Session_Factory;
Id : out Ada.Strings.Unbounded.String_Access) is
use Ada.Streams;
use Interfaces;
Rand : Stream_Element_Array (0 .. 4 * Factory.Id_Size - 1);
Buffer : Stream_Element_Array (0 .. 4 * 3 * Factory.Id_Size);
Encoder : Util.Encoders.Base64.Encoder;
Last : Stream_Element_Offset;
Encoded : Stream_Element_Offset;
begin
Factory.Lock.Write;
-- Generate the random sequence.
for I in 0 .. Factory.Id_Size - 1 loop
declare
Value : constant Unsigned_32 := Id_Random.Random (Factory.Random);
begin
Rand (4 * I) := Stream_Element (Value and 16#0FF#);
Rand (4 * I + 1) := Stream_Element (Shift_Right (Value, 8) and 16#0FF#);
Rand (4 * I + 2) := Stream_Element (Shift_Right (Value, 16) and 16#0FF#);
Rand (4 * I + 3) := Stream_Element (Shift_Right (Value, 24) and 16#0FF#);
end;
end loop;
Factory.Lock.Release_Write;
-- Encode the random stream in base64 and save it into the Id string.
Encoder.Transform (Data => Rand, Into => Buffer,
Last => Last, Encoded => Encoded);
Id := new String (1 .. Natural (Encoded + 1));
for I in 0 .. Encoded loop
Id (Natural (I + 1)) := Character'Val (Buffer (I));
end loop;
Log.Info ("Allocated session {0}", Id.all);
end Allocate_Session_Id;
-- ------------------------------
-- Create a new session
-- ------------------------------
procedure Create_Session (Factory : in out Session_Factory;
Result : out Session) is
Sess : Session;
Impl : constant Session_Record_Access
:= new Session_Record '(Ada.Finalization.Limited_Controlled with
Ref_Counter => Util.Concurrent.Counters.ONE,
Create_Time => Ada.Calendar.Clock,
Max_Inactive => Factory.Max_Inactive,
others => <>);
begin
Impl.Access_Time := Impl.Create_Time;
Sess.Impl := Impl;
Session_Factory'Class (Factory).Allocate_Session_Id (Impl.Id);
Factory.Lock.Write;
Factory.Sessions.Insert (Impl.Id.all'Access, Sess);
Factory.Lock.Release_Write;
Result := Sess;
end Create_Session;
-- ------------------------------
-- Deletes the session.
-- ------------------------------
procedure Delete_Session (Factory : in out Session_Factory;
Sess : in out Session) is
begin
null;
end Delete_Session;
-- ------------------------------
-- Finds the session knowing the session identifier.
-- If the session is found, the last access time is updated.
-- Otherwise, the null session object is returned.
-- ------------------------------
procedure Find_Session (Factory : in out Session_Factory;
Id : in String;
Result : out Session) is
begin
Result := Null_Session;
Factory.Lock.Read;
declare
Pos : constant Session_Maps.Cursor := Factory.Sessions.Find (Id'Unrestricted_Access);
begin
if Session_Maps.Has_Element (Pos) then
Result := Session_Maps.Element (Pos);
end if;
end;
Factory.Lock.Release_Read;
if Result.Is_Valid then
Result.Impl.Access_Time := Ada.Calendar.Clock;
Log.Info ("Found active session {0}", Id);
else
Log.Info ("Invalid session {0}", Id);
end if;
end Find_Session;
-- ------------------------------
-- Returns the maximum time interval, in seconds, that the servlet container will
-- keep this session open between client accesses. After this interval, the servlet
-- container will invalidate the session. The maximum time interval can be set with
-- the Set_Max_Inactive_Interval method.
-- A negative time indicates the session should never timeout.
-- ------------------------------
function Get_Max_Inactive_Interval (Factory : in Session_Factory) return Duration is
begin
return Factory.Max_Inactive;
end Get_Max_Inactive_Interval;
-- ------------------------------
-- Specifies the time, in seconds, between client requests before the servlet
-- container will invalidate this session. A negative time indicates the session
-- should never timeout.
-- ------------------------------
procedure Set_Max_Inactive_Interval (Factory : in out Session_Factory;
Interval : in Duration) is
begin
Factory.Max_Inactive := Interval;
end Set_Max_Inactive_Interval;
-- ------------------------------
-- Initialize the session factory.
-- ------------------------------
overriding
procedure Initialize (Factory : in out Session_Factory) is
begin
Id_Random.Reset (Factory.Random);
end Initialize;
end ASF.Sessions.Factory;
|
-----------------------------------------------------------------------
-- asf.sessions.factory -- ASF Sessions factory
-- Copyright (C) 2010, 2011, 2012, 2014 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Encoders.Base64;
with Util.Log.Loggers;
-- The <b>ASF.Sessions.Factory</b> package is a factory for creating, searching
-- and deleting sessions.
package body ASF.Sessions.Factory is
use Ada.Finalization;
use Ada.Strings.Unbounded;
-- The logger
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("ASF.Sessions.Factory");
-- ------------------------------
-- Allocate a unique and random session identifier. The default implementation
-- generates a 256 bit random number that it serializes as base64 in the string.
-- Upon successful completion, the sequence string buffer is allocated and
-- returned in <b>Id</b>. The buffer will be freed when the session is removed.
-- ------------------------------
procedure Allocate_Session_Id (Factory : in out Session_Factory;
Id : out Ada.Strings.Unbounded.String_Access) is
use Ada.Streams;
Rand : Stream_Element_Array (0 .. 4 * Factory.Id_Size - 1);
Buffer : Stream_Element_Array (0 .. 4 * 3 * Factory.Id_Size);
Encoder : Util.Encoders.Base64.Encoder;
Last : Stream_Element_Offset;
Encoded : Stream_Element_Offset;
begin
Factory.Sessions.Generate_Id (Rand);
-- Encode the random stream in base64 and save it into the Id string.
Encoder.Transform (Data => Rand, Into => Buffer,
Last => Last, Encoded => Encoded);
Id := new String (1 .. Natural (Encoded + 1));
for I in 0 .. Encoded loop
Id (Natural (I + 1)) := Character'Val (Buffer (I));
end loop;
Log.Info ("Allocated session {0}", Id.all);
end Allocate_Session_Id;
-- ------------------------------
-- Create a new session
-- ------------------------------
procedure Create_Session (Factory : in out Session_Factory;
Result : out Session) is
Sess : Session;
Impl : constant Session_Record_Access
:= new Session_Record '(Ada.Finalization.Limited_Controlled with
Ref_Counter => Util.Concurrent.Counters.ONE,
Create_Time => Ada.Calendar.Clock,
Max_Inactive => Factory.Max_Inactive,
others => <>);
begin
Impl.Access_Time := Impl.Create_Time;
Sess.Impl := Impl;
Session_Factory'Class (Factory).Allocate_Session_Id (Impl.Id);
Factory.Sessions.Insert (Sess);
Result := Sess;
end Create_Session;
-- ------------------------------
-- Deletes the session.
-- ------------------------------
procedure Delete_Session (Factory : in out Session_Factory;
Sess : in out Session) is
begin
null;
end Delete_Session;
-- ------------------------------
-- Finds the session knowing the session identifier.
-- If the session is found, the last access time is updated.
-- Otherwise, the null session object is returned.
-- ------------------------------
procedure Find_Session (Factory : in out Session_Factory;
Id : in String;
Result : out Session) is
begin
Result := Factory.Sessions.Find (Id);
if Result.Is_Valid then
Result.Impl.Access_Time := Ada.Calendar.Clock;
Log.Info ("Found active session {0}", Id);
else
Log.Info ("Invalid session {0}", Id);
end if;
end Find_Session;
-- ------------------------------
-- Returns the maximum time interval, in seconds, that the servlet container will
-- keep this session open between client accesses. After this interval, the servlet
-- container will invalidate the session. The maximum time interval can be set with
-- the Set_Max_Inactive_Interval method.
-- A negative time indicates the session should never timeout.
-- ------------------------------
function Get_Max_Inactive_Interval (Factory : in Session_Factory) return Duration is
begin
return Factory.Max_Inactive;
end Get_Max_Inactive_Interval;
-- ------------------------------
-- Specifies the time, in seconds, between client requests before the servlet
-- container will invalidate this session. A negative time indicates the session
-- should never timeout.
-- ------------------------------
procedure Set_Max_Inactive_Interval (Factory : in out Session_Factory;
Interval : in Duration) is
begin
Factory.Max_Inactive := Interval;
end Set_Max_Inactive_Interval;
-- ------------------------------
-- Initialize the session factory.
-- ------------------------------
overriding
procedure Initialize (Factory : in out Session_Factory) is
begin
Factory.Sessions.Initialize;
end Initialize;
protected body Session_Cache is
-- ------------------------------
-- Find the session in the session cache.
-- ------------------------------
function Find (Id : in String) return Session is
Pos : constant Session_Maps.Cursor := Sessions.Find (Id'Unrestricted_Access);
begin
if Session_Maps.Has_Element (Pos) then
return Session_Maps.Element (Pos);
else
return Null_Session;
end if;
end Find;
-- ------------------------------
-- Insert the session in the session cache.
-- ------------------------------
procedure Insert (Sess : in Session) is
begin
Sessions.Insert (Sess.Impl.Id.all'Access, Sess);
end Insert;
-- ------------------------------
-- Generate a random bitstream.
-- ------------------------------
procedure Generate_Id (Rand : out Ada.Streams.Stream_Element_Array) is
use Ada.Streams;
use Interfaces;
Size : Stream_Element_Offset := Rand'Length / 4;
begin
-- Generate the random sequence.
for I in 0 .. Size - 1 loop
declare
Value : constant Unsigned_32 := Id_Random.Random (Random);
begin
Rand (4 * I) := Stream_Element (Value and 16#0FF#);
Rand (4 * I + 1) := Stream_Element (Shift_Right (Value, 8) and 16#0FF#);
Rand (4 * I + 2) := Stream_Element (Shift_Right (Value, 16) and 16#0FF#);
Rand (4 * I + 3) := Stream_Element (Shift_Right (Value, 24) and 16#0FF#);
end;
end loop;
end Generate_Id;
-- ------------------------------
-- Initialize the random generator.
-- ------------------------------
procedure Initialize is
begin
Id_Random.Reset (Random);
end Initialize;
end Session_Cache;
end ASF.Sessions.Factory;
|
Use a protected type for the session cache management and session id generation
|
Use a protected type for the session cache management and session id generation
|
Ada
|
apache-2.0
|
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
|
5ed6489e71e0295ad277b1f35209540b5daa92d7
|
src/asf-rest.adb
|
src/asf-rest.adb
|
-----------------------------------------------------------------------
-- asf-rest -- REST Support
-- 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.Routes;
with ASF.Routes.Servlets.Rest;
with ASF.Servlets.Rest;
with Util.Log.Loggers;
package body ASF.Rest is
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("ASF.Rest");
-- ------------------------------
-- Get the permission index associated with the REST operation.
-- ------------------------------
function Get_Permission (Handler : in Descriptor)
return Security.Permissions.Permission_Index is
begin
return Handler.Permission;
end Get_Permission;
-- ------------------------------
-- Register the API descriptor in a list.
-- ------------------------------
procedure Register (List : in out Descriptor_Access;
Item : in Descriptor_Access) is
begin
Item.Next := List;
List := Item;
end Register;
-- ------------------------------
-- Register the list of API descriptors for a given servlet and a root path.
-- ------------------------------
procedure Register (Registry : in out ASF.Servlets.Servlet_Registry;
Name : in String;
URI : in String;
ELContext : in EL.Contexts.ELContext'Class;
List : in Descriptor_Access) is
procedure Insert (Route : in out ASF.Routes.Route_Type_Ref);
use type ASF.Routes.Route_Type_Access;
Item : Descriptor_Access := List;
procedure Insert (Route : in out ASF.Routes.Route_Type_Ref) is
R : constant ASF.Routes.Route_Type_Access := Route.Value;
D : ASF.Routes.Servlets.Rest.API_Route_Type_Access;
begin
if R /= null then
if not (R.all in ASF.Routes.Servlets.Rest.API_Route_Type'Class) then
Log.Error ("Route API for {0}/{1} already used by another page",
URI, Item.Pattern.all);
return;
end if;
D := ASF.Routes.Servlets.Rest.API_Route_Type (R.all)'Access;
else
D := ASF.Servlets.Rest.Create_Route (Registry, Name);
Route := ASF.Routes.Route_Type_Refs.Create (D.all'Access);
end if;
if D.Descriptors (Item.Method) /= null then
Log.Error ("Route API for {0}/{1} is already used", URI, Item.Pattern.all);
end if;
D.Descriptors (Item.Method) := Item;
end Insert;
begin
Log.Info ("Adding API route {0}", URI);
while Item /= null loop
Log.Debug ("Adding API route {0}/{1}", URI, Item.Pattern.all);
Registry.Add_Route (URI & "/" & Item.Pattern.all, ELContext, Insert'Access);
Item := Item.Next;
end loop;
end Register;
end ASF.Rest;
|
-----------------------------------------------------------------------
-- asf-rest -- REST Support
-- 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.Routes;
with ASF.Routes.Servlets.Rest;
with ASF.Servlets.Rest;
with EL.Contexts.Default;
with Util.Log.Loggers;
package body ASF.Rest is
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("ASF.Rest");
-- ------------------------------
-- Get the permission index associated with the REST operation.
-- ------------------------------
function Get_Permission (Handler : in Descriptor)
return Security.Permissions.Permission_Index is
begin
return Handler.Permission;
end Get_Permission;
-- ------------------------------
-- Register the API descriptor in a list.
-- ------------------------------
procedure Register (List : in out Descriptor_Access;
Item : in Descriptor_Access) is
begin
Item.Next := List;
List := Item;
end Register;
-- ------------------------------
-- Register the list of API descriptors for a given servlet and a root path.
-- ------------------------------
procedure Register (Registry : in out ASF.Servlets.Servlet_Registry;
Name : in String;
URI : in String;
ELContext : in EL.Contexts.ELContext'Class;
List : in Descriptor_Access) is
procedure Insert (Route : in out ASF.Routes.Route_Type_Ref);
use type ASF.Routes.Route_Type_Access;
Item : Descriptor_Access := List;
procedure Insert (Route : in out ASF.Routes.Route_Type_Ref) is
R : constant ASF.Routes.Route_Type_Access := Route.Value;
D : ASF.Routes.Servlets.Rest.API_Route_Type_Access;
begin
if R /= null then
if not (R.all in ASF.Routes.Servlets.Rest.API_Route_Type'Class) then
Log.Error ("Route API for {0}/{1} already used by another page",
URI, Item.Pattern.all);
return;
end if;
D := ASF.Routes.Servlets.Rest.API_Route_Type (R.all)'Access;
else
D := ASF.Servlets.Rest.Create_Route (Registry, Name);
Route := ASF.Routes.Route_Type_Refs.Create (D.all'Access);
end if;
if D.Descriptors (Item.Method) /= null then
Log.Error ("Route API for {0}/{1} is already used", URI, Item.Pattern.all);
end if;
D.Descriptors (Item.Method) := Item;
end Insert;
begin
Log.Info ("Adding API route {0}", URI);
while Item /= null loop
Log.Debug ("Adding API route {0}/{1}", URI, Item.Pattern.all);
Registry.Add_Route (URI & "/" & Item.Pattern.all, ELContext, Insert'Access);
Item := Item.Next;
end loop;
end Register;
-- Dispatch the request to the API handler.
overriding
procedure Dispatch (Handler : in Static_Descriptor;
Req : in out ASF.Rest.Request'Class;
Reply : in out ASF.Rest.Response'Class;
Stream : in out Output_Stream'Class) is
begin
Handler.Handler (Req, Reply, Stream);
end Dispatch;
-- Register the API definition in the servlet registry.
procedure Register (Registry : in out ASF.Servlets.Servlet_Registry'Class;
Definition : in Descriptor_Access) is
use type ASF.Routes.Route_Type_Access;
use type ASF.Servlets.Servlet_Access;
Dispatcher : constant ASF.Servlets.Request_Dispatcher
:= Registry.Get_Request_Dispatcher (Definition.Pattern.all);
Servlet : ASF.Servlets.Servlet_Access := ASF.Servlets.Get_Servlet (Dispatcher);
procedure Insert (Route : in out ASF.Routes.Route_Type_Ref) is
R : constant ASF.Routes.Route_Type_Access := Route.Value;
D : ASF.Routes.Servlets.Rest.API_Route_Type_Access;
begin
if R /= null then
if not (R.all in ASF.Routes.Servlets.Rest.API_Route_Type'Class) then
Log.Error ("Route API for {0} already used by another page",
Definition.Pattern.all);
return;
end if;
D := ASF.Routes.Servlets.Rest.API_Route_Type (R.all)'Access;
else
D := ASF.Servlets.Rest.Create_Route (Servlet);
Route := ASF.Routes.Route_Type_Refs.Create (D.all'Access);
end if;
if D.Descriptors (Definition.Method) /= null then
Log.Error ("Route API for {0} is already used", Definition.Pattern.all);
end if;
D.Descriptors (Definition.Method) := Definition;
end Insert;
Ctx : EL.Contexts.Default.Default_Context;
begin
if Servlet = null then
Log.Error ("Cannot register REST operation {0}: no REST servlet",
Definition.Pattern.all);
return;
end if;
Registry.Add_Route (Definition.Pattern.all, Ctx, Insert'Access);
end Register;
end ASF.Rest;
|
Implement the Dispatch and Register operation
|
Implement the Dispatch and Register operation
|
Ada
|
apache-2.0
|
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
|
9814e8c74faade8a218529f52b85ff40685a5d23
|
src/ado-sessions-factory.adb
|
src/ado-sessions-factory.adb
|
-----------------------------------------------------------------------
-- factory -- Session Factory
-- 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 ADO.Sequences.Hilo;
with ADO.Schemas.Entities;
with ADO.Queries.Loaders;
package body ADO.Sessions.Factory is
-- ------------------------------
-- Get a read-only session from the factory.
-- ------------------------------
function Get_Session (Factory : in Session_Factory) return Session is
R : Session;
S : constant Session_Record_Access := new Session_Record;
begin
R.Impl := S;
S.Entities := Factory.Entities;
S.Values := Factory.Cache_Values;
S.Queries := Factory.Queries'Unrestricted_Access;
Factory.Source.Create_Connection (S.Database);
return R;
end Get_Session;
-- ------------------------------
-- Get a read-only session from the session proxy.
-- If the session has been invalidated, raise the SESSION_EXPIRED exception.
-- ------------------------------
function Get_Session (Proxy : in Session_Record_Access) return Session is
R : Session;
begin
if Proxy = null then
raise ADO.Objects.SESSION_EXPIRED;
end if;
R.Impl := Proxy;
Util.Concurrent.Counters.Increment (R.Impl.Counter);
return R;
end Get_Session;
-- ------------------------------
-- Get a read-write session from the factory.
-- ------------------------------
function Get_Master_Session (Factory : in Session_Factory) return Master_Session is
R : Master_Session;
S : constant Session_Record_Access := new Session_Record;
begin
R.Impl := S;
R.Sequences := Factory.Sequences;
S.Entities := Factory.Entities;
S.Values := Factory.Cache_Values;
S.Queries := Factory.Queries'Unrestricted_Access;
Factory.Source.Create_Connection (S.Database);
return R;
end Get_Master_Session;
-- ------------------------------
-- Initialize the sequence factory associated with the session factory.
-- ------------------------------
procedure Initialize_Sequences (Factory : in out Session_Factory) is
use ADO.Sequences;
begin
Factory.Sequences := Factory.Seq_Factory'Unchecked_Access;
Set_Default_Generator (Factory.Seq_Factory,
ADO.Sequences.Hilo.Create_HiLo_Generator'Access,
Factory'Unchecked_Access);
end Initialize_Sequences;
-- ------------------------------
-- Create the session factory to connect to the database represented
-- by the data source.
-- ------------------------------
procedure Create (Factory : out Session_Factory;
Source : in ADO.Sessions.Sources.Data_Source) is
begin
Factory.Source := Source;
Factory.Entities := new ADO.Schemas.Entities.Entity_Cache;
Factory.Cache_Values := Factory.Cache'Unchecked_Access;
Factory.Cache.Add_Cache (ENTITY_CACHE_NAME, Factory.Entities.all'Access);
ADO.Queries.Loaders.Initialize (Factory.Queries, Factory.Source);
Initialize_Sequences (Factory);
if Factory.Source.Get_Database /= "" then
declare
S : Session := Factory.Get_Session;
begin
ADO.Schemas.Entities.Initialize (Factory.Entities.all, S);
end;
end if;
end Create;
-- ------------------------------
-- Create the session factory to connect to the database identified
-- by the URI.
-- ------------------------------
procedure Create (Factory : out Session_Factory;
URI : in String) is
begin
Factory.Source.Set_Connection (URI);
Factory.Entities := new ADO.Schemas.Entities.Entity_Cache;
Factory.Cache_Values := Factory.Cache'Unchecked_Access;
Factory.Cache.Add_Cache (ENTITY_CACHE_NAME, Factory.Entities.all'Access);
ADO.Queries.Loaders.Initialize (Factory.Queries, Factory.Source);
Initialize_Sequences (Factory);
if Factory.Source.Get_Database /= "" then
declare
S : Session := Factory.Get_Session;
begin
ADO.Schemas.Entities.Initialize (Factory.Entities.all, S);
end;
end if;
end Create;
end ADO.Sessions.Factory;
|
-----------------------------------------------------------------------
-- factory -- Session Factory
-- 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 ADO.Sequences.Hilo;
with ADO.Schemas.Entities;
with ADO.Queries.Loaders;
package body ADO.Sessions.Factory is
-- ------------------------------
-- Get a read-only session from the factory.
-- ------------------------------
function Get_Session (Factory : in Session_Factory) return Session is
R : Session;
S : constant Session_Record_Access := new Session_Record;
begin
R.Impl := S;
S.Entities := Factory.Entities;
S.Values := Factory.Cache_Values;
S.Queries := Factory.Queries'Unrestricted_Access;
Factory.Source.Create_Connection (S.Database);
return R;
end Get_Session;
-- ------------------------------
-- Get a read-only session from the session proxy.
-- If the session has been invalidated, raise the Session_Error exception.
-- ------------------------------
function Get_Session (Proxy : in Session_Record_Access) return Session is
R : Session;
begin
if Proxy = null then
raise Session_Error;
end if;
R.Impl := Proxy;
Util.Concurrent.Counters.Increment (R.Impl.Counter);
return R;
end Get_Session;
-- ------------------------------
-- Get a read-write session from the factory.
-- ------------------------------
function Get_Master_Session (Factory : in Session_Factory) return Master_Session is
R : Master_Session;
S : constant Session_Record_Access := new Session_Record;
begin
R.Impl := S;
R.Sequences := Factory.Sequences;
S.Entities := Factory.Entities;
S.Values := Factory.Cache_Values;
S.Queries := Factory.Queries'Unrestricted_Access;
Factory.Source.Create_Connection (S.Database);
return R;
end Get_Master_Session;
-- ------------------------------
-- Initialize the sequence factory associated with the session factory.
-- ------------------------------
procedure Initialize_Sequences (Factory : in out Session_Factory) is
use ADO.Sequences;
begin
Factory.Sequences := Factory.Seq_Factory'Unchecked_Access;
Set_Default_Generator (Factory.Seq_Factory,
ADO.Sequences.Hilo.Create_HiLo_Generator'Access,
Factory'Unchecked_Access);
end Initialize_Sequences;
-- ------------------------------
-- Create the session factory to connect to the database represented
-- by the data source.
-- ------------------------------
procedure Create (Factory : out Session_Factory;
Source : in ADO.Sessions.Sources.Data_Source) is
begin
Factory.Source := Source;
Factory.Entities := new ADO.Schemas.Entities.Entity_Cache;
Factory.Cache_Values := Factory.Cache'Unchecked_Access;
Factory.Cache.Add_Cache (ENTITY_CACHE_NAME, Factory.Entities.all'Access);
ADO.Queries.Loaders.Initialize (Factory.Queries, Factory.Source);
Initialize_Sequences (Factory);
if Factory.Source.Get_Database /= "" then
declare
S : Session := Factory.Get_Session;
begin
ADO.Schemas.Entities.Initialize (Factory.Entities.all, S);
end;
end if;
end Create;
-- ------------------------------
-- Create the session factory to connect to the database identified
-- by the URI.
-- ------------------------------
procedure Create (Factory : out Session_Factory;
URI : in String) is
begin
Factory.Source.Set_Connection (URI);
Factory.Entities := new ADO.Schemas.Entities.Entity_Cache;
Factory.Cache_Values := Factory.Cache'Unchecked_Access;
Factory.Cache.Add_Cache (ENTITY_CACHE_NAME, Factory.Entities.all'Access);
ADO.Queries.Loaders.Initialize (Factory.Queries, Factory.Source);
Initialize_Sequences (Factory);
if Factory.Source.Get_Database /= "" then
declare
S : Session := Factory.Get_Session;
begin
ADO.Schemas.Entities.Initialize (Factory.Entities.all, S);
end;
end if;
end Create;
end ADO.Sessions.Factory;
|
Raise the Session_Error exception instead of SESSION_EXPIRED
|
Raise the Session_Error exception instead of SESSION_EXPIRED
|
Ada
|
apache-2.0
|
stcarrez/ada-ado
|
bd0fa7ccf4bc5a4414de6a5d575d39fc207f52ef
|
src/asf-security-filters.adb
|
src/asf-security-filters.adb
|
-----------------------------------------------------------------------
-- security-filters -- Security filter
-- Copyright (C) 2011 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Util.Log.Loggers;
with ASF.Cookies;
with ASF.Applications.Main;
with Security.Contexts;
with Security.Policies.Urls;
package body ASF.Security.Filters is
use Util.Log;
-- The logger
Log : constant Loggers.Logger := Loggers.Create ("Security.Filters");
-- ------------------------------
-- Called by the servlet container to indicate to a servlet that the servlet
-- is being placed into service.
-- ------------------------------
procedure Initialize (Server : in out Auth_Filter;
Context : in ASF.Servlets.Servlet_Registry'Class) is
use ASF.Applications.Main;
begin
if Context in Application'Class then
Server.Set_Permission_Manager (Application'Class (Context).Get_Security_Manager);
end if;
end Initialize;
-- ------------------------------
-- Set the permission manager that must be used to verify the permission.
-- ------------------------------
procedure Set_Permission_Manager (Filter : in out Auth_Filter;
Manager : in Policies.Policy_Manager_Access) is
begin
Filter.Manager := Manager;
end Set_Permission_Manager;
-- ------------------------------
-- Filter the request to make sure the user is authenticated.
-- Invokes the <b>Do_Login</b> procedure if there is no user.
-- If a permission manager is defined, check that the user has the permission
-- to view the page. Invokes the <b>Do_Deny</b> procedure if the permission
-- is denied.
-- ------------------------------
procedure Do_Filter (F : in Auth_Filter;
Request : in out ASF.Requests.Request'Class;
Response : in out ASF.Responses.Response'Class;
Chain : in out ASF.Servlets.Filter_Chain) is
use Ada.Strings.Unbounded;
use Policies.Urls;
use type Policies.Policy_Manager_Access;
Session : ASF.Sessions.Session;
SID : Unbounded_String;
AID : Unbounded_String;
Auth : ASF.Principals.Principal_Access;
pragma Unreferenced (SID);
procedure Fetch_Cookie (Cookie : in ASF.Cookies.Cookie);
-- ------------------------------
-- Collect the AID and SID cookies.
-- ------------------------------
procedure Fetch_Cookie (Cookie : in ASF.Cookies.Cookie) is
Name : constant String := ASF.Cookies.Get_Name (Cookie);
begin
if Name = SID_COOKIE then
SID := To_Unbounded_String (ASF.Cookies.Get_Value (Cookie));
elsif Name = AID_COOKIE then
AID := To_Unbounded_String (ASF.Cookies.Get_Value (Cookie));
end if;
end Fetch_Cookie;
Context : aliased Contexts.Security_Context;
begin
Request.Iterate_Cookies (Fetch_Cookie'Access);
Session := Request.Get_Session (Create => True);
-- If the session does not have a principal, try to authenticate the user with
-- the auto-login cookie.
Auth := Session.Get_Principal;
if Auth = null then
Auth_Filter'Class (F).Authenticate (Request, Response, Session, To_String (AID), Auth);
if Auth /= null then
Session.Set_Principal (Auth);
end if;
end if;
-- No principal, redirect to the login page.
if Auth = null then
Auth_Filter'Class (F).Do_Login (Request, Response);
return;
end if;
-- A permission manager is installed, check that the user can display the page.
if F.Manager /= null then
Context.Set_Context (F.Manager, Auth.all'Access);
declare
URI : constant String := Request.Get_Path_Info;
Perm : constant Policies.URLs.URI_Permission (1, URI'Length)
:= URI_Permission '(1, Len => URI'Length, URI => URI);
begin
if not F.Manager.Has_Permission (Context, Perm) then
Log.Info ("Deny access on {0}", URI);
-- Auth_Filter'Class (F).Do_Deny (Request, Response);
-- return;
end if;
end;
end if;
-- Request is authorized, proceed to the next filter.
ASF.Servlets.Do_Filter (Chain => Chain,
Request => Request,
Response => Response);
end Do_Filter;
-- ------------------------------
-- Display or redirects the user to the login page. This procedure is called when
-- the user is not authenticated.
-- ------------------------------
procedure Do_Login (F : in Auth_Filter;
Request : in out ASF.Requests.Request'Class;
Response : in out ASF.Responses.Response'Class) is
begin
null;
end Do_Login;
-- ------------------------------
-- Display the forbidden access page. This procedure is called when the user is not
-- authorized to see the page. The default implementation returns the SC_FORBIDDEN error.
-- ------------------------------
procedure Do_Deny (F : in Auth_Filter;
Request : in out ASF.Requests.Request'Class;
Response : in out ASF.Responses.Response'Class) is
pragma Unreferenced (F, Request);
begin
Response.Set_Status (ASF.Responses.SC_FORBIDDEN);
end Do_Deny;
-- ------------------------------
-- Authenticate a user by using the auto-login cookie. This procedure is called if the
-- current session does not have any principal. Based on the request and the optional
-- auto-login cookie passed in <b>Auth_Id</b>, it should identify the user and return
-- a principal object. The principal object will be freed when the session is closed.
-- If the user cannot be authenticated, the returned principal should be null.
--
-- The default implementation returns a null principal.
-- ------------------------------
procedure Authenticate (F : in Auth_Filter;
Request : in out ASF.Requests.Request'Class;
Response : in out ASF.Responses.Response'Class;
Session : in ASF.Sessions.Session;
Auth_Id : in String;
Principal : out ASF.Principals.Principal_Access) is
pragma Unreferenced (F, Request, Response, Session, Auth_Id);
begin
Principal := null;
end Authenticate;
end ASF.Security.Filters;
|
-----------------------------------------------------------------------
-- security-filters -- Security filter
-- Copyright (C) 2011 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Util.Log.Loggers;
with ASF.Cookies;
with ASF.Applications.Main;
with Security.Contexts;
with Security.Policies.Urls;
package body ASF.Security.Filters is
use Util.Log;
-- The logger
Log : constant Loggers.Logger := Loggers.Create ("Security.Filters");
-- ------------------------------
-- Called by the servlet container to indicate to a servlet that the servlet
-- is being placed into service.
-- ------------------------------
procedure Initialize (Server : in out Auth_Filter;
Context : in ASF.Servlets.Servlet_Registry'Class) is
use ASF.Applications.Main;
begin
if Context in Application'Class then
Server.Set_Permission_Manager (Application'Class (Context).Get_Security_Manager);
end if;
end Initialize;
-- ------------------------------
-- Set the permission manager that must be used to verify the permission.
-- ------------------------------
procedure Set_Permission_Manager (Filter : in out Auth_Filter;
Manager : in Policies.Policy_Manager_Access) is
begin
Filter.Manager := Manager;
end Set_Permission_Manager;
-- ------------------------------
-- Filter the request to make sure the user is authenticated.
-- Invokes the <b>Do_Login</b> procedure if there is no user.
-- If a permission manager is defined, check that the user has the permission
-- to view the page. Invokes the <b>Do_Deny</b> procedure if the permission
-- is denied.
-- ------------------------------
procedure Do_Filter (F : in Auth_Filter;
Request : in out ASF.Requests.Request'Class;
Response : in out ASF.Responses.Response'Class;
Chain : in out ASF.Servlets.Filter_Chain) is
use Ada.Strings.Unbounded;
use Policies.Urls;
use type Policies.Policy_Manager_Access;
Session : ASF.Sessions.Session;
SID : Unbounded_String;
AID : Unbounded_String;
Auth : ASF.Principals.Principal_Access;
pragma Unreferenced (SID);
procedure Fetch_Cookie (Cookie : in ASF.Cookies.Cookie);
-- ------------------------------
-- Collect the AID and SID cookies.
-- ------------------------------
procedure Fetch_Cookie (Cookie : in ASF.Cookies.Cookie) is
Name : constant String := ASF.Cookies.Get_Name (Cookie);
begin
if Name = SID_COOKIE then
SID := To_Unbounded_String (ASF.Cookies.Get_Value (Cookie));
elsif Name = AID_COOKIE then
AID := To_Unbounded_String (ASF.Cookies.Get_Value (Cookie));
end if;
end Fetch_Cookie;
Context : aliased Contexts.Security_Context;
begin
Request.Iterate_Cookies (Fetch_Cookie'Access);
Session := Request.Get_Session (Create => True);
-- If the session does not have a principal, try to authenticate the user with
-- the auto-login cookie.
Auth := Session.Get_Principal;
if Auth = null then
Auth_Filter'Class (F).Authenticate (Request, Response, Session, To_String (AID), Auth);
if Auth /= null then
Session.Set_Principal (Auth);
end if;
end if;
-- No principal, redirect to the login page.
if Auth = null then
Auth_Filter'Class (F).Do_Login (Request, Response);
return;
end if;
-- A permission manager is installed, check that the user can display the page.
if F.Manager /= null then
Context.Set_Context (F.Manager, Auth.all'Access);
declare
URI : constant String := Request.Get_Path_Info;
Perm : constant Policies.URLs.URI_Permission (URI'Length)
:= URI_Permission '(Len => URI'Length, URI => URI);
begin
if not F.Manager.Has_Permission (Context, Perm) then
Log.Info ("Deny access on {0}", URI);
-- Auth_Filter'Class (F).Do_Deny (Request, Response);
-- return;
end if;
end;
end if;
-- Request is authorized, proceed to the next filter.
ASF.Servlets.Do_Filter (Chain => Chain,
Request => Request,
Response => Response);
end Do_Filter;
-- ------------------------------
-- Display or redirects the user to the login page. This procedure is called when
-- the user is not authenticated.
-- ------------------------------
procedure Do_Login (F : in Auth_Filter;
Request : in out ASF.Requests.Request'Class;
Response : in out ASF.Responses.Response'Class) is
begin
null;
end Do_Login;
-- ------------------------------
-- Display the forbidden access page. This procedure is called when the user is not
-- authorized to see the page. The default implementation returns the SC_FORBIDDEN error.
-- ------------------------------
procedure Do_Deny (F : in Auth_Filter;
Request : in out ASF.Requests.Request'Class;
Response : in out ASF.Responses.Response'Class) is
pragma Unreferenced (F, Request);
begin
Response.Set_Status (ASF.Responses.SC_FORBIDDEN);
end Do_Deny;
-- ------------------------------
-- Authenticate a user by using the auto-login cookie. This procedure is called if the
-- current session does not have any principal. Based on the request and the optional
-- auto-login cookie passed in <b>Auth_Id</b>, it should identify the user and return
-- a principal object. The principal object will be freed when the session is closed.
-- If the user cannot be authenticated, the returned principal should be null.
--
-- The default implementation returns a null principal.
-- ------------------------------
procedure Authenticate (F : in Auth_Filter;
Request : in out ASF.Requests.Request'Class;
Response : in out ASF.Responses.Response'Class;
Session : in ASF.Sessions.Session;
Auth_Id : in String;
Principal : out ASF.Principals.Principal_Access) is
pragma Unreferenced (F, Request, Response, Session, Auth_Id);
begin
Principal := null;
end Authenticate;
end ASF.Security.Filters;
|
Fix compilation
|
Fix compilation
|
Ada
|
apache-2.0
|
Letractively/ada-asf,Letractively/ada-asf,Letractively/ada-asf
|
5cd0f0b8fc5bb63258274176e4271aa08569e902
|
ARM/STM32/drivers/stm32-pwm.adb
|
ARM/STM32/drivers/stm32-pwm.adb
|
------------------------------------------------------------------------------
-- --
-- Copyright (C) 2015, AdaCore --
-- --
-- Redistribution and use in source and binary forms, with or without --
-- modification, are permitted provided that the following conditions are --
-- met: --
-- 1. Redistributions of source code must retain the above copyright --
-- notice, this list of conditions and the following disclaimer. --
-- 2. Redistributions in binary form must reproduce the above copyright --
-- notice, this list of conditions and the following disclaimer in --
-- the documentation and/or other materials provided with the --
-- distribution. --
-- 3. Neither the name of STMicroelectronics nor the names of its --
-- contributors may be used to endorse or promote products derived --
-- from this software without specific prior written permission. --
-- --
-- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS --
-- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT --
-- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR --
-- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT --
-- HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, --
-- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT --
-- LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, --
-- DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY --
-- THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT --
-- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE --
-- OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. --
-- --
------------------------------------------------------------------------------
with System; use System;
with STM32_SVD; use STM32_SVD;
with STM32.Device; use STM32.Device;
package body STM32.PWM is
subtype Hertz is Word;
procedure Compute_Prescalar_and_Period
(This : access Timer;
Requested_Frequency : Hertz;
Prescalar : out Word;
Period : out Word)
with Pre => Requested_Frequency > 0;
-- Computes the minimum prescaler and thus the maximum resolution for the
-- given timer, based on the system clocks and the requested frequency
function Has_APB2_Frequency (This : Timer) return Boolean;
-- timers 1, 8, 9, 10, 11
function Has_APB1_Frequency (This : Timer) return Boolean;
-- timers 3, 4, 6, 7, 12, 13, 14
procedure Configure_PWM_GPIO
(Output : GPIO_Point;
PWM_AF : GPIO_Alternate_Function);
--------------------
-- Set_Duty_Cycle --
--------------------
procedure Set_Duty_Cycle
(This : in out PWM_Modulator;
Channel : Timer_Channel;
Value : Percentage)
is
Pulse : Short;
begin
This.Outputs (Channel).Duty_Cycle := Value;
if Value = 0 then
Set_Compare_Value (This.Output_Timer.all, Channel, Short'(0));
else
Pulse := Short ((This.Timer_Period + 1) * Word (Value) / 100) - 1;
-- for a Value of 0, the computation of Pulse wraps around to
-- 65535, so we only compute it when not zero
Set_Compare_Value (This.Output_Timer.all, Channel, Pulse);
end if;
end Set_Duty_Cycle;
-------------------
-- Set_Duty_Time --
-------------------
procedure Set_Duty_Time
(This : in out PWM_Modulator;
Channel : Timer_Channel;
Value : Microseconds)
is
Pulse : Short;
Period : constant Word := This.Timer_Period + 1;
uS_Per_Period : constant Word := 1_000_000 / This.Frequency;
begin
if Value > uS_per_Period then
raise Invalid_Request with "duty time too high";
end if;
Pulse := Short ((Period * Value) / uS_per_Period) - 1;
Set_Compare_Value (This.Output_Timer.all, Channel, Pulse);
end Set_Duty_Time;
------------------------
-- Current_Duty_Cycle --
------------------------
function Current_Duty_Cycle
(This : PWM_Modulator;
Channel : Timer_Channel)
return Percentage
is
begin
return This.Outputs (Channel).Duty_Cycle;
end Current_Duty_Cycle;
------------------------------
-- Initialise_PWM_Modulator --
------------------------------
procedure Initialise_PWM_Modulator
(This : in out PWM_Modulator;
Requested_Frequency : Float;
PWM_Timer : not null access Timer;
PWM_AF : GPIO_Alternate_Function)
is
Prescalar : Word;
begin
This.Output_Timer := PWM_Timer;
This.AF := PWM_AF;
Enable_Clock (PWM_Timer.all);
Compute_Prescalar_and_Period
(PWM_Timer,
Requested_Frequency => Word (Requested_Frequency),
Prescalar => Prescalar,
Period => This.Timer_Period);
This.Timer_Period := This.Timer_Period - 1;
This.Frequency := Word (Requested_Frequency);
Configure
(PWM_Timer.all,
Prescaler => Short (Prescalar),
Period => This.Timer_Period,
Clock_Divisor => Div1,
Counter_Mode => Up);
Set_Autoreload_Preload (PWM_Timer.all, True);
Enable (PWM_Timer.all);
for Channel in Timer_Channel loop
This.Outputs (Channel).Attached := False;
end loop;
end Initialise_PWM_Modulator;
------------------------
-- Attach_PWM_Channel --
------------------------
procedure Attach_PWM_Channel
(This : in out PWM_Modulator;
Channel : Timer_Channel;
Point : GPIO_Point)
is
begin
This.Outputs (Channel).Attached := True;
Enable_CLock (Point);
Configure_PWM_GPIO (Point, This.AF);
Configure_Channel_Output
(This.Output_Timer.all,
Channel => Channel,
Mode => PWM1,
State => Disable,
Pulse => 0,
Polarity => High);
Set_Compare_Value (This.Output_Timer.all, Channel, Short (0));
end Attach_PWM_Channel;
procedure Enable_PWM_Channel
(This : in out PWM_Modulator;
Channel : Timer_Channel)
is
begin
Enable_Channel (This.Output_Timer.all, Channel);
end Enable_PWM_Channel;
procedure Disable_PWM_Channel
(This : in out PWM_Modulator;
Channel : Timer_Channel)
is
begin
Disable_Channel (This.Output_Timer.all, Channel);
end Disable_PWM_Channel;
--------------
-- Attached --
--------------
function Attached (This : PWM_Modulator; Channel : Timer_Channel) return Boolean is
(This.Outputs (Channel).Attached);
------------------------
-- Configure_PWM_GPIO --
------------------------
procedure Configure_PWM_GPIO
(Output : GPIO_Point;
PWM_AF : GPIO_Alternate_Function)
is
Configuration : GPIO_Port_Configuration;
begin
Configuration.Mode := Mode_AF;
Configuration.Output_Type := Push_Pull;
Configuration.Speed := Speed_100MHz;
Configuration.Resistors := Floating;
Configure_IO (Point => Output,
Config => Configuration);
Configure_Alternate_Function (Output, AF => PWM_AF);
Lock (Output);
end Configure_PWM_GPIO;
----------------------------------
-- Compute_Prescalar_and_Period --
----------------------------------
procedure Compute_Prescalar_And_Period
(This : access Timer;
Requested_Frequency : Hertz;
Prescalar : out Word;
Period : out Word)
is
Max_Prescalar : constant := 16#FFFF#;
Max_Period : Word;
Hardware_Frequency : Word;
Clocks : constant RCC_System_Clocks := System_Clock_Frequencies;
begin
if Has_APB1_Frequency (This.all) then
Hardware_Frequency := Clocks.TIMCLK1;
elsif Has_APB2_Frequency (This.all) then
Hardware_Frequency := Clocks.TIMCLK2;
else
raise Unknown_Timer;
end if;
if Has_32bit_Counter (This.all) then
Max_Period := 16#FFFF_FFFF#;
else
Max_Period := 16#FFFF#;
end if;
if Requested_Frequency > Hardware_Frequency then
raise Invalid_Request with "Freq too high";
end if;
Prescalar := 0;
loop
Period := Hardware_Frequency / (Prescalar + 1);
Period := Period / Requested_Frequency;
exit when not
((Period > Max_Period) and
(Prescalar <= Max_Prescalar));
Prescalar := Prescalar + 1;
end loop;
if Prescalar > Max_Prescalar then
raise Invalid_Request with "Freq too low";
end if;
end Compute_Prescalar_and_Period;
------------------------
-- Has_APB2_Frequency --
------------------------
function Has_APB2_Frequency (This : Timer) return Boolean is
(This'Address = STM32_SVD.TIM1_Base or
This'Address = STM32_SVD.TIM8_Base or
This'Address = STM32_SVD.TIM9_Base or
This'Address = STM32_SVD.TIM10_Base or
This'Address = STM32_SVD.TIM11_Base);
------------------------
-- Has_APB1_Frequency --
------------------------
function Has_APB1_Frequency (This : Timer) return Boolean is
(This'Address = STM32_SVD.TIM3_Base or
This'Address = STM32_SVD.TIM4_Base or
This'Address = STM32_SVD.TIM6_Base or
This'Address = STM32_SVD.TIM7_Base or
This'Address = STM32_SVD.TIM12_Base or
This'Address = STM32_SVD.TIM13_Base or
This'Address = STM32_SVD.TIM14_Base);
end STM32.PWM;
|
------------------------------------------------------------------------------
-- --
-- Copyright (C) 2015, AdaCore --
-- --
-- Redistribution and use in source and binary forms, with or without --
-- modification, are permitted provided that the following conditions are --
-- met: --
-- 1. Redistributions of source code must retain the above copyright --
-- notice, this list of conditions and the following disclaimer. --
-- 2. Redistributions in binary form must reproduce the above copyright --
-- notice, this list of conditions and the following disclaimer in --
-- the documentation and/or other materials provided with the --
-- distribution. --
-- 3. Neither the name of STMicroelectronics nor the names of its --
-- contributors may be used to endorse or promote products derived --
-- from this software without specific prior written permission. --
-- --
-- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS --
-- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT --
-- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR --
-- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT --
-- HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, --
-- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT --
-- LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, --
-- DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY --
-- THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT --
-- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE --
-- OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. --
-- --
------------------------------------------------------------------------------
with System; use System;
with STM32_SVD; use STM32_SVD;
with STM32.Device; use STM32.Device;
package body STM32.PWM is
subtype Hertz is Word;
procedure Compute_Prescalar_and_Period
(This : access Timer;
Requested_Frequency : Hertz;
Prescalar : out Word;
Period : out Word)
with Pre => Requested_Frequency > 0;
-- Computes the minimum prescaler and thus the maximum resolution for the
-- given timer, based on the system clocks and the requested frequency
function Has_APB2_Frequency (This : Timer) return Boolean;
-- timers 1, 8, 9, 10, 11
function Has_APB1_Frequency (This : Timer) return Boolean;
-- timers 3, 4, 6, 7, 12, 13, 14
procedure Configure_PWM_GPIO
(Output : GPIO_Point;
PWM_AF : GPIO_Alternate_Function);
--------------------
-- Set_Duty_Cycle --
--------------------
procedure Set_Duty_Cycle
(This : in out PWM_Modulator;
Channel : Timer_Channel;
Value : Percentage)
is
Pulse : Short;
begin
This.Outputs (Channel).Duty_Cycle := Value;
if Value = 0 then
Set_Compare_Value (This.Output_Timer.all, Channel, Short'(0));
else
Pulse := Short ((This.Timer_Period + 1) * Word (Value) / 100) - 1;
-- for a Value of 0, the computation of Pulse wraps around to
-- 65535, so we only compute it when not zero
Set_Compare_Value (This.Output_Timer.all, Channel, Pulse);
end if;
end Set_Duty_Cycle;
-------------------
-- Set_Duty_Time --
-------------------
procedure Set_Duty_Time
(This : in out PWM_Modulator;
Channel : Timer_Channel;
Value : Microseconds)
is
Pulse : Short;
Period : constant Word := This.Timer_Period + 1;
uS_Per_Period : constant Word := 1_000_000 / This.Frequency;
begin
if Value > uS_per_Period then
raise Invalid_Request with "duty time too high";
end if;
Pulse := Short ((Period * Value) / uS_per_Period) - 1;
Set_Compare_Value (This.Output_Timer.all, Channel, Pulse);
end Set_Duty_Time;
------------------------
-- Current_Duty_Cycle --
------------------------
function Current_Duty_Cycle
(This : PWM_Modulator;
Channel : Timer_Channel)
return Percentage
is
begin
return This.Outputs (Channel).Duty_Cycle;
end Current_Duty_Cycle;
------------------------------
-- Initialise_PWM_Modulator --
------------------------------
procedure Initialise_PWM_Modulator
(This : in out PWM_Modulator;
Requested_Frequency : Float;
PWM_Timer : not null access Timer;
PWM_AF : GPIO_Alternate_Function)
is
Prescalar : Word;
begin
This.Output_Timer := PWM_Timer;
This.AF := PWM_AF;
Enable_Clock (PWM_Timer.all);
Compute_Prescalar_and_Period
(PWM_Timer,
Requested_Frequency => Word (Requested_Frequency),
Prescalar => Prescalar,
Period => This.Timer_Period);
This.Timer_Period := This.Timer_Period - 1;
This.Frequency := Word (Requested_Frequency);
Configure
(PWM_Timer.all,
Prescaler => Short (Prescalar),
Period => This.Timer_Period,
Clock_Divisor => Div1,
Counter_Mode => Up);
Set_Autoreload_Preload (PWM_Timer.all, True);
if Advanced_Timer (This.Output_Timer.all) then
Enable_Main_Output (This.Output_Timer.all);
end if;
Enable (PWM_Timer.all);
for Channel in Timer_Channel loop
This.Outputs (Channel).Attached := False;
end loop;
end Initialise_PWM_Modulator;
------------------------
-- Attach_PWM_Channel --
------------------------
procedure Attach_PWM_Channel
(This : in out PWM_Modulator;
Channel : Timer_Channel;
Point : GPIO_Point)
is
begin
This.Outputs (Channel).Attached := True;
Enable_CLock (Point);
Configure_PWM_GPIO (Point, This.AF);
Configure_Channel_Output
(This.Output_Timer.all,
Channel => Channel,
Mode => PWM1,
State => Disable,
Pulse => 0,
Polarity => High);
Set_Compare_Value (This.Output_Timer.all, Channel, Short (0));
end Attach_PWM_Channel;
procedure Enable_PWM_Channel
(This : in out PWM_Modulator;
Channel : Timer_Channel)
is
begin
Enable_Channel (This.Output_Timer.all, Channel);
end Enable_PWM_Channel;
procedure Disable_PWM_Channel
(This : in out PWM_Modulator;
Channel : Timer_Channel)
is
begin
Disable_Channel (This.Output_Timer.all, Channel);
end Disable_PWM_Channel;
--------------
-- Attached --
--------------
function Attached (This : PWM_Modulator; Channel : Timer_Channel) return Boolean is
(This.Outputs (Channel).Attached);
------------------------
-- Configure_PWM_GPIO --
------------------------
procedure Configure_PWM_GPIO
(Output : GPIO_Point;
PWM_AF : GPIO_Alternate_Function)
is
Configuration : GPIO_Port_Configuration;
begin
Configuration.Mode := Mode_AF;
Configuration.Output_Type := Push_Pull;
Configuration.Speed := Speed_100MHz;
Configuration.Resistors := Floating;
Configure_IO (Point => Output,
Config => Configuration);
Configure_Alternate_Function (Output, AF => PWM_AF);
Lock (Output);
end Configure_PWM_GPIO;
----------------------------------
-- Compute_Prescalar_and_Period --
----------------------------------
procedure Compute_Prescalar_And_Period
(This : access Timer;
Requested_Frequency : Hertz;
Prescalar : out Word;
Period : out Word)
is
Max_Prescalar : constant := 16#FFFF#;
Max_Period : Word;
Hardware_Frequency : Word;
Clocks : constant RCC_System_Clocks := System_Clock_Frequencies;
begin
if Has_APB1_Frequency (This.all) then
Hardware_Frequency := Clocks.TIMCLK1;
elsif Has_APB2_Frequency (This.all) then
Hardware_Frequency := Clocks.TIMCLK2;
else
raise Unknown_Timer;
end if;
if Has_32bit_Counter (This.all) then
Max_Period := 16#FFFF_FFFF#;
else
Max_Period := 16#FFFF#;
end if;
if Requested_Frequency > Hardware_Frequency then
raise Invalid_Request with "Freq too high";
end if;
Prescalar := 0;
loop
Period := Hardware_Frequency / (Prescalar + 1);
Period := Period / Requested_Frequency;
exit when not
((Period > Max_Period) and
(Prescalar <= Max_Prescalar));
Prescalar := Prescalar + 1;
end loop;
if Prescalar > Max_Prescalar then
raise Invalid_Request with "Freq too low";
end if;
end Compute_Prescalar_and_Period;
------------------------
-- Has_APB2_Frequency --
------------------------
function Has_APB2_Frequency (This : Timer) return Boolean is
(This'Address = STM32_SVD.TIM1_Base or
This'Address = STM32_SVD.TIM8_Base or
This'Address = STM32_SVD.TIM9_Base or
This'Address = STM32_SVD.TIM10_Base or
This'Address = STM32_SVD.TIM11_Base);
------------------------
-- Has_APB1_Frequency --
------------------------
function Has_APB1_Frequency (This : Timer) return Boolean is
(This'Address = STM32_SVD.TIM3_Base or
This'Address = STM32_SVD.TIM4_Base or
This'Address = STM32_SVD.TIM6_Base or
This'Address = STM32_SVD.TIM7_Base or
This'Address = STM32_SVD.TIM12_Base or
This'Address = STM32_SVD.TIM13_Base or
This'Address = STM32_SVD.TIM14_Base);
end STM32.PWM;
|
Enable main output for advanced timers
|
STM32.PWM: Enable main output for advanced timers
|
Ada
|
bsd-3-clause
|
Fabien-Chouteau/Ada_Drivers_Library,simonjwright/Ada_Drivers_Library,Fabien-Chouteau/Ada_Drivers_Library,ellamosi/Ada_BMP_Library,AdaCore/Ada_Drivers_Library,lambourg/Ada_Drivers_Library,simonjwright/Ada_Drivers_Library,AdaCore/Ada_Drivers_Library
|
fffb6b8dfa701b1a66dde14f8532a4441e46a792
|
awa/src/awa-events-queues.adb
|
awa/src/awa-events-queues.adb
|
-----------------------------------------------------------------------
-- awa-events-queues -- AWA Event Queues
-- Copyright (C) 2012, 2019 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Unchecked_Deallocation;
with Util.Serialize.Mappers;
with AWA.Events.Queues.Fifos;
with AWA.Events.Queues.Persistents;
package body AWA.Events.Queues is
-- ------------------------------
-- Queue the event.
-- ------------------------------
procedure Enqueue (Into : in Queue_Ref;
Event : in AWA.Events.Module_Event'Class) is
begin
if not Into.Is_Null then
declare
Q : constant Queue_Info_Accessor := Into.Value;
begin
if Q.Queue /= null then
Q.Queue.Enqueue (Event);
end if;
end;
end if;
end Enqueue;
-- ------------------------------
-- Dequeue an event and process it with the <b>Process</b> procedure.
-- ------------------------------
procedure Dequeue (From : in Queue_Ref;
Process : access procedure (Event : in Module_Event'Class)) is
begin
if not From.Is_Null then
declare
Q : constant Queue_Info_Accessor := From.Value;
begin
if Q.Queue /= null then
From.Value.Queue.Dequeue (Process);
end if;
end;
end if;
end Dequeue;
-- ------------------------------
-- Returns true if the queue is available.
-- ------------------------------
function Has_Queue (Queue : in Queue_Ref'Class) return Boolean is
begin
return not Queue.Is_Null and then Queue.Value.Queue /= null;
end Has_Queue;
-- ------------------------------
-- Returns the queue name.
-- ------------------------------
function Get_Name (Queue : in Queue_Ref'Class) return String is
begin
if Queue.Is_Null then
return "";
else
return Queue.Value.Name;
end if;
end Get_Name;
-- ------------------------------
-- Get the model queue reference object.
-- Returns a null object if the queue is not persistent.
-- ------------------------------
function Get_Queue (Queue : in Queue_Ref'Class) return AWA.Events.Models.Queue_Ref is
begin
if Queue.Is_Null or else Queue.Value.Queue = null then
return AWA.Events.Models.Null_Queue;
else
return Queue.Value.Queue.Get_Queue;
end if;
end Get_Queue;
FIFO_QUEUE_TYPE : constant String := "fifo";
PERSISTENT_QUEUE_TYPE : constant String := "persist";
-- ------------------------------
-- Create the event queue identified by the name <b>Name</b>. The queue factory
-- identified by <b>Kind</b> is called to create the event queue instance.
-- Returns a reference to the queue.
-- ------------------------------
function Create_Queue (Name : in String;
Kind : in String;
Props : in EL.Beans.Param_Vectors.Vector;
Context : in EL.Contexts.ELContext'Class)
return Queue_Ref is
Result : Queue_Ref;
Q : constant Queue_Info_Access := new Queue_Info '(Util.Refs.Ref_Entity with
Length => Name'Length,
Name => Name,
others => <>);
begin
Queue_Refs.Ref (Result) := Queue_Refs.Create (Q);
if Kind = FIFO_QUEUE_TYPE then
Q.Queue := AWA.Events.Queues.Fifos.Create_Queue (Name, Props, Context);
elsif Kind = PERSISTENT_QUEUE_TYPE then
Q.Queue := AWA.Events.Queues.Persistents.Create_Queue (Name, Props, Context);
else
raise Util.Serialize.Mappers.Field_Error with "Invalid queue type: " & Kind;
end if;
return Result;
end Create_Queue;
function Null_Queue return Queue_Ref is
Result : Queue_Ref;
begin
return Result;
end Null_Queue;
-- ------------------------------
-- Finalize the referenced object. This is called before the object is freed.
-- ------------------------------
overriding
procedure Finalize (Object : in out Queue_Info) is
procedure Free is
new Ada.Unchecked_Deallocation (Object => Queue'Class,
Name => Queue_Access);
begin
if Object.Queue /= null then
Object.Queue.Finalize;
Free (Object.Queue);
end if;
end Finalize;
end AWA.Events.Queues;
|
-----------------------------------------------------------------------
-- awa-events-queues -- AWA Event Queues
-- Copyright (C) 2012, 2019, 2020 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Unchecked_Deallocation;
with Util.Serialize.Mappers;
with AWA.Events.Queues.Fifos;
with AWA.Events.Queues.Persistents;
with AWA.Events.Queues.Observers;
package body AWA.Events.Queues is
-- ------------------------------
-- Queue the event.
-- ------------------------------
procedure Enqueue (Into : in Queue_Ref;
Event : in AWA.Events.Module_Event'Class) is
begin
if not Into.Is_Null then
declare
Q : constant Queue_Info_Accessor := Into.Value;
begin
if Q.Queue /= null then
Q.Queue.Enqueue (Event);
Observers.Notify (Q.Listeners, Into);
end if;
end;
end if;
end Enqueue;
-- ------------------------------
-- Dequeue an event and process it with the <b>Process</b> procedure.
-- ------------------------------
procedure Dequeue (From : in Queue_Ref;
Process : access procedure (Event : in Module_Event'Class)) is
begin
if not From.Is_Null then
declare
Q : constant Queue_Info_Accessor := From.Value;
begin
if Q.Queue /= null then
From.Value.Queue.Dequeue (Process);
end if;
end;
end if;
end Dequeue;
-- ------------------------------
-- Add a listener that will be called each time an event is queued.
-- ------------------------------
procedure Add_Listener (Into : in Queue_Ref;
Listener : in Util.Listeners.Listener_Access) is
begin
if not Into.Is_Null then
declare
Q : constant Queue_Info_Accessor := Into.Value;
begin
Q.Listeners.Append (Listener);
end;
end if;
end Add_Listener;
-- ------------------------------
-- Returns true if the queue is available.
-- ------------------------------
function Has_Queue (Queue : in Queue_Ref'Class) return Boolean is
begin
return not Queue.Is_Null and then Queue.Value.Queue /= null;
end Has_Queue;
-- ------------------------------
-- Returns the queue name.
-- ------------------------------
function Get_Name (Queue : in Queue_Ref'Class) return String is
begin
if Queue.Is_Null then
return "";
else
return Queue.Value.Name;
end if;
end Get_Name;
-- ------------------------------
-- Get the model queue reference object.
-- Returns a null object if the queue is not persistent.
-- ------------------------------
function Get_Queue (Queue : in Queue_Ref'Class) return AWA.Events.Models.Queue_Ref is
begin
if Queue.Is_Null or else Queue.Value.Queue = null then
return AWA.Events.Models.Null_Queue;
else
return Queue.Value.Queue.Get_Queue;
end if;
end Get_Queue;
-- ------------------------------
-- Create the event queue identified by the name <b>Name</b>. The queue factory
-- identified by <b>Kind</b> is called to create the event queue instance.
-- Returns a reference to the queue.
-- ------------------------------
function Create_Queue (Name : in String;
Kind : in String;
Props : in EL.Beans.Param_Vectors.Vector;
Context : in EL.Contexts.ELContext'Class)
return Queue_Ref is
Result : Queue_Ref;
Q : constant Queue_Info_Access
:= new Queue_Info '(Util.Refs.Ref_Entity with
Length => Name'Length,
Name => Name,
others => <>);
begin
Queue_Refs.Ref (Result) := Queue_Refs.Create (Q);
if Kind = FIFO_QUEUE_TYPE then
Q.Queue := Queues.Fifos.Create_Queue (Name, Props, Context);
elsif Kind = PERSISTENT_QUEUE_TYPE then
Q.Queue := Queues.Persistents.Create_Queue (Name, Props, Context);
else
raise Util.Serialize.Mappers.Field_Error with "Invalid queue type: " & Kind;
end if;
return Result;
end Create_Queue;
function Null_Queue return Queue_Ref is
Result : Queue_Ref;
begin
return Result;
end Null_Queue;
-- ------------------------------
-- Finalize the referenced object. This is called before the object is freed.
-- ------------------------------
overriding
procedure Finalize (Object : in out Queue_Info) is
procedure Free is
new Ada.Unchecked_Deallocation (Object => Queue'Class,
Name => Queue_Access);
begin
if Object.Queue /= null then
Object.Queue.Finalize;
Free (Object.Queue);
end if;
end Finalize;
end AWA.Events.Queues;
|
Add Add_Listener procedure and call the observer Notify procedure when an event is posted
|
Add Add_Listener procedure and call the observer Notify procedure when an event is posted
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
bfc98c9deacc435bbd58cd7b95bd7b0f75da131f
|
awa/src/awa-oauth-filters.adb
|
awa/src/awa-oauth-filters.adb
|
-----------------------------------------------------------------------
-- awa-oauth-filters -- OAuth filter
-- Copyright (C) 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Security;
with Security.OAuth.Servers;
with Util.Beans.Objects;
with AWA.Applications;
with AWA.Services.Contexts;
package body AWA.OAuth.Filters is
-- Initialize the filter.
overriding
procedure Initialize (Filter : in out Auth_Filter;
Config : in ASF.Servlets.Filter_Config) is
begin
null;
end Initialize;
function Get_Access_Token (Req : in ASF.Requests.Request'Class) return String is
begin
return "";
end Get_Access_Token;
-- The Do_Filter method of the Filter is called by the container each time
-- a request/response pair is passed through the chain due to a client request
-- for a resource at the end of the chain. The Filter_Chain passed in to this
-- method allows the Filter to pass on the request and response to the next
-- entity in the chain.
--
-- Before passing the control to the next filter, initialize the service
-- context to give access to the current application, current user and
-- manage possible transaction rollbacks.
overriding
procedure Do_Filter (F : in Auth_Filter;
Request : in out ASF.Requests.Request'Class;
Response : in out ASF.Responses.Response'Class;
Chain : in out ASF.Servlets.Filter_Chain) is
use type AWA.OAuth.Services.Auth_Manager_Access;
use type ASF.Principals.Principal_Access;
type Context_Type is new AWA.Services.Contexts.Service_Context with null record;
-- Get the attribute registered under the given name in the HTTP session.
overriding
function Get_Session_Attribute (Ctx : in Context_Type;
Name : in String) return Util.Beans.Objects.Object;
-- Set the attribute registered under the given name in the HTTP session.
overriding
procedure Set_Session_Attribute (Ctx : in out Context_Type;
Name : in String;
Value : in Util.Beans.Objects.Object);
overriding
function Get_Session_Attribute (Ctx : in Context_Type;
Name : in String) return Util.Beans.Objects.Object is
pragma Unreferenced (Ctx);
begin
return Request.Get_Session.Get_Attribute (Name);
end Get_Session_Attribute;
-- Set the attribute registered under the given name in the HTTP session.
overriding
procedure Set_Session_Attribute (Ctx : in out Context_Type;
Name : in String;
Value : in Util.Beans.Objects.Object) is
pragma Unreferenced (Ctx);
S : ASF.Sessions.Session := Request.Get_Session;
begin
S.Set_Attribute (Name, Value);
end Set_Session_Attribute;
App : constant ASF.Servlets.Servlet_Registry_Access
:= ASF.Servlets.Get_Servlet_Context (Chain);
Bearer : constant String := Get_Access_Token (Request);
Auth : Security.Principal_Access;
Grant : Security.OAuth.Servers.Grant_Type;
begin
if F.Realm = null then
return;
end if;
F.Realm.Authenticate (Bearer, Grant);
declare
Context : aliased Context_Type;
Application : AWA.Applications.Application_Access;
begin
-- Get the application
if App.all in AWA.Applications.Application'Class then
Application := AWA.Applications.Application'Class (App.all)'Access;
else
Application := null;
end if;
-- Context.Set_Context (Application, Grant.Auth);
-- Give the control to the next chain up to the servlet.
ASF.Servlets.Do_Filter (Chain => Chain,
Request => Request,
Response => Response);
-- By leaving this scope, the active database transactions are rollbacked
-- (finalization of Service_Context)
end;
end Do_Filter;
end AWA.OAuth.Filters;
|
-----------------------------------------------------------------------
-- awa-oauth-filters -- OAuth filter
-- Copyright (C) 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Security;
with Security.OAuth.Servers;
with Util.Beans.Objects;
with ASF.Principals;
with AWA.Applications;
with AWA.Services.Contexts;
package body AWA.OAuth.Filters is
-- Initialize the filter.
overriding
procedure Initialize (Filter : in out Auth_Filter;
Config : in ASF.Servlets.Filter_Config) is
begin
null;
end Initialize;
function Get_Access_Token (Req : in ASF.Requests.Request'Class) return String is
begin
return "";
end Get_Access_Token;
-- The Do_Filter method of the Filter is called by the container each time
-- a request/response pair is passed through the chain due to a client request
-- for a resource at the end of the chain. The Filter_Chain passed in to this
-- method allows the Filter to pass on the request and response to the next
-- entity in the chain.
--
-- Before passing the control to the next filter, initialize the service
-- context to give access to the current application, current user and
-- manage possible transaction rollbacks.
overriding
procedure Do_Filter (F : in Auth_Filter;
Request : in out ASF.Requests.Request'Class;
Response : in out ASF.Responses.Response'Class;
Chain : in out ASF.Servlets.Filter_Chain) is
use type AWA.OAuth.Services.Auth_Manager_Access;
use type ASF.Principals.Principal_Access;
type Context_Type is new AWA.Services.Contexts.Service_Context with null record;
-- Get the attribute registered under the given name in the HTTP session.
overriding
function Get_Session_Attribute (Ctx : in Context_Type;
Name : in String) return Util.Beans.Objects.Object;
-- Set the attribute registered under the given name in the HTTP session.
overriding
procedure Set_Session_Attribute (Ctx : in out Context_Type;
Name : in String;
Value : in Util.Beans.Objects.Object);
overriding
function Get_Session_Attribute (Ctx : in Context_Type;
Name : in String) return Util.Beans.Objects.Object is
pragma Unreferenced (Ctx);
begin
return Request.Get_Session.Get_Attribute (Name);
end Get_Session_Attribute;
-- Set the attribute registered under the given name in the HTTP session.
overriding
procedure Set_Session_Attribute (Ctx : in out Context_Type;
Name : in String;
Value : in Util.Beans.Objects.Object) is
pragma Unreferenced (Ctx);
S : ASF.Sessions.Session := Request.Get_Session;
begin
S.Set_Attribute (Name, Value);
end Set_Session_Attribute;
App : constant ASF.Servlets.Servlet_Registry_Access
:= ASF.Servlets.Get_Servlet_Context (Chain);
Bearer : constant String := Get_Access_Token (Request);
Auth : Security.Principal_Access;
Grant : Security.OAuth.Servers.Grant_Type;
begin
if F.Realm = null then
return;
end if;
F.Realm.Authenticate (Bearer, Grant);
declare
Context : aliased Context_Type;
Application : AWA.Applications.Application_Access;
begin
-- Get the application
if App.all in AWA.Applications.Application'Class then
Application := AWA.Applications.Application'Class (App.all)'Access;
else
Application := null;
end if;
-- Context.Set_Context (Application, Grant.Auth);
-- Give the control to the next chain up to the servlet.
ASF.Servlets.Do_Filter (Chain => Chain,
Request => Request,
Response => Response);
-- By leaving this scope, the active database transactions are rollbacked
-- (finalization of Service_Context)
end;
end Do_Filter;
end AWA.OAuth.Filters;
|
Remove unused with clauses
|
Remove unused with clauses
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
6a9d87c13f140811741ddee849704b93d93f9cfe
|
awa/regtests/awa-testsuite.adb
|
awa/regtests/awa-testsuite.adb
|
-----------------------------------------------------------------------
-- Util testsuite - Util Testsuite
-- Copyright (C) 2009, 2010, 2011, 2012, 2013, 2014, 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with AWA.Users.Services.Tests;
with AWA.Users.Tests;
with AWA.Blogs.Modules.Tests;
with AWA.Helpers.Selectors.Tests;
with AWA.Storages.Services.Tests;
with AWA.Events.Services.Tests;
with AWA.Mail.Clients.Tests;
with AWA.Mail.Modules.Tests;
with AWA.Images.Services.Tests;
with AWA.Votes.Modules.Tests;
with AWA.Tags.Modules.Tests;
with AWA.Questions.Modules.Tests;
with AWA.Counters.Modules.Tests;
with AWA.Modules.Tests;
with ASF.Converters.Dates;
with AWA.Users.Modules;
with AWA.Mail.Modules;
with AWA.Blogs.Modules;
with AWA.Workspaces.Modules;
with AWA.Storages.Modules;
with AWA.Images.Modules;
with AWA.Questions.Modules;
with AWA.Votes.Modules;
with AWA.Tags.Modules;
with AWA.Changelogs.Modules;
with AWA.Counters.Modules;
with AWA.Converters.Dates;
with AWA.Tests;
with AWA.Services.Contexts;
with AWA.Jobs.Services.Tests;
with AWA.Jobs.Modules.Tests;
with AWA.Settings.Modules.Tests;
with AWA.Comments.Modules.Tests;
with AWA.Changelogs.Modules.Tests;
with AWA.Wikis.Modules.Tests;
with ASF.Server.Web;
with ASF.Server.Tests;
package body AWA.Testsuite is
Users : aliased AWA.Users.Modules.User_Module;
Workspaces : aliased AWA.Workspaces.Modules.Workspace_Module;
Mail : aliased AWA.Mail.Modules.Mail_Module;
Jobs : aliased AWA.Jobs.Modules.Job_Module;
Comments : aliased AWA.Comments.Modules.Comment_Module;
Blogs : aliased AWA.Blogs.Modules.Blog_Module;
Storages : aliased AWA.Storages.Modules.Storage_Module;
Images : aliased AWA.Images.Modules.Image_Module;
Questions : aliased AWA.Questions.Modules.Question_Module;
Votes : aliased AWA.Votes.Modules.Vote_Module;
Tags : aliased AWA.Tags.Modules.Tag_Module;
Settings : aliased AWA.Settings.Modules.Setting_Module;
Changelogs : aliased AWA.Changelogs.Modules.Changelog_Module;
Wikis : aliased AWA.Wikis.Modules.Wiki_Module;
Counters : aliased AWA.Counters.Modules.Counter_Module;
Date_Converter : aliased ASF.Converters.Dates.Date_Converter;
Rel_Date_Converter : aliased AWA.Converters.Dates.Relative_Date_Converter;
Tests : aliased Util.Tests.Test_Suite;
function Suite return Util.Tests.Access_Test_Suite is
Ret : constant Util.Tests.Access_Test_Suite := Tests'Access;
begin
AWA.Modules.Tests.Add_Tests (Ret);
AWA.Events.Services.Tests.Add_Tests (Ret);
AWA.Mail.Clients.Tests.Add_Tests (Ret);
AWA.Mail.Modules.Tests.Add_Tests (Ret);
AWA.Users.Services.Tests.Add_Tests (Ret);
AWA.Users.Tests.Add_Tests (Ret);
AWA.Counters.Modules.Tests.Add_Tests (Ret);
AWA.Helpers.Selectors.Tests.Add_Tests (Ret);
AWA.Jobs.Modules.Tests.Add_Tests (Ret);
AWA.Jobs.Services.Tests.Add_Tests (Ret);
AWA.Settings.Modules.Tests.Add_Tests (Ret);
AWA.Comments.Modules.Tests.Add_Tests (Ret);
AWA.Blogs.Modules.Tests.Add_Tests (Ret);
AWA.Storages.Services.Tests.Add_Tests (Ret);
AWA.Images.Services.Tests.Add_Tests (Ret);
AWA.Changelogs.Modules.Tests.Add_Tests (Ret);
AWA.Votes.Modules.Tests.Add_Tests (Ret);
AWA.Tags.Modules.Tests.Add_Tests (Ret);
AWA.Questions.Modules.Tests.Add_Tests (Ret);
AWA.Wikis.Modules.Tests.Add_Tests (Ret);
return Ret;
end Suite;
procedure Initialize (Props : in Util.Properties.Manager) is
begin
Initialize (null, Props, True);
end Initialize;
-- ------------------------------
-- Initialize the AWA test framework mockup.
-- ------------------------------
procedure Initialize (App : in AWA.Applications.Application_Access;
Props : in Util.Properties.Manager;
Add_Modules : in Boolean) is
use AWA.Applications;
begin
AWA.Tests.Initialize (App, Props, Add_Modules);
if Add_Modules then
declare
Application : constant Applications.Application_Access := AWA.Tests.Get_Application;
Ctx : AWA.Services.Contexts.Service_Context;
Users : constant AWA.Users.Modules.User_Module_Access := AWA.Testsuite.Users'Access;
begin
Ctx.Set_Context (Application, null);
Register (App => Application.all'Access,
Name => AWA.Users.Modules.NAME,
URI => "user",
Module => Users.all'Access);
Register (App => Application.all'Access,
Name => "mail",
URI => "mail",
Module => Mail'Access);
Register (App => Application.all'Access,
Name => "workspaces",
URI => "workspaces",
Module => Workspaces'Access);
Register (App => Application.all'Access,
Name => AWA.Counters.Modules.NAME,
URI => "counters",
Module => Counters'Access);
Register (App => Application.all'Access,
Name => AWA.Comments.Modules.NAME,
URI => "comments",
Module => Comments'Access);
Register (App => Application.all'Access,
Name => AWA.Storages.Modules.NAME,
URI => "storages",
Module => Storages'Access);
Register (App => Application.all'Access,
Name => AWA.Images.Modules.NAME,
URI => "images",
Module => Images'Access);
Register (App => Application.all'Access,
Name => AWA.Jobs.Modules.NAME,
URI => "jobs",
Module => Jobs'Access);
Register (App => Application.all'Access,
Name => AWA.Settings.Modules.NAME,
URI => "settings",
Module => Settings'Access);
Register (App => Application.all'Access,
Name => AWA.Votes.Modules.NAME,
URI => "votes",
Module => Votes'Access);
Register (App => Application.all'Access,
Name => AWA.Changelogs.Modules.NAME,
URI => "changelogs",
Module => Changelogs'Access);
Register (App => Application.all'Access,
Name => AWA.Tags.Modules.NAME,
URI => "tags",
Module => Tags'Access);
Register (App => Application.all'Access,
Name => AWA.Blogs.Modules.NAME,
URI => "blogs",
Module => Blogs'Access);
Register (App => Application.all'Access,
Name => AWA.Questions.Modules.NAME,
URI => "questions",
Module => Questions'Access);
Register (App => Application.all'Access,
Name => AWA.Wikis.Modules.NAME,
URI => "wikis",
Module => Wikis'Access);
Application.Start;
if Props.Exists ("test.server") then
declare
WS : ASF.Server.Web.AWS_Container;
begin
Application.Add_Converter (Name => "dateConverter",
Converter => Date_Converter'Access);
Application.Add_Converter (Name => "smartDateConverter",
Converter => Rel_Date_Converter'Access);
WS.Register_Application ("/asfunit", Application.all'Access);
WS.Start;
delay 6000.0;
end;
end if;
ASF.Server.Tests.Set_Context (Application.all'Access);
end;
end if;
end Initialize;
end AWA.Testsuite;
|
-----------------------------------------------------------------------
-- Util testsuite - Util Testsuite
-- Copyright (C) 2009, 2010, 2011, 2012, 2013, 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 AWA.Users.Services.Tests;
with AWA.Users.Tests;
with AWA.Blogs.Modules.Tests;
with AWA.Helpers.Selectors.Tests;
with AWA.Storages.Services.Tests;
with AWA.Events.Services.Tests;
with AWA.Mail.Clients.Tests;
with AWA.Mail.Modules.Tests;
with AWA.Images.Services.Tests;
with AWA.Votes.Modules.Tests;
with AWA.Tags.Modules.Tests;
with AWA.Questions.Modules.Tests;
with AWA.Counters.Modules.Tests;
with AWA.Modules.Tests;
with ASF.Converters.Dates;
with AWA.Users.Modules;
with AWA.Mail.Modules;
with AWA.Blogs.Modules;
with AWA.Workspaces.Modules;
with AWA.Storages.Modules;
with AWA.Images.Modules;
with AWA.Questions.Modules;
with AWA.Votes.Modules;
with AWA.Tags.Modules;
with AWA.Changelogs.Modules;
with AWA.Counters.Modules;
with AWA.Converters.Dates;
with AWA.Tests;
with AWA.Services.Contexts;
with AWA.Jobs.Services.Tests;
with AWA.Jobs.Modules.Tests;
with AWA.Settings.Modules.Tests;
with AWA.Comments.Modules.Tests;
with AWA.Changelogs.Modules.Tests;
with AWA.Wikis.Modules.Tests;
-- with ASF.Server.Web;
with ASF.Server.Tests;
package body AWA.Testsuite is
Users : aliased AWA.Users.Modules.User_Module;
Workspaces : aliased AWA.Workspaces.Modules.Workspace_Module;
Mail : aliased AWA.Mail.Modules.Mail_Module;
Jobs : aliased AWA.Jobs.Modules.Job_Module;
Comments : aliased AWA.Comments.Modules.Comment_Module;
Blogs : aliased AWA.Blogs.Modules.Blog_Module;
Storages : aliased AWA.Storages.Modules.Storage_Module;
Images : aliased AWA.Images.Modules.Image_Module;
Questions : aliased AWA.Questions.Modules.Question_Module;
Votes : aliased AWA.Votes.Modules.Vote_Module;
Tags : aliased AWA.Tags.Modules.Tag_Module;
Settings : aliased AWA.Settings.Modules.Setting_Module;
Changelogs : aliased AWA.Changelogs.Modules.Changelog_Module;
Wikis : aliased AWA.Wikis.Modules.Wiki_Module;
Counters : aliased AWA.Counters.Modules.Counter_Module;
Date_Converter : aliased ASF.Converters.Dates.Date_Converter;
Rel_Date_Converter : aliased AWA.Converters.Dates.Relative_Date_Converter;
Tests : aliased Util.Tests.Test_Suite;
function Suite return Util.Tests.Access_Test_Suite is
Ret : constant Util.Tests.Access_Test_Suite := Tests'Access;
begin
AWA.Modules.Tests.Add_Tests (Ret);
AWA.Events.Services.Tests.Add_Tests (Ret);
AWA.Mail.Clients.Tests.Add_Tests (Ret);
AWA.Mail.Modules.Tests.Add_Tests (Ret);
AWA.Users.Services.Tests.Add_Tests (Ret);
AWA.Users.Tests.Add_Tests (Ret);
AWA.Counters.Modules.Tests.Add_Tests (Ret);
AWA.Helpers.Selectors.Tests.Add_Tests (Ret);
AWA.Jobs.Modules.Tests.Add_Tests (Ret);
AWA.Jobs.Services.Tests.Add_Tests (Ret);
AWA.Settings.Modules.Tests.Add_Tests (Ret);
AWA.Comments.Modules.Tests.Add_Tests (Ret);
AWA.Blogs.Modules.Tests.Add_Tests (Ret);
AWA.Storages.Services.Tests.Add_Tests (Ret);
AWA.Images.Services.Tests.Add_Tests (Ret);
AWA.Changelogs.Modules.Tests.Add_Tests (Ret);
AWA.Votes.Modules.Tests.Add_Tests (Ret);
AWA.Tags.Modules.Tests.Add_Tests (Ret);
AWA.Questions.Modules.Tests.Add_Tests (Ret);
AWA.Wikis.Modules.Tests.Add_Tests (Ret);
return Ret;
end Suite;
procedure Initialize (Props : in Util.Properties.Manager) is
begin
Initialize (null, Props, True);
end Initialize;
-- ------------------------------
-- Initialize the AWA test framework mockup.
-- ------------------------------
procedure Initialize (App : in AWA.Applications.Application_Access;
Props : in Util.Properties.Manager;
Add_Modules : in Boolean) is
use AWA.Applications;
begin
AWA.Tests.Initialize (App, Props, Add_Modules);
if Add_Modules then
declare
Application : constant Applications.Application_Access := AWA.Tests.Get_Application;
Ctx : AWA.Services.Contexts.Service_Context;
Users : constant AWA.Users.Modules.User_Module_Access := AWA.Testsuite.Users'Access;
begin
Ctx.Set_Context (Application, null);
Register (App => Application.all'Access,
Name => AWA.Users.Modules.NAME,
URI => "user",
Module => Users.all'Access);
Register (App => Application.all'Access,
Name => "mail",
URI => "mail",
Module => Mail'Access);
Register (App => Application.all'Access,
Name => "workspaces",
URI => "workspaces",
Module => Workspaces'Access);
Register (App => Application.all'Access,
Name => AWA.Counters.Modules.NAME,
URI => "counters",
Module => Counters'Access);
Register (App => Application.all'Access,
Name => AWA.Comments.Modules.NAME,
URI => "comments",
Module => Comments'Access);
Register (App => Application.all'Access,
Name => AWA.Storages.Modules.NAME,
URI => "storages",
Module => Storages'Access);
Register (App => Application.all'Access,
Name => AWA.Images.Modules.NAME,
URI => "images",
Module => Images'Access);
Register (App => Application.all'Access,
Name => AWA.Jobs.Modules.NAME,
URI => "jobs",
Module => Jobs'Access);
Register (App => Application.all'Access,
Name => AWA.Settings.Modules.NAME,
URI => "settings",
Module => Settings'Access);
Register (App => Application.all'Access,
Name => AWA.Votes.Modules.NAME,
URI => "votes",
Module => Votes'Access);
Register (App => Application.all'Access,
Name => AWA.Changelogs.Modules.NAME,
URI => "changelogs",
Module => Changelogs'Access);
Register (App => Application.all'Access,
Name => AWA.Tags.Modules.NAME,
URI => "tags",
Module => Tags'Access);
Register (App => Application.all'Access,
Name => AWA.Blogs.Modules.NAME,
URI => "blogs",
Module => Blogs'Access);
Register (App => Application.all'Access,
Name => AWA.Questions.Modules.NAME,
URI => "questions",
Module => Questions'Access);
Register (App => Application.all'Access,
Name => AWA.Wikis.Modules.NAME,
URI => "wikis",
Module => Wikis'Access);
Application.Start;
-- if Props.Exists ("test.server") then
-- declare
-- WS : ASF.Server.Web.AWS_Container;
-- begin
-- Application.Add_Converter (Name => "dateConverter",
-- Converter => Date_Converter'Access);
-- Application.Add_Converter (Name => "smartDateConverter",
-- Converter => Rel_Date_Converter'Access);
--
-- WS.Register_Application ("/asfunit", Application.all'Access);
--
-- WS.Start;
-- delay 6000.0;
-- end;
-- end if;
ASF.Server.Tests.Set_Context (Application.all'Access);
end;
end if;
end Initialize;
end AWA.Testsuite;
|
Disable and comment out the AWS server with the test.server mode
|
Disable and comment out the AWS server with the test.server mode
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
5c02539b35cd7c07d383d4b8d73ef347eb93bc88
|
src/gen-model.adb
|
src/gen-model.adb
|
-----------------------------------------------------------------------
-- gen-model -- Model for Code Generator
-- Copyright (C) 2009, 2010, 2011, 2012, 2018 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Fixed;
with Ada.Strings.Maps;
with DOM.Core.Nodes;
with Gen.Utils;
package body Gen.Model is
Trim_Chars : constant Ada.Strings.Maps.Character_Set
:= Ada.Strings.Maps.To_Set (" " & ASCII.HT & ASCII.LF & ASCII.CR);
-- ------------------------------
-- Get the object unique name.
-- ------------------------------
function Get_Name (From : in Definition) return String is
begin
return Ada.Strings.Unbounded.To_String (From.Def_Name);
end Get_Name;
function Name (From : in Definition) return Ada.Strings.Unbounded.Unbounded_String is
begin
return From.Def_Name;
end Name;
-- ------------------------------
-- Set the object unique name.
-- ------------------------------
procedure Set_Name (Def : in out Definition;
Name : in String) is
begin
Def.Def_Name := Ada.Strings.Unbounded.To_Unbounded_String (Name);
end Set_Name;
procedure Set_Name (Def : in out Definition;
Name : in Ada.Strings.Unbounded.Unbounded_String) is
begin
Def.Def_Name := Name;
end Set_Name;
-- ------------------------------
-- Get the value identified by the name.
-- If the name cannot be found, the method should return the Null object.
-- ------------------------------
function Get_Value (From : in Definition;
Name : in String) return Util.Beans.Objects.Object is
begin
if Name = "comment" then
return From.Comment;
elsif Name = "rowIndex" then
return Util.Beans.Objects.To_Object (From.Row_Index);
elsif Name = "name" then
return Util.Beans.Objects.To_Object (From.Def_Name);
else
return From.Attrs.Get_Value (Name);
end if;
end Get_Value;
-- ------------------------------
-- Get the value identified by the name.
-- If the name cannot be found, the method should return the Null object.
-- ------------------------------
function Get_Attribute (From : in Definition;
Name : in String) return String is
V : constant Util.Beans.Objects.Object := From.Get_Value (Name);
begin
return Util.Beans.Objects.To_String (V);
end Get_Attribute;
-- ------------------------------
-- Get the value identified by the name.
-- If the name cannot be found, the method should return the Null object.
-- ------------------------------
function Get_Attribute (From : in Definition;
Name : in String) return Ada.Strings.Unbounded.Unbounded_String is
begin
return Ada.Strings.Unbounded.To_Unbounded_String (From.Get_Attribute (Name));
end Get_Attribute;
-- ------------------------------
-- Set the comment associated with the element.
-- ------------------------------
procedure Set_Comment (Def : in out Definition;
Comment : in String) is
Trimmed_Comment : constant String := Ada.Strings.Fixed.Trim (Comment, Trim_Chars, Trim_Chars);
begin
Def.Comment := Util.Beans.Objects.To_Object (Trimmed_Comment);
end Set_Comment;
-- ------------------------------
-- Get the comment associated with the element.
-- ------------------------------
function Get_Comment (Def : in Definition) return Util.Beans.Objects.Object is
begin
return Def.Comment;
end Get_Comment;
-- ------------------------------
-- Set the location (file and line) where the model element is defined in the XMI file.
-- ------------------------------
procedure Set_Location (Node : in out Definition;
Location : in String) is
begin
Node.Location := Ada.Strings.Unbounded.To_Unbounded_String (Location);
end Set_Location;
-- ------------------------------
-- Get the location file and line where the model element is defined.
-- ------------------------------
function Get_Location (Node : in Definition) return String is
begin
return Ada.Strings.Unbounded.To_String (Node.Location);
end Get_Location;
-- ------------------------------
-- Initialize the definition from the DOM node attributes.
-- ------------------------------
procedure Initialize (Def : in out Definition;
Name : in Ada.Strings.Unbounded.Unbounded_String;
Node : in DOM.Core.Node) is
use type DOM.Core.Node;
Attrs : constant DOM.Core.Named_Node_Map := DOM.Core.Nodes.Attributes (Node);
begin
Def.Def_Name := Name;
Def.Comment := Util.Beans.Objects.To_Object (Gen.Utils.Get_Comment (Node));
for I in 0 .. DOM.Core.Nodes.Length (Attrs) loop
declare
A : constant DOM.Core.Node := DOM.Core.Nodes.Item (Attrs, I);
begin
if A /= null then
declare
Name : constant DOM.Core.DOM_String := DOM.Core.Nodes.Node_Name (A);
Value : constant DOM.Core.DOM_String := DOM.Core.Nodes.Node_Value (A);
begin
Def.Attrs.Include (Name, Util.Beans.Objects.To_Object (Value));
end;
end if;
end;
end loop;
end Initialize;
-- ------------------------------
-- Validate the definition by checking and reporting problems to the logger interface.
-- ------------------------------
procedure Validate (Def : in out Definition;
Log : in out Util.Log.Logging'Class) is
begin
if Ada.Strings.Unbounded.Length (Def.Def_Name) = 0 then
Log.Error (Def.Get_Location & ": name is empty");
end if;
end Validate;
end Gen.Model;
|
-----------------------------------------------------------------------
-- gen-model -- Model for Code Generator
-- Copyright (C) 2009, 2010, 2011, 2012, 2018, 2019 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Fixed;
with Ada.Strings.Maps;
with DOM.Core.Nodes;
with Gen.Utils;
package body Gen.Model is
Trim_Chars : constant Ada.Strings.Maps.Character_Set
:= Ada.Strings.Maps.To_Set (" " & ASCII.HT & ASCII.LF & ASCII.CR);
-- ------------------------------
-- Get the object unique name.
-- ------------------------------
function Get_Name (From : in Definition) return String is
begin
return Ada.Strings.Unbounded.To_String (From.Def_Name);
end Get_Name;
function Name (From : in Definition) return Ada.Strings.Unbounded.Unbounded_String is
begin
return From.Def_Name;
end Name;
-- ------------------------------
-- Set the object unique name.
-- ------------------------------
procedure Set_Name (Def : in out Definition;
Name : in String) is
begin
Def.Def_Name := Ada.Strings.Unbounded.To_Unbounded_String (Name);
end Set_Name;
procedure Set_Name (Def : in out Definition;
Name : in Ada.Strings.Unbounded.Unbounded_String) is
begin
Def.Def_Name := Name;
end Set_Name;
-- ------------------------------
-- Get the value identified by the name.
-- If the name cannot be found, the method should return the Null object.
-- ------------------------------
function Get_Value (From : in Definition;
Name : in String) return Util.Beans.Objects.Object is
begin
if Name = "comment" then
return From.Comment;
elsif Name = "rowIndex" then
return Util.Beans.Objects.To_Object (From.Row_Index);
elsif Name = "name" then
return Util.Beans.Objects.To_Object (From.Def_Name);
else
return From.Attrs.Get_Value (Name);
end if;
end Get_Value;
-- ------------------------------
-- Get the value identified by the name.
-- If the name cannot be found, the method should return the Null object.
-- ------------------------------
function Get_Attribute (From : in Definition;
Name : in String) return String is
V : constant Util.Beans.Objects.Object := From.Get_Value (Name);
begin
return Util.Beans.Objects.To_String (V);
end Get_Attribute;
-- ------------------------------
-- Get the value identified by the name.
-- If the name cannot be found, the method should return the Null object.
-- ------------------------------
function Get_Attribute (From : in Definition;
Name : in String) return Ada.Strings.Unbounded.Unbounded_String is
begin
return Ada.Strings.Unbounded.To_Unbounded_String (From.Get_Attribute (Name));
end Get_Attribute;
-- ------------------------------
-- Set the comment associated with the element.
-- ------------------------------
procedure Set_Comment (Def : in out Definition;
Comment : in String) is
Trimmed_Comment : constant String
:= Ada.Strings.Fixed.Trim (Comment, Trim_Chars, Trim_Chars);
begin
Def.Comment := Util.Beans.Objects.To_Object (Trimmed_Comment);
end Set_Comment;
-- ------------------------------
-- Get the comment associated with the element.
-- ------------------------------
function Get_Comment (Def : in Definition) return Util.Beans.Objects.Object is
begin
return Def.Comment;
end Get_Comment;
-- ------------------------------
-- Set the location (file and line) where the model element is defined in the XMI file.
-- ------------------------------
procedure Set_Location (Node : in out Definition;
Location : in String) is
begin
Node.Location := Ada.Strings.Unbounded.To_Unbounded_String (Location);
end Set_Location;
-- ------------------------------
-- Get the location file and line where the model element is defined.
-- ------------------------------
function Get_Location (Node : in Definition) return String is
begin
return Ada.Strings.Unbounded.To_String (Node.Location);
end Get_Location;
-- ------------------------------
-- Initialize the definition from the DOM node attributes.
-- ------------------------------
procedure Initialize (Def : in out Definition;
Name : in Ada.Strings.Unbounded.Unbounded_String;
Node : in DOM.Core.Node) is
use type DOM.Core.Node;
Attrs : constant DOM.Core.Named_Node_Map := DOM.Core.Nodes.Attributes (Node);
begin
Def.Def_Name := Name;
Def.Comment := Util.Beans.Objects.To_Object (Gen.Utils.Get_Comment (Node));
for I in 0 .. DOM.Core.Nodes.Length (Attrs) loop
declare
A : constant DOM.Core.Node := DOM.Core.Nodes.Item (Attrs, I);
begin
if A /= null then
declare
Name : constant DOM.Core.DOM_String := DOM.Core.Nodes.Node_Name (A);
Value : constant DOM.Core.DOM_String := DOM.Core.Nodes.Node_Value (A);
begin
Def.Attrs.Include (Name, Util.Beans.Objects.To_Object (Value));
end;
end if;
end;
end loop;
end Initialize;
-- ------------------------------
-- Validate the definition by checking and reporting problems to the logger interface.
-- ------------------------------
procedure Validate (Def : in out Definition;
Log : in out Util.Log.Logging'Class) is
begin
if Ada.Strings.Unbounded.Length (Def.Def_Name) = 0 then
Log.Error (Def.Get_Location & ": name is empty");
end if;
end Validate;
end Gen.Model;
|
Fix style compilation warning
|
Fix style compilation warning
|
Ada
|
apache-2.0
|
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
|
c844a38a91bed493374ad69a3e4068409b9e2229
|
src/replicant.ads
|
src/replicant.ads
|
-- This file is covered by the Internet Software Consortium (ISC) License
-- Reference: ../License.txt
with Ada.Text_IO;
with JohnnyText;
with Definitions; use Definitions;
package Replicant is
package JT renames JohnnyText;
package TIO renames Ada.Text_IO;
scenario_unexpected : exception;
type slave_options is record
need_procfs : Boolean := False;
need_linprocfs : Boolean := False;
end record;
-- For every single port to be built, the build need to first be created
-- and then destroyed when the build is complete.
procedure launch_slave (id : builders; opts : slave_options);
procedure destroy_slave (id : builders; opts : slave_options);
-- This procedure needs to be run once.
-- It basically sets the operating system "flavor" which affects the
-- mount command spawning. It also creates the password database
procedure initialize (testmode : Boolean; num_cores : cpu_range);
-- This removes the password database
procedure finalize;
-- Returns True if any mounts are detected (used by pilot)
function synth_mounts_exist return Boolean;
-- Returns True if any _work/_localbase dirs are detected (used by pilot)
function disk_workareas_exist return Boolean;
-- Returns True if the attempt to clear mounts is successful.
function clear_existing_mounts return Boolean;
-- Returns True if the attempt to remove the disk work areas is successful
function clear_existing_workareas return Boolean;
-- In order to do scanning in a clean environment prior to the true build
-- Returns True on success
function standalone_pkg8_install (id : builders) return Boolean;
-- The actual command to build a local repository (Returns True on success)
function build_repository (id : builders; sign_command : String := "")
return Boolean;
-- Returns all the UNAME_x environment variables
-- They will be passed to the buildcycle package
function jail_environment return JT.Text;
-- On FreeBSD, if "/boot" exists but "/boot/modules" does not, return True
-- This is a pre-run validity check
function boot_modules_directory_missing return Boolean;
private
type mount_mode is (readonly, readwrite);
type nullfs_flavor is (unknown, freebsd, dragonfly);
type folder_operation is (lock, unlock);
type folder is (bin, sbin, lib, libexec,
usr_bin,
usr_include,
usr_lib,
usr_libdata,
usr_libexec,
usr_sbin,
usr_share,
usr_lib32, xports, options, packages, distfiles,
dev, etc, etc_default, etc_mtree, etc_rcd, home, linux,
proc, root, tmp, var, wrkdirs, usr_local, usr_src, ccache,
boot);
subtype subfolder is folder range bin .. usr_share;
-- home and root need to be set readonly
reference_base : constant String := "Base";
root_bin : constant String := "/bin";
root_sbin : constant String := "/sbin";
root_usr_bin : constant String := "/usr/bin";
root_usr_include : constant String := "/usr/include";
root_usr_lib : constant String := "/usr/lib";
root_usr_lib32 : constant String := "/usr/lib32";
root_usr_libdata : constant String := "/usr/libdata";
root_usr_libexec : constant String := "/usr/libexec";
root_usr_sbin : constant String := "/usr/sbin";
root_usr_share : constant String := "/usr/share";
root_usr_src : constant String := "/usr/src";
root_dev : constant String := "/dev";
root_etc : constant String := "/etc";
root_etc_default : constant String := "/etc/defaults";
root_etc_mtree : constant String := "/etc/mtree";
root_etc_rcd : constant String := "/etc/rc.d";
root_lib : constant String := "/lib";
root_tmp : constant String := "/tmp";
root_var : constant String := "/var";
root_home : constant String := "/home";
root_boot : constant String := "/boot";
root_kmodules : constant String := "/boot/modules";
root_lmodules : constant String := "/boot/modules.local";
root_root : constant String := "/root";
root_proc : constant String := "/proc";
root_linux : constant String := "/compat/linux";
root_linproc : constant String := "/compat/linux/proc";
root_xports : constant String := "/xports";
root_options : constant String := "/options";
root_libexec : constant String := "/libexec";
root_wrkdirs : constant String := "/construction";
root_packages : constant String := "/packages";
root_distfiles : constant String := "/distfiles";
root_ccache : constant String := "/ccache";
root_localbase : constant String := "/usr/local";
chroot : constant String := "/usr/sbin/chroot ";
flavor : nullfs_flavor := unknown;
smp_cores : cpu_range := cpu_range'First;
support_locks : Boolean;
developer_mode : Boolean;
abn_log_ready : Boolean;
builder_env : JT.Text;
abnormal_log : TIO.File_Type;
abnormal_cmd_logname : constant String := "05_abnormal_cmd.out";
-- Throws exception if mount attempt was unsuccessful
procedure mount_nullfs (target, mount_point : String;
mode : mount_mode := readonly);
-- Throws exception if mount attempt was unsuccessful
procedure mount_tmpfs (mount_point : String; max_size_M : Natural := 0);
-- Throws exception if unmount attempt was unsuccessful
procedure unmount (device_or_node : String);
-- Throws exception if directory was not successfully created
procedure forge_directory (target : String);
-- Return the full path of the mount point
function location (mount_base : String; point : folder) return String;
function mount_target (point : folder) return String;
-- Query configuration to determine the master mount
function get_master_mount return String;
function get_slave_mount (id : builders) return String;
-- returns "SLXX" where XX is a zero-padded integer (01 .. 32)
function slave_name (id : builders) return String;
-- locks and unlocks folders, even from root
procedure folder_access (path : String; operation : folder_operation);
-- self explanatory
procedure create_symlink (destination, symbolic_link : String);
-- generic command, throws exception if exit code is not 0
procedure execute (command : String);
procedure silent_exec (command : String);
function internal_system_command (command : String) return JT.Text;
-- create slave's /var directory tree. Path should be an empty directory.
procedure populate_var_folder (path : String);
-- create /etc/make.conf in slave
procedure create_make_conf (path_to_etc : String);
-- create /etc/passwd (and databases) to define system users
procedure create_passwd (path_to_etc : String);
procedure create_base_passwd (path_to_mm : String);
-- create /etc/group to define root user
procedure create_group (path_to_etc : String);
procedure create_base_group (path_to_mm : String);
-- copy host's /etc/resolv.conf to slave
procedure copy_resolv_conf (path_to_etc : String);
-- copy host's /etc/mtree files to slave
procedure copy_mtree_files (path_to_mtree : String);
-- copy host's conf defaults
procedure copy_rc_default (path_to_etc : String);
-- create minimal /etc/services
procedure create_etc_services (path_to_etc : String);
-- create a dummy fstab for linux packages (looks for linprocfs)
procedure create_etc_fstab (path_to_etc : String);
-- mount the devices
procedure mount_devices (path_to_dev : String);
-- execute ldconfig as last action of slave creation
procedure execute_ldconfig (id : builders);
-- Used for per-profile make.conf fragments (if they exist)
procedure concatenate_makeconf (makeconf_handle : TIO.File_Type;
target_name : String);
-- Wrapper for rm -rf <directory>
procedure annihilate_directory_tree (tree : String);
-- This is only done for FreeBSD. For DragonFly, it's a null-op
procedure mount_linprocfs (mount_point : String);
-- It turns out at least one major port uses procfs (gnustep)
procedure mount_procfs (path_to_proc : String);
-- Cache variables that spawn to get populated to extended make.conf
procedure cache_port_variables (path_to_mm : String);
-- Used to generic mtree exclusion files
procedure write_common_mtree_exclude_base (mtreefile : TIO.File_Type);
procedure write_preinstall_section (mtreefile : TIO.File_Type);
procedure create_mtree_exc_preconfig (path_to_mm : String);
procedure create_mtree_exc_preinst (path_to_mm : String);
-- Get OSVERSION from <sys/param.h>
function get_osversion_from_param_header return String;
-- Derived from /usr/bin/file -b <slave>/bin/sh
function get_arch_from_bourne_shell return String;
-- capture unexpected output while setting up builders (e.g. mount)
procedure start_abnormal_logging;
procedure stop_abnormal_logging;
end Replicant;
|
-- This file is covered by the Internet Software Consortium (ISC) License
-- Reference: ../License.txt
with Ada.Text_IO;
with JohnnyText;
with Definitions; use Definitions;
package Replicant is
package JT renames JohnnyText;
package TIO renames Ada.Text_IO;
scenario_unexpected : exception;
type slave_options is record
need_procfs : Boolean := False;
need_linprocfs : Boolean := False;
end record;
-- For every single port to be built, the build need to first be created
-- and then destroyed when the build is complete.
procedure launch_slave (id : builders; opts : slave_options);
procedure destroy_slave (id : builders; opts : slave_options);
-- This procedure needs to be run once.
-- It basically sets the operating system "flavor" which affects the
-- mount command spawning. It also creates the password database
procedure initialize (testmode : Boolean; num_cores : cpu_range);
-- This removes the password database
procedure finalize;
-- Returns True if any mounts are detected (used by pilot)
function synth_mounts_exist return Boolean;
-- Returns True if any _work/_localbase dirs are detected (used by pilot)
function disk_workareas_exist return Boolean;
-- Returns True if the attempt to clear mounts is successful.
function clear_existing_mounts return Boolean;
-- Returns True if the attempt to remove the disk work areas is successful
function clear_existing_workareas return Boolean;
-- In order to do scanning in a clean environment prior to the true build
-- Returns True on success
function standalone_pkg8_install (id : builders) return Boolean;
-- The actual command to build a local repository (Returns True on success)
function build_repository (id : builders; sign_command : String := "")
return Boolean;
-- Returns all the UNAME_x environment variables
-- They will be passed to the buildcycle package
function jail_environment return JT.Text;
-- On FreeBSD, if "/boot" exists but "/boot/modules" does not, return True
-- This is a pre-run validity check
function boot_modules_directory_missing return Boolean;
private
type mount_mode is (readonly, readwrite);
type nullfs_flavor is (unknown, freebsd, dragonfly);
type folder_operation is (lock, unlock);
type folder is (bin, sbin, lib, libexec,
usr_bin,
usr_include,
usr_lib,
usr_libdata,
usr_libexec,
usr_sbin,
usr_share,
usr_lib32, xports, options, packages, distfiles,
dev, etc, etc_default, etc_mtree, etc_rcd, home, linux,
proc, root, tmp, var, wrkdirs, usr_local, usr_src, ccache,
boot);
subtype subfolder is folder range bin .. usr_share;
-- home and root need to be set readonly
reference_base : constant String := "Base";
root_bin : constant String := "/bin";
root_sbin : constant String := "/sbin";
root_usr_bin : constant String := "/usr/bin";
root_usr_include : constant String := "/usr/include";
root_usr_lib : constant String := "/usr/lib";
root_usr_lib32 : constant String := "/usr/lib32";
root_usr_libdata : constant String := "/usr/libdata";
root_usr_libexec : constant String := "/usr/libexec";
root_usr_sbin : constant String := "/usr/sbin";
root_usr_share : constant String := "/usr/share";
root_usr_src : constant String := "/usr/src";
root_dev : constant String := "/dev";
root_etc : constant String := "/etc";
root_etc_default : constant String := "/etc/defaults";
root_etc_mtree : constant String := "/etc/mtree";
root_etc_rcd : constant String := "/etc/rc.d";
root_lib : constant String := "/lib";
root_tmp : constant String := "/tmp";
root_var : constant String := "/var";
root_home : constant String := "/home";
root_boot : constant String := "/boot";
root_kmodules : constant String := "/boot/modules";
root_lmodules : constant String := "/boot/modules.local";
root_root : constant String := "/root";
root_proc : constant String := "/proc";
root_linux : constant String := "/compat/linux";
root_linproc : constant String := "/compat/linux/proc";
root_xports : constant String := "/xports";
root_options : constant String := "/options";
root_libexec : constant String := "/libexec";
root_wrkdirs : constant String := "/construction";
root_packages : constant String := "/packages";
root_distfiles : constant String := "/distfiles";
root_ccache : constant String := "/ccache";
root_localbase : constant String := "/usr/local";
chroot : constant String := "/usr/sbin/chroot ";
flavor : nullfs_flavor := unknown;
smp_cores : cpu_range := cpu_range'First;
support_locks : Boolean;
developer_mode : Boolean;
abn_log_ready : Boolean;
builder_env : JT.Text;
abnormal_log : TIO.File_Type;
abnormal_cmd_logname : constant String := "05_abnormal_command_output.log";
-- Throws exception if mount attempt was unsuccessful
procedure mount_nullfs (target, mount_point : String;
mode : mount_mode := readonly);
-- Throws exception if mount attempt was unsuccessful
procedure mount_tmpfs (mount_point : String; max_size_M : Natural := 0);
-- Throws exception if unmount attempt was unsuccessful
procedure unmount (device_or_node : String);
-- Throws exception if directory was not successfully created
procedure forge_directory (target : String);
-- Return the full path of the mount point
function location (mount_base : String; point : folder) return String;
function mount_target (point : folder) return String;
-- Query configuration to determine the master mount
function get_master_mount return String;
function get_slave_mount (id : builders) return String;
-- returns "SLXX" where XX is a zero-padded integer (01 .. 32)
function slave_name (id : builders) return String;
-- locks and unlocks folders, even from root
procedure folder_access (path : String; operation : folder_operation);
-- self explanatory
procedure create_symlink (destination, symbolic_link : String);
-- generic command, throws exception if exit code is not 0
procedure execute (command : String);
procedure silent_exec (command : String);
function internal_system_command (command : String) return JT.Text;
-- create slave's /var directory tree. Path should be an empty directory.
procedure populate_var_folder (path : String);
-- create /etc/make.conf in slave
procedure create_make_conf (path_to_etc : String);
-- create /etc/passwd (and databases) to define system users
procedure create_passwd (path_to_etc : String);
procedure create_base_passwd (path_to_mm : String);
-- create /etc/group to define root user
procedure create_group (path_to_etc : String);
procedure create_base_group (path_to_mm : String);
-- copy host's /etc/resolv.conf to slave
procedure copy_resolv_conf (path_to_etc : String);
-- copy host's /etc/mtree files to slave
procedure copy_mtree_files (path_to_mtree : String);
-- copy host's conf defaults
procedure copy_rc_default (path_to_etc : String);
-- create minimal /etc/services
procedure create_etc_services (path_to_etc : String);
-- create a dummy fstab for linux packages (looks for linprocfs)
procedure create_etc_fstab (path_to_etc : String);
-- mount the devices
procedure mount_devices (path_to_dev : String);
-- execute ldconfig as last action of slave creation
procedure execute_ldconfig (id : builders);
-- Used for per-profile make.conf fragments (if they exist)
procedure concatenate_makeconf (makeconf_handle : TIO.File_Type;
target_name : String);
-- Wrapper for rm -rf <directory>
procedure annihilate_directory_tree (tree : String);
-- This is only done for FreeBSD. For DragonFly, it's a null-op
procedure mount_linprocfs (mount_point : String);
-- It turns out at least one major port uses procfs (gnustep)
procedure mount_procfs (path_to_proc : String);
-- Cache variables that spawn to get populated to extended make.conf
procedure cache_port_variables (path_to_mm : String);
-- Used to generic mtree exclusion files
procedure write_common_mtree_exclude_base (mtreefile : TIO.File_Type);
procedure write_preinstall_section (mtreefile : TIO.File_Type);
procedure create_mtree_exc_preconfig (path_to_mm : String);
procedure create_mtree_exc_preinst (path_to_mm : String);
-- Get OSVERSION from <sys/param.h>
function get_osversion_from_param_header return String;
-- Derived from /usr/bin/file -b <slave>/bin/sh
function get_arch_from_bourne_shell return String;
-- capture unexpected output while setting up builders (e.g. mount)
procedure start_abnormal_logging;
procedure stop_abnormal_logging;
end Replicant;
|
Change name of abnormal command output log
|
Change name of abnormal command output log
The ".out" suffix isn't handled well with apache webserver.
|
Ada
|
isc
|
jrmarino/synth,jrmarino/synth,jrmarino/synth,jrmarino/synth
|
776045bf0651868e260a3bcda2cb3d5a9a9e6905
|
regtests/util-commands-tests.adb
|
regtests/util-commands-tests.adb
|
-----------------------------------------------------------------------
-- util-commands-tests - Test for commands
-- Copyright (C) 2018 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with GNAT.Command_Line;
with Util.Test_Caller;
with Util.Commands.Parsers.GNAT_Parser;
with Util.Commands.Drivers;
package body Util.Commands.Tests is
package Caller is new Util.Test_Caller (Test, "Commands");
type Test_Context_Type is record
Number : Integer;
Success : Boolean := False;
end record;
package Test_Command is new
Util.Commands.Drivers (Context_Type => Test_Context_Type,
Config_Parser => Util.Commands.Parsers.GNAT_Parser.Config_Parser,
Driver_Name => "test");
type Test_Command_Type is new Test_Command.Command_Type with record
Opt_Count : aliased Integer := 0;
Opt_V : aliased Boolean := False;
Opt_N : aliased Boolean := False;
Expect_V : Boolean := False;
Expect_N : Boolean := False;
Expect_C : Integer := 0;
Expect_A : Integer := 0;
Expect_Help : Boolean := False;
end record;
overriding
procedure Execute (Command : in Test_Command_Type;
Name : in String;
Args : in Argument_List'Class;
Context : in out Test_Context_Type);
-- Setup the command before parsing the arguments and executing it.
procedure Setup (Command : in out Test_Command_Type;
Config : in out GNAT.Command_Line.Command_Line_Configuration);
-- Write the help associated with the command.
procedure Help (Command : in Test_Command_Type;
Context : in out Test_Context_Type);
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test Util.Commands.Driver.Execute",
Test_Execute'Access);
Caller.Add_Test (Suite, "Test Util.Commands.Driver.Help",
Test_Help'Access);
Caller.Add_Test (Suite, "Test Util.Commands.Driver.Usage",
Test_Usage'Access);
end Add_Tests;
overriding
procedure Execute (Command : in Test_Command_Type;
Name : in String;
Args : in Argument_List'Class;
Context : in out Test_Context_Type) is
begin
Context.Success := Command.Opt_Count = Command.Expect_C and
Command.Opt_V = Command.Expect_V and
Command.Opt_N = Command.Expect_N and
Args.Get_Count = Command.Expect_A and
not Command.Expect_Help;
end Execute;
-- ------------------------------
-- Setup the command before parsing the arguments and executing it.
-- ------------------------------
procedure Setup (Command : in out Test_Command_Type;
Config : in out GNAT.Command_Line.Command_Line_Configuration) is
begin
GNAT.Command_Line.Define_Switch (Config => Config,
Switch => "-c:",
Long_Switch => "--count=",
Help => "Number option",
Section => "",
Initial => Integer (0),
Default => Integer (10),
Output => Command.Opt_Count'Access);
GNAT.Command_Line.Define_Switch (Config => Config,
Switch => "-v",
Long_Switch => "--verbose",
Help => "Verbose option",
Section => "",
Output => Command.Opt_V'Access);
GNAT.Command_Line.Define_Switch (Config => Config,
Switch => "-n",
Long_Switch => "--not",
Help => "Not option",
Section => "",
Output => Command.Opt_N'Access);
end Setup;
-- ------------------------------
-- Write the help associated with the command.
-- ------------------------------
procedure Help (Command : in Test_Command_Type;
Context : in out Test_Context_Type) is
begin
Context.Success := Command.Expect_Help;
end Help;
-- ------------------------------
-- Tests when the execution of commands.
-- ------------------------------
procedure Test_Execute (T : in out Test) is
C1 : aliased Test_Command_Type;
C2 : aliased Test_Command_Type;
D : Test_Command.Driver_Type;
Args : String_Argument_List (500, 30);
begin
D.Set_Description ("Test command");
D.Add_Command ("list", C1'Unchecked_Access);
D.Add_Command ("print", C2'Unchecked_Access);
declare
Ctx : Test_Context_Type;
begin
C1.Expect_V := True;
C1.Expect_N := True;
C1.Expect_C := 4;
C1.Expect_A := 2;
Initialize (Args, "list --count=4 -v -n test titi");
D.Execute ("list", Args, Ctx);
T.Assert (Ctx.Success, "Some arguments not parsed correctly");
end;
declare
Ctx : Test_Context_Type;
begin
C1.Expect_V := False;
C1.Expect_N := True;
C1.Expect_C := 8;
C1.Expect_A := 3;
Initialize (Args, "list -c 8 -n test titi last");
D.Execute ("list", Args, Ctx);
T.Assert (Ctx.Success, "Some arguments not parsed correctly");
end;
end Test_Execute;
-- ------------------------------
-- Test execution of help.
-- ------------------------------
procedure Test_Help (T : in out Test) is
C1 : aliased Test_Command_Type;
C2 : aliased Test_Command_Type;
H : aliased Test_Command.Help_Command_Type;
D : Test_Command.Driver_Type;
Args : String_Argument_List (500, 30);
begin
D.Set_Description ("Test command");
D.Add_Command ("list", C1'Unchecked_Access);
D.Add_Command ("print", C2'Unchecked_Access);
D.Add_Command ("help", H'Unchecked_Access);
declare
Ctx : Test_Context_Type;
begin
C1.Expect_Help := True;
Initialize (Args, "help list");
D.Execute ("help", Args, Ctx);
T.Assert (Ctx.Success, "Some arguments not parsed correctly");
end;
declare
Ctx : Test_Context_Type;
begin
C2.Expect_Help := True;
Initialize (Args, "help print");
D.Execute ("help", Args, Ctx);
T.Assert (Ctx.Success, "Some arguments not parsed correctly");
end;
end Test_Help;
-- ------------------------------
-- Test usage operation.
-- ------------------------------
procedure Test_Usage (T : in out Test) is
C1 : aliased Test_Command_Type;
C2 : aliased Test_Command_Type;
H : aliased Test_Command.Help_Command_Type;
D : Test_Command.Driver_Type;
Args : String_Argument_List (500, 30);
begin
D.Set_Description ("Test command");
D.Add_Command ("list", C1'Unchecked_Access);
D.Add_Command ("print", C2'Unchecked_Access);
D.Add_Command ("help", H'Unchecked_Access);
D.Usage (Args);
declare
Ctx : Test_Context_Type;
begin
C1.Expect_Help := True;
Initialize (Args, "help list");
D.Execute ("help", Args, Ctx);
T.Assert (Ctx.Success, "Some arguments not parsed correctly");
end;
end Test_Usage;
end Util.Commands.Tests;
|
-----------------------------------------------------------------------
-- util-commands-tests - Test for commands
-- Copyright (C) 2018 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with GNAT.Command_Line;
with Util.Test_Caller;
with Util.Commands.Parsers.GNAT_Parser;
with Util.Commands.Drivers;
package body Util.Commands.Tests is
package Caller is new Util.Test_Caller (Test, "Commands");
type Test_Context_Type is record
Number : Integer;
Success : Boolean := False;
end record;
package Test_Command is new
Util.Commands.Drivers (Context_Type => Test_Context_Type,
Config_Parser => Util.Commands.Parsers.GNAT_Parser.Config_Parser,
Driver_Name => "test");
type Test_Command_Type is new Test_Command.Command_Type with record
Opt_Count : aliased Integer := 0;
Opt_V : aliased Boolean := False;
Opt_N : aliased Boolean := False;
Expect_V : Boolean := False;
Expect_N : Boolean := False;
Expect_C : Integer := 0;
Expect_A : Integer := 0;
Expect_Help : Boolean := False;
end record;
overriding
procedure Execute (Command : in out Test_Command_Type;
Name : in String;
Args : in Argument_List'Class;
Context : in out Test_Context_Type);
-- Setup the command before parsing the arguments and executing it.
procedure Setup (Command : in out Test_Command_Type;
Config : in out GNAT.Command_Line.Command_Line_Configuration);
-- Write the help associated with the command.
procedure Help (Command : in Test_Command_Type;
Context : in out Test_Context_Type);
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test Util.Commands.Driver.Execute",
Test_Execute'Access);
Caller.Add_Test (Suite, "Test Util.Commands.Driver.Help",
Test_Help'Access);
Caller.Add_Test (Suite, "Test Util.Commands.Driver.Usage",
Test_Usage'Access);
end Add_Tests;
overriding
procedure Execute (Command : in out Test_Command_Type;
Name : in String;
Args : in Argument_List'Class;
Context : in out Test_Context_Type) is
begin
Context.Success := Command.Opt_Count = Command.Expect_C and
Command.Opt_V = Command.Expect_V and
Command.Opt_N = Command.Expect_N and
Args.Get_Count = Command.Expect_A and
not Command.Expect_Help;
end Execute;
-- ------------------------------
-- Setup the command before parsing the arguments and executing it.
-- ------------------------------
procedure Setup (Command : in out Test_Command_Type;
Config : in out GNAT.Command_Line.Command_Line_Configuration) is
begin
GNAT.Command_Line.Define_Switch (Config => Config,
Switch => "-c:",
Long_Switch => "--count=",
Help => "Number option",
Section => "",
Initial => Integer (0),
Default => Integer (10),
Output => Command.Opt_Count'Access);
GNAT.Command_Line.Define_Switch (Config => Config,
Switch => "-v",
Long_Switch => "--verbose",
Help => "Verbose option",
Section => "",
Output => Command.Opt_V'Access);
GNAT.Command_Line.Define_Switch (Config => Config,
Switch => "-n",
Long_Switch => "--not",
Help => "Not option",
Section => "",
Output => Command.Opt_N'Access);
end Setup;
-- ------------------------------
-- Write the help associated with the command.
-- ------------------------------
procedure Help (Command : in Test_Command_Type;
Context : in out Test_Context_Type) is
begin
Context.Success := Command.Expect_Help;
end Help;
-- ------------------------------
-- Tests when the execution of commands.
-- ------------------------------
procedure Test_Execute (T : in out Test) is
C1 : aliased Test_Command_Type;
C2 : aliased Test_Command_Type;
D : Test_Command.Driver_Type;
Args : String_Argument_List (500, 30);
begin
D.Set_Description ("Test command");
D.Add_Command ("list", C1'Unchecked_Access);
D.Add_Command ("print", C2'Unchecked_Access);
declare
Ctx : Test_Context_Type;
begin
C1.Expect_V := True;
C1.Expect_N := True;
C1.Expect_C := 4;
C1.Expect_A := 2;
Initialize (Args, "list --count=4 -v -n test titi");
D.Execute ("list", Args, Ctx);
T.Assert (Ctx.Success, "Some arguments not parsed correctly");
end;
declare
Ctx : Test_Context_Type;
begin
C1.Expect_V := False;
C1.Expect_N := True;
C1.Expect_C := 8;
C1.Expect_A := 3;
Initialize (Args, "list -c 8 -n test titi last");
D.Execute ("list", Args, Ctx);
T.Assert (Ctx.Success, "Some arguments not parsed correctly");
end;
end Test_Execute;
-- ------------------------------
-- Test execution of help.
-- ------------------------------
procedure Test_Help (T : in out Test) is
C1 : aliased Test_Command_Type;
C2 : aliased Test_Command_Type;
H : aliased Test_Command.Help_Command_Type;
D : Test_Command.Driver_Type;
Args : String_Argument_List (500, 30);
begin
D.Set_Description ("Test command");
D.Add_Command ("list", C1'Unchecked_Access);
D.Add_Command ("print", C2'Unchecked_Access);
D.Add_Command ("help", H'Unchecked_Access);
declare
Ctx : Test_Context_Type;
begin
C1.Expect_Help := True;
Initialize (Args, "help list");
D.Execute ("help", Args, Ctx);
T.Assert (Ctx.Success, "Some arguments not parsed correctly");
end;
declare
Ctx : Test_Context_Type;
begin
C2.Expect_Help := True;
Initialize (Args, "help print");
D.Execute ("help", Args, Ctx);
T.Assert (Ctx.Success, "Some arguments not parsed correctly");
end;
end Test_Help;
-- ------------------------------
-- Test usage operation.
-- ------------------------------
procedure Test_Usage (T : in out Test) is
C1 : aliased Test_Command_Type;
C2 : aliased Test_Command_Type;
H : aliased Test_Command.Help_Command_Type;
D : Test_Command.Driver_Type;
Args : String_Argument_List (500, 30);
begin
D.Set_Description ("Test command");
D.Add_Command ("list", C1'Unchecked_Access);
D.Add_Command ("print", C2'Unchecked_Access);
D.Add_Command ("help", H'Unchecked_Access);
D.Usage (Args);
declare
Ctx : Test_Context_Type;
begin
C1.Expect_Help := True;
Initialize (Args, "help list");
D.Execute ("help", Args, Ctx);
T.Assert (Ctx.Success, "Some arguments not parsed correctly");
end;
end Test_Usage;
end Util.Commands.Tests;
|
Change the Execute procedure to use in out parameter for the Command_Type parameter
|
Change the Execute procedure to use in out parameter for the Command_Type parameter
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
0a5693ef3f212845e9ac3acf384a1615d7d71ad6
|
src/ado-queries-loaders.adb
|
src/ado-queries-loaders.adb
|
-----------------------------------------------------------------------
-- ado-queries-loaders -- Loader for Database Queries
-- Copyright (C) 2011, 2012, 2013, 2014, 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Interfaces;
with Ada.IO_Exceptions;
with Ada.Directories;
with Util.Files;
with Util.Log.Loggers;
with Util.Beans.Objects;
with Util.Serialize.IO.XML;
with Util.Serialize.Mappers.Record_Mapper;
package body ADO.Queries.Loaders is
use Util.Log;
use ADO.Drivers.Connections;
use Interfaces;
use Ada.Calendar;
Log : constant Loggers.Logger := Loggers.Create ("ADO.Queries.Loaders");
Base_Time : constant Ada.Calendar.Time := Ada.Calendar.Time_Of (Year => 1970,
Month => 1,
Day => 1);
-- Check for file modification time at most every 60 seconds.
FILE_CHECK_DELTA_TIME : constant Unsigned_32 := 60;
-- The list of query files defined by the application.
Query_Files : Query_File_Access := null;
Last_Query : Query_Index := 0;
Last_File : File_Index := 0;
-- Convert a Time to an Unsigned_32.
function To_Unsigned_32 (T : in Ada.Calendar.Time) return Unsigned_32;
pragma Inline_Always (To_Unsigned_32);
-- Get the modification time of the XML query file associated with the query.
function Modification_Time (File : in Query_File_Info) return Unsigned_32;
-- Initialize the query SQL pattern with the value
procedure Set_Query_Pattern (Into : in out Query_Pattern;
Value : in Util.Beans.Objects.Object);
-- ------------------------------
-- Register the query definition in the query file. Registration is done
-- in the package elaboration phase.
-- ------------------------------
procedure Register (File : in Query_File_Access;
Query : in Query_Definition_Access) is
begin
Last_Query := Last_Query + 1;
Query.File := File;
Query.Next := File.Queries;
Query.Query := Last_Query;
File.Queries := Query;
if File.Next = null and then Query_Files /= File then
Last_File := Last_File + 1;
File.Next := Query_Files;
File.File := Last_File;
Query_Files := File;
end if;
end Register;
function Find_Driver (Name : in String) return Integer;
function Find_Driver (Name : in String) return Integer is
begin
if Name'Length = 0 then
return 0;
end if;
declare
Driver : constant Drivers.Connections.Driver_Access
:= Drivers.Connections.Get_Driver (Name);
begin
if Driver = null then
-- There is no problem to have an SQL query for unsupported drivers, but still
-- report some warning.
Log.Warn ("Database driver {0} not found", Name);
return -1;
end if;
return Integer (Driver.Get_Driver_Index);
end;
end Find_Driver;
-- ------------------------------
-- Convert a Time to an Unsigned_32.
-- ------------------------------
function To_Unsigned_32 (T : in Ada.Calendar.Time) return Unsigned_32 is
D : constant Duration := Duration '(T - Base_Time);
begin
return Unsigned_32 (D);
end To_Unsigned_32;
-- ------------------------------
-- Get the modification time of the XML query file associated with the query.
-- ------------------------------
function Modification_Time (File : in Query_File_Info) return Unsigned_32 is
Path : constant String := To_String (File.Path);
begin
return To_Unsigned_32 (Ada.Directories.Modification_Time (Path));
exception
when Ada.IO_Exceptions.Name_Error =>
Log.Error ("XML query file '{0}' does not exist", Path);
return 0;
end Modification_Time;
-- ------------------------------
-- Returns True if the XML query file must be reloaded.
-- ------------------------------
function Is_Modified (File : in out Query_File_Info) return Boolean is
Now : constant Unsigned_32 := To_Unsigned_32 (Ada.Calendar.Clock);
begin
-- Have we passed the next check time?
if File.Next_Check > Now then
return False;
end if;
-- Next check in N seconds (60 by default).
File.Next_Check := Now + FILE_CHECK_DELTA_TIME;
-- See if the file was changed.
declare
M : constant Unsigned_32 := Modification_Time (File);
begin
if File.Last_Modified = M then
return False;
end if;
File.Last_Modified := M;
return True;
end;
end Is_Modified;
-- ------------------------------
-- Initialize the query SQL pattern with the value
-- ------------------------------
procedure Set_Query_Pattern (Into : in out Query_Pattern;
Value : in Util.Beans.Objects.Object) is
begin
Into.SQL := Util.Beans.Objects.To_Unbounded_String (Value);
end Set_Query_Pattern;
procedure Read_Query (Manager : in Query_Manager;
File : in out Query_File_Info) is
type Query_Info_Fields is (FIELD_CLASS_NAME, FIELD_PROPERTY_TYPE,
FIELD_PROPERTY_NAME, FIELD_QUERY_NAME,
FIELD_SQL_DRIVER,
FIELD_SQL, FIELD_SQL_COUNT, FIELD_QUERY);
-- The Query_Loader holds context and state information for loading
-- the XML query file and initializing the Query_Definition.
type Query_Loader is record
-- File : Query_File_Access;
Hash_Value : Unbounded_String;
Query_Def : Query_Definition_Access;
Query : Query_Info_Ref.Ref;
Driver : Integer;
end record;
type Query_Loader_Access is access all Query_Loader;
procedure Set_Member (Into : in out Query_Loader;
Field : in Query_Info_Fields;
Value : in Util.Beans.Objects.Object);
-- ------------------------------
-- Called by the de-serialization when a given field is recognized.
-- ------------------------------
procedure Set_Member (Into : in out Query_Loader;
Field : in Query_Info_Fields;
Value : in Util.Beans.Objects.Object) is
use ADO.Drivers;
begin
case Field is
when FIELD_CLASS_NAME =>
Append (Into.Hash_Value, " class=");
Append (Into.Hash_Value, Util.Beans.Objects.To_Unbounded_String (Value));
when FIELD_PROPERTY_TYPE =>
Append (Into.Hash_Value, " type=");
Append (Into.Hash_Value, Util.Beans.Objects.To_Unbounded_String (Value));
when FIELD_PROPERTY_NAME =>
Append (Into.Hash_Value, " name=");
Append (Into.Hash_Value, Util.Beans.Objects.To_Unbounded_String (Value));
when FIELD_QUERY_NAME =>
Into.Query_Def := Find_Query (File, Util.Beans.Objects.To_String (Value));
Into.Driver := 0;
if Into.Query_Def /= null then
Into.Query := Query_Info_Ref.Create;
end if;
when FIELD_SQL_DRIVER =>
Into.Driver := Find_Driver (Util.Beans.Objects.To_String (Value));
when FIELD_SQL =>
if not Into.Query.Is_Null and Into.Driver >= 0 and Into.Query_Def /= null then
Set_Query_Pattern (Into.Query.Value.Main_Query (Driver_Index (Into.Driver)),
Value);
end if;
Into.Driver := 0;
when FIELD_SQL_COUNT =>
if not Into.Query.Is_Null and Into.Driver >= 0 and Into.Query_Def /= null then
Set_Query_Pattern (Into.Query.Value.Count_Query (Driver_Index (Into.Driver)),
Value);
end if;
Into.Driver := 0;
when FIELD_QUERY =>
if Into.Query_Def /= null then
-- Now we can safely setup the query info associated with the query definition.
Manager.Queries (Into.Query_Def.Query) := Into.Query;
end if;
Into.Query_Def := null;
end case;
end Set_Member;
package Query_Mapper is
new Util.Serialize.Mappers.Record_Mapper (Element_Type => Query_Loader,
Element_Type_Access => Query_Loader_Access,
Fields => Query_Info_Fields,
Set_Member => Set_Member);
Loader : aliased Query_Loader;
Sql_Mapper : aliased Query_Mapper.Mapper;
Reader : Util.Serialize.IO.XML.Parser;
Mapper : Util.Serialize.Mappers.Processing;
Path : constant String := To_String (File.Path);
begin
Log.Info ("Reading XML query {0}", Path);
-- Loader.File := Into;
Loader.Driver := 0;
-- Create the mapping to load the XML query file.
Sql_Mapper.Add_Mapping ("class/@name", FIELD_CLASS_NAME);
Sql_Mapper.Add_Mapping ("class/property/@type", FIELD_PROPERTY_TYPE);
Sql_Mapper.Add_Mapping ("class/property/@name", FIELD_PROPERTY_NAME);
Sql_Mapper.Add_Mapping ("query/@name", FIELD_QUERY_NAME);
Sql_Mapper.Add_Mapping ("query/sql", FIELD_SQL);
Sql_Mapper.Add_Mapping ("query/sql/@driver", FIELD_SQL_DRIVER);
Sql_Mapper.Add_Mapping ("query/sql-count", FIELD_SQL_COUNT);
Sql_Mapper.Add_Mapping ("query", FIELD_QUERY);
Mapper.Add_Mapping ("query-mapping", Sql_Mapper'Unchecked_Access);
-- Set the context for Set_Member.
Query_Mapper.Set_Context (Mapper, Loader'Access);
-- Read the XML query file.
Reader.Parse (Path, Mapper);
File.Next_Check := To_Unsigned_32 (Ada.Calendar.Clock) + FILE_CHECK_DELTA_TIME;
exception
when Ada.IO_Exceptions.Name_Error =>
Log.Error ("XML query file '{0}' does not exist", Path);
end Read_Query;
-- ------------------------------
-- Read the query definition.
-- ------------------------------
procedure Read_Query (Manager : in Query_Manager;
Into : in Query_Definition_Access) is
begin
if Manager.Queries (Into.Query).Is_Null
or else Is_Modified (Manager.Files (Into.File.File))
then
Read_Query (Manager, Manager.Files (Into.File.File));
end if;
end Read_Query;
-- ------------------------------
-- Initialize the queries to look in the list of directories specified by <b>Paths</b>.
-- Each search directory is separated by ';' (yes, even on Unix).
-- When <b>Load</b> is true, read the XML query file and initialize the query
-- definitions from that file.
-- ------------------------------
procedure Initialize (Manager : in out Query_Manager;
Config : in ADO.Drivers.Connections.Configuration'Class) is
Paths : constant String := Config.Get_Property ("ado.queries.paths");
Load : constant Boolean := Config.Get_Property ("ado.queries.load") = "true";
File : Query_File_Access := Query_Files;
begin
Log.Info ("Initializing query search paths to {0}", Paths);
if Manager.Queries = null then
Manager.Queries := new Query_Table (1 .. Last_Query);
end if;
if Manager.Files = null then
Manager.Files := new File_Table (1 .. Last_File);
end if;
Manager.Driver := Config.Get_Driver;
while File /= null loop
declare
Path : constant String := Util.Files.Find_File_Path (Name => File.Name.all,
Paths => Paths);
begin
Manager.Files (File.File).File := File;
Manager.Files (File.File).Path := To_Unbounded_String (Path);
if Load then
Read_Query (Manager, Manager.Files (File.File));
end if;
end;
File := File.Next;
end loop;
end Initialize;
-- ------------------------------
-- Find the query identified by the given name.
-- ------------------------------
function Find_Query (Name : in String) return Query_Definition_Access is
File : Query_File_Access := Query_Files;
begin
while File /= null loop
declare
Query : Query_Definition_Access := File.Queries;
begin
while Query /= null loop
if Query.Name.all = Name then
return Query;
end if;
Query := Query.Next;
end loop;
end;
File := File.Next;
end loop;
Log.Warn ("Query {0} not found", Name);
return null;
end Find_Query;
package body File is
begin
File.Name := Name'Access;
File.Sha1_Map := Hash'Access;
end File;
package body Query is
begin
Query.Name := Query_Name'Access;
Query.File := File;
Register (File => File, Query => Query'Access);
end Query;
end ADO.Queries.Loaders;
|
-----------------------------------------------------------------------
-- ado-queries-loaders -- Loader for Database Queries
-- Copyright (C) 2011, 2012, 2013, 2014, 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Interfaces;
with Ada.IO_Exceptions;
with Ada.Directories;
with Util.Files;
with Util.Log.Loggers;
with Util.Beans.Objects;
with Util.Serialize.IO.XML;
with Util.Serialize.Mappers.Record_Mapper;
package body ADO.Queries.Loaders is
use Util.Log;
use ADO.Drivers.Connections;
use Interfaces;
use Ada.Calendar;
Log : constant Loggers.Logger := Loggers.Create ("ADO.Queries.Loaders");
Base_Time : constant Ada.Calendar.Time := Ada.Calendar.Time_Of (Year => 1970,
Month => 1,
Day => 1);
-- Check for file modification time at most every 60 seconds.
FILE_CHECK_DELTA_TIME : constant Unsigned_32 := 60;
-- The list of query files defined by the application.
Query_Files : Query_File_Access := null;
Last_Query : Query_Index := 0;
Last_File : File_Index := 0;
-- Convert a Time to an Unsigned_32.
function To_Unsigned_32 (T : in Ada.Calendar.Time) return Unsigned_32;
pragma Inline_Always (To_Unsigned_32);
-- Get the modification time of the XML query file associated with the query.
function Modification_Time (File : in Query_File_Info) return Unsigned_32;
-- Initialize the query SQL pattern with the value
procedure Set_Query_Pattern (Into : in out Query_Pattern;
Value : in Util.Beans.Objects.Object);
-- ------------------------------
-- Register the query definition in the query file. Registration is done
-- in the package elaboration phase.
-- ------------------------------
procedure Register (File : in Query_File_Access;
Query : in Query_Definition_Access) is
begin
Last_Query := Last_Query + 1;
Query.File := File;
Query.Next := File.Queries;
Query.Query := Last_Query;
File.Queries := Query;
if File.Next = null and then Query_Files /= File then
Last_File := Last_File + 1;
File.Next := Query_Files;
File.File := Last_File;
Query_Files := File;
end if;
end Register;
function Find_Driver (Name : in String) return Integer;
function Find_Driver (Name : in String) return Integer is
begin
if Name'Length = 0 then
return 0;
end if;
declare
Driver : constant Drivers.Connections.Driver_Access
:= Drivers.Connections.Get_Driver (Name);
begin
if Driver = null then
-- There is no problem to have an SQL query for unsupported drivers, but still
-- report some warning.
Log.Warn ("Database driver {0} not found", Name);
return -1;
end if;
return Integer (Driver.Get_Driver_Index);
end;
end Find_Driver;
-- ------------------------------
-- Convert a Time to an Unsigned_32.
-- ------------------------------
function To_Unsigned_32 (T : in Ada.Calendar.Time) return Unsigned_32 is
D : constant Duration := Duration '(T - Base_Time);
begin
return Unsigned_32 (D);
end To_Unsigned_32;
-- ------------------------------
-- Get the modification time of the XML query file associated with the query.
-- ------------------------------
function Modification_Time (File : in Query_File_Info) return Unsigned_32 is
Path : constant String := To_String (File.Path);
begin
return To_Unsigned_32 (Ada.Directories.Modification_Time (Path));
exception
when Ada.IO_Exceptions.Name_Error =>
Log.Error ("XML query file '{0}' does not exist", Path);
return 0;
end Modification_Time;
-- ------------------------------
-- Returns True if the XML query file must be reloaded.
-- ------------------------------
function Is_Modified (File : in out Query_File_Info) return Boolean is
Now : constant Unsigned_32 := To_Unsigned_32 (Ada.Calendar.Clock);
begin
-- Have we passed the next check time?
if File.Next_Check > Now then
return False;
end if;
-- Next check in N seconds (60 by default).
File.Next_Check := Now + FILE_CHECK_DELTA_TIME;
-- See if the file was changed.
declare
M : constant Unsigned_32 := Modification_Time (File);
begin
if File.Last_Modified = M then
return False;
end if;
File.Last_Modified := M;
return True;
end;
end Is_Modified;
-- ------------------------------
-- Initialize the query SQL pattern with the value
-- ------------------------------
procedure Set_Query_Pattern (Into : in out Query_Pattern;
Value : in Util.Beans.Objects.Object) is
begin
Into.SQL := Util.Beans.Objects.To_Unbounded_String (Value);
end Set_Query_Pattern;
procedure Read_Query (Manager : in Query_Manager;
File : in out Query_File_Info) is
type Query_Info_Fields is (FIELD_CLASS_NAME, FIELD_PROPERTY_TYPE,
FIELD_PROPERTY_NAME, FIELD_QUERY_NAME,
FIELD_SQL_DRIVER,
FIELD_SQL, FIELD_SQL_COUNT, FIELD_QUERY);
-- The Query_Loader holds context and state information for loading
-- the XML query file and initializing the Query_Definition.
type Query_Loader is record
-- File : Query_File_Access;
Hash_Value : Unbounded_String;
Query_Def : Query_Definition_Access;
Query : Query_Info_Ref.Ref;
Driver : Integer;
end record;
type Query_Loader_Access is access all Query_Loader;
procedure Set_Member (Into : in out Query_Loader;
Field : in Query_Info_Fields;
Value : in Util.Beans.Objects.Object);
-- ------------------------------
-- Called by the de-serialization when a given field is recognized.
-- ------------------------------
procedure Set_Member (Into : in out Query_Loader;
Field : in Query_Info_Fields;
Value : in Util.Beans.Objects.Object) is
use ADO.Drivers;
begin
case Field is
when FIELD_CLASS_NAME =>
Append (Into.Hash_Value, " class=");
Append (Into.Hash_Value, Util.Beans.Objects.To_Unbounded_String (Value));
when FIELD_PROPERTY_TYPE =>
Append (Into.Hash_Value, " type=");
Append (Into.Hash_Value, Util.Beans.Objects.To_Unbounded_String (Value));
when FIELD_PROPERTY_NAME =>
Append (Into.Hash_Value, " name=");
Append (Into.Hash_Value, Util.Beans.Objects.To_Unbounded_String (Value));
when FIELD_QUERY_NAME =>
Into.Query_Def := Find_Query (File, Util.Beans.Objects.To_String (Value));
Into.Driver := 0;
if Into.Query_Def /= null then
Into.Query := Query_Info_Ref.Create;
end if;
when FIELD_SQL_DRIVER =>
Into.Driver := Find_Driver (Util.Beans.Objects.To_String (Value));
when FIELD_SQL =>
if not Into.Query.Is_Null and Into.Driver >= 0 and Into.Query_Def /= null then
Set_Query_Pattern (Into.Query.Value.Main_Query (Driver_Index (Into.Driver)),
Value);
end if;
Into.Driver := 0;
when FIELD_SQL_COUNT =>
if not Into.Query.Is_Null and Into.Driver >= 0 and Into.Query_Def /= null then
Set_Query_Pattern (Into.Query.Value.Count_Query (Driver_Index (Into.Driver)),
Value);
end if;
Into.Driver := 0;
when FIELD_QUERY =>
if Into.Query_Def /= null then
-- Now we can safely setup the query info associated with the query definition.
Manager.Queries (Into.Query_Def.Query) := Into.Query;
end if;
Into.Query_Def := null;
end case;
end Set_Member;
package Query_Mapper is
new Util.Serialize.Mappers.Record_Mapper (Element_Type => Query_Loader,
Element_Type_Access => Query_Loader_Access,
Fields => Query_Info_Fields,
Set_Member => Set_Member);
Loader : aliased Query_Loader;
Sql_Mapper : aliased Query_Mapper.Mapper;
Reader : Util.Serialize.IO.XML.Parser;
Mapper : Util.Serialize.Mappers.Processing;
Path : constant String := To_String (File.Path);
begin
Log.Info ("Reading XML query {0}", Path);
-- Loader.File := Into;
Loader.Driver := 0;
-- Create the mapping to load the XML query file.
Sql_Mapper.Add_Mapping ("class/@name", FIELD_CLASS_NAME);
Sql_Mapper.Add_Mapping ("class/property/@type", FIELD_PROPERTY_TYPE);
Sql_Mapper.Add_Mapping ("class/property/@name", FIELD_PROPERTY_NAME);
Sql_Mapper.Add_Mapping ("query/@name", FIELD_QUERY_NAME);
Sql_Mapper.Add_Mapping ("query/sql", FIELD_SQL);
Sql_Mapper.Add_Mapping ("query/sql/@driver", FIELD_SQL_DRIVER);
Sql_Mapper.Add_Mapping ("query/sql-count", FIELD_SQL_COUNT);
Sql_Mapper.Add_Mapping ("query", FIELD_QUERY);
Mapper.Add_Mapping ("query-mapping", Sql_Mapper'Unchecked_Access);
-- Set the context for Set_Member.
Query_Mapper.Set_Context (Mapper, Loader'Access);
-- Read the XML query file.
Reader.Parse (Path, Mapper);
File.Next_Check := To_Unsigned_32 (Ada.Calendar.Clock) + FILE_CHECK_DELTA_TIME;
exception
when Ada.IO_Exceptions.Name_Error =>
Log.Error ("XML query file '{0}' does not exist", Path);
end Read_Query;
-- ------------------------------
-- Read the query definition.
-- ------------------------------
procedure Read_Query (Manager : in Query_Manager;
Into : in Query_Definition_Access) is
begin
if Manager.Queries (Into.Query).Is_Null
or else Is_Modified (Manager.Files (Into.File.File))
then
Read_Query (Manager, Manager.Files (Into.File.File));
end if;
end Read_Query;
-- ------------------------------
-- Initialize the queries to look in the list of directories specified by <b>Paths</b>.
-- Each search directory is separated by ';' (yes, even on Unix).
-- When <b>Load</b> is true, read the XML query file and initialize the query
-- definitions from that file.
-- ------------------------------
procedure Initialize (Manager : in out Query_Manager;
Config : in ADO.Drivers.Connections.Configuration'Class) is
Paths : constant String := Config.Get_Property ("ado.queries.paths");
Load : constant Boolean := Config.Get_Property ("ado.queries.load") = "true";
File : Query_File_Access := Query_Files;
begin
Log.Info ("Initializing query search paths to {0}", Paths);
if Manager.Queries = null then
Manager.Queries := new Query_Table (1 .. Last_Query);
end if;
if Manager.Files = null then
Manager.Files := new File_Table (1 .. Last_File);
end if;
Manager.Driver := Config.Get_Driver;
while File /= null loop
declare
Path : constant String := Util.Files.Find_File_Path (Name => File.Name.all,
Paths => Paths);
begin
Manager.Files (File.File).File := File;
Manager.Files (File.File).Last_Modified := 0;
Manager.Files (File.File).Next_Check := 0;
Manager.Files (File.File).Path := To_Unbounded_String (Path);
if Load then
Read_Query (Manager, Manager.Files (File.File));
end if;
end;
File := File.Next;
end loop;
end Initialize;
-- ------------------------------
-- Find the query identified by the given name.
-- ------------------------------
function Find_Query (Name : in String) return Query_Definition_Access is
File : Query_File_Access := Query_Files;
begin
while File /= null loop
declare
Query : Query_Definition_Access := File.Queries;
begin
while Query /= null loop
if Query.Name.all = Name then
return Query;
end if;
Query := Query.Next;
end loop;
end;
File := File.Next;
end loop;
Log.Warn ("Query {0} not found", Name);
return null;
end Find_Query;
package body File is
begin
File.Name := Name'Access;
File.Sha1_Map := Hash'Access;
end File;
package body Query is
begin
Query.Name := Query_Name'Access;
Query.File := File;
Register (File => File, Query => Query'Access);
end Query;
end ADO.Queries.Loaders;
|
Initialize Last_Modified and Next_Check for each query file
|
Initialize Last_Modified and Next_Check for each query file
|
Ada
|
apache-2.0
|
stcarrez/ada-ado
|
6491a593b689f995e714a57911752bd98f7bb91e
|
src/asf-views-nodes-jsf.adb
|
src/asf-views-nodes-jsf.adb
|
-----------------------------------------------------------------------
-- views.nodes.jsf -- JSF Core Tag Library
-- 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 ASF.Converters;
with ASF.Validators.Texts;
with ASF.Validators.Numbers;
with ASF.Components.Holders;
with ASF.Components.Core.Views;
package body ASF.Views.Nodes.Jsf is
use ASF;
use EL.Objects;
-- ------------------------------
-- Converter Tag
-- ------------------------------
-- ------------------------------
-- Create the Converter Tag
-- ------------------------------
function Create_Converter_Tag_Node (Name : Unbounded_String;
Line : Views.Line_Info;
Parent : Views.Nodes.Tag_Node_Access;
Attributes : Views.Nodes.Tag_Attribute_Array_Access)
return Views.Nodes.Tag_Node_Access is
use ASF.Views.Nodes;
Node : constant Converter_Tag_Node_Access := new Converter_Tag_Node;
Conv : constant Tag_Attribute_Access := Find_Attribute (Attributes,
"converterId");
begin
Initialize (Node.all'Access, Name, Line, Parent, Attributes);
if Conv = null then
Node.Error ("Missing 'converterId' attribute");
else
Node.Converter := EL.Objects.To_Object (Conv.Value);
end if;
return Node.all'Access;
end Create_Converter_Tag_Node;
-- ------------------------------
-- Build the component tree from the tag node and attach it as
-- the last child of the given parent. Calls recursively the
-- method to create children. Get the specified converter and
-- add it to the parent component. This operation does not create any
-- new UIComponent.
-- ------------------------------
overriding
procedure Build_Components (Node : access Converter_Tag_Node;
Parent : in UIComponent_Access;
Context : in out Contexts.Facelets.Facelet_Context'Class) is
use ASF.Components.Holders;
use type ASF.Converters.Converter_Access;
Cvt : constant Converters.Converter_Access := Context.Get_Converter (Node.Converter);
begin
if not (Parent.all in Value_Holder'Class) then
Node.Error ("Parent component is not an instance of Value_Holder");
return;
end if;
if Cvt = null then
Node.Error ("Converter was not found");
return;
end if;
declare
VH : constant access Value_Holder'Class := Value_Holder'Class (Parent.all)'Access;
begin
VH.Set_Converter (Converter => Cvt);
end;
end Build_Components;
-- ------------------------------
-- Validator Tag
-- ------------------------------
-- ------------------------------
-- Create the Validator Tag
-- ------------------------------
function Create_Validator_Tag_Node (Name : Unbounded_String;
Line : Views.Line_Info;
Parent : Views.Nodes.Tag_Node_Access;
Attributes : Views.Nodes.Tag_Attribute_Array_Access)
return Views.Nodes.Tag_Node_Access is
use ASF.Views.Nodes;
Node : constant Validator_Tag_Node_Access := new Validator_Tag_Node;
Vid : constant Tag_Attribute_Access := Find_Attribute (Attributes,
"validatorId");
begin
Initialize (Node.all'Access, Name, Line, Parent, Attributes);
if Vid = null then
Node.Error ("Missing 'validatorId' attribute");
else
Node.Validator := EL.Objects.To_Object (Vid.Value);
end if;
return Node.all'Access;
end Create_Validator_Tag_Node;
-- ------------------------------
-- Get the specified validator and add it to the parent component.
-- This operation does not create any new UIComponent.
-- ------------------------------
overriding
procedure Build_Components (Node : access Validator_Tag_Node;
Parent : in UIComponent_Access;
Context : in out Contexts.Facelets.Facelet_Context'Class) is
use ASF.Components.Holders;
use type ASF.Validators.Validator_Access;
V : Validators.Validator_Access;
Shared : Boolean;
begin
if not (Parent.all in Editable_Value_Holder'Class) then
Node.Error ("Parent component is not an instance of Editable_Value_Holder");
return;
end if;
Validator_Tag_Node'Class (Node.all).Get_Validator (Context, V, Shared);
if V = null then
Node.Error ("Validator was not found");
return;
end if;
declare
VH : constant access Editable_Value_Holder'Class
:= Editable_Value_Holder'Class (Parent.all)'Access;
begin
VH.Add_Validator (Validator => V, Shared => Shared);
end;
end Build_Components;
-- ------------------------------
-- Get the validator instance that corresponds to the validator tag.
-- Returns in <b>Validator</b> the instance if it exists and indicate
-- in <b>Shared</b> whether it must be freed or not when the component is deleted.
-- ------------------------------
procedure Get_Validator (Node : in Validator_Tag_Node;
Context : in out Contexts.Facelets.Facelet_Context'Class;
Validator : out Validators.Validator_Access;
Shared : out Boolean) is
begin
Validator := Context.Get_Validator (Node.Validator);
Shared := True;
end Get_Validator;
-- ------------------------------
-- Range Validator Tag
-- ------------------------------
-- Create the Range_Validator Tag
function Create_Range_Validator_Tag_Node (Name : Unbounded_String;
Line : Views.Line_Info;
Parent : Views.Nodes.Tag_Node_Access;
Attributes : Views.Nodes.Tag_Attribute_Array_Access)
return Views.Nodes.Tag_Node_Access is
use ASF.Views.Nodes;
Node : constant Range_Validator_Tag_Node_Access := new Range_Validator_Tag_Node;
begin
Initialize (Node.all'Access, Name, Line, Parent, Attributes);
Node.Minimum := Find_Attribute (Attributes, "minimum");
Node.Maximum := Find_Attribute (Attributes, "maximum");
if Node.Minimum = null and Node.Maximum = null then
Node.Error ("Missing 'minimum' or 'maximum' attribute");
end if;
return Node.all'Access;
end Create_Range_Validator_Tag_Node;
-- Get the validator instance that corresponds to the range validator.
-- Returns in <b>Validator</b> the validator instance if it exists and indicate
-- in <b>Shared</b> whether it must be freed or not when the component is deleted.
overriding
procedure Get_Validator (Node : in Range_Validator_Tag_Node;
Context : in out Contexts.Facelets.Facelet_Context'Class;
Validator : out Validators.Validator_Access;
Shared : out Boolean) is
use type ASF.Validators.Validator_Access;
Min : Long_Long_Integer := Long_Long_Integer'First;
Max : Long_Long_Integer := Long_Long_Integer'Last;
begin
-- Get the minimum and maximum attributes.
begin
if Node.Minimum /= null then
Min := EL.Objects.To_Long_Long_Integer (Get_Value (Node.Minimum.all, Context));
end if;
if Node.Maximum /= null then
Max := EL.Objects.To_Long_Long_Integer (Get_Value (Node.Maximum.all, Context));
end if;
exception
when Constraint_Error =>
Node.Error ("Invalid minimum or maximum value");
end;
Shared := False;
if Max < Min then
Node.Error ("Minimum ({0}) should be less than maximum ({1})",
Long_Long_Integer'Image (Min), Long_Long_Integer'Image (Max));
return;
end if;
Validator := Validators.Numbers.Create_Range_Validator (Minimum => Min,
Maximum => Max);
end Get_Validator;
-- ------------------------------
-- Length Validator Tag
-- ------------------------------
-- ------------------------------
-- Create the Length_Validator Tag. Verifies that the XML node defines
-- the <b>minimum</b> or the <b>maximum</b> or both attributes.
-- ------------------------------
function Create_Length_Validator_Tag_Node (Name : Unbounded_String;
Line : Views.Line_Info;
Parent : Views.Nodes.Tag_Node_Access;
Attributes : Views.Nodes.Tag_Attribute_Array_Access)
return Views.Nodes.Tag_Node_Access is
use ASF.Views.Nodes;
Node : constant Length_Validator_Tag_Node_Access := new Length_Validator_Tag_Node;
begin
Initialize (Node.all'Access, Name, Line, Parent, Attributes);
Node.Minimum := Find_Attribute (Attributes, "minimum");
Node.Maximum := Find_Attribute (Attributes, "maximum");
if Node.Minimum = null and Node.Maximum = null then
Node.Error ("Missing 'minimum' or 'maximum' attribute");
end if;
return Node.all'Access;
end Create_Length_Validator_Tag_Node;
-- ------------------------------
-- Get the validator instance that corresponds to the validator tag.
-- Returns in <b>Validator</b> the instance if it exists and indicate
-- in <b>Shared</b> whether it must be freed or not when the component is deleted.
-- ------------------------------
overriding
procedure Get_Validator (Node : in Length_Validator_Tag_Node;
Context : in out Contexts.Facelets.Facelet_Context'Class;
Validator : out Validators.Validator_Access;
Shared : out Boolean) is
use type ASF.Validators.Validator_Access;
Min : Natural := 0;
Max : Natural := Natural'Last;
begin
-- Get the minimum and maximum attributes.
begin
if Node.Minimum /= null then
Min := Natural (EL.Objects.To_Integer (Get_Value (Node.Minimum.all, Context)));
end if;
if Node.Maximum /= null then
Max := Natural (EL.Objects.To_Integer (Get_Value (Node.Maximum.all, Context)));
end if;
exception
when Constraint_Error =>
Node.Error ("Invalid minimum or maximum value");
end;
Shared := False;
if Max < Min then
Node.Error ("Minimum ({0}) should be less than maximum ({1})",
Natural'Image (Min), Natural'Image (Max));
return;
end if;
Validator := Validators.Texts.Create_Length_Validator (Minimum => Min,
Maximum => Max);
end Get_Validator;
-- ------------------------------
-- Attribute Tag
-- ------------------------------
-- ------------------------------
-- Create the Attribute Tag
-- ------------------------------
function Create_Attribute_Tag_Node (Name : Unbounded_String;
Line : Views.Line_Info;
Parent : Views.Nodes.Tag_Node_Access;
Attributes : Views.Nodes.Tag_Attribute_Array_Access)
return Views.Nodes.Tag_Node_Access is
use ASF.Views.Nodes;
Node : constant Attribute_Tag_Node_Access := new Attribute_Tag_Node;
begin
Initialize (Node.all'Access, Name, Line, Parent, Attributes);
Node.Attr_Name := Find_Attribute (Attributes, "name");
Node.Value := Find_Attribute (Attributes, "value");
if Node.Attr_Name = null then
Node.Error ("Missing 'name' attribute");
end if;
if Node.Value = null then
Node.Error ("Missing 'value' attribute");
end if;
return Node.all'Access;
end Create_Attribute_Tag_Node;
-- ------------------------------
-- Build the component tree from the tag node and attach it as
-- the last child of the given parent. Calls recursively the
-- method to create children.
-- Adds the attribute to the component node.
-- This operation does not create any new UIComponent.
-- ------------------------------
overriding
procedure Build_Components (Node : access Attribute_Tag_Node;
Parent : in UIComponent_Access;
Context : in out Contexts.Facelets.Facelet_Context'Class) is
use EL.Expressions;
begin
if Node.Attr_Name /= null and Node.Value /= null then
declare
Name : constant EL.Objects.Object := Get_Value (Node.Attr_Name.all, Context);
begin
Node.Attr.Name := EL.Objects.To_Unbounded_String (Name);
if Node.Value.Binding /= null then
declare
Expr : constant EL.Expressions.Expression
:= ASF.Views.Nodes.Reduce_Expression (Node.Value.all, Context);
begin
Parent.Set_Attribute (Def => Node.Attr'Access, Value => Expr);
end;
else
Parent.Set_Attribute (Def => Node.Attr'Access,
Value => Get_Value (Node.Value.all, Context));
end if;
end;
end if;
end Build_Components;
-- ------------------------------
-- Facet Tag
-- ------------------------------
-- ------------------------------
-- Create the Facet Tag
-- ------------------------------
function Create_Facet_Tag_Node (Name : Unbounded_String;
Line : Views.Line_Info;
Parent : Views.Nodes.Tag_Node_Access;
Attributes : Views.Nodes.Tag_Attribute_Array_Access)
return Views.Nodes.Tag_Node_Access is
use ASF.Views.Nodes;
Node : constant Facet_Tag_Node_Access := new Facet_Tag_Node;
begin
Initialize (Node.all'Access, Name, Line, Parent, Attributes);
Node.Facet_Name := Find_Attribute (Attributes, "name");
if Node.Facet_Name = null then
Node.Error ("Missing 'name' attribute");
end if;
return Node.all'Access;
end Create_Facet_Tag_Node;
-- ------------------------------
-- Build the component tree from the tag node and attach it as
-- the facet component of the given parent. Calls recursively the
-- method to create children.
-- ------------------------------
overriding
procedure Build_Components (Node : access Facet_Tag_Node;
Parent : in UIComponent_Access;
Context : in out Contexts.Facelets.Facelet_Context'Class) is
begin
null;
end Build_Components;
-- ------------------------------
-- Metadata Tag
-- ------------------------------
-- ------------------------------
-- Create the Metadata Tag
-- ------------------------------
function Create_Metadata_Tag_Node (Name : Unbounded_String;
Line : Views.Line_Info;
Parent : Views.Nodes.Tag_Node_Access;
Attributes : Views.Nodes.Tag_Attribute_Array_Access)
return Views.Nodes.Tag_Node_Access is
use ASF.Views.Nodes;
Node : constant Metadata_Tag_Node_Access := new Metadata_Tag_Node;
begin
Initialize (Node.all'Access, Name, Line, Parent, Attributes);
return Node.all'Access;
end Create_Metadata_Tag_Node;
-- ------------------------------
-- Build the component tree from the tag node and attach it as a metadata information
-- facet for the UIView parent component.
-- ------------------------------
overriding
procedure Build_Components (Node : access Metadata_Tag_Node;
Parent : in UIComponent_Access;
Context : in out Contexts.Facelets.Facelet_Context'Class) is
use ASF.Components.Core.Views;
begin
if not (Parent.all in UIView'Class) then
Node.Error ("Parent component of <f:metadata> must be a <f:view>");
return;
end if;
declare
UI : constant UIViewMetaData_Access := new UIViewMetaData;
begin
UIView'Class (Parent.all).Set_Metadata (UI, Node);
Build_Attributes (UI.all, Node.all, Context);
UI.Initialize (UI.Get_Context.all);
Node.Build_Children (UI.all'Access, Context);
end;
end Build_Components;
end ASF.Views.Nodes.Jsf;
|
-----------------------------------------------------------------------
-- views.nodes.jsf -- JSF Core Tag Library
-- Copyright (C) 2010, 2011, 2012, 2013 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with ASF.Converters;
with ASF.Validators.Texts;
with ASF.Validators.Numbers;
with ASF.Components.Holders;
with ASF.Components.Core.Views;
package body ASF.Views.Nodes.Jsf is
use ASF;
use EL.Objects;
-- ------------------------------
-- Converter Tag
-- ------------------------------
-- ------------------------------
-- Create the Converter Tag
-- ------------------------------
function Create_Converter_Tag_Node (Binding : in Binding_Access;
Line : in Views.Line_Info;
Parent : in Views.Nodes.Tag_Node_Access;
Attributes : in Views.Nodes.Tag_Attribute_Array_Access)
return Views.Nodes.Tag_Node_Access is
use ASF.Views.Nodes;
Node : constant Converter_Tag_Node_Access := new Converter_Tag_Node;
Conv : constant Tag_Attribute_Access := Find_Attribute (Attributes,
"converterId");
begin
Initialize (Node.all'Access, Binding, Line, Parent, Attributes);
if Conv = null then
Node.Error ("Missing 'converterId' attribute");
else
Node.Converter := EL.Objects.To_Object (Conv.Value);
end if;
return Node.all'Access;
end Create_Converter_Tag_Node;
-- ------------------------------
-- Build the component tree from the tag node and attach it as
-- the last child of the given parent. Calls recursively the
-- method to create children. Get the specified converter and
-- add it to the parent component. This operation does not create any
-- new UIComponent.
-- ------------------------------
overriding
procedure Build_Components (Node : access Converter_Tag_Node;
Parent : in UIComponent_Access;
Context : in out Contexts.Facelets.Facelet_Context'Class) is
use ASF.Components.Holders;
use type ASF.Converters.Converter_Access;
Cvt : constant Converters.Converter_Access := Context.Get_Converter (Node.Converter);
begin
if not (Parent.all in Value_Holder'Class) then
Node.Error ("Parent component is not an instance of Value_Holder");
return;
end if;
if Cvt = null then
Node.Error ("Converter was not found");
return;
end if;
declare
VH : constant access Value_Holder'Class := Value_Holder'Class (Parent.all)'Access;
begin
VH.Set_Converter (Converter => Cvt);
end;
end Build_Components;
-- ------------------------------
-- Validator Tag
-- ------------------------------
-- ------------------------------
-- Create the Validator Tag
-- ------------------------------
function Create_Validator_Tag_Node (Binding : in Binding_Access;
Line : in Views.Line_Info;
Parent : in Views.Nodes.Tag_Node_Access;
Attributes : in Views.Nodes.Tag_Attribute_Array_Access)
return Views.Nodes.Tag_Node_Access is
use ASF.Views.Nodes;
Node : constant Validator_Tag_Node_Access := new Validator_Tag_Node;
Vid : constant Tag_Attribute_Access := Find_Attribute (Attributes,
"validatorId");
begin
Initialize (Node.all'Access, Binding, Line, Parent, Attributes);
if Vid = null then
Node.Error ("Missing 'validatorId' attribute");
else
Node.Validator := EL.Objects.To_Object (Vid.Value);
end if;
return Node.all'Access;
end Create_Validator_Tag_Node;
-- ------------------------------
-- Get the specified validator and add it to the parent component.
-- This operation does not create any new UIComponent.
-- ------------------------------
overriding
procedure Build_Components (Node : access Validator_Tag_Node;
Parent : in UIComponent_Access;
Context : in out Contexts.Facelets.Facelet_Context'Class) is
use ASF.Components.Holders;
use type ASF.Validators.Validator_Access;
V : Validators.Validator_Access;
Shared : Boolean;
begin
if not (Parent.all in Editable_Value_Holder'Class) then
Node.Error ("Parent component is not an instance of Editable_Value_Holder");
return;
end if;
Validator_Tag_Node'Class (Node.all).Get_Validator (Context, V, Shared);
if V = null then
Node.Error ("Validator was not found");
return;
end if;
declare
VH : constant access Editable_Value_Holder'Class
:= Editable_Value_Holder'Class (Parent.all)'Access;
begin
VH.Add_Validator (Validator => V, Shared => Shared);
end;
end Build_Components;
-- ------------------------------
-- Get the validator instance that corresponds to the validator tag.
-- Returns in <b>Validator</b> the instance if it exists and indicate
-- in <b>Shared</b> whether it must be freed or not when the component is deleted.
-- ------------------------------
procedure Get_Validator (Node : in Validator_Tag_Node;
Context : in out Contexts.Facelets.Facelet_Context'Class;
Validator : out Validators.Validator_Access;
Shared : out Boolean) is
begin
Validator := Context.Get_Validator (Node.Validator);
Shared := True;
end Get_Validator;
-- ------------------------------
-- Range Validator Tag
-- ------------------------------
-- Create the Range_Validator Tag
function Create_Range_Validator_Tag_Node (Binding : in Binding_Access;
Line : in Views.Line_Info;
Parent : in Views.Nodes.Tag_Node_Access;
Attributes : in Views.Nodes.Tag_Attribute_Array_Access)
return Views.Nodes.Tag_Node_Access is
use ASF.Views.Nodes;
Node : constant Range_Validator_Tag_Node_Access := new Range_Validator_Tag_Node;
begin
Initialize (Node.all'Access, Binding, Line, Parent, Attributes);
Node.Minimum := Find_Attribute (Attributes, "minimum");
Node.Maximum := Find_Attribute (Attributes, "maximum");
if Node.Minimum = null and Node.Maximum = null then
Node.Error ("Missing 'minimum' or 'maximum' attribute");
end if;
return Node.all'Access;
end Create_Range_Validator_Tag_Node;
-- Get the validator instance that corresponds to the range validator.
-- Returns in <b>Validator</b> the validator instance if it exists and indicate
-- in <b>Shared</b> whether it must be freed or not when the component is deleted.
overriding
procedure Get_Validator (Node : in Range_Validator_Tag_Node;
Context : in out Contexts.Facelets.Facelet_Context'Class;
Validator : out Validators.Validator_Access;
Shared : out Boolean) is
use type ASF.Validators.Validator_Access;
Min : Long_Long_Integer := Long_Long_Integer'First;
Max : Long_Long_Integer := Long_Long_Integer'Last;
begin
-- Get the minimum and maximum attributes.
begin
if Node.Minimum /= null then
Min := EL.Objects.To_Long_Long_Integer (Get_Value (Node.Minimum.all, Context));
end if;
if Node.Maximum /= null then
Max := EL.Objects.To_Long_Long_Integer (Get_Value (Node.Maximum.all, Context));
end if;
exception
when Constraint_Error =>
Node.Error ("Invalid minimum or maximum value");
end;
Shared := False;
if Max < Min then
Node.Error ("Minimum ({0}) should be less than maximum ({1})",
Long_Long_Integer'Image (Min), Long_Long_Integer'Image (Max));
return;
end if;
Validator := Validators.Numbers.Create_Range_Validator (Minimum => Min,
Maximum => Max);
end Get_Validator;
-- ------------------------------
-- Length Validator Tag
-- ------------------------------
-- ------------------------------
-- Create the Length_Validator Tag. Verifies that the XML node defines
-- the <b>minimum</b> or the <b>maximum</b> or both attributes.
-- ------------------------------
function Create_Length_Validator_Tag_Node (Binding : in Binding_Access;
Line : in Views.Line_Info;
Parent : in Views.Nodes.Tag_Node_Access;
Attributes : in Views.Nodes.Tag_Attribute_Array_Access)
return Views.Nodes.Tag_Node_Access is
use ASF.Views.Nodes;
Node : constant Length_Validator_Tag_Node_Access := new Length_Validator_Tag_Node;
begin
Initialize (Node.all'Access, Binding, Line, Parent, Attributes);
Node.Minimum := Find_Attribute (Attributes, "minimum");
Node.Maximum := Find_Attribute (Attributes, "maximum");
if Node.Minimum = null and Node.Maximum = null then
Node.Error ("Missing 'minimum' or 'maximum' attribute");
end if;
return Node.all'Access;
end Create_Length_Validator_Tag_Node;
-- ------------------------------
-- Get the validator instance that corresponds to the validator tag.
-- Returns in <b>Validator</b> the instance if it exists and indicate
-- in <b>Shared</b> whether it must be freed or not when the component is deleted.
-- ------------------------------
overriding
procedure Get_Validator (Node : in Length_Validator_Tag_Node;
Context : in out Contexts.Facelets.Facelet_Context'Class;
Validator : out Validators.Validator_Access;
Shared : out Boolean) is
use type ASF.Validators.Validator_Access;
Min : Natural := 0;
Max : Natural := Natural'Last;
begin
-- Get the minimum and maximum attributes.
begin
if Node.Minimum /= null then
Min := Natural (EL.Objects.To_Integer (Get_Value (Node.Minimum.all, Context)));
end if;
if Node.Maximum /= null then
Max := Natural (EL.Objects.To_Integer (Get_Value (Node.Maximum.all, Context)));
end if;
exception
when Constraint_Error =>
Node.Error ("Invalid minimum or maximum value");
end;
Shared := False;
if Max < Min then
Node.Error ("Minimum ({0}) should be less than maximum ({1})",
Natural'Image (Min), Natural'Image (Max));
return;
end if;
Validator := Validators.Texts.Create_Length_Validator (Minimum => Min,
Maximum => Max);
end Get_Validator;
-- ------------------------------
-- Attribute Tag
-- ------------------------------
-- ------------------------------
-- Create the Attribute Tag
-- ------------------------------
function Create_Attribute_Tag_Node (Binding : in Binding_Access;
Line : in Views.Line_Info;
Parent : in Views.Nodes.Tag_Node_Access;
Attributes : in Views.Nodes.Tag_Attribute_Array_Access)
return Views.Nodes.Tag_Node_Access is
use ASF.Views.Nodes;
Attr : constant Tag_Attribute_Access := Find_Attribute (Attributes, "name");
Node : Attribute_Tag_Node_Access;
begin
Node := new Attribute_Tag_Node;
Initialize (Node.all'Access, Binding, Line, Parent, Attributes);
Node.Attr_Name := Attr;
Node.Value := Find_Attribute (Attributes, "value");
if Node.Attr_Name = null then
Node.Error ("Missing 'name' attribute");
else
Node.Attr.Name := Attr.Value;
end if;
if Node.Value = null then
Node.Error ("Missing 'value' attribute");
end if;
return Node.all'Access;
end Create_Attribute_Tag_Node;
-- ------------------------------
-- Build the component tree from the tag node and attach it as
-- the last child of the given parent. Calls recursively the
-- method to create children.
-- Adds the attribute to the component node.
-- This operation does not create any new UIComponent.
-- ------------------------------
overriding
procedure Build_Components (Node : access Attribute_Tag_Node;
Parent : in UIComponent_Access;
Context : in out Contexts.Facelets.Facelet_Context'Class) is
use EL.Expressions;
begin
if Node.Attr_Name /= null and Node.Value /= null then
if Node.Value.Binding /= null then
declare
Expr : constant EL.Expressions.Expression
:= ASF.Views.Nodes.Reduce_Expression (Node.Value.all, Context);
begin
Parent.Set_Attribute (Def => Node.Attr'Access, Value => Expr);
end;
else
Parent.Set_Attribute (Def => Node.Attr'Access,
Value => Get_Value (Node.Value.all, Context));
end if;
end if;
end Build_Components;
-- ------------------------------
-- Facet Tag
-- ------------------------------
-- ------------------------------
-- Create the Facet Tag
-- ------------------------------
function Create_Facet_Tag_Node (Binding : in Binding_Access;
Line : in Views.Line_Info;
Parent : in Views.Nodes.Tag_Node_Access;
Attributes : in Views.Nodes.Tag_Attribute_Array_Access)
return Views.Nodes.Tag_Node_Access is
use ASF.Views.Nodes;
Node : constant Facet_Tag_Node_Access := new Facet_Tag_Node;
begin
Initialize (Node.all'Access, Binding, Line, Parent, Attributes);
Node.Facet_Name := Find_Attribute (Attributes, "name");
if Node.Facet_Name = null then
Node.Error ("Missing 'name' attribute");
end if;
return Node.all'Access;
end Create_Facet_Tag_Node;
-- ------------------------------
-- Build the component tree from the tag node and attach it as
-- the facet component of the given parent. Calls recursively the
-- method to create children.
-- ------------------------------
overriding
procedure Build_Components (Node : access Facet_Tag_Node;
Parent : in UIComponent_Access;
Context : in out Contexts.Facelets.Facelet_Context'Class) is
begin
null;
end Build_Components;
-- ------------------------------
-- Metadata Tag
-- ------------------------------
-- ------------------------------
-- Create the Metadata Tag
-- ------------------------------
function Create_Metadata_Tag_Node (Binding : in Binding_Access;
Line : in Views.Line_Info;
Parent : in Views.Nodes.Tag_Node_Access;
Attributes : in Views.Nodes.Tag_Attribute_Array_Access)
return Views.Nodes.Tag_Node_Access is
use ASF.Views.Nodes;
Node : constant Metadata_Tag_Node_Access := new Metadata_Tag_Node;
begin
Initialize (Node.all'Access, Binding, Line, Parent, Attributes);
return Node.all'Access;
end Create_Metadata_Tag_Node;
-- ------------------------------
-- Build the component tree from the tag node and attach it as a metadata information
-- facet for the UIView parent component.
-- ------------------------------
overriding
procedure Build_Components (Node : access Metadata_Tag_Node;
Parent : in UIComponent_Access;
Context : in out Contexts.Facelets.Facelet_Context'Class) is
use ASF.Components.Core.Views;
begin
if not (Parent.all in UIView'Class) then
Node.Error ("Parent component of <f:metadata> must be a <f:view>");
return;
end if;
declare
UI : constant UIViewMetaData_Access := new UIViewMetaData;
begin
UIView'Class (Parent.all).Set_Metadata (UI, Node);
Build_Attributes (UI.all, Node.all, Context);
UI.Initialize (UI.Get_Context.all);
Node.Build_Children (UI.all'Access, Context);
end;
end Build_Components;
end ASF.Views.Nodes.Jsf;
|
Change the Name parameter to a Binding access
|
Change the Name parameter to a Binding access
|
Ada
|
apache-2.0
|
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
|
e1c3dd64657c1619b7c4f3f05f493395c6adf5f6
|
src/util-texts-builders.adb
|
src/util-texts-builders.adb
|
-----------------------------------------------------------------------
-- util-texts-builders -- Text builder
-- Copyright (C) 2013 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Unchecked_Deallocation;
package body Util.Texts.Builders is
-- ------------------------------
-- Get the length of the item builder.
-- ------------------------------
function Length (Source : in Builder) return Natural is
begin
return Source.Length;
end Length;
-- ------------------------------
-- Get the capacity of the builder.
-- ------------------------------
function Capacity (Source : in Builder) return Natural is
B : constant Block_Access := Source.Current;
begin
return Source.Length + B.Len - B.Last;
end Capacity;
-- ------------------------------
-- Get the builder block size.
-- ------------------------------
function Block_Size (Source : in Builder) return Positive is
begin
return Source.Block_Size;
end Block_Size;
-- ------------------------------
-- Set the block size for the allocation of next chunks.
-- ------------------------------
procedure Set_Block_Size (Source : in out Builder;
Size : in Positive) is
begin
Source.Block_Size := Size;
end Set_Block_Size;
-- ------------------------------
-- Append the <tt>New_Item</tt> at the end of the source growing the buffer if necessary.
-- ------------------------------
procedure Append (Source : in out Builder;
New_Item : in Input) is
B : Block_Access := Source.Current;
Start : Natural := New_Item'First;
Last : constant Natural := New_Item'Last;
begin
while Start <= Last loop
declare
Space : Natural := B.Len - B.Last;
Size : constant Natural := Last - Start + 1;
begin
if Space > Size then
Space := Size;
elsif Space = 0 then
if Size > Source.Block_Size then
B.Next_Block := new Block (Size);
else
B.Next_Block := new Block (Source.Block_Size);
end if;
B := B.Next_Block;
Source.Current := B;
if B.Len > Size then
Space := Size;
else
Space := B.Len;
end if;
end if;
B.Content (B.Last + 1 .. B.Last + Space) := New_Item (Start .. Start + Space - 1);
Source.Length := Source.Length + Space;
B.Last := B.Last + Space;
Start := Start + Space;
end;
end loop;
end Append;
-- ------------------------------
-- Append the <tt>New_Item</tt> at the end of the source growing the buffer if necessary.
-- ------------------------------
procedure Append (Source : in out Builder;
New_Item : in Element_Type) is
B : Block_Access := Source.Current;
begin
if B.Len = B.Last then
B.Next_Block := new Block (Source.Block_Size);
B := B.Next_Block;
Source.Current := B;
end if;
Source.Length := Source.Length + 1;
B.Last := B.Last + 1;
B.Content (B.Last) := New_Item;
end Append;
-- ------------------------------
-- Clear the source freeing any storage allocated for the buffer.
-- ------------------------------
procedure Clear (Source : in out Builder) is
procedure Free is
new Ada.Unchecked_Deallocation (Object => Block, Name => Block_Access);
Current, Next : Block_Access;
begin
Next := Source.First.Next_Block;
while Next /= null loop
Current := Next;
Next := Current.Next_Block;
Free (Current);
end loop;
Source.First.Next_Block := null;
Source.First.Last := 0;
Source.Current := Source.First'Unchecked_Access;
Source.Length := 0;
end Clear;
-- ------------------------------
-- Iterate over the buffer content calling the <tt>Process</tt> procedure with each
-- chunk.
-- ------------------------------
procedure Iterate (Source : in Builder;
Process : not null access procedure (Chunk : in Input)) is
begin
if Source.First.Last > 0 then
Process (Source.First.Content (1 .. Source.First.Last));
declare
B : Block_Access := Source.First.Next_Block;
begin
while B /= null loop
Process (B.Content (1 .. B.Last));
B := B.Next_Block;
end loop;
end;
end if;
end Iterate;
-- ------------------------------
-- Get the buffer content as an array.
-- ------------------------------
function To_Array (Source : in Builder) return Input is
Result : Input (1 .. Source.Length);
begin
if Source.First.Last > 0 then
declare
Pos : Positive := Source.First.Last;
B : Block_Access := Source.First.Next_Block;
begin
Result (1 .. Pos) := Source.First.Content (1 .. Pos);
while B /= null loop
Result (Pos + 1 .. Pos + B.Last) := B.Content (1 .. B.Last);
Pos := Pos + B.Last;
B := B.Next_Block;
end loop;
end;
end if;
return Result;
end To_Array;
-- ------------------------------
-- Setup the builder.
-- ------------------------------
overriding
procedure Initialize (Source : in out Builder) is
begin
Source.Current := Source.First'Unchecked_Access;
end Initialize;
-- ------------------------------
-- Finalize the builder releasing the storage.
-- ------------------------------
overriding
procedure Finalize (Source : in out Builder) is
begin
Clear (Source);
end Finalize;
end Util.Texts.Builders;
|
-----------------------------------------------------------------------
-- util-texts-builders -- Text builder
-- Copyright (C) 2013, 2016 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Unchecked_Deallocation;
package body Util.Texts.Builders is
-- ------------------------------
-- Get the length of the item builder.
-- ------------------------------
function Length (Source : in Builder) return Natural is
begin
return Source.Length;
end Length;
-- ------------------------------
-- Get the capacity of the builder.
-- ------------------------------
function Capacity (Source : in Builder) return Natural is
B : constant Block_Access := Source.Current;
begin
return Source.Length + B.Len - B.Last;
end Capacity;
-- ------------------------------
-- Get the builder block size.
-- ------------------------------
function Block_Size (Source : in Builder) return Positive is
begin
return Source.Block_Size;
end Block_Size;
-- ------------------------------
-- Set the block size for the allocation of next chunks.
-- ------------------------------
procedure Set_Block_Size (Source : in out Builder;
Size : in Positive) is
begin
Source.Block_Size := Size;
end Set_Block_Size;
-- ------------------------------
-- Append the <tt>New_Item</tt> at the end of the source growing the buffer if necessary.
-- ------------------------------
procedure Append (Source : in out Builder;
New_Item : in Input) is
B : Block_Access := Source.Current;
Start : Natural := New_Item'First;
Last : constant Natural := New_Item'Last;
begin
while Start <= Last loop
declare
Space : Natural := B.Len - B.Last;
Size : constant Natural := Last - Start + 1;
begin
if Space > Size then
Space := Size;
elsif Space = 0 then
if Size > Source.Block_Size then
B.Next_Block := new Block (Size);
else
B.Next_Block := new Block (Source.Block_Size);
end if;
B := B.Next_Block;
Source.Current := B;
if B.Len > Size then
Space := Size;
else
Space := B.Len;
end if;
end if;
B.Content (B.Last + 1 .. B.Last + Space) := New_Item (Start .. Start + Space - 1);
Source.Length := Source.Length + Space;
B.Last := B.Last + Space;
Start := Start + Space;
end;
end loop;
end Append;
-- ------------------------------
-- Append the <tt>New_Item</tt> at the end of the source growing the buffer if necessary.
-- ------------------------------
procedure Append (Source : in out Builder;
New_Item : in Element_Type) is
B : Block_Access := Source.Current;
begin
if B.Len = B.Last then
B.Next_Block := new Block (Source.Block_Size);
B := B.Next_Block;
Source.Current := B;
end if;
Source.Length := Source.Length + 1;
B.Last := B.Last + 1;
B.Content (B.Last) := New_Item;
end Append;
-- ------------------------------
-- Clear the source freeing any storage allocated for the buffer.
-- ------------------------------
procedure Clear (Source : in out Builder) is
procedure Free is
new Ada.Unchecked_Deallocation (Object => Block, Name => Block_Access);
Current, Next : Block_Access;
begin
Next := Source.First.Next_Block;
while Next /= null loop
Current := Next;
Next := Current.Next_Block;
Free (Current);
end loop;
Source.First.Next_Block := null;
Source.First.Last := 0;
Source.Current := Source.First'Unchecked_Access;
Source.Length := 0;
end Clear;
-- ------------------------------
-- Iterate over the buffer content calling the <tt>Process</tt> procedure with each
-- chunk.
-- ------------------------------
procedure Iterate (Source : in Builder;
Process : not null access procedure (Chunk : in Input)) is
begin
if Source.First.Last > 0 then
Process (Source.First.Content (1 .. Source.First.Last));
declare
B : Block_Access := Source.First.Next_Block;
begin
while B /= null loop
Process (B.Content (1 .. B.Last));
B := B.Next_Block;
end loop;
end;
end if;
end Iterate;
-- ------------------------------
-- Return the content starting from the tail and up to <tt>Length</tt> items.
-- ------------------------------
function Tail (Source : in Builder;
Length : in Natural) return Input is
Last : constant Natural := Source.Current.Last;
begin
if Last >= Length then
return Source.Current.Content (Last - Length + 1 .. Last);
elsif Length >= Source.Length then
return To_Array (Source);
else
declare
Result : Input (1 .. Length);
Offset : Natural := Source.Length - Length;
B : Block_Access := Source.First'Unrestricted_Access;
Src_Pos : Positive := 1;
Dst_Pos : Positive := 1;
Len : Natural;
begin
-- Skip the data moving to next blocks as needed.
while Offset /= 0 loop
if Offset < B.Last then
Src_Pos := Offset + 1;
Offset := 0;
else
Offset := Offset - B.Last + 1;
B := B.Next_Block;
end if;
end loop;
-- Copy what remains until we reach the length.
while Dst_Pos <= Length loop
Len := B.Last - Src_Pos + 1;
Result (Dst_Pos .. Dst_Pos + Len - 1) := B.Content (Src_Pos .. B.Last);
Src_Pos := 1;
Dst_Pos := Dst_Pos + Len;
B := B.Next_Block;
end loop;
return Result;
end;
end if;
end Tail;
-- ------------------------------
-- Get the buffer content as an array.
-- ------------------------------
function To_Array (Source : in Builder) return Input is
Result : Input (1 .. Source.Length);
begin
if Source.First.Last > 0 then
declare
Pos : Positive := Source.First.Last;
B : Block_Access := Source.First.Next_Block;
begin
Result (1 .. Pos) := Source.First.Content (1 .. Pos);
while B /= null loop
Result (Pos + 1 .. Pos + B.Last) := B.Content (1 .. B.Last);
Pos := Pos + B.Last;
B := B.Next_Block;
end loop;
end;
end if;
return Result;
end To_Array;
-- ------------------------------
-- Setup the builder.
-- ------------------------------
overriding
procedure Initialize (Source : in out Builder) is
begin
Source.Current := Source.First'Unchecked_Access;
end Initialize;
-- ------------------------------
-- Finalize the builder releasing the storage.
-- ------------------------------
overriding
procedure Finalize (Source : in out Builder) is
begin
Clear (Source);
end Finalize;
end Util.Texts.Builders;
|
Implement the Tail function
|
Implement the Tail function
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
7b15e061315956b158987cbbf2ca1816bd1f80a1
|
src/security-policies-urls.ads
|
src/security-policies-urls.ads
|
-----------------------------------------------------------------------
-- security-policies-urls -- URL security policy
-- 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.Containers.Hashed_Maps;
with Ada.Containers.Vectors;
with Util.Refs;
with Util.Serialize.IO.XML;
with GNAT.Regexp;
package Security.Policies.Urls is
NAME : constant String := "URL-Policy";
-- ------------------------------
-- URI Permission
-- ------------------------------
-- Represents a permission to access a given URI.
type URI_Permission (Len : Natural) is new Permissions.Permission with record
URI : String (1 .. Len);
end record;
-- ------------------------------
-- URL policy
-- ------------------------------
type URL_Policy is new Policy with private;
type URL_Policy_Access is access all URL_Policy'Class;
Invalid_Name : exception;
-- Get the policy name.
overriding
function Get_Name (From : in URL_Policy) return String;
-- Returns True if the user has the permission to access the given URI permission.
function Has_Permission (Manager : in URL_Policy;
Context : in Security_Context_Access;
Permission : in URI_Permission'Class) return Boolean;
-- Grant the permission to access to the given <b>URI</b> to users having the <b>To</b>
-- permissions.
procedure Grant_URI_Permission (Manager : in out URL_Policy;
URI : in String;
To : in String);
-- Initialize the permission manager.
overriding
procedure Initialize (Manager : in out URL_Policy);
-- Finalize the permission manager.
overriding
procedure Finalize (Manager : in out URL_Policy);
-- Setup the XML parser to read the <b>policy</b> description.
overriding
procedure Prepare_Config (Policy : in out URL_Policy;
Reader : in out Util.Serialize.IO.XML.Parser);
-- Finish reading the XML policy configuration. The security policy implementation can use
-- this procedure to perform any configuration setup after the configuration is parsed.
overriding
procedure Finish_Config (Into : in out URL_Policy;
Reader : in out Util.Serialize.IO.XML.Parser);
private
-- The <b>Access_Rule</b> represents a list of permissions to verify to grant
-- access to the resource. To make it simple, the user must have one of the
-- permission from the list. Each permission will refer to a specific permission
-- controller.
type Access_Rule (Count : Natural) is new Util.Refs.Ref_Entity with record
Permissions : Permission_Index_Array (1 .. Count);
end record;
type Access_Rule_Access is access all Access_Rule;
package Access_Rule_Refs is
new Util.Refs.Indefinite_References (Element_Type => Access_Rule,
Element_Access => Access_Rule_Access);
subtype Access_Rule_Ref is Access_Rule_Refs.Ref;
-- Find the access rule of the policy that matches the given URI.
-- Returns the No_Rule value (disable access) if no rule is found.
function Find_Access_Rule (Manager : in URL_Policy;
URI : in String) return Access_Rule_Ref;
-- The <b>Policy</b> defines the access rules that are applied on a given
-- URL, set of URLs or files.
type Policy is record
Id : Natural;
Pattern : GNAT.Regexp.Regexp;
Rule : Access_Rule_Ref;
end record;
-- The <b>Policy_Vector</b> represents the whole permission policy. The order of
-- policy in the list is important as policies can override each other.
package Policy_Vector is new Ada.Containers.Vectors (Index_Type => Positive,
Element_Type => Policy);
package Rules_Maps is new Ada.Containers.Hashed_Maps (Key_Type => String_Ref,
Element_Type => Access_Rule_Ref,
Hash => Hash,
Equivalent_Keys => Equivalent_Keys,
"=" => Access_Rule_Refs."=");
type Rules is new Util.Refs.Ref_Entity with record
Map : Rules_Maps.Map;
end record;
type Rules_Access is access all Rules;
package Rules_Ref is new Util.Refs.References (Rules, Rules_Access);
type Rules_Ref_Access is access Rules_Ref.Atomic_Ref;
type Controller_Access_Array_Access is access all Controller_Access_Array;
type URL_Policy is new Security.Policies.Policy with record
Cache : Rules_Ref_Access;
Policies : Policy_Vector.Vector;
end record;
end Security.Policies.Urls;
|
-----------------------------------------------------------------------
-- security-policies-urls -- URL security policy
-- 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.Containers.Hashed_Maps;
with Ada.Containers.Vectors;
with Util.Refs;
with Util.Strings;
with Util.Serialize.IO.XML;
with GNAT.Regexp;
package Security.Policies.Urls is
NAME : constant String := "URL-Policy";
-- ------------------------------
-- URI Permission
-- ------------------------------
-- Represents a permission to access a given URI.
type URI_Permission (Len : Natural) is new Permissions.Permission with record
URI : String (1 .. Len);
end record;
-- ------------------------------
-- URL policy
-- ------------------------------
type URL_Policy is new Policy with private;
type URL_Policy_Access is access all URL_Policy'Class;
Invalid_Name : exception;
-- Get the policy name.
overriding
function Get_Name (From : in URL_Policy) return String;
-- Returns True if the user has the permission to access the given URI permission.
function Has_Permission (Manager : in URL_Policy;
Context : in Security_Context_Access;
Permission : in URI_Permission'Class) return Boolean;
-- Grant the permission to access to the given <b>URI</b> to users having the <b>To</b>
-- permissions.
procedure Grant_URI_Permission (Manager : in out URL_Policy;
URI : in String;
To : in String);
-- Initialize the permission manager.
overriding
procedure Initialize (Manager : in out URL_Policy);
-- Finalize the permission manager.
overriding
procedure Finalize (Manager : in out URL_Policy);
-- Setup the XML parser to read the <b>policy</b> description.
overriding
procedure Prepare_Config (Policy : in out URL_Policy;
Reader : in out Util.Serialize.IO.XML.Parser);
-- Finish reading the XML policy configuration. The security policy implementation can use
-- this procedure to perform any configuration setup after the configuration is parsed.
overriding
procedure Finish_Config (Into : in out URL_Policy;
Reader : in out Util.Serialize.IO.XML.Parser);
private
use Util.Strings;
-- The <b>Access_Rule</b> represents a list of permissions to verify to grant
-- access to the resource. To make it simple, the user must have one of the
-- permission from the list. Each permission will refer to a specific permission
-- controller.
type Access_Rule (Count : Natural) is new Util.Refs.Ref_Entity with record
Permissions : Permission_Index_Array (1 .. Count);
end record;
type Access_Rule_Access is access all Access_Rule;
package Access_Rule_Refs is
new Util.Refs.Indefinite_References (Element_Type => Access_Rule,
Element_Access => Access_Rule_Access);
subtype Access_Rule_Ref is Access_Rule_Refs.Ref;
-- Find the access rule of the policy that matches the given URI.
-- Returns the No_Rule value (disable access) if no rule is found.
function Find_Access_Rule (Manager : in URL_Policy;
URI : in String) return Access_Rule_Ref;
-- The <b>Policy</b> defines the access rules that are applied on a given
-- URL, set of URLs or files.
type Policy is record
Id : Natural;
Pattern : GNAT.Regexp.Regexp;
Rule : Access_Rule_Ref;
end record;
-- The <b>Policy_Vector</b> represents the whole permission policy. The order of
-- policy in the list is important as policies can override each other.
package Policy_Vector is new Ada.Containers.Vectors (Index_Type => Positive,
Element_Type => Policy);
package Rules_Maps is new Ada.Containers.Hashed_Maps (Key_Type => String_Ref,
Element_Type => Access_Rule_Ref,
Hash => Hash,
Equivalent_Keys => Equivalent_Keys,
"=" => Access_Rule_Refs."=");
type Rules is new Util.Refs.Ref_Entity with record
Map : Rules_Maps.Map;
end record;
type Rules_Access is access all Rules;
package Rules_Ref is new Util.Refs.References (Rules, Rules_Access);
type Rules_Ref_Access is access Rules_Ref.Atomic_Ref;
type Controller_Access_Array_Access is access all Controller_Access_Array;
type URL_Policy is new Security.Policies.Policy with record
Cache : Rules_Ref_Access;
Policies : Policy_Vector.Vector;
end record;
end Security.Policies.Urls;
|
Add with clause for Util.Strings
|
Add with clause for Util.Strings
|
Ada
|
apache-2.0
|
stcarrez/ada-security
|
b0d661f50edc2305d44a531cc1681b5f1bccff79
|
src/natools-web-reload_pages.ads
|
src/natools-web-reload_pages.ads
|
------------------------------------------------------------------------------
-- 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. --
------------------------------------------------------------------------------
------------------------------------------------------------------------------
-- Natools.Web.Reload_Pages provides a URL endpoint that unconditionally --
-- reloads the site upon POST request and redirects to the given path. --
-- --
-- WARNING: site reload can be a very expensive operation, and no access --
-- restriction or rate-limiting is implemented at this time, so care should --
-- be taken to ensure this endpoint is only accessible to trusted clients. --
------------------------------------------------------------------------------
with Natools.S_Expressions;
with Natools.Web.Sites;
private with Natools.S_Expressions.Atom_Refs;
package Natools.Web.Reload_Pages is
type Reload_Page is new Sites.Page with private;
overriding procedure Respond
(Object : in out Reload_Page;
Exchange : in out Sites.Exchange;
Extra_Path : in S_Expressions.Atom);
type Loader is new Sites.Page_Loader with private;
overriding procedure Load
(Object : in out Loader;
Builder : in out Sites.Site_Builder;
Path : in S_Expressions.Atom);
function Create (File : in S_Expressions.Atom)
return Sites.Page_Loader'Class;
private
type Reload_Page is new Sites.Page with record
Target : S_Expressions.Atom_Refs.Immutable_Reference;
end record;
type Loader is new Sites.Page_Loader with record
Target : S_Expressions.Atom_Refs.Immutable_Reference;
end record;
end Natools.Web.Reload_Pages;
|
------------------------------------------------------------------------------
-- Copyright (c) 2015-2019, Natacha Porté --
-- --
-- Permission to use, copy, modify, and distribute this software for any --
-- purpose with or without fee is hereby granted, provided that the above --
-- copyright notice and this permission notice appear in all copies. --
-- --
-- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES --
-- WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF --
-- MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR --
-- ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES --
-- WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN --
-- ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF --
-- OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. --
------------------------------------------------------------------------------
------------------------------------------------------------------------------
-- Natools.Web.Reload_Pages provides a URL endpoint that unconditionally --
-- reloads the site upon POST request and redirects to the given path. --
-- --
-- WARNING: site reload can be a very expensive operation, and no access --
-- restriction or rate-limiting is implemented at this time, so care should --
-- be taken to ensure this endpoint is only accessible to trusted clients. --
------------------------------------------------------------------------------
with Natools.S_Expressions;
with Natools.Web.Sites;
private with Natools.S_Expressions.Atom_Refs;
package Natools.Web.Reload_Pages is
type Reload_Page is new Sites.Page with private;
overriding procedure Respond
(Object : in out Reload_Page;
Exchange : in out Sites.Exchange;
Extra_Path : in S_Expressions.Atom);
type Loader is new Sites.Transient_Page_Loader with private;
overriding function Can_Be_Stored (Object : in Loader) return Boolean
is (False);
overriding procedure Load
(Object : in out Loader;
Builder : in out Sites.Site_Builder;
Path : in S_Expressions.Atom);
function Create (File : in S_Expressions.Atom)
return Sites.Page_Loader'Class;
private
type Reload_Page is new Sites.Page with record
Target : S_Expressions.Atom_Refs.Immutable_Reference;
end record;
type Loader is new Sites.Transient_Page_Loader with record
Target : S_Expressions.Atom_Refs.Immutable_Reference;
end record;
end Natools.Web.Reload_Pages;
|
use the new transient page loader interface
|
reload-pages: use the new transient page loader interface
|
Ada
|
isc
|
faelys/natools-web,faelys/natools-web
|
7043598f6f08ad6e2063656f0a9ae326b7e59c81
|
src/natools-web-simple_pages.adb
|
src/natools-web-simple_pages.adb
|
------------------------------------------------------------------------------
-- Copyright (c) 2014-2017, Natacha Porté --
-- --
-- Permission to use, copy, modify, and distribute this software for any --
-- purpose with or without fee is hereby granted, provided that the above --
-- copyright notice and this permission notice appear in all copies. --
-- --
-- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES --
-- WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF --
-- MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR --
-- ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES --
-- WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN --
-- ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF --
-- OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. --
------------------------------------------------------------------------------
with Natools.S_Expressions.Atom_Ref_Constructors;
with Natools.S_Expressions.File_Readers;
with Natools.S_Expressions.Interpreter_Loop;
with Natools.S_Expressions.Templates.Dates;
with Natools.Static_Maps.Web.Simple_Pages;
with Natools.Web.Error_Pages;
with Natools.Web.Exchanges;
with Natools.Web.Fallback_Render;
package body Natools.Web.Simple_Pages is
Expiration_Date_Key : constant S_Expressions.Atom
:= S_Expressions.To_Atom ("!expire");
Publication_Date_Key : constant S_Expressions.Atom
:= S_Expressions.To_Atom ("!publish");
procedure Append
(Exchange : in out Sites.Exchange;
Page : in Page_Data;
Data : in S_Expressions.Atom);
procedure Execute
(Data : in out Page_Data;
Context : in Meaningless_Type;
Name : in S_Expressions.Atom;
Arguments : in out S_Expressions.Lockable.Descriptor'Class);
procedure Render
(Exchange : in out Sites.Exchange;
Page : in Page_Data;
Name : in S_Expressions.Atom;
Arguments : in out S_Expressions.Lockable.Descriptor'Class);
procedure Read_Page is new S_Expressions.Interpreter_Loop
(Page_Data, Meaningless_Type, Execute);
procedure Render_Page is new S_Expressions.Interpreter_Loop
(Sites.Exchange, Page_Data, Render, Append);
---------------------------
-- Page Data Constructor --
---------------------------
procedure Execute
(Data : in out Page_Data;
Context : in Meaningless_Type;
Name : in S_Expressions.Atom;
Arguments : in out S_Expressions.Lockable.Descriptor'Class)
is
pragma Unreferenced (Context);
package Components renames Natools.Static_Maps.Web.Simple_Pages;
begin
case Components.To_Component (S_Expressions.To_String (Name)) is
when Components.Error =>
Log (Severities.Error, "Unknown page component """
& S_Expressions.To_String (Name) & '"');
when Components.Comment_List =>
Data.Comment_List.Set (Arguments);
when Components.Dates =>
Containers.Set_Dates (Data.Dates, Arguments);
when Components.Elements =>
Containers.Set_Expressions (Data.Elements, Arguments);
when Components.Maps =>
Data.Maps := String_Tables.Create (Arguments);
when Components.Tags =>
Tags.Append (Data.Tags, Arguments);
end case;
end Execute;
-------------------
-- Page Renderer --
-------------------
procedure Append
(Exchange : in out Sites.Exchange;
Page : in Page_Data;
Data : in S_Expressions.Atom)
is
pragma Unreferenced (Page);
begin
Exchange.Append (Data);
end Append;
procedure Render
(Exchange : in out Sites.Exchange;
Page : in Page_Data;
Name : in S_Expressions.Atom;
Arguments : in out S_Expressions.Lockable.Descriptor'Class)
is
use type S_Expressions.Events.Event;
procedure Re_Enter
(Exchange : in out Sites.Exchange;
Expression : in out S_Expressions.Lockable.Descriptor'Class);
procedure Render_Date (Log_Error : in Boolean);
procedure Re_Enter
(Exchange : in out Sites.Exchange;
Expression : in out S_Expressions.Lockable.Descriptor'Class) is
begin
Render_Page (Expression, Exchange, Page);
end Re_Enter;
procedure Render_Date (Log_Error : in Boolean) is
begin
if Arguments.Current_Event = S_Expressions.Events.Add_Atom then
declare
Cursor : constant Containers.Date_Maps.Cursor
:= Page.Dates.Find (Arguments.Current_Atom);
begin
if not Containers.Date_Maps.Has_Element (Cursor) then
if Log_Error then
Log (Severities.Error, "Unable to find date """
& S_Expressions.To_String (Arguments.Current_Atom)
& """ in page date map");
end if;
return;
end if;
Arguments.Next;
declare
Item : constant Containers.Date
:= Containers.Date_Maps.Element (Cursor);
begin
S_Expressions.Templates.Dates.Render
(Exchange, Arguments, Item.Time, Item.Offset);
end;
end;
end if;
end Render_Date;
package Commands renames Natools.Static_Maps.Web.Simple_Pages;
begin
case Commands.To_Command (S_Expressions.To_String (Name)) is
when Commands.Unknown_Command =>
Fallback_Render
(Exchange, Name, Arguments,
"simple page",
Re_Enter'Access, Page.Elements);
when Commands.Comment_List =>
Comments.Render (Exchange, Page.Comment_List, Arguments);
when Commands.Date =>
Render_Date (True);
when Commands.My_Tags =>
if Arguments.Current_Event = S_Expressions.Events.Add_Atom then
declare
Prefix : constant S_Expressions.Atom
:= Arguments.Current_Atom;
begin
Arguments.Next;
Tags.Render
(Exchange,
Page.Tags,
Exchange.Site.Get_Tags,
Prefix,
Arguments);
end;
end if;
when Commands.If_No_Date =>
if Arguments.Current_Event = S_Expressions.Events.Add_Atom
and then not Page.Dates.Contains (Arguments.Current_Atom)
then
Arguments.Next;
Render_Page (Arguments, Exchange, Page);
end if;
when Commands.Maps =>
String_Tables.Render (Exchange, Page.Maps, Arguments);
when Commands.Optional_Date =>
Render_Date (False);
when Commands.Path =>
Exchange.Append (Page.Web_Path.Query);
when Commands.Tags =>
Tags.Render
(Exchange,
Exchange.Site.Get_Tags,
Arguments,
Page.Tags);
end case;
end Render;
-------------------------
-- Page_Data Interface --
-------------------------
not overriding procedure Get_Element
(Data : in Page_Data;
Name : in S_Expressions.Atom;
Element : out S_Expressions.Caches.Cursor;
Found : out Boolean)
is
Cursor : constant Containers.Expression_Maps.Cursor
:= Data.Elements.Find (Name);
begin
Found := Containers.Expression_Maps.Has_Element (Cursor);
if Found then
Element := Containers.Expression_Maps.Element (Cursor);
end if;
end Get_Element;
----------------------
-- Public Interface --
----------------------
function Create
(Expression : in out S_Expressions.Lockable.Descriptor'Class)
return Page_Ref
is
Page : constant Data_Refs.Data_Access := new Page_Data;
Result : constant Page_Ref := (Ref => Data_Refs.Create (Page));
begin
Page.Self := Tags.Visible_Access (Page);
Read_Page (Expression, Page.all, Meaningless_Value);
return Result;
end Create;
function Create
(File_Path, Web_Path : in S_Expressions.Atom_Refs.Immutable_Reference)
return Page_Ref
is
Page : constant Data_Refs.Data_Access := new Page_Data'
(File_Path => File_Path,
Web_Path => Web_Path,
Tags => <>,
Self => null,
Comment_List | Elements | Dates | Maps => <>);
Result : constant Page_Ref := (Ref => Data_Refs.Create (Page));
begin
Page.Self := Tags.Visible_Access (Page);
Create_Page :
declare
Reader : Natools.S_Expressions.File_Readers.S_Reader
:= Natools.S_Expressions.File_Readers.Reader
(S_Expressions.To_String (File_Path.Query));
begin
Read_Page (Reader, Page.all, Meaningless_Value);
end Create_Page;
return Result;
end Create;
procedure Get_Lifetime
(Page : in Page_Ref;
Publication : out Ada.Calendar.Time;
Has_Publication : out Boolean;
Expiration : out Ada.Calendar.Time;
Has_Expiration : out Boolean)
is
Accessor : constant Data_Refs.Accessor := Page.Ref.Query;
Cursor : Containers.Date_Maps.Cursor;
begin
Cursor := Accessor.Dates.Find (Expiration_Date_Key);
if Containers.Date_Maps.Has_Element (Cursor) then
Has_Expiration := True;
Expiration := Containers.Date_Maps.Element (Cursor).Time;
else
Has_Expiration := False;
end if;
Cursor := Accessor.Dates.Find (Publication_Date_Key);
if Containers.Date_Maps.Has_Element (Cursor) then
Has_Publication := True;
Publication := Containers.Date_Maps.Element (Cursor).Time;
else
Has_Publication := False;
end if;
end Get_Lifetime;
procedure Register
(Page : in Page_Ref;
Builder : in out Sites.Site_Builder;
Path : in S_Expressions.Atom) is
begin
Time_Check :
declare
use type Ada.Calendar.Time;
Now : constant Ada.Calendar.Time := Ada.Calendar.Clock;
Publication : Ada.Calendar.Time;
Has_Publication : Boolean;
Expiration : Ada.Calendar.Time;
Has_Expiration : Boolean;
begin
Get_Lifetime
(Page, Publication, Has_Publication, Expiration, Has_Expiration);
if (Has_Publication and then Publication >= Now)
or else (Has_Expiration and then Expiration < Now)
then
return;
end if;
end Time_Check;
if Path'Length > 0 then
Sites.Insert (Builder, Path, Page);
end if;
Sites.Insert (Builder, Page.Get_Tags, Page);
Load_Comments :
declare
Mutator : constant Data_Refs.Mutator := Page.Ref.Update;
begin
Mutator.Comment_List.Load (Builder, Mutator.Self, Mutator.Web_Path);
end Load_Comments;
end Register;
overriding procedure Render
(Exchange : in out Sites.Exchange;
Object : in Page_Ref;
Expression : in out S_Expressions.Lockable.Descriptor'Class) is
begin
Render_Page
(Expression,
Exchange,
Object.Ref.Query.Data.all);
end Render;
overriding procedure Render
(Exchange : in out Sites.Exchange;
Object : in Page_Data;
Expression : in out S_Expressions.Lockable.Descriptor'Class) is
begin
Render_Page (Expression, Exchange, Object);
end Render;
overriding procedure Respond
(Object : in out Page_Ref;
Exchange : in out Sites.Exchange;
Extra_Path : in S_Expressions.Atom)
is
use type S_Expressions.Offset;
begin
if Extra_Path'Length = 9
and then S_Expressions.To_String (Extra_Path) = "/comments"
then
Object.Ref.Update.Comment_List.Respond
(Exchange, Extra_Path (Extra_Path'First + 9 .. Extra_Path'Last));
return;
end if;
if Extra_Path'Length > 0 then
return;
end if;
declare
Accessor : constant Data_Refs.Accessor := Object.Ref.Query;
Expression : S_Expressions.Caches.Cursor;
begin
Check_Method :
declare
use Exchanges;
Allowed : Boolean;
begin
Error_Pages.Check_Method
(Exchange,
(GET, HEAD),
Allowed);
if not Allowed then
return;
end if;
end Check_Method;
Expression := Exchange.Site.Get_Template
(Accessor.Data.Elements,
Expression,
Exchange.Site.Default_Template,
Lookup_Element => True,
Lookup_Template => True,
Lookup_Name => True);
Render_Page (Expression, Exchange, Accessor.Data.all);
end;
end Respond;
-----------------------
-- Page Constructors --
-----------------------
function Create (File : in S_Expressions.Atom)
return Sites.Page_Loader'Class is
begin
return Loader'(File_Path
=> S_Expressions.Atom_Ref_Constructors.Create (File));
end Create;
overriding procedure Load
(Object : in out Loader;
Builder : in out Sites.Site_Builder;
Path : in S_Expressions.Atom)
is
Page : constant Page_Ref := Create
(Object.File_Path,
S_Expressions.Atom_Ref_Constructors.Create (Path));
begin
Register (Page, Builder, Path);
end Load;
procedure Register_Loader (Site : in out Sites.Site) is
begin
Site.Register ("simple-page", Create'Access);
end Register_Loader;
end Natools.Web.Simple_Pages;
|
------------------------------------------------------------------------------
-- Copyright (c) 2014-2017, Natacha Porté --
-- --
-- Permission to use, copy, modify, and distribute this software for any --
-- purpose with or without fee is hereby granted, provided that the above --
-- copyright notice and this permission notice appear in all copies. --
-- --
-- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES --
-- WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF --
-- MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR --
-- ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES --
-- WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN --
-- ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF --
-- OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. --
------------------------------------------------------------------------------
with Natools.S_Expressions.Atom_Ref_Constructors;
with Natools.S_Expressions.File_Readers;
with Natools.S_Expressions.Interpreter_Loop;
with Natools.S_Expressions.Templates.Dates;
with Natools.Static_Maps.Web.Simple_Pages;
with Natools.Web.Error_Pages;
with Natools.Web.Exchanges;
with Natools.Web.Fallback_Render;
package body Natools.Web.Simple_Pages is
Expiration_Date_Key : constant S_Expressions.Atom
:= S_Expressions.To_Atom ("!expire");
Publication_Date_Key : constant S_Expressions.Atom
:= S_Expressions.To_Atom ("!publish");
procedure Append
(Exchange : in out Sites.Exchange;
Page : in Page_Data;
Data : in S_Expressions.Atom);
procedure Execute
(Data : in out Page_Data;
Context : in Meaningless_Type;
Name : in S_Expressions.Atom;
Arguments : in out S_Expressions.Lockable.Descriptor'Class);
procedure Render
(Exchange : in out Sites.Exchange;
Page : in Page_Data;
Name : in S_Expressions.Atom;
Arguments : in out S_Expressions.Lockable.Descriptor'Class);
procedure Read_Page is new S_Expressions.Interpreter_Loop
(Page_Data, Meaningless_Type, Execute);
procedure Render_Page is new S_Expressions.Interpreter_Loop
(Sites.Exchange, Page_Data, Render, Append);
---------------------------
-- Page Data Constructor --
---------------------------
procedure Execute
(Data : in out Page_Data;
Context : in Meaningless_Type;
Name : in S_Expressions.Atom;
Arguments : in out S_Expressions.Lockable.Descriptor'Class)
is
pragma Unreferenced (Context);
package Components renames Natools.Static_Maps.Web.Simple_Pages;
begin
case Components.To_Component (S_Expressions.To_String (Name)) is
when Components.Error =>
Log (Severities.Error, "Unknown page component """
& S_Expressions.To_String (Name) & '"');
when Components.Comment_List =>
Data.Comment_List.Set (Arguments);
when Components.Dates =>
Containers.Set_Dates (Data.Dates, Arguments);
when Components.Elements =>
Containers.Set_Expressions (Data.Elements, Arguments);
when Components.Maps =>
Data.Maps := String_Tables.Create (Arguments);
when Components.Tags =>
Tags.Append (Data.Tags, Arguments);
end case;
end Execute;
-------------------
-- Page Renderer --
-------------------
procedure Append
(Exchange : in out Sites.Exchange;
Page : in Page_Data;
Data : in S_Expressions.Atom)
is
pragma Unreferenced (Page);
begin
Exchange.Append (Data);
end Append;
procedure Render
(Exchange : in out Sites.Exchange;
Page : in Page_Data;
Name : in S_Expressions.Atom;
Arguments : in out S_Expressions.Lockable.Descriptor'Class)
is
use type S_Expressions.Events.Event;
procedure Re_Enter
(Exchange : in out Sites.Exchange;
Expression : in out S_Expressions.Lockable.Descriptor'Class);
procedure Render_Date (Log_Error : in Boolean);
procedure Re_Enter
(Exchange : in out Sites.Exchange;
Expression : in out S_Expressions.Lockable.Descriptor'Class) is
begin
Render_Page (Expression, Exchange, Page);
end Re_Enter;
procedure Render_Date (Log_Error : in Boolean) is
begin
if Arguments.Current_Event = S_Expressions.Events.Add_Atom then
declare
Cursor : constant Containers.Date_Maps.Cursor
:= Page.Dates.Find (Arguments.Current_Atom);
begin
if not Containers.Date_Maps.Has_Element (Cursor) then
if Log_Error then
Log (Severities.Error, "Unable to find date """
& S_Expressions.To_String (Arguments.Current_Atom)
& """ in page date map");
end if;
return;
end if;
Arguments.Next;
declare
Item : constant Containers.Date
:= Containers.Date_Maps.Element (Cursor);
begin
S_Expressions.Templates.Dates.Render
(Exchange, Arguments, Item.Time, Item.Offset);
end;
end;
end if;
end Render_Date;
package Commands renames Natools.Static_Maps.Web.Simple_Pages;
begin
case Commands.To_Command (S_Expressions.To_String (Name)) is
when Commands.Unknown_Command =>
Fallback_Render
(Exchange, Name, Arguments,
"simple page",
Re_Enter'Access, Page.Elements);
when Commands.Comment_List =>
Comments.Render (Exchange, Page.Comment_List, Arguments);
when Commands.Date =>
Render_Date (True);
when Commands.My_Tags =>
if Arguments.Current_Event = S_Expressions.Events.Add_Atom then
declare
Prefix : constant S_Expressions.Atom
:= Arguments.Current_Atom;
begin
Arguments.Next;
Tags.Render
(Exchange,
Page.Tags,
Exchange.Site.Get_Tags,
Prefix,
Arguments);
end;
end if;
when Commands.If_No_Date =>
if Arguments.Current_Event = S_Expressions.Events.Add_Atom
and then not Page.Dates.Contains (Arguments.Current_Atom)
then
Arguments.Next;
Render_Page (Arguments, Exchange, Page);
end if;
when Commands.Maps =>
String_Tables.Render (Exchange, Page.Maps, Arguments);
when Commands.Optional_Date =>
Render_Date (False);
when Commands.Path =>
Exchange.Append (Page.Web_Path.Query);
when Commands.Tags =>
Tags.Render
(Exchange,
Exchange.Site.Get_Tags,
Arguments,
Page.Tags);
end case;
end Render;
-------------------------
-- Page_Data Interface --
-------------------------
not overriding procedure Get_Element
(Data : in Page_Data;
Name : in S_Expressions.Atom;
Element : out S_Expressions.Caches.Cursor;
Found : out Boolean)
is
Cursor : constant Containers.Expression_Maps.Cursor
:= Data.Elements.Find (Name);
begin
Found := Containers.Expression_Maps.Has_Element (Cursor);
if Found then
Element := Containers.Expression_Maps.Element (Cursor);
end if;
end Get_Element;
----------------------
-- Public Interface --
----------------------
function Create
(Expression : in out S_Expressions.Lockable.Descriptor'Class)
return Page_Ref
is
Page : constant Data_Refs.Data_Access := new Page_Data;
Result : constant Page_Ref := (Ref => Data_Refs.Create (Page));
begin
Page.Self := Tags.Visible_Access (Page);
Read_Page (Expression, Page.all, Meaningless_Value);
return Result;
end Create;
function Create
(File_Path, Web_Path : in S_Expressions.Atom_Refs.Immutable_Reference)
return Page_Ref
is
Page : constant Data_Refs.Data_Access := new Page_Data'
(File_Path => File_Path,
Web_Path => Web_Path,
Tags => <>,
Self => null,
Comment_List | Elements | Dates | Maps => <>);
Result : constant Page_Ref := (Ref => Data_Refs.Create (Page));
begin
Page.Self := Tags.Visible_Access (Page);
Create_Page :
declare
Reader : Natools.S_Expressions.File_Readers.S_Reader
:= Natools.S_Expressions.File_Readers.Reader
(S_Expressions.To_String (File_Path.Query));
begin
Read_Page (Reader, Page.all, Meaningless_Value);
end Create_Page;
return Result;
end Create;
procedure Get_Lifetime
(Page : in Page_Ref;
Publication : out Ada.Calendar.Time;
Has_Publication : out Boolean;
Expiration : out Ada.Calendar.Time;
Has_Expiration : out Boolean)
is
Accessor : constant Data_Refs.Accessor := Page.Ref.Query;
Cursor : Containers.Date_Maps.Cursor;
begin
Cursor := Accessor.Dates.Find (Expiration_Date_Key);
if Containers.Date_Maps.Has_Element (Cursor) then
Has_Expiration := True;
Expiration := Containers.Date_Maps.Element (Cursor).Time;
else
Has_Expiration := False;
end if;
Cursor := Accessor.Dates.Find (Publication_Date_Key);
if Containers.Date_Maps.Has_Element (Cursor) then
Has_Publication := True;
Publication := Containers.Date_Maps.Element (Cursor).Time;
else
Has_Publication := False;
end if;
end Get_Lifetime;
procedure Register
(Page : in Page_Ref;
Builder : in out Sites.Site_Builder;
Path : in S_Expressions.Atom) is
begin
Time_Check :
declare
use type Ada.Calendar.Time;
Now : constant Ada.Calendar.Time := Ada.Calendar.Clock;
Publication : Ada.Calendar.Time;
Has_Publication : Boolean;
Expiration : Ada.Calendar.Time;
Has_Expiration : Boolean;
begin
Get_Lifetime
(Page, Publication, Has_Publication, Expiration, Has_Expiration);
if Has_Publication and then Publication >= Now then
Sites.Expire_At (Builder, Publication);
return;
end if;
if Has_Expiration then
if Expiration < Now then
return;
else
Sites.Expire_At (Builder, Expiration);
end if;
end if;
end Time_Check;
if Path'Length > 0 then
Sites.Insert (Builder, Path, Page);
end if;
Sites.Insert (Builder, Page.Get_Tags, Page);
Load_Comments :
declare
Mutator : constant Data_Refs.Mutator := Page.Ref.Update;
begin
Mutator.Comment_List.Load (Builder, Mutator.Self, Mutator.Web_Path);
end Load_Comments;
end Register;
overriding procedure Render
(Exchange : in out Sites.Exchange;
Object : in Page_Ref;
Expression : in out S_Expressions.Lockable.Descriptor'Class) is
begin
Render_Page
(Expression,
Exchange,
Object.Ref.Query.Data.all);
end Render;
overriding procedure Render
(Exchange : in out Sites.Exchange;
Object : in Page_Data;
Expression : in out S_Expressions.Lockable.Descriptor'Class) is
begin
Render_Page (Expression, Exchange, Object);
end Render;
overriding procedure Respond
(Object : in out Page_Ref;
Exchange : in out Sites.Exchange;
Extra_Path : in S_Expressions.Atom)
is
use type S_Expressions.Offset;
begin
if Extra_Path'Length = 9
and then S_Expressions.To_String (Extra_Path) = "/comments"
then
Object.Ref.Update.Comment_List.Respond
(Exchange, Extra_Path (Extra_Path'First + 9 .. Extra_Path'Last));
return;
end if;
if Extra_Path'Length > 0 then
return;
end if;
declare
Accessor : constant Data_Refs.Accessor := Object.Ref.Query;
Expression : S_Expressions.Caches.Cursor;
begin
Check_Method :
declare
use Exchanges;
Allowed : Boolean;
begin
Error_Pages.Check_Method
(Exchange,
(GET, HEAD),
Allowed);
if not Allowed then
return;
end if;
end Check_Method;
Expression := Exchange.Site.Get_Template
(Accessor.Data.Elements,
Expression,
Exchange.Site.Default_Template,
Lookup_Element => True,
Lookup_Template => True,
Lookup_Name => True);
Render_Page (Expression, Exchange, Accessor.Data.all);
end;
end Respond;
-----------------------
-- Page Constructors --
-----------------------
function Create (File : in S_Expressions.Atom)
return Sites.Page_Loader'Class is
begin
return Loader'(File_Path
=> S_Expressions.Atom_Ref_Constructors.Create (File));
end Create;
overriding procedure Load
(Object : in out Loader;
Builder : in out Sites.Site_Builder;
Path : in S_Expressions.Atom)
is
Page : constant Page_Ref := Create
(Object.File_Path,
S_Expressions.Atom_Ref_Constructors.Create (Path));
begin
Register (Page, Builder, Path);
end Load;
procedure Register_Loader (Site : in out Sites.Site) is
begin
Site.Register ("simple-page", Create'Access);
end Register_Loader;
end Natools.Web.Simple_Pages;
|
update site expiration to auto-publish and auto-expire
|
simple_pages: update site expiration to auto-publish and auto-expire
|
Ada
|
isc
|
faelys/natools-web,faelys/natools-web
|
4b0ab2e7d07f3856fb793a3eb4e8e65bd3787bd3
|
mat/src/mat-readers.adb
|
mat/src/mat-readers.adb
|
-----------------------------------------------------------------------
-- mat-readers -- Reader
-- Copyright (C) 2014 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Log.Loggers;
with MAT.Events;
with MAT.Types;
with MAT.Readers.Marshaller;
with Interfaces;
package body MAT.Readers is
-- The logger
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("MAT.Readers");
function Hash (Key : in MAT.Types.Uint16) return Ada.Containers.Hash_Type is
begin
return Ada.Containers.Hash_Type (Key);
end Hash;
procedure Register_Servant (Adapter : in Manager;
Proxy : in Servant) is
begin
if Proxy.Owner /= null then
raise PROGRAM_ERROR;
end if;
Proxy.Owner := Adapter;
end Register_Servant;
procedure Register_Reader (Into : in out Manager_Base;
Name : in String;
Id : in MAT.Events.Internal_Reference;
Model : in MAT.Events.Attribute_Table_Ptr) is
Handler : Message_Handler;
begin
Handler.Id := Id;
Handler.Attributes := Model;
Handler.Mapping := new MAT.Events.Attribute_Table (Model'Range);
Handler.Mapping.all := Model.all;
Into.Readers.Insert (Name, Handler);
end Register_Reader;
procedure Register_Message_Analyzer (Proxy : in Reader_Access;
Name : in String;
Id : in MAT.Events.Internal_Reference;
Model : in MAT.Events.Attribute_Table;
Table : out MAT.Events.Attribute_Table_Ptr) is
Handler : Message_Handler := (For_Servant => Proxy, Id => Id);
Adapter : IpcManager := IpcManager_Base (Proxy.Owner.all)'Access;
N : String_Ptr := new String'(Name);
It : Event_Def_AVL.Iterator := Find (adapter.Event_Types, N);
begin
if Is_Done (It) then
return;
end if;
declare
Event_Def : Event_Description_Ptr := Current_Item (It);
Inserted : Boolean;
begin
Insert (T => Adapter.Handlers,
Element => Handler,
The_Key => Event_Def.Id,
Not_Found => Inserted);
Table := new Attribute_Table (1 .. Event_Def.Nb_Attributes);
Table (Table'Range) := Event_Def.Def (Table'Range);
for I in Table'Range loop
Table (I).Ref := 0;
for J in Model'Range loop
if Table (I).Name.all = Model (I).Name.all then
Table (I).Ref := Model (I).Ref;
exit;
end if;
end loop;
end loop;
end;
end Register_Message_Analyzer;
procedure Dispatch_Message (Client : in out Manager_Base;
Msg : in out Message) is
Event : constant MAT.Types.Uint16 := MAT.Readers.Marshaller.Get_Uint16 (Msg.Buffer);
Pos : constant Handler_Maps.Cursor := Client.Handlers.Find (Event);
begin
if Handler_Maps.Has_Element (Pos) then
-- Message is not handled, skip it.
null;
else
declare
Handler : constant Message_Handler := Handler_Maps.Element (Pos);
begin
Dispatch (Handler.For_Servant.all, Handler.Id, Handler.Mapping.all'Access, Msg);
end;
end if;
end Dispatch_Message;
-- ------------------------------
-- Read an event definition from the stream and configure the reader.
-- ------------------------------
procedure Read_Definition (Client : in out Manager_Base;
Msg : in out Message) is
Name : constant String := MAT.Readers.Marshaller.Get_String (Msg.Buffer);
Event : constant MAT.Types.Uint16 := MAT.Readers.Marshaller.Get_Uint16 (Msg.Buffer);
Count : constant MAT.Types.Uint8 := MAT.Readers.Marshaller.Get_Uint8 (Msg.Buffer);
Pos : constant Reader_Maps.Cursor := Client.Readers.Find (Name);
procedure Read_Attributes (Key : in String;
Element : in out Message_Handler) is
begin
Element.Mapping := new MAT.Events.Attribute_Table (1 .. Natural (Count));
for I in 1 .. Natural (Count) loop
declare
Name : constant String := MAT.Readers.Marshaller.Get_String (Msg.Buffer);
Size : constant MAT.Types.Uint16 := MAT.Readers.Marshaller.Get_Uint16 (Msg.Buffer);
begin
for J in Element.Attributes'Range loop
if Element.Attributes (J).Name.all = Name then
Element.Mapping (I) := Element.Attributes (J);
end if;
end loop;
end;
end loop;
end Read_Attributes;
begin
Log.Debug ("Read event definition {0}", Name);
if Reader_Maps.Has_Element (Pos) then
Client.Readers.Update_Element (Pos, Read_Attributes'Access);
end if;
end Read_Definition;
procedure Read_Headers (Client : in out Manager_Base;
Msg : in out Message) is
Count : MAT.Types.Uint16;
begin
Client.Version := MAT.Readers.Marshaller.Get_Uint16 (Msg.Buffer);
Client.Flags := MAT.Readers.Marshaller.Get_Uint16 (Msg.Buffer);
Count := MAT.Readers.Marshaller.Get_Uint16 (Msg.Buffer);
Log.Info ("Read event stream version {0} with {1} definitions",
MAT.Types.Uint16'Image (Client.Version),
MAT.Types.Uint16'Image (Count));
for I in 1 .. Count loop
Read_Definition (Client, Msg);
end loop;
end Read_Headers;
end MAT.Readers;
|
-----------------------------------------------------------------------
-- mat-readers -- Reader
-- Copyright (C) 2014 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Log.Loggers;
with MAT.Events;
with MAT.Types;
with MAT.Readers.Marshaller;
with Interfaces;
package body MAT.Readers is
-- The logger
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("MAT.Readers");
function Hash (Key : in MAT.Types.Uint16) return Ada.Containers.Hash_Type is
begin
return Ada.Containers.Hash_Type (Key);
end Hash;
procedure Register_Servant (Adapter : in Manager;
Proxy : in Servant) is
begin
if Proxy.Owner /= null then
raise PROGRAM_ERROR;
end if;
Proxy.Owner := Adapter;
end Register_Servant;
-- ------------------------------
-- Register the reader to handle the event identified by the given name.
-- The event is mapped to the given id and the attributes table is used
-- to setup the mapping from the data stream attributes.
-- ------------------------------
procedure Register_Reader (Into : in out Manager_Base;
Reader : in Reader_Access;
Name : in String;
Id : in MAT.Events.Internal_Reference;
Model : in MAT.Events.Attribute_Table_Ptr) is
Handler : Message_Handler;
begin
Handler.For_Servant := Reader;
Handler.Id := Id;
Handler.Attributes := Model;
Handler.Mapping := null;
Into.Readers.Insert (Name, Handler);
end Register_Reader;
procedure Register_Message_Analyzer (Proxy : in Reader_Access;
Name : in String;
Id : in MAT.Events.Internal_Reference;
Model : in MAT.Events.Attribute_Table;
Table : out MAT.Events.Attribute_Table_Ptr) is
Handler : Message_Handler := (For_Servant => Proxy, Id => Id);
Adapter : IpcManager := IpcManager_Base (Proxy.Owner.all)'Access;
N : String_Ptr := new String'(Name);
It : Event_Def_AVL.Iterator := Find (adapter.Event_Types, N);
begin
if Is_Done (It) then
return;
end if;
declare
Event_Def : Event_Description_Ptr := Current_Item (It);
Inserted : Boolean;
begin
Insert (T => Adapter.Handlers,
Element => Handler,
The_Key => Event_Def.Id,
Not_Found => Inserted);
Table := new Attribute_Table (1 .. Event_Def.Nb_Attributes);
Table (Table'Range) := Event_Def.Def (Table'Range);
for I in Table'Range loop
Table (I).Ref := 0;
for J in Model'Range loop
if Table (I).Name.all = Model (I).Name.all then
Table (I).Ref := Model (I).Ref;
exit;
end if;
end loop;
end loop;
end;
end Register_Message_Analyzer;
procedure Dispatch_Message (Client : in out Manager_Base;
Msg : in out Message) is
Event : constant MAT.Types.Uint16 := MAT.Readers.Marshaller.Get_Uint16 (Msg.Buffer);
Pos : constant Handler_Maps.Cursor := Client.Handlers.Find (Event);
begin
if Handler_Maps.Has_Element (Pos) then
-- Message is not handled, skip it.
null;
else
declare
Handler : constant Message_Handler := Handler_Maps.Element (Pos);
begin
Dispatch (Handler.For_Servant.all, Handler.Id, Handler.Mapping.all'Access, Msg);
end;
end if;
end Dispatch_Message;
-- ------------------------------
-- Read an event definition from the stream and configure the reader.
-- ------------------------------
procedure Read_Definition (Client : in out Manager_Base;
Msg : in out Message) is
Name : constant String := MAT.Readers.Marshaller.Get_String (Msg.Buffer);
Event : constant MAT.Types.Uint16 := MAT.Readers.Marshaller.Get_Uint16 (Msg.Buffer);
Count : constant MAT.Types.Uint8 := MAT.Readers.Marshaller.Get_Uint8 (Msg.Buffer);
Pos : constant Reader_Maps.Cursor := Client.Readers.Find (Name);
procedure Read_Attributes (Key : in String;
Element : in out Message_Handler) is
begin
Element.Mapping := new MAT.Events.Attribute_Table (1 .. Natural (Count));
for I in 1 .. Natural (Count) loop
declare
Name : constant String := MAT.Readers.Marshaller.Get_String (Msg.Buffer);
Size : constant MAT.Types.Uint16 := MAT.Readers.Marshaller.Get_Uint16 (Msg.Buffer);
begin
for J in Element.Attributes'Range loop
if Element.Attributes (J).Name.all = Name then
Element.Mapping (I) := Element.Attributes (J);
end if;
end loop;
end;
end loop;
end Read_Attributes;
begin
Log.Debug ("Read event definition {0}", Name);
if Reader_Maps.Has_Element (Pos) then
Client.Readers.Update_Element (Pos, Read_Attributes'Access);
end if;
end Read_Definition;
procedure Read_Headers (Client : in out Manager_Base;
Msg : in out Message) is
Count : MAT.Types.Uint16;
begin
Client.Version := MAT.Readers.Marshaller.Get_Uint16 (Msg.Buffer);
Client.Flags := MAT.Readers.Marshaller.Get_Uint16 (Msg.Buffer);
Count := MAT.Readers.Marshaller.Get_Uint16 (Msg.Buffer);
Log.Info ("Read event stream version {0} with {1} definitions",
MAT.Types.Uint16'Image (Client.Version),
MAT.Types.Uint16'Image (Count));
for I in 1 .. Count loop
Read_Definition (Client, Msg);
end loop;
end Read_Headers;
end MAT.Readers;
|
Update and fix the Register_Reader operation
|
Update and fix the Register_Reader operation
|
Ada
|
apache-2.0
|
stcarrez/mat,stcarrez/mat,stcarrez/mat
|
8c8ff2255b09e5d770b666bba17a957b7a72a204
|
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;
-- 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 : aliased ADO.Queries.Query_Manager;
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, 2018 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with ADO.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;
-- 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_Error 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 : aliased ADO.Queries.Query_Manager;
end record;
-- Initialize the sequence factory associated with the session factory.
procedure Initialize_Sequences (Factory : in out Session_Factory);
end ADO.Sessions.Factory;
|
Update the documentation
|
Update the documentation
|
Ada
|
apache-2.0
|
stcarrez/ada-ado
|
bfafde825d01f2b1eb8378b7e1f2c8f232948832
|
testutil/util-tests-reporter.adb
|
testutil/util-tests-reporter.adb
|
------------------------------------------------------------------------------
-- --
-- GNAT COMPILER COMPONENTS --
-- --
-- A U N I T . R E P O R T E R . X M L --
-- --
-- B o d y --
-- --
-- --
-- Copyright (C) 2000-2009, AdaCore --
-- --
-- GNAT is free software; you can redistribute it and/or modify it under --
-- terms of the GNU General Public License as published by the Free Soft- --
-- ware Foundation; either version 2, or (at your option) any later ver- --
-- sion. GNAT is distributed in the hope that it will be useful, but WITH- --
-- OUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY --
-- or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License --
-- for more details. You should have received a copy of the GNU General --
-- Public License distributed with GNAT; see file COPYING. If not, write --
-- to the Free Software Foundation, 51 Franklin Street, Fifth Floor, --
-- Boston, MA 02110-1301, USA. --
-- --
-- GNAT is maintained by AdaCore (http://www.adacore.com) --
-- --
------------------------------------------------------------------------------
with AUnit.Time_Measure;
with Util.Strings;
-- Very simple reporter to console
package body Util.Tests.Reporter is
use AUnit.Test_Results;
use AUnit.Time_Measure;
use type AUnit.Message_String;
use Ada.Text_IO;
procedure Dump_Result_List (File : in Ada.Text_IO.File_Type;
L : in Result_Lists.List);
-- List failed assertions
-- procedure Put_Measure is new Gen_Put_Measure;
-- Output elapsed time
procedure Report_Test (File : in Ada.Text_IO.File_Type;
Test : in Test_Result);
-- Report a single assertion failure or unexpected exception
procedure Put (File : in Ada.Text_IO.File_Type;
I : in Integer);
procedure Put (File : in Ada.Text_IO.File_Type;
I : in Integer) is
begin
Ada.Text_IO.Put (File, Util.Strings.Image (I));
end Put;
----------------------
-- Dump_Result_List --
----------------------
procedure Dump_Result_List (File : in Ada.Text_IO.File_Type;
L : in Result_Lists.List) is
use Result_Lists;
C : Cursor := First (L);
begin
-- Note: can't use Iterate because it violates restriction
-- No_Implicit_Dynamic_Code
while Has_Element (C) loop
Report_Test (File, Element (C));
Next (C);
end loop;
end Dump_Result_List;
------------
-- Report --
------------
procedure Report (Engine : XML_Reporter;
R : in out Result'Class)
is
Output : Ada.Text_IO.File_Type;
begin
Ada.Text_IO.Create (File => Output,
Mode => Ada.Text_IO.Out_File,
Name => To_String (Engine.File));
Engine.Report (Output, R);
Ada.Text_IO.Close (Output);
end Report;
------------
-- Report --
------------
procedure Report (Engine : XML_Reporter;
File : in out Ada.Text_IO.File_Type;
R : in out Result'Class)
is
pragma Unreferenced (Engine);
procedure Put (I : in Integer);
procedure Put (S : in String);
T : AUnit_Duration;
procedure Put (I : in Integer) is
begin
Ada.Text_IO.Put (File, Integer'Image (I));
end Put;
procedure Put (S : in String) is
begin
Put (File, S);
end Put;
procedure Put_Measure is new AUnit.Time_Measure.Gen_Put_Measure;
begin
Put_Line (File, "<?xml version='1.0' encoding='utf-8' ?>");
Put (File, "<TestRun");
if Elapsed (R) /= AUnit.Time_Measure.Null_Time then
T := Get_Measure (Elapsed (R));
Put (File, " elapsed='");
Put_Measure (T);
Put_Line (File, "'>");
else
Put_Line (File, ">");
end if;
Put_Line (File, " <Statistics>");
Put (File, " <Tests>");
Put (File, Integer (Test_Count (R)));
Put_Line (File, "</Tests>");
Put (File, " <FailuresTotal>");
Put (File, Integer (Failure_Count (R)) + Integer (Error_Count (R)));
Put_Line (File, "</FailuresTotal>");
Put (File, " <Failures>");
Put (File, Integer (Failure_Count (R)));
Put_Line (File, "</Failures>");
Put (File, " <Errors>");
Put (File, Integer (Error_Count (R)));
Put_Line (File, "</Errors>");
Put_Line (File, " </Statistics>");
declare
S : Result_Lists.List;
begin
Put_Line (File, " <SuccessfulTests>");
Successes (R, S);
Dump_Result_List (File, S);
Put_Line (File, " </SuccessfulTests>");
end;
Put_Line (File, " <FailedTests>");
declare
F : Result_Lists.List;
begin
Failures (R, F);
Dump_Result_List (File, F);
end;
declare
E : Result_Lists.List;
begin
Errors (R, E);
Dump_Result_List (File, E);
end;
Put_Line (File, " </FailedTests>");
Put_Line (File, "</TestRun>");
end Report;
------------------
-- Report_Error --
------------------
procedure Report_Test (File : in Ada.Text_IO.File_Type;
Test : in Test_Result) is
procedure Put (I : in Integer);
procedure Put (S : in String);
Is_Assert : Boolean;
T : AUnit_Duration;
procedure Put (I : in Integer) is
begin
Put (File, I);
end Put;
procedure Put (S : in String) is
begin
Put (File, S);
end Put;
procedure Put_Measure is new AUnit.Time_Measure.Gen_Put_Measure;
begin
Put (File, " <Test");
if Test.Elapsed /= AUnit.Time_Measure.Null_Time then
T := Get_Measure (Test.Elapsed);
Put (File, " elapsed='");
Put_Measure (T);
Put_Line (File, "'>");
else
Put_Line (File, ">");
end if;
Put (File, " <Name>");
Put (File, Test.Test_Name.all);
if Test.Routine_Name /= null then
Put (File, " : ");
Put (File, Test.Routine_Name.all);
end if;
Put_Line (File, "</Name>");
if Test.Failure /= null or else Test.Error /= null then
if Test.Failure /= null then
Is_Assert := True;
else
Is_Assert := False;
end if;
Put (File, " <FailureType>");
if Is_Assert then
Put (File, "Assertion");
else
Put (File, "Error");
end if;
Put_Line (File, "</FailureType>");
Put (File, " <Message>");
if Is_Assert then
Put (File, Test.Failure.Message.all);
else
Put (File, Test.Error.Exception_Name.all);
end if;
Put_Line (File, "</Message>");
if Is_Assert then
Put_Line (File, " <Location>");
Put (File, " <File>");
Put (File, Test.Failure.Source_Name.all);
Put_Line (File, "</File>");
Put (File, " <Line>");
Put (File, Test.Failure.Line);
Put_Line (File, "</Line>");
Put_Line (File, " </Location>");
else
Put_Line (File, " <Exception>");
Put (File, " <Message>");
Put (File, Test.Error.Exception_Name.all);
Put_Line (File, "</Message>");
if Test.Error.Exception_Message /= null then
Put (File, " <Information>");
Put (File, Test.Error.Exception_Message.all);
Put_Line (File, "</Information>");
end if;
if Test.Error.Traceback /= null then
Put (File, " <Traceback>");
Put (File, Test.Error.Traceback.all);
Put_Line (File, "</Traceback>");
end if;
Put_Line (File, " </Exception>");
end if;
end if;
Put_Line (File, " </Test>");
end Report_Test;
end Util.Tests.Reporter;
|
------------------------------------------------------------------------------
-- --
-- GNAT COMPILER COMPONENTS --
-- --
-- A U N I T . R E P O R T E R . X M L --
-- --
-- B o d y --
-- --
-- --
-- Copyright (C) 2000-2009, AdaCore --
-- --
-- GNAT is free software; you can redistribute it and/or modify it under --
-- terms of the GNU General Public License as published by the Free Soft- --
-- ware Foundation; either version 2, or (at your option) any later ver- --
-- sion. GNAT is distributed in the hope that it will be useful, but WITH- --
-- OUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY --
-- or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License --
-- for more details. You should have received a copy of the GNU General --
-- Public License distributed with GNAT; see file COPYING. If not, write --
-- to the Free Software Foundation, 51 Franklin Street, Fifth Floor, --
-- Boston, MA 02110-1301, USA. --
-- --
-- GNAT is maintained by AdaCore (http://www.adacore.com) --
-- --
------------------------------------------------------------------------------
with AUnit.Time_Measure;
with Util.Strings;
-- Very simple reporter to console
package body Util.Tests.Reporter is
use AUnit.Test_Results;
use AUnit.Time_Measure;
use type AUnit.Message_String;
use Ada.Text_IO;
procedure Print_Summary (R : in out Result'Class);
procedure Dump_Result_List (File : in Ada.Text_IO.File_Type;
L : in Result_Lists.List);
-- List failed assertions
-- procedure Put_Measure is new Gen_Put_Measure;
-- Output elapsed time
procedure Report_Test (File : in Ada.Text_IO.File_Type;
Test : in Test_Result);
-- Report a single assertion failure or unexpected exception
procedure Put (File : in Ada.Text_IO.File_Type;
I : in Integer);
procedure Put (File : in Ada.Text_IO.File_Type;
I : in Integer) is
begin
Ada.Text_IO.Put (File, Util.Strings.Image (I));
end Put;
----------------------
-- Dump_Result_List --
----------------------
procedure Dump_Result_List (File : in Ada.Text_IO.File_Type;
L : in Result_Lists.List) is
use Result_Lists;
C : Cursor := First (L);
begin
-- Note: can't use Iterate because it violates restriction
-- No_Implicit_Dynamic_Code
while Has_Element (C) loop
Report_Test (File, Element (C));
Next (C);
end loop;
end Dump_Result_List;
------------
-- Report --
------------
procedure Report (Engine : XML_Reporter;
R : in out Result'Class)
is
Output : Ada.Text_IO.File_Type;
begin
Ada.Text_IO.Create (File => Output,
Mode => Ada.Text_IO.Out_File,
Name => To_String (Engine.File));
Engine.Report (Output, R);
Ada.Text_IO.Close (Output);
end Report;
procedure Print_Summary (R : in out Result'Class) is
S_Count : constant Integer := Integer (Success_Count (R));
F_Count : constant Integer := Integer (Failure_Count (R));
E_Count : constant Integer := Integer (Error_Count (R));
begin
New_Line;
Put ("Total Tests Run: ");
Put (Util.Strings.Image (Integer (Test_Count (R))));
New_Line;
Put ("Successful Tests: ");
Put (Util.Strings.Image (S_Count));
New_Line;
Put ("Failed Assertions: ");
Put (Util.Strings.Image (F_Count));
New_Line;
Put ("Unexpected Errors: ");
Put (Util.Strings.Image (E_Count));
New_Line;
end Print_Summary;
------------
-- Report --
------------
procedure Report (Engine : XML_Reporter;
File : in out Ada.Text_IO.File_Type;
R : in out Result'Class)
is
pragma Unreferenced (Engine);
procedure Put (I : in Integer);
procedure Put (S : in String);
T : AUnit_Duration;
procedure Put (I : in Integer) is
begin
Ada.Text_IO.Put (File, Integer'Image (I));
end Put;
procedure Put (S : in String) is
begin
Put (File, S);
end Put;
procedure Put_Measure is new AUnit.Time_Measure.Gen_Put_Measure;
begin
Put_Line (File, "<?xml version='1.0' encoding='utf-8' ?>");
Put (File, "<TestRun");
if Elapsed (R) /= AUnit.Time_Measure.Null_Time then
T := Get_Measure (Elapsed (R));
Put (File, " elapsed='");
Put_Measure (T);
Put_Line (File, "'>");
else
Put_Line (File, ">");
end if;
Print_Summary (R);
Put_Line (File, " <Statistics>");
Put (File, " <Tests>");
Put (File, Integer (Test_Count (R)));
Put_Line (File, "</Tests>");
Put (File, " <FailuresTotal>");
Put (File, Integer (Failure_Count (R)) + Integer (Error_Count (R)));
Put_Line (File, "</FailuresTotal>");
Put (File, " <Failures>");
Put (File, Integer (Failure_Count (R)));
Put_Line (File, "</Failures>");
Put (File, " <Errors>");
Put (File, Integer (Error_Count (R)));
Put_Line (File, "</Errors>");
Put_Line (File, " </Statistics>");
declare
S : Result_Lists.List;
begin
Put_Line (File, " <SuccessfulTests>");
Successes (R, S);
Dump_Result_List (File, S);
Put_Line (File, " </SuccessfulTests>");
end;
Put_Line (File, " <FailedTests>");
declare
F : Result_Lists.List;
begin
Failures (R, F);
Dump_Result_List (File, F);
end;
declare
E : Result_Lists.List;
begin
Errors (R, E);
Dump_Result_List (File, E);
end;
Put_Line (File, " </FailedTests>");
Put_Line (File, "</TestRun>");
end Report;
------------------
-- Report_Error --
------------------
procedure Report_Test (File : in Ada.Text_IO.File_Type;
Test : in Test_Result) is
procedure Put (I : in Integer);
procedure Put (S : in String);
Is_Assert : Boolean;
T : AUnit_Duration;
procedure Put (I : in Integer) is
begin
Put (File, I);
end Put;
procedure Put (S : in String) is
begin
Put (File, S);
end Put;
procedure Put_Measure is new AUnit.Time_Measure.Gen_Put_Measure;
begin
Put (File, " <Test");
if Test.Elapsed /= AUnit.Time_Measure.Null_Time then
T := Get_Measure (Test.Elapsed);
Put (File, " elapsed='");
Put_Measure (T);
Put_Line (File, "'>");
else
Put_Line (File, ">");
end if;
Put (File, " <Name>");
Put (File, Test.Test_Name.all);
if Test.Routine_Name /= null then
Put (File, " : ");
Put (File, Test.Routine_Name.all);
end if;
Put_Line (File, "</Name>");
if Test.Failure /= null or else Test.Error /= null then
if Test.Failure /= null then
Is_Assert := True;
else
Is_Assert := False;
end if;
Put (File, " <FailureType>");
if Is_Assert then
Put (File, "Assertion");
else
Put (File, "Error");
end if;
Put_Line (File, "</FailureType>");
Put (File, " <Message>");
if Is_Assert then
Put (File, Test.Failure.Message.all);
else
Put (File, Test.Error.Exception_Name.all);
end if;
Put_Line (File, "</Message>");
if Is_Assert then
Put_Line (File, " <Location>");
Put (File, " <File>");
Put (File, Test.Failure.Source_Name.all);
Put_Line (File, "</File>");
Put (File, " <Line>");
Put (File, Test.Failure.Line);
Put_Line (File, "</Line>");
Put_Line (File, " </Location>");
else
Put_Line (File, " <Exception>");
Put (File, " <Message>");
Put (File, Test.Error.Exception_Name.all);
Put_Line (File, "</Message>");
if Test.Error.Exception_Message /= null then
Put (File, " <Information>");
Put (File, Test.Error.Exception_Message.all);
Put_Line (File, "</Information>");
end if;
if Test.Error.Traceback /= null then
Put (File, " <Traceback>");
Put (File, Test.Error.Traceback.all);
Put_Line (File, "</Traceback>");
end if;
Put_Line (File, " </Exception>");
end if;
end if;
Put_Line (File, " </Test>");
end Report_Test;
end Util.Tests.Reporter;
|
Print a summary of results on stdout
|
Print a summary of results on stdout
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
191bec94a6feb68d908e844e432e2306a9c7a8e2
|
src/security-permissions.ads
|
src/security-permissions.ads
|
-----------------------------------------------------------------------
-- security-permissions -- Definition of permissions
-- Copyright (C) 2010, 2011, 2012, 2016, 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
private with Interfaces;
-- == Permission ==
-- The <b>Security.Permissions</b> package defines the different permissions that can be
-- checked by the access control manager. An application should declare each permission
-- by instantiating the <tt>Definition</tt> package:
--
-- package Perm_Create_Workspace is new Security.Permissions.Definition ("create-workspace");
--
-- This declares a permission that can be represented by "<tt>create-workspace</tt>" in
-- configuration files. In Ada, the permission is used as follows:
--
-- Perm_Create_Workspace.Permission
--
package Security.Permissions is
Invalid_Name : exception;
-- Max number of permissions supported by the implementation.
MAX_PERMISSION : constant Natural := 255;
type Permission_Index is new Natural range 0 .. MAX_PERMISSION;
type Permission_Index_Array is array (Positive range <>) of Permission_Index;
NONE : constant Permission_Index := Permission_Index'First;
-- Get the permission index associated with the name.
function Get_Permission_Index (Name : in String) return Permission_Index;
-- Get the permission name given the index.
function Get_Name (Index : in Permission_Index) return String;
-- The permission root class.
-- Each permission is represented by a <b>Permission_Index</b> number to provide a fast
-- and efficient permission check.
type Permission (Id : Permission_Index) is tagged limited null record;
generic
Name : String;
package Definition is
function Permission return Permission_Index;
pragma Inline_Always (Permission);
end Definition;
-- Add the permission name and allocate a unique permission index.
procedure Add_Permission (Name : in String;
Index : out Permission_Index);
type Permission_Index_Set is private;
-- Check if the permission index set contains the given permission index.
function Has_Permission (Set : in Permission_Index_Set;
Index : in Permission_Index) return Boolean;
-- Add the permission index to the set.
procedure Add_Permission (Set : in out Permission_Index_Set;
Index : in Permission_Index);
-- Get the last permission index registered in the global permission map.
function Get_Last_Permission_Index return Permission_Index;
-- The empty set of permission indexes.
EMPTY_SET : constant Permission_Index_Set;
private
INDEX_SET_SIZE : constant Natural := (MAX_PERMISSION + 7) / 8;
type Permission_Index_Set is array (0 .. INDEX_SET_SIZE - 1) of Interfaces.Unsigned_8;
EMPTY_SET : constant Permission_Index_Set := (others => 0);
end Security.Permissions;
|
-----------------------------------------------------------------------
-- security-permissions -- Definition of permissions
-- Copyright (C) 2010, 2011, 2012, 2016, 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
private with Interfaces;
-- == Permission ==
-- The <b>Security.Permissions</b> package defines the different permissions that can be
-- checked by the access control manager. An application should declare each permission
-- by instantiating the <tt>Definition</tt> package:
--
-- package Perm_Create_Workspace is new Security.Permissions.Definition ("create-workspace");
--
-- This declares a permission that can be represented by "<tt>create-workspace</tt>" in
-- configuration files. In Ada, the permission is used as follows:
--
-- Perm_Create_Workspace.Permission
--
package Security.Permissions is
Invalid_Name : exception;
-- Max number of permissions supported by the implementation.
MAX_PERMISSION : constant Natural := 255;
type Permission_Index is new Natural range 0 .. MAX_PERMISSION;
type Permission_Index_Array is array (Positive range <>) of Permission_Index;
NONE : constant Permission_Index := Permission_Index'First;
-- Get the permission index associated with the name.
function Get_Permission_Index (Name : in String) return Permission_Index;
-- Get the list of permissions whose name is given in the string with separated comma.
function Get_Permission_Array (List : in String) return Permission_Index_Array;
-- Get the permission name given the index.
function Get_Name (Index : in Permission_Index) return String;
-- The permission root class.
-- Each permission is represented by a <b>Permission_Index</b> number to provide a fast
-- and efficient permission check.
type Permission (Id : Permission_Index) is tagged limited null record;
generic
Name : String;
package Definition is
function Permission return Permission_Index;
pragma Inline_Always (Permission);
end Definition;
-- Add the permission name and allocate a unique permission index.
procedure Add_Permission (Name : in String;
Index : out Permission_Index);
type Permission_Index_Set is private;
-- Check if the permission index set contains the given permission index.
function Has_Permission (Set : in Permission_Index_Set;
Index : in Permission_Index) return Boolean;
-- Add the permission index to the set.
procedure Add_Permission (Set : in out Permission_Index_Set;
Index : in Permission_Index);
-- Get the last permission index registered in the global permission map.
function Get_Last_Permission_Index return Permission_Index;
-- The empty set of permission indexes.
EMPTY_SET : constant Permission_Index_Set;
private
INDEX_SET_SIZE : constant Natural := (MAX_PERMISSION + 7) / 8;
type Permission_Index_Set is array (0 .. INDEX_SET_SIZE - 1) of Interfaces.Unsigned_8;
EMPTY_SET : constant Permission_Index_Set := (others => 0);
end Security.Permissions;
|
Declare the Get_Permission_Array function
|
Declare the Get_Permission_Array function
|
Ada
|
apache-2.0
|
stcarrez/ada-security
|
86b7c3df75c7db04230727fcd79f5cf341fe1c69
|
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.
-- Each permission is represented by a <b>Permission_Index</b> number to provide a fast
-- and efficient permission check.
type Permission (Id : Permission_Index) is tagged limited null record;
generic
Name : String;
package Permission_ACL is
function Permission return Permission_Index;
pragma Inline_Always (Permission);
end Permission_ACL;
end Security.Permissions;
|
-----------------------------------------------------------------------
-- security-permissions -- Definition of permissions
-- Copyright (C) 2010, 2011, 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
-- The <b>Security.Permissions</b> package defines the different permissions that can be
-- checked by the access control manager.
package Security.Permissions is
Invalid_Name : exception;
type Permission_Index is new Natural;
-- Get the permission index associated with the name.
function Get_Permission_Index (Name : in String) return Permission_Index;
-- The permission root class.
-- Each permission is represented by a <b>Permission_Index</b> number to provide a fast
-- and efficient permission check.
type Permission (Id : Permission_Index) is tagged limited null record;
generic
Name : String;
package Definition is
function Permission return Permission_Index;
pragma Inline_Always (Permission);
end Definition;
-- Add the permission name and allocate a unique permission index.
procedure Add_Permission (Name : in String;
Index : out Permission_Index);
private
-- Get the last permission index registered in the global permission map.
function Get_Last_Permission_Index return Permission_Index;
end Security.Permissions;
|
Rename the package Permission_ACL into Definition
|
Rename the package Permission_ACL into Definition
|
Ada
|
apache-2.0
|
Letractively/ada-security
|
32d4a4ccf796a6615362946760286791572a766f
|
demo/texture.adb
|
demo/texture.adb
|
-- Simple Lumen demo/test program, using earliest incomplete library.
with Ada.Characters.Handling;
with Ada.Command_Line;
with System.Address_To_Access_Conversions;
with Lumen.Events.Animate;
with Lumen.Image;
with Lumen.Window;
with GL;
with GLU;
procedure Texture is
---------------------------------------------------------------------------
-- Rotation wraps around at this point, in degrees
Max_Rotation : constant := 359;
-- Traditional cinema framrate, in frames per second
Framerate : constant := 24;
---------------------------------------------------------------------------
Win : Lumen.Window.Handle;
Event : Lumen.Events.Event_Data;
Wide : Natural; -- no longer have default values since they're now set by the image size
High : Natural;
Rotation : Natural := 0;
Image : Lumen.Image.Descriptor;
Img_Wide : GL.glFloat;
Img_High : GL.glFloat;
Tx_Name : aliased GL.GLuint;
Direct : Boolean := True; -- want direct rendering by default
Attrs : Lumen.Window.Context_Attributes :=
(
(Lumen.Window.Attr_Red_Size, 8),
(Lumen.Window.Attr_Green_Size, 8),
(Lumen.Window.Attr_Blue_Size, 8),
(Lumen.Window.Attr_Alpha_Size, 8),
(Lumen.Window.Attr_Depth_Size, 24)
);
---------------------------------------------------------------------------
Program_Error : exception;
Program_Exit : exception;
---------------------------------------------------------------------------
-- Create a texture and bind a 2D image to it
procedure Create_Texture is
use GL;
use GLU;
package GLB is new System.Address_To_Access_Conversions (GLubyte);
IP : GLpointer;
begin -- Create_Texture
-- Allocate a texture name
glGenTextures (1, Tx_Name'Unchecked_Access);
-- Bind texture operations to the newly-created texture name
glBindTexture (GL_TEXTURE_2D, Tx_Name);
-- Select modulate to mix texture with color for shading
glTexEnvi (GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
-- Wrap textures at both edges
glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
-- How the texture behaves when minified and magnified
glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
-- Create a pointer to the image. This sort of horror show is going to
-- be disappearing once Lumen includes its own OpenGL bindings.
IP := GLB.To_Pointer (Image.Values (0, 0)'Address).all'Unchecked_Access;
-- Build our texture from the image we loaded earlier
glTexImage2D (GL_TEXTURE_2D, 0, GL_RGBA, GLsizei (Image.Width), GLsizei (Image.Height), 0,
GL_RGBA, GL_UNSIGNED_BYTE, IP);
end Create_Texture;
---------------------------------------------------------------------------
-- Set or reset the window view parameters
procedure Set_View (W, H : in Natural) is
use GL;
use GLU;
Aspect : GLdouble;
begin -- Set_View
-- Viewport dimensions
glViewport (0, 0, GLsizei (W), GLsizei (H));
-- Size of rectangle upon which image is mapped
if Wide > High then
Img_Wide := glFloat (1.5);
Img_High := glFloat (1.5) * glFloat (Float (High) / Float (Wide));
else
Img_Wide := glFloat (1.5) * glFloat (Float (Wide) / Float (High));
Img_High := glFloat (1.5);
end if;
-- Set up the projection matrix based on the window's shape--wider than
-- high, or higher than wide
glMatrixMode (GL_PROJECTION);
glLoadIdentity;
-- Set up a 3D viewing frustum, which is basically a truncated pyramid
-- in which the scene takes place. Roughly, the narrow end is your
-- screen, and the wide end is 10 units away from the camera.
if W <= H then
Aspect := GLdouble (H) / GLdouble (W);
glFrustum (-1.0, 1.0, -Aspect, Aspect, 2.0, 10.0);
else
Aspect := GLdouble (W) / GLdouble (H);
glFrustum (-Aspect, Aspect, -1.0, 1.0, 2.0, 10.0);
end if;
end Set_View;
---------------------------------------------------------------------------
-- Draw our scene
procedure Draw is
use GL;
begin -- Draw
-- Set a black background
glClearColor (0.8, 0.8, 0.8, 1.0);
glClear (GL_COLOR_BUFFER_BIT or GL_DEPTH_BUFFER_BIT);
-- Draw a texture-mapped rectangle with the same aspect ratio as the
-- original image
glBegin (GL_POLYGON);
begin
glTexCoord3f (0.0, 1.0, 0.0);
glVertex3f (-Img_Wide, -Img_High, 0.0);
glTexCoord3f (0.0, 0.0, 0.0);
glVertex3f (-Img_Wide, Img_High, 0.0);
glTexCoord3f (1.0, 0.0, 0.0);
glVertex3f ( Img_Wide, Img_High, 0.0);
glTexCoord3f (1.0, 1.0, 0.0);
glVertex3f ( Img_Wide, -Img_High, 0.0);
end;
glEnd;
-- Rotate the object around the Y and Z axes by the current amount, to
-- give a "tumbling" effect.
glMatrixMode (GL_MODELVIEW);
glLoadIdentity;
glTranslated (0.0, 0.0, -4.0);
glRotated (GLdouble (Rotation), 0.0, 1.0, 0.0);
glRotated (GLdouble (Rotation), 0.0, 0.0, 1.0);
glFlush;
-- Now show it
Lumen.Window.Swap (Win);
end Draw;
---------------------------------------------------------------------------
-- Simple event handler routine for keypresses and close-window events
procedure Quit_Handler (Event : in Lumen.Events.Event_Data) is
begin -- Quit_Handler
raise Program_Exit;
end Quit_Handler;
---------------------------------------------------------------------------
-- Simple event handler routine for Exposed events
procedure Expose_Handler (Event : in Lumen.Events.Event_Data) is
begin -- Expose_Handler
Draw;
end Expose_Handler;
---------------------------------------------------------------------------
-- Simple event handler routine for Resized events
procedure Resize_Handler (Event : in Lumen.Events.Event_Data) is
begin -- Resize_Handler
Wide := Event.Resize_Data.Width;
High := Event.Resize_Data.Height;
Set_View (Wide, High);
Draw;
end Resize_Handler;
---------------------------------------------------------------------------
-- Our draw-a-frame routine, should get called FPS times a second
procedure New_Frame (Frame_Delta : in Duration) is
begin -- New_Frame
if Rotation >= Max_Rotation then
Rotation := 0;
else
Rotation := Rotation + 1;
end if;
Draw;
end New_Frame;
---------------------------------------------------------------------------
begin -- Texture
-- If we haven't been given an image to work with, just do nothing
if Ada.Command_Line.Argument_Count < 1 then
raise Program_Error with "You did not supply an image file pathname on the command line";
end if;
-- If other command-line arguments were given then process them
for Index in 2 .. Ada.Command_Line.Argument_Count loop
declare
use Lumen.Window;
Arg : String := Ada.Command_Line.Argument (Index);
begin
case Arg (Arg'First) is
when 'a' =>
Attrs (4) := (Attr_Alpha_Size, Integer'Value (Arg (Arg'First + 1 .. Arg'Last)));
when 'c' =>
Attrs (1) := (Attr_Red_Size, Integer'Value (Arg (Arg'First + 1 .. Arg'Last)));
Attrs (2) := (Attr_Blue_Size, Integer'Value (Arg (Arg'First + 1 .. Arg'Last)));
Attrs (3) := (Attr_Green_Size, Integer'Value (Arg (Arg'First + 1 .. Arg'Last)));
when 'd' =>
Attrs (5) := (Attr_Depth_Size, Integer'Value (Arg (Arg'First + 1 .. Arg'Last)));
when 'n' =>
Direct := False;
when others =>
null;
end case;
end;
end loop;
-- Read image and use it to size the window. This will suck if your image
-- is very large.
Image := Lumen.Image.From_File (Ada.Command_Line.Argument (1));
Wide := Image.Width;
High := Image.Height;
-- Create Lumen window, accepting most defaults; turn double buffering off
-- for simplicity
Lumen.Window.Create (Win,
Name => "Spinning Picture Demo",
Width => Wide,
Height => High,
Direct => Direct,
Attributes => Attrs,
Events => (Lumen.Window.Want_Key_Press => True,
Lumen.Window.Want_Exposure => True,
others => False));
-- Set up the viewport and scene parameters
Set_View (Wide, High);
-- Now create the texture and set up to use it
Create_Texture;
GL.glEnable (GL.GL_TEXTURE_2D);
GL.glBindTexture (GL.GL_TEXTURE_2D, Tx_Name);
-- Enter the event loop
declare
use Lumen.Events;
begin
Animate.Select_Events (Win => Win,
Calls => (Key_Press => Quit_Handler'Unrestricted_Access,
Exposed => Expose_Handler'Unrestricted_Access,
Resized => Resize_Handler'Unrestricted_Access,
Close_Window => Quit_Handler'Unrestricted_Access,
others => No_Callback),
FPS => Framerate,
Frame => New_Frame'Unrestricted_Access);
end;
exception
when Program_Exit =>
null; -- just exit this block, which terminates the app
end Texture;
|
-- Simple Lumen demo/test program, using earliest incomplete library.
with Ada.Characters.Handling;
with Ada.Command_Line;
with System.Address_To_Access_Conversions;
with Lumen.Events.Animate;
with Lumen.Image;
with Lumen.Window;
with GL;
with GLU;
procedure Texture is
---------------------------------------------------------------------------
-- Rotation wraps around at this point, in degrees
Max_Rotation : constant := 359;
-- Traditional cinema framrate, in frames per second
Framerate : constant := 24;
---------------------------------------------------------------------------
Win : Lumen.Window.Handle;
Event : Lumen.Events.Event_Data;
Wide : Natural; -- no longer have default values since they're now set by the image size
High : Natural;
Rotation : Natural := 0;
Image : Lumen.Image.Descriptor;
Img_Wide : GL.glFloat;
Img_High : GL.glFloat;
Tx_Name : aliased GL.GLuint;
Direct : Boolean := True; -- want direct rendering by default
Attrs : Lumen.Window.Context_Attributes :=
(
(Lumen.Window.Attr_Red_Size, 8),
(Lumen.Window.Attr_Green_Size, 8),
(Lumen.Window.Attr_Blue_Size, 8),
(Lumen.Window.Attr_Alpha_Size, 8),
(Lumen.Window.Attr_Depth_Size, 24)
);
---------------------------------------------------------------------------
Program_Error : exception;
Program_Exit : exception;
---------------------------------------------------------------------------
-- Create a texture and bind a 2D image to it
procedure Create_Texture is
use GL;
use GLU;
package GLB is new System.Address_To_Access_Conversions (GLubyte);
IP : GLpointer;
begin -- Create_Texture
-- Allocate a texture name
glGenTextures (1, Tx_Name'Unchecked_Access);
-- Bind texture operations to the newly-created texture name
glBindTexture (GL_TEXTURE_2D, Tx_Name);
-- Select modulate to mix texture with color for shading
glTexEnvi (GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
-- Wrap textures at both edges
glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
-- How the texture behaves when minified and magnified
glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
-- Create a pointer to the image. This sort of horror show is going to
-- be disappearing once Lumen includes its own OpenGL bindings.
IP := GLB.To_Pointer (Image.Values.all'Address).all'Unchecked_Access;
-- Build our texture from the image we loaded earlier
glTexImage2D (GL_TEXTURE_2D, 0, GL_RGBA, GLsizei (Image.Width), GLsizei (Image.Height), 0,
GL_RGBA, GL_UNSIGNED_BYTE, IP);
end Create_Texture;
---------------------------------------------------------------------------
-- Set or reset the window view parameters
procedure Set_View (W, H : in Natural) is
use GL;
use GLU;
Aspect : GLdouble;
begin -- Set_View
-- Viewport dimensions
glViewport (0, 0, GLsizei (W), GLsizei (H));
-- Size of rectangle upon which image is mapped
if Wide > High then
Img_Wide := glFloat (1.5);
Img_High := glFloat (1.5) * glFloat (Float (High) / Float (Wide));
else
Img_Wide := glFloat (1.5) * glFloat (Float (Wide) / Float (High));
Img_High := glFloat (1.5);
end if;
-- Set up the projection matrix based on the window's shape--wider than
-- high, or higher than wide
glMatrixMode (GL_PROJECTION);
glLoadIdentity;
-- Set up a 3D viewing frustum, which is basically a truncated pyramid
-- in which the scene takes place. Roughly, the narrow end is your
-- screen, and the wide end is 10 units away from the camera.
if W <= H then
Aspect := GLdouble (H) / GLdouble (W);
glFrustum (-1.0, 1.0, -Aspect, Aspect, 2.0, 10.0);
else
Aspect := GLdouble (W) / GLdouble (H);
glFrustum (-Aspect, Aspect, -1.0, 1.0, 2.0, 10.0);
end if;
end Set_View;
---------------------------------------------------------------------------
-- Draw our scene
procedure Draw is
use GL;
begin -- Draw
-- Set a black background
glClearColor (0.8, 0.8, 0.8, 1.0);
glClear (GL_COLOR_BUFFER_BIT or GL_DEPTH_BUFFER_BIT);
-- Draw a texture-mapped rectangle with the same aspect ratio as the
-- original image
glBegin (GL_POLYGON);
begin
glTexCoord3f (0.0, 1.0, 0.0);
glVertex3f (-Img_Wide, -Img_High, 0.0);
glTexCoord3f (0.0, 0.0, 0.0);
glVertex3f (-Img_Wide, Img_High, 0.0);
glTexCoord3f (1.0, 0.0, 0.0);
glVertex3f ( Img_Wide, Img_High, 0.0);
glTexCoord3f (1.0, 1.0, 0.0);
glVertex3f ( Img_Wide, -Img_High, 0.0);
end;
glEnd;
-- Rotate the object around the Y and Z axes by the current amount, to
-- give a "tumbling" effect.
glMatrixMode (GL_MODELVIEW);
glLoadIdentity;
glTranslated (0.0, 0.0, -4.0);
glRotated (GLdouble (Rotation), 0.0, 1.0, 0.0);
glRotated (GLdouble (Rotation), 0.0, 0.0, 1.0);
glFlush;
-- Now show it
Lumen.Window.Swap (Win);
end Draw;
---------------------------------------------------------------------------
-- Simple event handler routine for keypresses and close-window events
procedure Quit_Handler (Event : in Lumen.Events.Event_Data) is
begin -- Quit_Handler
raise Program_Exit;
end Quit_Handler;
---------------------------------------------------------------------------
-- Simple event handler routine for Exposed events
procedure Expose_Handler (Event : in Lumen.Events.Event_Data) is
begin -- Expose_Handler
Draw;
end Expose_Handler;
---------------------------------------------------------------------------
-- Simple event handler routine for Resized events
procedure Resize_Handler (Event : in Lumen.Events.Event_Data) is
begin -- Resize_Handler
Wide := Event.Resize_Data.Width;
High := Event.Resize_Data.Height;
Set_View (Wide, High);
Draw;
end Resize_Handler;
---------------------------------------------------------------------------
-- Our draw-a-frame routine, should get called FPS times a second
procedure New_Frame (Frame_Delta : in Duration) is
begin -- New_Frame
if Rotation >= Max_Rotation then
Rotation := 0;
else
Rotation := Rotation + 1;
end if;
Draw;
end New_Frame;
---------------------------------------------------------------------------
begin -- Texture
-- If we haven't been given an image to work with, just do nothing
if Ada.Command_Line.Argument_Count < 1 then
raise Program_Error with "You did not supply an image file pathname on the command line";
end if;
-- If other command-line arguments were given then process them
for Index in 2 .. Ada.Command_Line.Argument_Count loop
declare
use Lumen.Window;
Arg : String := Ada.Command_Line.Argument (Index);
begin
case Arg (Arg'First) is
when 'a' =>
Attrs (4) := (Attr_Alpha_Size, Integer'Value (Arg (Arg'First + 1 .. Arg'Last)));
when 'c' =>
Attrs (1) := (Attr_Red_Size, Integer'Value (Arg (Arg'First + 1 .. Arg'Last)));
Attrs (2) := (Attr_Blue_Size, Integer'Value (Arg (Arg'First + 1 .. Arg'Last)));
Attrs (3) := (Attr_Green_Size, Integer'Value (Arg (Arg'First + 1 .. Arg'Last)));
when 'd' =>
Attrs (5) := (Attr_Depth_Size, Integer'Value (Arg (Arg'First + 1 .. Arg'Last)));
when 'n' =>
Direct := False;
when others =>
null;
end case;
end;
end loop;
-- Read image and use it to size the window. This will suck if your image
-- is very large.
Image := Lumen.Image.From_File (Ada.Command_Line.Argument (1));
Wide := Image.Width;
High := Image.Height;
-- Create Lumen window, accepting most defaults; turn double buffering off
-- for simplicity
Lumen.Window.Create (Win,
Name => "Spinning Picture Demo",
Width => Wide,
Height => High,
Direct => Direct,
Attributes => Attrs,
Events => (Lumen.Window.Want_Key_Press => True,
Lumen.Window.Want_Exposure => True,
others => False));
-- Set up the viewport and scene parameters
Set_View (Wide, High);
-- Now create the texture and set up to use it
Create_Texture;
GL.glEnable (GL.GL_TEXTURE_2D);
GL.glBindTexture (GL.GL_TEXTURE_2D, Tx_Name);
-- Enter the event loop
declare
use Lumen.Events;
begin
Animate.Select_Events (Win => Win,
Calls => (Key_Press => Quit_Handler'Unrestricted_Access,
Exposed => Expose_Handler'Unrestricted_Access,
Resized => Resize_Handler'Unrestricted_Access,
Close_Window => Quit_Handler'Unrestricted_Access,
others => No_Callback),
FPS => Framerate,
Frame => New_Frame'Unrestricted_Access);
end;
exception
when Program_Exit =>
null; -- just exit this block, which terminates the app
end Texture;
|
Create address to image buffer in a more portable way, as Julian's BMP package uses 1-based indexes, and other future packages may too
|
Create address to image buffer in a more portable way, as Julian's BMP package
uses 1-based indexes, and other future packages may too
|
Ada
|
isc
|
darkestkhan/lumen,darkestkhan/lumen2
|
9a00519d1c63d366087a34d065172766c6535a39
|
mat/src/mat-readers-files.ads
|
mat/src/mat-readers-files.ads
|
-----------------------------------------------------------------------
-- mat-readers-files -- Reader for files
-- Copyright (C) 2014 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Streams.Buffered;
with Util.Streams.Files;
package MAT.Readers.Files is
type File_Reader_Type is new Manager_Base with private;
-- Open the file.
procedure Open (Reader : in out File_Reader_Type;
Path : in String);
procedure Read_All (Reader : in out File_Reader_Type);
private
type File_Reader_Type is new Manager_Base with record
File : aliased Util.Streams.Files.File_Stream;
Stream : Util.Streams.Buffered.Buffered_Stream;
end record;
end MAT.Readers.Files;
|
-----------------------------------------------------------------------
-- mat-readers-files -- Reader for files
-- Copyright (C) 2014 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Streams.Buffered;
with Util.Streams.Files;
with MAT.Readers.Streams;
package MAT.Readers.Files is
type File_Reader_Type is new MAT.Readers.Streams.Stream_Reader_Type with private;
-- Open the file.
procedure Open (Reader : in out File_Reader_Type;
Path : in String);
private
type File_Reader_Type is new MAT.Readers.Streams.Stream_Reader_Type with record
File : aliased Util.Streams.Files.File_Stream;
end record;
end MAT.Readers.Files;
|
Use the MAT.Readers.Streams package for the file reader implementation
|
Use the MAT.Readers.Streams package for the file reader implementation
|
Ada
|
apache-2.0
|
stcarrez/mat,stcarrez/mat,stcarrez/mat
|
c147ca95c0c731e28b5f1c5bf562b18ca6c0dc99
|
src/asf-views.ads
|
src/asf-views.ads
|
-----------------------------------------------------------------------
-- asf-views -- Views
-- Copyright (C) 2009, 2010, 2011, 2012, 2013 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
-- The <b>ASF.Views</b> package defines the abstractions to represent
-- an XHTML view that can be instantiated to create the JSF component
-- tree. The <b>ASF.Views</b> are read only once and they are shared
-- by the JSF component trees that are instantiated from it.
--
-- The XHTML view is read using a SAX parser which creates nodes
-- and attributes to represent the view.
--
-- The <b>ASF.Views</b> is composed of nodes represented by <b>Tag_Node</b>
-- and attributes represented by <b>Tag_Attribute</b>. In a sense, this
-- is very close to an XML DOM tree.
package ASF.Views is
-- ------------------------------
-- Source line information
-- ------------------------------
type File_Info (<>) is limited private;
type File_Info_Access is access all File_Info;
-- Create a <b>File_Info</b> record to identify the file whose path is <b>Path</b>
-- and whose relative path portion starts at <b>Relative_Position</b>.
function Create_File_Info (Path : in String;
Relative_Position : in Natural) return File_Info_Access;
-- Get the relative path name
function Relative_Path (File : in File_Info) return String;
type Line_Info is private;
-- Get the line number
function Line (Info : in Line_Info) return Natural;
pragma Inline (Line);
-- Get the source file
function File (Info : in Line_Info) return String;
pragma Inline (File);
private
type File_Info (Length : Natural) is limited record
Relative_Pos : Natural;
Path : String (1 .. Length);
end record;
NO_FILE : aliased File_Info := File_Info '(Length => 0, Path => "", Relative_Pos => 0);
type Line_Info is record
Line : Natural := 0;
Column : Natural := 0;
File : File_Info_Access := NO_FILE'Access;
end record;
end ASF.Views;
|
-----------------------------------------------------------------------
-- asf-views -- Views
-- Copyright (C) 2009, 2010, 2011, 2012, 2013 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
-- The <b>ASF.Views</b> package defines the abstractions to represent
-- an XHTML view that can be instantiated to create the JSF component
-- tree. The <b>ASF.Views</b> are read only once and they are shared
-- by the JSF component trees that are instantiated from it.
--
-- The XHTML view is read using a SAX parser which creates nodes
-- and attributes to represent the view.
--
-- The <b>ASF.Views</b> is composed of nodes represented by <b>Tag_Node</b>
-- and attributes represented by <b>Tag_Attribute</b>. In a sense, this
-- is very close to an XML DOM tree.
package ASF.Views is
pragma Preelaborate;
-- ------------------------------
-- Source line information
-- ------------------------------
type File_Info (<>) is limited private;
type File_Info_Access is access all File_Info;
-- Create a <b>File_Info</b> record to identify the file whose path is <b>Path</b>
-- and whose relative path portion starts at <b>Relative_Position</b>.
function Create_File_Info (Path : in String;
Relative_Position : in Natural) return File_Info_Access;
-- Get the relative path name
function Relative_Path (File : in File_Info) return String;
type Line_Info is private;
-- Get the line number
function Line (Info : in Line_Info) return Natural;
pragma Inline (Line);
-- Get the source file
function File (Info : in Line_Info) return String;
pragma Inline (File);
private
type File_Info (Length : Natural) is limited record
Relative_Pos : Natural;
Path : String (1 .. Length);
end record;
NO_FILE : aliased File_Info := File_Info '(Length => 0, Path => "", Relative_Pos => 0);
type Line_Info is record
Line : Natural := 0;
Column : Natural := 0;
File : File_Info_Access := NO_FILE'Access;
end record;
end ASF.Views;
|
Make the package Preelaborate
|
Make the package Preelaborate
|
Ada
|
apache-2.0
|
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
|
c69e0e6bcae4407aade54def6aaa04479910d472
|
src/asf-navigations.adb
|
src/asf-navigations.adb
|
-----------------------------------------------------------------------
-- asf-navigations -- Navigations
-- 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 ASF.Components.Root;
with Util.Strings;
with Util.Beans.Objects;
with Util.Log.Loggers;
with ASF.Applications.Main;
with ASF.Navigations.Render;
package body ASF.Navigations is
-- ------------------------------
-- Navigation Case
-- ------------------------------
use Util.Log;
-- The logger
Log : constant Loggers.Logger := Loggers.Create ("ASF.Navigations");
-- ------------------------------
-- Check if the navigator specific condition matches the current execution context.
-- ------------------------------
function Matches (Navigator : in Navigation_Case;
Action : in String;
Outcome : in String;
Context : in ASF.Contexts.Faces.Faces_Context'Class) return Boolean is
begin
-- outcome must match
if Navigator.Outcome /= null and then Navigator.Outcome.all /= Outcome then
return False;
end if;
-- action must match
if Navigator.Action /= null and then Navigator.Action.all /= Action then
return False;
end if;
-- condition must be true
if not Navigator.Condition.Is_Constant then
declare
Value : constant Util.Beans.Objects.Object
:= Navigator.Condition.Get_Value (Context.Get_ELContext.all);
begin
if not Util.Beans.Objects.To_Boolean (Value) then
return False;
end if;
end;
end if;
return True;
end Matches;
-- ------------------------------
-- Navigation Rule
-- ------------------------------
-- ------------------------------
-- Search for the navigator that matches the current action, outcome and context.
-- Returns the navigator or null if there was no match.
-- ------------------------------
function Find_Navigation (Controller : in Rule;
Action : in String;
Outcome : in String;
Context : in Contexts.Faces.Faces_Context'Class)
return Navigation_Access is
Iter : Navigator_Vector.Cursor := Controller.Navigators.First;
Navigator : Navigation_Access;
begin
while Navigator_Vector.Has_Element (Iter) loop
Navigator := Navigator_Vector.Element (Iter);
-- Check if this navigator matches the action/outcome.
if Navigator.Matches (Action, Outcome, Context) then
return Navigator;
end if;
Navigator_Vector.Next (Iter);
end loop;
return null;
end Find_Navigation;
-- ------------------------------
-- Navigation Handler
-- ------------------------------
-- ------------------------------
-- After executing an action and getting the action outcome, proceed to the navigation
-- to the next page.
-- ------------------------------
procedure Handle_Navigation (Handler : in Navigation_Handler;
Action : in String;
Outcome : in String;
Context : in out ASF.Contexts.Faces.Faces_Context'Class) is
Nav_Rules : constant Navigation_Rules_Access := Handler.Rules;
View : constant Components.Root.UIViewRoot := Context.Get_View_Root;
Name : constant String := Components.Root.Get_View_Id (View);
function Find_Navigation (View : in String) return Navigation_Access is
Pos : constant Rule_Map.Cursor := Nav_Rules.Rules.Find (To_Unbounded_String (View));
begin
if not Rule_Map.Has_Element (Pos) then
return null;
end if;
return Rule_Map.Element (Pos).Find_Navigation (Action, Outcome, Context);
end Find_Navigation;
Navigator : Navigation_Access;
begin
Log.Info ("Navigate from view {0} and action {1} with outcome {2}", Name, Action, Outcome);
-- Find an exact match
Navigator := Find_Navigation (Name);
-- Find a wildcard match
if Navigator = null then
declare
Last : Natural := Name'Last;
N : Natural;
begin
loop
N := Util.Strings.Rindex (Name, '/', Last);
exit when N = 0;
Navigator := Find_Navigation (Name (Name'First .. N) & "*");
exit when Navigator /= null or N = Name'First;
Last := Name'First - 1;
end loop;
end;
end if;
-- Execute the navigation action.
if Navigator /= null then
Navigator.Navigate (Context);
end if;
end Handle_Navigation;
-- ------------------------------
-- Initialize the the lifecycle handler.
-- ------------------------------
procedure Initialize (Handler : in out Navigation_Handler;
App : access ASF.Applications.Main.Application'Class) is
begin
Handler.Rules := new Navigation_Rules;
Handler.Application := App;
end Initialize;
-- ------------------------------
-- Free the storage used by the navigation handler.
-- ------------------------------
overriding
procedure Finalize (Handler : in out Navigation_Handler) is
begin
null;
end Finalize;
-- ------------------------------
-- Add a navigation case to navigate from the view identifier by <b>From</b>
-- to the result view identified by <b>To</b>. Some optional conditions are evaluated
-- The <b>Outcome</b> must match unless it is empty.
-- The <b>Action</b> must match unless it is empty.
-- The <b>Condition</b> expression must evaluate to True.
-- ------------------------------
procedure Add_Navigation_Case (Handler : in out Navigation_Handler;
From : in String;
To : in String;
Outcome : in String := "";
Action : in String := "";
Condition : in String := "") is
C : constant Navigation_Access := Render.Create_Render_Navigator (To);
begin
if Outcome'Length > 0 then
C.Outcome := new String '(Outcome);
end if;
if Action'Length > 0 then
C.Action := new String '(Action);
end if;
C.View_Handler := Handler.Application.Get_View_Handler;
declare
View : constant Unbounded_String := To_Unbounded_String (From);
Pos : constant Rule_Map.Cursor := Handler.Rules.Rules.Find (View);
R : Rule_Access;
begin
if not Rule_Map.Has_Element (Pos) then
R := new Rule;
Handler.Rules.Rules.Include (Key => View,
New_Item => R);
else
R := Rule_Map.Element (Pos);
end if;
R.Navigators.Append (C);
end;
end Add_Navigation_Case;
end ASF.Navigations;
|
-----------------------------------------------------------------------
-- asf-navigations -- Navigations
-- 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 ASF.Components.Root;
with Util.Strings;
with Util.Beans.Objects;
with Util.Log.Loggers;
with ASF.Applications.Main;
with ASF.Navigations.Render;
package body ASF.Navigations is
-- ------------------------------
-- Navigation Case
-- ------------------------------
use Util.Log;
-- The logger
Log : constant Loggers.Logger := Loggers.Create ("ASF.Navigations");
-- ------------------------------
-- Check if the navigator specific condition matches the current execution context.
-- ------------------------------
function Matches (Navigator : in Navigation_Case;
Action : in String;
Outcome : in String;
Context : in ASF.Contexts.Faces.Faces_Context'Class) return Boolean is
begin
-- outcome must match
if Navigator.Outcome /= null and then Navigator.Outcome.all /= Outcome then
return False;
end if;
-- action must match
if Navigator.Action /= null and then Navigator.Action.all /= Action then
return False;
end if;
-- condition must be true
if not Navigator.Condition.Is_Constant then
declare
Value : constant Util.Beans.Objects.Object
:= Navigator.Condition.Get_Value (Context.Get_ELContext.all);
begin
if not Util.Beans.Objects.To_Boolean (Value) then
return False;
end if;
end;
end if;
return True;
end Matches;
-- ------------------------------
-- Navigation Rule
-- ------------------------------
-- ------------------------------
-- Search for the navigator that matches the current action, outcome and context.
-- Returns the navigator or null if there was no match.
-- ------------------------------
function Find_Navigation (Controller : in Rule;
Action : in String;
Outcome : in String;
Context : in Contexts.Faces.Faces_Context'Class)
return Navigation_Access is
Iter : Navigator_Vector.Cursor := Controller.Navigators.First;
Navigator : Navigation_Access;
begin
while Navigator_Vector.Has_Element (Iter) loop
Navigator := Navigator_Vector.Element (Iter);
-- Check if this navigator matches the action/outcome.
if Navigator.Matches (Action, Outcome, Context) then
return Navigator;
end if;
Navigator_Vector.Next (Iter);
end loop;
return null;
end Find_Navigation;
-- ------------------------------
-- Navigation Handler
-- ------------------------------
-- ------------------------------
-- After executing an action and getting the action outcome, proceed to the navigation
-- to the next page.
-- ------------------------------
procedure Handle_Navigation (Handler : in Navigation_Handler;
Action : in String;
Outcome : in String;
Context : in out ASF.Contexts.Faces.Faces_Context'Class) is
Nav_Rules : constant Navigation_Rules_Access := Handler.Rules;
View : constant Components.Root.UIViewRoot := Context.Get_View_Root;
Name : constant String := Components.Root.Get_View_Id (View);
function Find_Navigation (View : in String) return Navigation_Access is
Pos : constant Rule_Map.Cursor := Nav_Rules.Rules.Find (To_Unbounded_String (View));
begin
if not Rule_Map.Has_Element (Pos) then
return null;
end if;
return Rule_Map.Element (Pos).Find_Navigation (Action, Outcome, Context);
end Find_Navigation;
Navigator : Navigation_Access;
begin
Log.Info ("Navigate from view {0} and action {1} with outcome {2}", Name, Action, Outcome);
-- Find an exact match
Navigator := Find_Navigation (Name);
-- Find a wildcard match
if Navigator = null then
declare
Last : Natural := Name'Last;
N : Natural;
begin
loop
N := Util.Strings.Rindex (Name, '/', Last);
exit when N = 0;
Navigator := Find_Navigation (Name (Name'First .. N) & "*");
exit when Navigator /= null or N = Name'First;
Last := N - 1;
end loop;
end;
end if;
-- Execute the navigation action.
if Navigator /= null then
Navigator.Navigate (Context);
end if;
end Handle_Navigation;
-- ------------------------------
-- Initialize the the lifecycle handler.
-- ------------------------------
procedure Initialize (Handler : in out Navigation_Handler;
App : access ASF.Applications.Main.Application'Class) is
begin
Handler.Rules := new Navigation_Rules;
Handler.Application := App;
end Initialize;
-- ------------------------------
-- Free the storage used by the navigation handler.
-- ------------------------------
overriding
procedure Finalize (Handler : in out Navigation_Handler) is
begin
null;
end Finalize;
-- ------------------------------
-- Add a navigation case to navigate from the view identifier by <b>From</b>
-- to the result view identified by <b>To</b>. Some optional conditions are evaluated
-- The <b>Outcome</b> must match unless it is empty.
-- The <b>Action</b> must match unless it is empty.
-- The <b>Condition</b> expression must evaluate to True.
-- ------------------------------
procedure Add_Navigation_Case (Handler : in out Navigation_Handler;
From : in String;
To : in String;
Outcome : in String := "";
Action : in String := "";
Condition : in String := "") is
C : constant Navigation_Access := Render.Create_Render_Navigator (To);
begin
if Outcome'Length > 0 then
C.Outcome := new String '(Outcome);
end if;
if Action'Length > 0 then
C.Action := new String '(Action);
end if;
C.View_Handler := Handler.Application.Get_View_Handler;
declare
View : constant Unbounded_String := To_Unbounded_String (From);
Pos : constant Rule_Map.Cursor := Handler.Rules.Rules.Find (View);
R : Rule_Access;
begin
if not Rule_Map.Has_Element (Pos) then
R := new Rule;
Handler.Rules.Rules.Include (Key => View,
New_Item => R);
else
R := Rule_Map.Element (Pos);
end if;
R.Navigators.Append (C);
end;
end Add_Navigation_Case;
end ASF.Navigations;
|
Fix navigation resolution
|
Fix navigation resolution
|
Ada
|
apache-2.0
|
Letractively/ada-asf,Letractively/ada-asf,Letractively/ada-asf
|
9a38ffd193f2d703d1f74c4a5370da5ddbe2843d
|
regtests/util-files-tests.adb
|
regtests/util-files-tests.adb
|
-----------------------------------------------------------------------
-- files.tests -- Unit tests for files
-- Copyright (C) 2009, 2010, 2011 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Test_Caller;
package body Util.Files.Tests is
use Util.Tests;
package Caller is new Util.Test_Caller (Test, "Files");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test Util.Files.Read_File",
Test_Read_File'Access);
Caller.Add_Test (Suite, "Test Util.Files.Read_File (missing)",
Test_Read_File'Access);
Caller.Add_Test (Suite, "Test Util.Files.Read_File (truncate)",
Test_Read_File'Access);
Caller.Add_Test (Suite, "Test Util.Files.Write_File",
Test_Write_File'Access);
Caller.Add_Test (Suite, "Test Util.Files.Iterate_Path",
Test_Iterate_Path'Access);
Caller.Add_Test (Suite, "Test Util.Files.Find_File_Path",
Test_Find_File_Path'Access);
Caller.Add_Test (Suite, "Test Util.Files.Compose_Path",
Test_Compose_Path'Access);
end Add_Tests;
-- Test reading a file into a string
-- Reads this ada source file and checks we have read it correctly
procedure Test_Read_File (T : in out Test) is
Result : Unbounded_String;
begin
Read_File (Path => "regtests/util-files-tests.adb", Into => Result);
T.Assert (Index (Result, "Util.Files.Tests") > 0,
"Content returned by Read_File is not correct");
T.Assert (Index (Result, "end Util.Files.Tests;") > 0,
"Content returned by Read_File is not correct");
end Test_Read_File;
procedure Test_Read_File_Missing (T : in out Test) is
Result : Unbounded_String;
pragma Unreferenced (Result);
begin
Read_File (Path => "regtests/files-test--util.adb", Into => Result);
T.Assert (False, "No exception raised");
exception
when others =>
null;
end Test_Read_File_Missing;
procedure Test_Read_File_Truncate (T : in out Test) is
Result : Unbounded_String;
begin
Read_File (Path => "regtests/util-files-tests.adb", Into => Result,
Max_Size => 50);
Assert_Equals (T, Length (Result), 50,
"Read_File did not truncate correctly");
T.Assert (Index (Result, "Apache License") > 0,
"Content returned by Read_File is not correct");
end Test_Read_File_Truncate;
-- Check writing a file
procedure Test_Write_File (T : in out Test) is
Path : constant String := Util.Tests.Get_Test_Path ("test-write.txt");
Content : constant String := "Testing Util.Files.Write_File" & ASCII.LF;
Result : Unbounded_String;
begin
Write_File (Path => Path, Content => Content);
Read_File (Path => Path, Into => Result);
Assert_Equals (T, To_String (Result), Content,
"Invalid content written or read");
end Test_Write_File;
-- Check Find_File_Path
procedure Test_Find_File_Path (T : in out Test) is
Dir : constant String := Util.Tests.Get_Path ("regtests");
Paths : constant String := ".;" & Dir;
begin
declare
P : constant String := Util.Files.Find_File_Path ("test.properties", Paths);
begin
Assert_Equals (T, Dir & "/test.properties", P,
"Invalid path returned");
end;
Assert_Equals (T, "blablabla.properties",
Util.Files.Find_File_Path ("blablabla.properties", Paths));
end Test_Find_File_Path;
-- ------------------------------
-- Check Iterate_Path
-- ------------------------------
procedure Test_Iterate_Path (T : in out Test) is
procedure Check_Path (Dir : in String;
Done : out Boolean);
Last : Unbounded_String;
procedure Check_Path (Dir : in String;
Done : out Boolean) is
begin
if Dir = "a" or Dir = "bc" or Dir = "de" then
Done := False;
else
Done := True;
Last := To_Unbounded_String (Dir);
end if;
end Check_Path;
begin
Iterate_Path ("a;bc;de;f", Check_Path'Access);
Assert_Equals (T, "f", Last, "Invalid last path");
Iterate_Path ("de;bc;de;b", Check_Path'Access);
Assert_Equals (T, "b", Last, "Invalid last path");
end Test_Iterate_Path;
-- ------------------------------
-- Test the Compose_Path operation
-- ------------------------------
procedure Test_Compose_Path (T : in out Test) is
begin
Assert_Equals (T, "/usr/bin;/usr/local/bin;/usr/bin",
Compose_Path ("/usr;/usr/local;/usr", "bin"),
"Invalid path composition");
end Test_Compose_Path;
end Util.Files.Tests;
|
-----------------------------------------------------------------------
-- files.tests -- Unit tests for files
-- 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.Directories;
with Util.Test_Caller;
package body Util.Files.Tests is
use Util.Tests;
package Caller is new Util.Test_Caller (Test, "Files");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test Util.Files.Read_File",
Test_Read_File'Access);
Caller.Add_Test (Suite, "Test Util.Files.Read_File (missing)",
Test_Read_File'Access);
Caller.Add_Test (Suite, "Test Util.Files.Read_File (truncate)",
Test_Read_File'Access);
Caller.Add_Test (Suite, "Test Util.Files.Write_File",
Test_Write_File'Access);
Caller.Add_Test (Suite, "Test Util.Files.Iterate_Path",
Test_Iterate_Path'Access);
Caller.Add_Test (Suite, "Test Util.Files.Find_File_Path",
Test_Find_File_Path'Access);
Caller.Add_Test (Suite, "Test Util.Files.Compose_Path",
Test_Compose_Path'Access);
end Add_Tests;
-- Test reading a file into a string
-- Reads this ada source file and checks we have read it correctly
procedure Test_Read_File (T : in out Test) is
Result : Unbounded_String;
begin
Read_File (Path => "regtests/util-files-tests.adb", Into => Result);
T.Assert (Index (Result, "Util.Files.Tests") > 0,
"Content returned by Read_File is not correct");
T.Assert (Index (Result, "end Util.Files.Tests;") > 0,
"Content returned by Read_File is not correct");
end Test_Read_File;
procedure Test_Read_File_Missing (T : in out Test) is
Result : Unbounded_String;
pragma Unreferenced (Result);
begin
Read_File (Path => "regtests/files-test--util.adb", Into => Result);
T.Assert (False, "No exception raised");
exception
when others =>
null;
end Test_Read_File_Missing;
procedure Test_Read_File_Truncate (T : in out Test) is
Result : Unbounded_String;
begin
Read_File (Path => "regtests/util-files-tests.adb", Into => Result,
Max_Size => 50);
Assert_Equals (T, Length (Result), 50,
"Read_File did not truncate correctly");
T.Assert (Index (Result, "Apache License") > 0,
"Content returned by Read_File is not correct");
end Test_Read_File_Truncate;
-- Check writing a file
procedure Test_Write_File (T : in out Test) is
Path : constant String := Util.Tests.Get_Test_Path ("test-write.txt");
Content : constant String := "Testing Util.Files.Write_File" & ASCII.LF;
Result : Unbounded_String;
begin
Write_File (Path => Path, Content => Content);
Read_File (Path => Path, Into => Result);
Assert_Equals (T, To_String (Result), Content,
"Invalid content written or read");
end Test_Write_File;
-- Check Find_File_Path
procedure Test_Find_File_Path (T : in out Test) is
Dir : constant String := Util.Tests.Get_Path ("regtests");
Paths : constant String := ".;" & Dir;
begin
declare
P : constant String := Util.Files.Find_File_Path ("test.properties", Paths);
begin
Assert_Equals (T, Dir & "/test.properties", P,
"Invalid path returned");
end;
Assert_Equals (T, "blablabla.properties",
Util.Files.Find_File_Path ("blablabla.properties", Paths));
end Test_Find_File_Path;
-- ------------------------------
-- Check Iterate_Path
-- ------------------------------
procedure Test_Iterate_Path (T : in out Test) is
procedure Check_Path (Dir : in String;
Done : out Boolean);
Last : Unbounded_String;
procedure Check_Path (Dir : in String;
Done : out Boolean) is
begin
if Dir = "a" or Dir = "bc" or Dir = "de" then
Done := False;
else
Done := True;
Last := To_Unbounded_String (Dir);
end if;
end Check_Path;
begin
Iterate_Path ("a;bc;de;f", Check_Path'Access);
Assert_Equals (T, "f", Last, "Invalid last path");
Iterate_Path ("de;bc;de;b", Check_Path'Access);
Assert_Equals (T, "b", Last, "Invalid last path");
end Test_Iterate_Path;
-- ------------------------------
-- Test the Compose_Path operation
-- ------------------------------
procedure Test_Compose_Path (T : in out Test) is
begin
Assert_Equals (T, "src/os-none",
Compose_Path ("src;regtests", "os-none"),
"Invalid path composition");
Assert_Equals (T, "regtests/bundles",
Compose_Path ("src;regtests", "bundles"),
"Invalid path composition");
if Ada.Directories.Exists ("/usr/bin") then
Assert_Equals (T, "/usr/bin;/usr/local/bin;/usr/bin",
Compose_Path ("/usr;/usr/local;/usr", "bin"),
"Invalid path composition");
end if;
end Test_Compose_Path;
end Util.Files.Tests;
|
Fix execution of Compose unit test on Windows - Do not execute one test that relies on the availability of /usr/bin directory - Add a compose test that uses the util directory hierarchy.
|
Fix execution of Compose unit test on Windows
- Do not execute one test that relies on the availability of /usr/bin directory
- Add a compose test that uses the util directory hierarchy.
|
Ada
|
apache-2.0
|
Letractively/ada-util,flottokarotto/ada-util,Letractively/ada-util,flottokarotto/ada-util
|
f5d477635a243651b67854a0878f8a621143fe97
|
awa/plugins/awa-tags/src/model/awa-tags-models.ads
|
awa/plugins/awa-tags/src/model/awa-tags-models.ads
|
-----------------------------------------------------------------------
-- AWA.Tags.Models -- AWA.Tags.Models
-----------------------------------------------------------------------
-- File generated by ada-gen DO NOT MODIFY
-- Template used: templates/model/package-spec.xhtml
-- Ada Generator: https://ada-gen.googlecode.com/svn/trunk Revision 1095
-----------------------------------------------------------------------
-- 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.
-----------------------------------------------------------------------
pragma Warnings (Off, "unit * is not referenced");
with ADO.Sessions;
with ADO.Objects;
with ADO.Statements;
with ADO.SQL;
with ADO.Schemas;
with ADO.Queries;
with ADO.Queries.Loaders;
with Ada.Containers.Vectors;
with Ada.Strings.Unbounded;
with Util.Beans.Objects;
with Util.Beans.Basic.Lists;
pragma Warnings (On, "unit * is not referenced");
package AWA.Tags.Models is
type Tag_Ref is new ADO.Objects.Object_Ref with null record;
type Tagged_Entity_Ref is new ADO.Objects.Object_Ref with null record;
-- --------------------
-- The tag definition.
-- --------------------
-- Create an object key for Tag.
function Tag_Key (Id : in ADO.Identifier) return ADO.Objects.Object_Key;
-- Create an object key for Tag from a string.
-- Raises Constraint_Error if the string cannot be converted into the object key.
function Tag_Key (Id : in String) return ADO.Objects.Object_Key;
Null_Tag : constant Tag_Ref;
function "=" (Left, Right : Tag_Ref'Class) return Boolean;
-- Set the tag identifier
procedure Set_Id (Object : in out Tag_Ref;
Value : in ADO.Identifier);
-- Get the tag identifier
function Get_Id (Object : in Tag_Ref)
return ADO.Identifier;
-- Set the tag name
procedure Set_Name (Object : in out Tag_Ref;
Value : in Ada.Strings.Unbounded.Unbounded_String);
procedure Set_Name (Object : in out Tag_Ref;
Value : in String);
-- Get the tag name
function Get_Name (Object : in Tag_Ref)
return Ada.Strings.Unbounded.Unbounded_String;
function Get_Name (Object : in Tag_Ref)
return String;
-- Load the entity identified by 'Id'.
-- Raises the NOT_FOUND exception if it does not exist.
procedure Load (Object : in out Tag_Ref;
Session : in out ADO.Sessions.Session'Class;
Id : in ADO.Identifier);
-- Load the entity identified by 'Id'.
-- Returns True in <b>Found</b> if the object was found and False if it does not exist.
procedure Load (Object : in out Tag_Ref;
Session : in out ADO.Sessions.Session'Class;
Id : in ADO.Identifier;
Found : out Boolean);
-- Find and load the entity.
overriding
procedure Find (Object : in out Tag_Ref;
Session : in out ADO.Sessions.Session'Class;
Query : in ADO.SQL.Query'Class;
Found : out Boolean);
-- Save the entity. If the entity does not have an identifier, an identifier is allocated
-- and it is inserted in the table. Otherwise, only data fields which have been changed
-- are updated.
overriding
procedure Save (Object : in out Tag_Ref;
Session : in out ADO.Sessions.Master_Session'Class);
-- Delete the entity.
overriding
procedure Delete (Object : in out Tag_Ref;
Session : in out ADO.Sessions.Master_Session'Class);
overriding
function Get_Value (From : in Tag_Ref;
Name : in String) return Util.Beans.Objects.Object;
-- Table definition
TAG_TABLE : constant ADO.Schemas.Class_Mapping_Access;
-- Internal method to allocate the Object_Record instance
overriding
procedure Allocate (Object : in out Tag_Ref);
-- Copy of the object.
procedure Copy (Object : in Tag_Ref;
Into : in out Tag_Ref);
package Tag_Vectors is
new Ada.Containers.Vectors (Index_Type => Natural,
Element_Type => Tag_Ref,
"=" => "=");
subtype Tag_Vector is Tag_Vectors.Vector;
procedure List (Object : in out Tag_Vector;
Session : in out ADO.Sessions.Session'Class;
Query : in ADO.SQL.Query'Class);
-- Create an object key for Tagged_Entity.
function Tagged_Entity_Key (Id : in ADO.Identifier) return ADO.Objects.Object_Key;
-- Create an object key for Tagged_Entity from a string.
-- Raises Constraint_Error if the string cannot be converted into the object key.
function Tagged_Entity_Key (Id : in String) return ADO.Objects.Object_Key;
Null_Tagged_Entity : constant Tagged_Entity_Ref;
function "=" (Left, Right : Tagged_Entity_Ref'Class) return Boolean;
-- Set the tag entity identifier
procedure Set_Id (Object : in out Tagged_Entity_Ref;
Value : in ADO.Identifier);
-- Get the tag entity identifier
function Get_Id (Object : in Tagged_Entity_Ref)
return ADO.Identifier;
-- Set Title: Tag model
-- Date: 2013-02-23the database entity to which the tag is associated
procedure Set_For_Entity_Id (Object : in out Tagged_Entity_Ref;
Value : in ADO.Identifier);
-- Get Title: Tag model
-- Date: 2013-02-23the database entity to which the tag is associated
function Get_For_Entity_Id (Object : in Tagged_Entity_Ref)
return ADO.Identifier;
-- Set the entity type
procedure Set_Entity_Type (Object : in out Tagged_Entity_Ref;
Value : in ADO.Entity_Type);
-- Get the entity type
function Get_Entity_Type (Object : in Tagged_Entity_Ref)
return ADO.Entity_Type;
--
procedure Set_Tag (Object : in out Tagged_Entity_Ref;
Value : in AWA.Tags.Models.Tag_Ref'Class);
--
function Get_Tag (Object : in Tagged_Entity_Ref)
return AWA.Tags.Models.Tag_Ref'Class;
-- Load the entity identified by 'Id'.
-- Raises the NOT_FOUND exception if it does not exist.
procedure Load (Object : in out Tagged_Entity_Ref;
Session : in out ADO.Sessions.Session'Class;
Id : in ADO.Identifier);
-- Load the entity identified by 'Id'.
-- Returns True in <b>Found</b> if the object was found and False if it does not exist.
procedure Load (Object : in out Tagged_Entity_Ref;
Session : in out ADO.Sessions.Session'Class;
Id : in ADO.Identifier;
Found : out Boolean);
-- Find and load the entity.
overriding
procedure Find (Object : in out Tagged_Entity_Ref;
Session : in out ADO.Sessions.Session'Class;
Query : in ADO.SQL.Query'Class;
Found : out Boolean);
-- Save the entity. If the entity does not have an identifier, an identifier is allocated
-- and it is inserted in the table. Otherwise, only data fields which have been changed
-- are updated.
overriding
procedure Save (Object : in out Tagged_Entity_Ref;
Session : in out ADO.Sessions.Master_Session'Class);
-- Delete the entity.
overriding
procedure Delete (Object : in out Tagged_Entity_Ref;
Session : in out ADO.Sessions.Master_Session'Class);
overriding
function Get_Value (From : in Tagged_Entity_Ref;
Name : in String) return Util.Beans.Objects.Object;
-- Table definition
TAGGED_ENTITY_TABLE : constant ADO.Schemas.Class_Mapping_Access;
-- Internal method to allocate the Object_Record instance
overriding
procedure Allocate (Object : in out Tagged_Entity_Ref);
-- Copy of the object.
procedure Copy (Object : in Tagged_Entity_Ref;
Into : in out Tagged_Entity_Ref);
package Tagged_Entity_Vectors is
new Ada.Containers.Vectors (Index_Type => Natural,
Element_Type => Tagged_Entity_Ref,
"=" => "=");
subtype Tagged_Entity_Vector is Tagged_Entity_Vectors.Vector;
procedure List (Object : in out Tagged_Entity_Vector;
Session : in out ADO.Sessions.Session'Class;
Query : in ADO.SQL.Query'Class);
Query_Check_Tag : constant ADO.Queries.Query_Definition_Access;
private
TAG_NAME : aliased constant String := "awa_tag";
COL_0_1_NAME : aliased constant String := "id";
COL_1_1_NAME : aliased constant String := "name";
TAG_DEF : aliased constant ADO.Schemas.Class_Mapping :=
(Count => 2,
Table => TAG_NAME'Access,
Members => (
1 => COL_0_1_NAME'Access,
2 => COL_1_1_NAME'Access
)
);
TAG_TABLE : constant ADO.Schemas.Class_Mapping_Access
:= TAG_DEF'Access;
Null_Tag : constant Tag_Ref
:= Tag_Ref'(ADO.Objects.Object_Ref with others => <>);
type Tag_Impl is
new ADO.Objects.Object_Record (Key_Type => ADO.Objects.KEY_INTEGER,
Of_Class => TAG_DEF'Access)
with record
Name : Ada.Strings.Unbounded.Unbounded_String;
end record;
type Tag_Access is access all Tag_Impl;
overriding
procedure Destroy (Object : access Tag_Impl);
overriding
procedure Find (Object : in out Tag_Impl;
Session : in out ADO.Sessions.Session'Class;
Query : in ADO.SQL.Query'Class;
Found : out Boolean);
overriding
procedure Load (Object : in out Tag_Impl;
Session : in out ADO.Sessions.Session'Class);
procedure Load (Object : in out Tag_Impl;
Stmt : in out ADO.Statements.Query_Statement'Class;
Session : in out ADO.Sessions.Session'Class);
overriding
procedure Save (Object : in out Tag_Impl;
Session : in out ADO.Sessions.Master_Session'Class);
procedure Create (Object : in out Tag_Impl;
Session : in out ADO.Sessions.Master_Session'Class);
overriding
procedure Delete (Object : in out Tag_Impl;
Session : in out ADO.Sessions.Master_Session'Class);
procedure Set_Field (Object : in out Tag_Ref'Class;
Impl : out Tag_Access);
TAGGED_ENTITY_NAME : aliased constant String := "awa_tagged_entity";
COL_0_2_NAME : aliased constant String := "id";
COL_1_2_NAME : aliased constant String := "for_entity_id";
COL_2_2_NAME : aliased constant String := "entity_type";
COL_3_2_NAME : aliased constant String := "tag_id";
TAGGED_ENTITY_DEF : aliased constant ADO.Schemas.Class_Mapping :=
(Count => 4,
Table => TAGGED_ENTITY_NAME'Access,
Members => (
1 => COL_0_2_NAME'Access,
2 => COL_1_2_NAME'Access,
3 => COL_2_2_NAME'Access,
4 => COL_3_2_NAME'Access
)
);
TAGGED_ENTITY_TABLE : constant ADO.Schemas.Class_Mapping_Access
:= TAGGED_ENTITY_DEF'Access;
Null_Tagged_Entity : constant Tagged_Entity_Ref
:= Tagged_Entity_Ref'(ADO.Objects.Object_Ref with others => <>);
type Tagged_Entity_Impl is
new ADO.Objects.Object_Record (Key_Type => ADO.Objects.KEY_INTEGER,
Of_Class => TAGGED_ENTITY_DEF'Access)
with record
For_Entity_Id : ADO.Identifier;
Entity_Type : ADO.Entity_Type;
Tag : AWA.Tags.Models.Tag_Ref;
end record;
type Tagged_Entity_Access is access all Tagged_Entity_Impl;
overriding
procedure Destroy (Object : access Tagged_Entity_Impl);
overriding
procedure Find (Object : in out Tagged_Entity_Impl;
Session : in out ADO.Sessions.Session'Class;
Query : in ADO.SQL.Query'Class;
Found : out Boolean);
overriding
procedure Load (Object : in out Tagged_Entity_Impl;
Session : in out ADO.Sessions.Session'Class);
procedure Load (Object : in out Tagged_Entity_Impl;
Stmt : in out ADO.Statements.Query_Statement'Class;
Session : in out ADO.Sessions.Session'Class);
overriding
procedure Save (Object : in out Tagged_Entity_Impl;
Session : in out ADO.Sessions.Master_Session'Class);
procedure Create (Object : in out Tagged_Entity_Impl;
Session : in out ADO.Sessions.Master_Session'Class);
overriding
procedure Delete (Object : in out Tagged_Entity_Impl;
Session : in out ADO.Sessions.Master_Session'Class);
procedure Set_Field (Object : in out Tagged_Entity_Ref'Class;
Impl : out Tagged_Entity_Access);
package File_1 is
new ADO.Queries.Loaders.File (Path => "tag-queries.xml",
Sha1 => "9B2B599473F75F92CB5AB5045675E4CCEF926543");
package Def_Check_Tag is
new ADO.Queries.Loaders.Query (Name => "check-tag",
File => File_1.File'Access);
Query_Check_Tag : constant ADO.Queries.Query_Definition_Access
:= Def_Check_Tag.Query'Access;
end AWA.Tags.Models;
|
-----------------------------------------------------------------------
-- AWA.Tags.Models -- AWA.Tags.Models
-----------------------------------------------------------------------
-- File generated by ada-gen DO NOT MODIFY
-- Template used: templates/model/package-spec.xhtml
-- Ada Generator: https://ada-gen.googlecode.com/svn/trunk Revision 1095
-----------------------------------------------------------------------
-- 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.
-----------------------------------------------------------------------
pragma Warnings (Off, "unit * is not referenced");
with ADO.Sessions;
with ADO.Objects;
with ADO.Statements;
with ADO.SQL;
with ADO.Schemas;
with ADO.Queries;
with ADO.Queries.Loaders;
with Ada.Containers.Vectors;
with Ada.Strings.Unbounded;
with Util.Beans.Objects;
with Util.Beans.Basic.Lists;
pragma Warnings (On, "unit * is not referenced");
package AWA.Tags.Models is
type Tag_Ref is new ADO.Objects.Object_Ref with null record;
type Tagged_Entity_Ref is new ADO.Objects.Object_Ref with null record;
-- --------------------
-- The tag definition.
-- --------------------
-- Create an object key for Tag.
function Tag_Key (Id : in ADO.Identifier) return ADO.Objects.Object_Key;
-- Create an object key for Tag from a string.
-- Raises Constraint_Error if the string cannot be converted into the object key.
function Tag_Key (Id : in String) return ADO.Objects.Object_Key;
Null_Tag : constant Tag_Ref;
function "=" (Left, Right : Tag_Ref'Class) return Boolean;
-- Set the tag identifier
procedure Set_Id (Object : in out Tag_Ref;
Value : in ADO.Identifier);
-- Get the tag identifier
function Get_Id (Object : in Tag_Ref)
return ADO.Identifier;
-- Set the tag name
procedure Set_Name (Object : in out Tag_Ref;
Value : in Ada.Strings.Unbounded.Unbounded_String);
procedure Set_Name (Object : in out Tag_Ref;
Value : in String);
-- Get the tag name
function Get_Name (Object : in Tag_Ref)
return Ada.Strings.Unbounded.Unbounded_String;
function Get_Name (Object : in Tag_Ref)
return String;
-- Load the entity identified by 'Id'.
-- Raises the NOT_FOUND exception if it does not exist.
procedure Load (Object : in out Tag_Ref;
Session : in out ADO.Sessions.Session'Class;
Id : in ADO.Identifier);
-- Load the entity identified by 'Id'.
-- Returns True in <b>Found</b> if the object was found and False if it does not exist.
procedure Load (Object : in out Tag_Ref;
Session : in out ADO.Sessions.Session'Class;
Id : in ADO.Identifier;
Found : out Boolean);
-- Find and load the entity.
overriding
procedure Find (Object : in out Tag_Ref;
Session : in out ADO.Sessions.Session'Class;
Query : in ADO.SQL.Query'Class;
Found : out Boolean);
-- Save the entity. If the entity does not have an identifier, an identifier is allocated
-- and it is inserted in the table. Otherwise, only data fields which have been changed
-- are updated.
overriding
procedure Save (Object : in out Tag_Ref;
Session : in out ADO.Sessions.Master_Session'Class);
-- Delete the entity.
overriding
procedure Delete (Object : in out Tag_Ref;
Session : in out ADO.Sessions.Master_Session'Class);
overriding
function Get_Value (From : in Tag_Ref;
Name : in String) return Util.Beans.Objects.Object;
-- Table definition
TAG_TABLE : constant ADO.Schemas.Class_Mapping_Access;
-- Internal method to allocate the Object_Record instance
overriding
procedure Allocate (Object : in out Tag_Ref);
-- Copy of the object.
procedure Copy (Object : in Tag_Ref;
Into : in out Tag_Ref);
package Tag_Vectors is
new Ada.Containers.Vectors (Index_Type => Natural,
Element_Type => Tag_Ref,
"=" => "=");
subtype Tag_Vector is Tag_Vectors.Vector;
procedure List (Object : in out Tag_Vector;
Session : in out ADO.Sessions.Session'Class;
Query : in ADO.SQL.Query'Class);
-- Create an object key for Tagged_Entity.
function Tagged_Entity_Key (Id : in ADO.Identifier) return ADO.Objects.Object_Key;
-- Create an object key for Tagged_Entity from a string.
-- Raises Constraint_Error if the string cannot be converted into the object key.
function Tagged_Entity_Key (Id : in String) return ADO.Objects.Object_Key;
Null_Tagged_Entity : constant Tagged_Entity_Ref;
function "=" (Left, Right : Tagged_Entity_Ref'Class) return Boolean;
-- Set the tag entity identifier
procedure Set_Id (Object : in out Tagged_Entity_Ref;
Value : in ADO.Identifier);
-- Get the tag entity identifier
function Get_Id (Object : in Tagged_Entity_Ref)
return ADO.Identifier;
-- Set Title: Tag model
-- Date: 2013-02-23the database entity to which the tag is associated
procedure Set_For_Entity_Id (Object : in out Tagged_Entity_Ref;
Value : in ADO.Identifier);
-- Get Title: Tag model
-- Date: 2013-02-23the database entity to which the tag is associated
function Get_For_Entity_Id (Object : in Tagged_Entity_Ref)
return ADO.Identifier;
-- Set the entity type
procedure Set_Entity_Type (Object : in out Tagged_Entity_Ref;
Value : in ADO.Entity_Type);
-- Get the entity type
function Get_Entity_Type (Object : in Tagged_Entity_Ref)
return ADO.Entity_Type;
--
procedure Set_Tag (Object : in out Tagged_Entity_Ref;
Value : in AWA.Tags.Models.Tag_Ref'Class);
--
function Get_Tag (Object : in Tagged_Entity_Ref)
return AWA.Tags.Models.Tag_Ref'Class;
-- Load the entity identified by 'Id'.
-- Raises the NOT_FOUND exception if it does not exist.
procedure Load (Object : in out Tagged_Entity_Ref;
Session : in out ADO.Sessions.Session'Class;
Id : in ADO.Identifier);
-- Load the entity identified by 'Id'.
-- Returns True in <b>Found</b> if the object was found and False if it does not exist.
procedure Load (Object : in out Tagged_Entity_Ref;
Session : in out ADO.Sessions.Session'Class;
Id : in ADO.Identifier;
Found : out Boolean);
-- Find and load the entity.
overriding
procedure Find (Object : in out Tagged_Entity_Ref;
Session : in out ADO.Sessions.Session'Class;
Query : in ADO.SQL.Query'Class;
Found : out Boolean);
-- Save the entity. If the entity does not have an identifier, an identifier is allocated
-- and it is inserted in the table. Otherwise, only data fields which have been changed
-- are updated.
overriding
procedure Save (Object : in out Tagged_Entity_Ref;
Session : in out ADO.Sessions.Master_Session'Class);
-- Delete the entity.
overriding
procedure Delete (Object : in out Tagged_Entity_Ref;
Session : in out ADO.Sessions.Master_Session'Class);
overriding
function Get_Value (From : in Tagged_Entity_Ref;
Name : in String) return Util.Beans.Objects.Object;
-- Table definition
TAGGED_ENTITY_TABLE : constant ADO.Schemas.Class_Mapping_Access;
-- Internal method to allocate the Object_Record instance
overriding
procedure Allocate (Object : in out Tagged_Entity_Ref);
-- Copy of the object.
procedure Copy (Object : in Tagged_Entity_Ref;
Into : in out Tagged_Entity_Ref);
package Tagged_Entity_Vectors is
new Ada.Containers.Vectors (Index_Type => Natural,
Element_Type => Tagged_Entity_Ref,
"=" => "=");
subtype Tagged_Entity_Vector is Tagged_Entity_Vectors.Vector;
procedure List (Object : in out Tagged_Entity_Vector;
Session : in out ADO.Sessions.Session'Class;
Query : in ADO.SQL.Query'Class);
Query_Check_Tag : constant ADO.Queries.Query_Definition_Access;
Query_Tag_List : constant ADO.Queries.Query_Definition_Access;
private
TAG_NAME : aliased constant String := "awa_tag";
COL_0_1_NAME : aliased constant String := "id";
COL_1_1_NAME : aliased constant String := "name";
TAG_DEF : aliased constant ADO.Schemas.Class_Mapping :=
(Count => 2,
Table => TAG_NAME'Access,
Members => (
1 => COL_0_1_NAME'Access,
2 => COL_1_1_NAME'Access
)
);
TAG_TABLE : constant ADO.Schemas.Class_Mapping_Access
:= TAG_DEF'Access;
Null_Tag : constant Tag_Ref
:= Tag_Ref'(ADO.Objects.Object_Ref with others => <>);
type Tag_Impl is
new ADO.Objects.Object_Record (Key_Type => ADO.Objects.KEY_INTEGER,
Of_Class => TAG_DEF'Access)
with record
Name : Ada.Strings.Unbounded.Unbounded_String;
end record;
type Tag_Access is access all Tag_Impl;
overriding
procedure Destroy (Object : access Tag_Impl);
overriding
procedure Find (Object : in out Tag_Impl;
Session : in out ADO.Sessions.Session'Class;
Query : in ADO.SQL.Query'Class;
Found : out Boolean);
overriding
procedure Load (Object : in out Tag_Impl;
Session : in out ADO.Sessions.Session'Class);
procedure Load (Object : in out Tag_Impl;
Stmt : in out ADO.Statements.Query_Statement'Class;
Session : in out ADO.Sessions.Session'Class);
overriding
procedure Save (Object : in out Tag_Impl;
Session : in out ADO.Sessions.Master_Session'Class);
procedure Create (Object : in out Tag_Impl;
Session : in out ADO.Sessions.Master_Session'Class);
overriding
procedure Delete (Object : in out Tag_Impl;
Session : in out ADO.Sessions.Master_Session'Class);
procedure Set_Field (Object : in out Tag_Ref'Class;
Impl : out Tag_Access);
TAGGED_ENTITY_NAME : aliased constant String := "awa_tagged_entity";
COL_0_2_NAME : aliased constant String := "id";
COL_1_2_NAME : aliased constant String := "for_entity_id";
COL_2_2_NAME : aliased constant String := "entity_type";
COL_3_2_NAME : aliased constant String := "tag_id";
TAGGED_ENTITY_DEF : aliased constant ADO.Schemas.Class_Mapping :=
(Count => 4,
Table => TAGGED_ENTITY_NAME'Access,
Members => (
1 => COL_0_2_NAME'Access,
2 => COL_1_2_NAME'Access,
3 => COL_2_2_NAME'Access,
4 => COL_3_2_NAME'Access
)
);
TAGGED_ENTITY_TABLE : constant ADO.Schemas.Class_Mapping_Access
:= TAGGED_ENTITY_DEF'Access;
Null_Tagged_Entity : constant Tagged_Entity_Ref
:= Tagged_Entity_Ref'(ADO.Objects.Object_Ref with others => <>);
type Tagged_Entity_Impl is
new ADO.Objects.Object_Record (Key_Type => ADO.Objects.KEY_INTEGER,
Of_Class => TAGGED_ENTITY_DEF'Access)
with record
For_Entity_Id : ADO.Identifier;
Entity_Type : ADO.Entity_Type;
Tag : AWA.Tags.Models.Tag_Ref;
end record;
type Tagged_Entity_Access is access all Tagged_Entity_Impl;
overriding
procedure Destroy (Object : access Tagged_Entity_Impl);
overriding
procedure Find (Object : in out Tagged_Entity_Impl;
Session : in out ADO.Sessions.Session'Class;
Query : in ADO.SQL.Query'Class;
Found : out Boolean);
overriding
procedure Load (Object : in out Tagged_Entity_Impl;
Session : in out ADO.Sessions.Session'Class);
procedure Load (Object : in out Tagged_Entity_Impl;
Stmt : in out ADO.Statements.Query_Statement'Class;
Session : in out ADO.Sessions.Session'Class);
overriding
procedure Save (Object : in out Tagged_Entity_Impl;
Session : in out ADO.Sessions.Master_Session'Class);
procedure Create (Object : in out Tagged_Entity_Impl;
Session : in out ADO.Sessions.Master_Session'Class);
overriding
procedure Delete (Object : in out Tagged_Entity_Impl;
Session : in out ADO.Sessions.Master_Session'Class);
procedure Set_Field (Object : in out Tagged_Entity_Ref'Class;
Impl : out Tagged_Entity_Access);
package File_1 is
new ADO.Queries.Loaders.File (Path => "tag-queries.xml",
Sha1 => "9B2B599473F75F92CB5AB5045675E4CCEF926543");
package Def_Check_Tag is
new ADO.Queries.Loaders.Query (Name => "check-tag",
File => File_1.File'Access);
Query_Check_Tag : constant ADO.Queries.Query_Definition_Access
:= Def_Check_Tag.Query'Access;
package Def_Tag_List is
new ADO.Queries.Loaders.Query (Name => "tag-list",
File => File_1.File'Access);
Query_Tag_List : constant ADO.Queries.Query_Definition_Access
:= Def_Tag_List.Query'Access;
end AWA.Tags.Models;
|
Rebuild the model files
|
Rebuild the model files
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
a8a3b7f6797a6c27d37d3031e130f52fec143a91
|
regtests/ado-drivers-tests.ads
|
regtests/ado-drivers-tests.ads
|
-----------------------------------------------------------------------
-- ado-drivers-tests -- Unit tests for database drivers
-- 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.Tests;
package ADO.Drivers.Tests is
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite);
type Test is new Util.Tests.Test with null record;
-- Test the Get_Config operation.
procedure Test_Get_Config (T : in out Test);
-- Test the Get_Driver operation.
procedure Test_Get_Driver (T : in out Test);
-- Test loading some invalid database driver.
procedure Test_Load_Invalid_Driver (T : in out Test);
-- Test the Get_Driver_Index operation.
procedure Test_Get_Driver_Index (T : in out Test);
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.Tests;
package ADO.Drivers.Tests is
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite);
type Test is new Util.Tests.Test with null record;
-- Test the Get_Config operation.
procedure Test_Get_Config (T : in out Test);
-- Test the Get_Driver operation.
procedure Test_Get_Driver (T : in out Test);
-- Test loading some invalid database driver.
procedure Test_Load_Invalid_Driver (T : in out Test);
-- Test the Get_Driver_Index operation.
procedure Test_Get_Driver_Index (T : in out Test);
-- Test the Set_Connection procedure with several error cases.
procedure Test_Set_Connection_Error (T : in out Test);
end ADO.Drivers.Tests;
|
Declare the Test_Set_Connection_Error test procedure
|
Declare the Test_Set_Connection_Error test procedure
|
Ada
|
apache-2.0
|
stcarrez/ada-ado
|
6ae7c11cfd399db0f9bf3285cc2a41ac08658d44
|
tools/druss-commands-status.ads
|
tools/druss-commands-status.ads
|
-----------------------------------------------------------------------
-- druss-commands-status -- Druss status commands
-- Copyright (C) 2017, 2018 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
package Druss.Commands.Status is
type Command_Type is new Druss.Commands.Drivers.Command_Type with null record;
procedure Do_Status (Command : in Command_Type;
Args : in Argument_List'Class;
Context : in out Context_Type);
-- Execute a status command to report information about the Bbox.
overriding
procedure Execute (Command : in out Command_Type;
Name : in String;
Args : in Argument_List'Class;
Context : in out Context_Type);
-- Write the help associated with the command.
overriding
procedure Help (Command : in Command_Type;
Context : in out Context_Type);
end Druss.Commands.Status;
|
-----------------------------------------------------------------------
-- druss-commands-status -- Druss status commands
-- Copyright (C) 2017, 2018, 2019 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
package Druss.Commands.Status is
type Command_Type is new Druss.Commands.Drivers.Command_Type with null record;
procedure Do_Status (Command : in Command_Type;
Args : in Argument_List'Class;
Context : in out Context_Type);
-- Execute a status command to report information about the Bbox.
overriding
procedure Execute (Command : in out Command_Type;
Name : in String;
Args : in Argument_List'Class;
Context : in out Context_Type);
-- Write the help associated with the command.
overriding
procedure Help (Command : in out Command_Type;
Context : in out Context_Type);
end Druss.Commands.Status;
|
Change Help command to accept in out command
|
Change Help command to accept in out command
|
Ada
|
apache-2.0
|
stcarrez/bbox-ada-api
|
655325db4f269f9472a62ac3a5ae49763ffaae64
|
mat/src/mat-readers-streams.ads
|
mat/src/mat-readers-streams.ads
|
-----------------------------------------------------------------------
-- mat-readers-streams -- Reader for streams
-- 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.Streams.Buffered;
package MAT.Readers.Streams is
type Stream_Reader_Type is new Manager_Base with private;
-- Read the events from the stream and stop when the end of the stream is reached.
procedure Read_All (Reader : in out Stream_Reader_Type);
-- Read a message from the stream.
overriding
procedure Read_Message (Reader : in out Stream_Reader_Type;
Msg : in out Message);
private
type Stream_Reader_Type is new Manager_Base with record
Stream : Util.Streams.Buffered.Buffered_Stream;
end record;
end MAT.Readers.Streams;
|
-----------------------------------------------------------------------
-- mat-readers-streams -- Reader for streams
-- 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.Streams.Buffered;
package MAT.Readers.Streams is
type Stream_Reader_Type is new Manager_Base with private;
-- Read the events from the stream and stop when the end of the stream is reached.
procedure Read_All (Reader : in out Stream_Reader_Type);
-- Read a message from the stream.
overriding
procedure Read_Message (Reader : in out Stream_Reader_Type;
Msg : in out Message);
private
type Stream_Reader_Type is new Manager_Base with record
Stream : Util.Streams.Buffered.Buffered_Stream;
Data : Util.Streams.Buffered.Buffer_Access;
end record;
end MAT.Readers.Streams;
|
Add the data buffer in the Stream_Reader_Type type
|
Add the data buffer in the Stream_Reader_Type type
|
Ada
|
apache-2.0
|
stcarrez/mat,stcarrez/mat,stcarrez/mat
|
bf5653dc143748a80683fc6ecae95762c3e481e9
|
samples/multipro.adb
|
samples/multipro.adb
|
-----------------------------------------------------------------------
-- multipro -- Points out multiprocessor issues when incrementing counters
-- Copyright (C) 2010, 2011 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Log;
with Util.Log.Loggers;
with Util.Concurrent.Counters;
with Util.Measures;
with Ada.Text_IO;
procedure Multipro is
use Util.Log;
use Util.Concurrent.Counters;
Log : constant Loggers.Logger := Loggers.Create ("multipro");
-- Target counter value we would like.
Max_Counter : constant Integer := 1_000_000;
-- Max number of tasks for executing the concurrent increment.
Max_Tasks : constant Integer := 16;
-- Performance measurement.
Perf : Util.Measures.Measure_Set;
T : Util.Measures.Stamp;
begin
for Task_Count in 1 .. Max_Tasks loop
declare
-- Each task will increment the counter by the following amount.
Increment_By_Task : constant Integer := Max_Counter / Task_Count;
-- Counter not protected for concurrency access.
Unsafe : Integer := 0;
-- Counter protected by concurrent accesses.
Counter : Util.Concurrent.Counters.Counter;
begin
declare
-- A task that increments the shared counter <b>Unsafe</b> and <b>Counter</b> by
-- the specified amount.
task type Worker is
entry Start (Count : in Natural);
end Worker;
task body Worker is
Cnt : Natural;
begin
accept Start (Count : in Natural) do
Cnt := Count;
end;
-- Increment the two counters as many times as necessary.
for I in 1 .. Cnt loop
Util.Concurrent.Counters.Increment (Counter);
Unsafe := Unsafe + 1;
end loop;
end Worker;
type Worker_Array is array (1 .. Task_Count) of Worker;
Tasks : Worker_Array;
begin
Log.Info ("Starting " & Integer'Image (Task_Count) & " tasks");
for I in Tasks'Range loop
Tasks (I).Start (Increment_By_Task);
end loop;
-- Leaving the Worker task scope means we are waiting for our tasks to finish.
end;
Util.Measures.Report (Measures => Perf,
S => T,
Title => "Increment counter with "
& Integer'Image (Task_Count) & " tasks");
-- Unsafe will be equal to Counter if Task_Count = 1 or if the host is mono-processor.
-- On dual/quad core, the Unsafe value becomes random and gets lower each time
-- the number of tasks increases.
Log.Info ("Expected value at the end : " & Integer'Image (Increment_By_Task * Task_Count));
Log.Info ("Counter value at the end : " & Integer'Image (Value (Counter)));
Log.Info ("Unprotected counter at the end : " & Integer'Image (Unsafe));
end;
end loop;
-- Dump the result
Util.Measures.Write (Perf, "Multipro", Ada.Text_IO.Standard_Output);
end Multipro;
|
-----------------------------------------------------------------------
-- multipro -- Points out multiprocessor issues when incrementing counters
-- Copyright (C) 2010, 2011 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Log;
with Util.Log.Loggers;
with Util.Concurrent.Counters;
with Util.Measures;
with Ada.Text_IO;
procedure Multipro is
use Util.Log;
use Util.Concurrent.Counters;
Log : constant Loggers.Logger := Loggers.Create ("multipro");
-- Target counter value we would like.
Max_Counter : constant Integer := 10_000_000;
-- Max number of tasks for executing the concurrent increment.
Max_Tasks : constant Integer := 16;
-- Performance measurement.
Perf : Util.Measures.Measure_Set;
T : Util.Measures.Stamp;
begin
for Task_Count in 1 .. Max_Tasks loop
declare
-- Each task will increment the counter by the following amount.
Increment_By_Task : constant Integer := Max_Counter / Task_Count;
-- Counter not protected for concurrency access.
Unsafe : Integer := 0;
-- Counter protected by concurrent accesses.
Counter : Util.Concurrent.Counters.Counter;
begin
declare
-- A task that increments the shared counter <b>Unsafe</b> and <b>Counter</b> by
-- the specified amount.
task type Worker is
entry Start (Count : in Natural);
end Worker;
task body Worker is
Cnt : Natural;
begin
accept Start (Count : in Natural) do
Cnt := Count;
end;
-- Increment the two counters as many times as necessary.
for I in 1 .. Cnt loop
Util.Concurrent.Counters.Increment (Counter);
Unsafe := Unsafe + 1;
end loop;
end Worker;
type Worker_Array is array (1 .. Task_Count) of Worker;
Tasks : Worker_Array;
begin
Log.Info ("Starting " & Integer'Image (Task_Count) & " tasks");
for I in Tasks'Range loop
Tasks (I).Start (Increment_By_Task);
end loop;
-- Leaving the Worker task scope means we are waiting for our tasks to finish.
end;
Util.Measures.Report (Measures => Perf,
S => T,
Title => "Increment counter with "
& Integer'Image (Task_Count) & " tasks");
-- Unsafe will be equal to Counter if Task_Count = 1 or if the host is mono-processor.
-- On dual/quad core, the Unsafe value becomes random and gets lower each time
-- the number of tasks increases.
Log.Info ("Expected value at the end : " & Integer'Image (Increment_By_Task * Task_Count));
Log.Info ("Counter value at the end : " & Integer'Image (Value (Counter)));
Log.Info ("Unprotected counter at the end : " & Integer'Image (Unsafe));
end;
end loop;
-- Dump the result
Util.Measures.Write (Perf, "Multipro", Ada.Text_IO.Standard_Output);
end Multipro;
|
Increase counter value
|
Increase counter value
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
5da10fcbb4cbd1c4a92498cbf73f917db1eba720
|
src/gen-artifacts-mappings.adb
|
src/gen-artifacts-mappings.adb
|
-----------------------------------------------------------------------
-- gen-artifacts-mappings -- Type mapping artifact for Code Generator
-- Copyright (C) 2011, 2012, 2015, 2018 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Util.Log.Loggers;
with Gen.Utils;
with Gen.Model;
with Gen.Model.Mappings;
-- The <b>Gen.Artifacts.Mappings</b> package is an artifact to map XML-based types
-- into Ada types.
package body Gen.Artifacts.Mappings is
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Gen.Artifacts.Query");
-- ------------------------------
-- 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) is
use Ada.Strings.Unbounded;
procedure Register_Mapping (O : in out Gen.Model.Packages.Model_Definition;
Node : in DOM.Core.Node);
procedure Register_Mappings (Model : in out Gen.Model.Packages.Model_Definition;
Node : in DOM.Core.Node);
-- ------------------------------
-- Register a new type mapping.
-- ------------------------------
procedure Register_Mapping (O : in out Gen.Model.Packages.Model_Definition;
Node : in DOM.Core.Node) is
procedure Register_Type (O : in out Gen.Model.Packages.Model_Definition;
Node : in DOM.Core.Node);
N : constant DOM.Core.Node := Gen.Utils.Get_Child (Node, "to");
To : constant String := Gen.Utils.Get_Data_Content (N);
Kind : constant String := To_String (Gen.Utils.Get_Attribute (Node, "type"));
Allow_Null : constant Boolean := Gen.Utils.Get_Attribute (Node, "allow-null", False);
Kind_Type : Gen.Model.Mappings.Basic_Type;
procedure Register_Type (O : in out Gen.Model.Packages.Model_Definition;
Node : in DOM.Core.Node) is
pragma Unreferenced (O);
From : constant String := Gen.Utils.Get_Data_Content (Node);
begin
Gen.Model.Mappings.Register_Type (Target => To,
From => From,
Kind => Kind_Type,
Allow_Null => Allow_Null);
end Register_Type;
procedure Iterate is
new Gen.Utils.Iterate_Nodes (T => Gen.Model.Packages.Model_Definition,
Process => Register_Type);
begin
if Kind = "date" or To = "Ada.Calendar.Time" then
Kind_Type := Gen.Model.Mappings.T_DATE;
elsif Kind = "identifier" or To = "ADO.Identifier" then
Kind_Type := Gen.Model.Mappings.T_IDENTIFIER;
elsif Kind = "boolean" then
Kind_Type := Gen.Model.Mappings.T_BOOLEAN;
elsif Kind = "string" or To = "Ada.Strings.Unbounded.Unbounded_String" then
Kind_Type := Gen.Model.Mappings.T_STRING;
elsif Kind = "blob" or To = "ADO.Blob_Ref" then
Kind_Type := Gen.Model.Mappings.T_BLOB;
else
Kind_Type := Gen.Model.Mappings.T_INTEGER;
end if;
Iterate (O, Node, "from");
end Register_Mapping;
-- ------------------------------
-- Register a model mapping
-- ------------------------------
procedure Register_Mappings (Model : in out Gen.Model.Packages.Model_Definition;
Node : in DOM.Core.Node) is
procedure Iterate is
new Gen.Utils.Iterate_Nodes (T => Gen.Model.Packages.Model_Definition,
Process => Register_Mapping);
Name : constant String := Gen.Utils.Get_Attribute (Node, "name");
begin
Gen.Model.Mappings.Set_Mapping_Name (Name);
Iterate (Model, Node, "mapping");
end Register_Mappings;
procedure Iterate is new Gen.Utils.Iterate_Nodes (T => Gen.Model.Packages.Model_Definition,
Process => Register_Mappings);
begin
Log.Debug ("Initializing mapping artifact for the configuration");
Gen.Artifacts.Artifact (Handler).Initialize (Path, Node, Model, Context);
Iterate (Gen.Model.Packages.Model_Definition (Model), Node, "mappings");
end Initialize;
end Gen.Artifacts.Mappings;
|
-----------------------------------------------------------------------
-- gen-artifacts-mappings -- Type mapping artifact for Code Generator
-- Copyright (C) 2011, 2012, 2015, 2018 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Util.Log.Loggers;
with Gen.Utils;
with Gen.Model;
with Gen.Model.Mappings;
-- The <b>Gen.Artifacts.Mappings</b> package is an artifact to map XML-based types
-- into Ada types.
package body Gen.Artifacts.Mappings is
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Gen.Artifacts.Query");
-- ------------------------------
-- 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) is
use Ada.Strings.Unbounded;
procedure Register_Mapping (O : in out Gen.Model.Packages.Model_Definition;
Node : in DOM.Core.Node);
procedure Register_Mappings (Model : in out Gen.Model.Packages.Model_Definition;
Node : in DOM.Core.Node);
-- ------------------------------
-- Register a new type mapping.
-- ------------------------------
procedure Register_Mapping (O : in out Gen.Model.Packages.Model_Definition;
Node : in DOM.Core.Node) is
procedure Register_Type (O : in out Gen.Model.Packages.Model_Definition;
Node : in DOM.Core.Node);
N : constant DOM.Core.Node := Gen.Utils.Get_Child (Node, "to");
To : constant String := Gen.Utils.Get_Data_Content (N);
Kind : constant String := To_String (Gen.Utils.Get_Attribute (Node, "type"));
Allow_Null : constant Boolean := Gen.Utils.Get_Attribute (Node, "allow-null", False);
Kind_Type : Gen.Model.Mappings.Basic_Type;
procedure Register_Type (O : in out Gen.Model.Packages.Model_Definition;
Node : in DOM.Core.Node) is
pragma Unreferenced (O);
From : constant String := Gen.Utils.Get_Data_Content (Node);
begin
Gen.Model.Mappings.Register_Type (Target => To,
From => From,
Kind => Kind_Type,
Allow_Null => Allow_Null);
end Register_Type;
procedure Iterate is
new Gen.Utils.Iterate_Nodes (T => Gen.Model.Packages.Model_Definition,
Process => Register_Type);
begin
if Kind = "date" or To = "Ada.Calendar.Time" then
Kind_Type := Gen.Model.Mappings.T_DATE;
elsif Kind = "identifier" or To = "ADO.Identifier" then
Kind_Type := Gen.Model.Mappings.T_IDENTIFIER;
elsif Kind = "boolean" then
Kind_Type := Gen.Model.Mappings.T_BOOLEAN;
elsif Kind = "string" or To = "Ada.Strings.Unbounded.Unbounded_String" then
Kind_Type := Gen.Model.Mappings.T_STRING;
elsif Kind = "blob" or To = "ADO.Blob_Ref" then
Kind_Type := Gen.Model.Mappings.T_BLOB;
elsif Kind = "entity_type" or To = "ADO.Entity_Type" then
Kind_Type := Gen.Model.Mappings.T_ENTITY_TYPE;
else
Kind_Type := Gen.Model.Mappings.T_INTEGER;
end if;
Iterate (O, Node, "from");
end Register_Mapping;
-- ------------------------------
-- Register a model mapping
-- ------------------------------
procedure Register_Mappings (Model : in out Gen.Model.Packages.Model_Definition;
Node : in DOM.Core.Node) is
procedure Iterate is
new Gen.Utils.Iterate_Nodes (T => Gen.Model.Packages.Model_Definition,
Process => Register_Mapping);
Name : constant String := Gen.Utils.Get_Attribute (Node, "name");
begin
Gen.Model.Mappings.Set_Mapping_Name (Name);
Iterate (Model, Node, "mapping");
end Register_Mappings;
procedure Iterate is new Gen.Utils.Iterate_Nodes (T => Gen.Model.Packages.Model_Definition,
Process => Register_Mappings);
begin
Log.Debug ("Initializing mapping artifact for the configuration");
Gen.Artifacts.Artifact (Handler).Initialize (Path, Node, Model, Context);
Iterate (Gen.Model.Packages.Model_Definition (Model), Node, "mappings");
end Initialize;
end Gen.Artifacts.Mappings;
|
Handle type 'entity_type' in the XML mapping
|
Handle type 'entity_type' in the XML mapping
|
Ada
|
apache-2.0
|
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
|
46433607da2e0c8d1abe075b6ea169670311c281
|
src/security-policies-urls.ads
|
src/security-policies-urls.ads
|
-----------------------------------------------------------------------
-- security-policies-urls -- URL security policy
-- 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.Containers.Hashed_Maps;
with Ada.Containers.Vectors;
with Util.Refs;
with Util.Strings;
with Util.Serialize.IO.XML;
with GNAT.Regexp;
-- == URL Security Policy ==
-- The <tt>Security.Policies.Urls</tt> implements a security policy intended to be used
-- in web servers. It allows to protect an URL by defining permissions that must be granted
-- for a user to get access to the URL. A typical example is a web server that has a set of
-- administration pages, these pages should be accessed by users having some admin permission.
--
-- === Policy creation ===
-- An instance of the <tt>URL_Policy</tt> must be created and registered in the policy manager.
-- Get or declare the following variables:
--
-- Manager : Security.Policies.Policy_Manager;
-- Policy : Security.Policies.Urls.URL_Policy_Access;
--
-- Create the URL policy and register it in the policy manager as follows:
--
-- Policy := new URL_Policy;
-- Manager.Add_Policy (Policy.all'Access);
--
-- === Policy Configuration ===
-- Once the URL policy is registered, the policy manager can read and process the following
-- XML configuration:
--
-- <policy-rules>
-- <url-policy id='1'>
-- <permission>create-workspace</permission>
-- <permission>admin</permission>
-- <url-pattern>/workspace/create</url-pattern>
-- <url-pattern>/workspace/setup/*</url-pattern>
-- </url-policy>
-- ...
-- </policy-rules>
--
-- This policy gives access to the URL that match one of the URL pattern if the
-- security context has the permission <b>create-workspace</b> or <b>admin</b>.
-- These two permissions are checked according to another security policy.
-- The XML configuration can define several <tt>url-policy</tt>. They are checked in
-- the order defined in the XML. In other words, the first <tt>url-policy</tt> that matches
-- the URL is used to verify the permission.
--
-- The <tt>url-policy</tt> definition can contain several <tt>permission</tt>.
-- The first permission that is granted gives access to the URL.
--
-- === Checking for permission ===
-- To check a URL permission, you must declare a <tt>URI_Permission</tt> object with the URL.
--
-- URI : constant String := ...;
-- Perm : constant Policies.URLs.URI_Permission (URI'Length)
-- := URI_Permission '(Len => URI'Length, URI => URI);
--
-- Then, we can check the permission:
--
-- Result : Boolean := Security.Contexts.Has_Permission (Perm);
--
package Security.Policies.Urls is
NAME : constant String := "URL-Policy";
package P_URL is new Security.Permissions.Definition ("url");
-- ------------------------------
-- URI Permission
-- ------------------------------
-- Represents a permission to access a given URI.
type URI_Permission (Len : Natural) is new Permissions.Permission (P_URL.Permission) with record
URI : String (1 .. Len);
end record;
-- ------------------------------
-- URL policy
-- ------------------------------
type URL_Policy is new Policy with private;
type URL_Policy_Access is access all URL_Policy'Class;
Invalid_Name : exception;
-- Get the policy name.
overriding
function Get_Name (From : in URL_Policy) return String;
-- Returns True if the user has the permission to access the given URI permission.
function Has_Permission (Manager : in URL_Policy;
Context : in Security_Context_Access;
Permission : in URI_Permission'Class) return Boolean;
-- Grant the permission to access to the given <b>URI</b> to users having the <b>To</b>
-- permissions.
procedure Grant_URI_Permission (Manager : in out URL_Policy;
URI : in String;
To : in String);
-- Initialize the permission manager.
overriding
procedure Initialize (Manager : in out URL_Policy);
-- Finalize the permission manager.
overriding
procedure Finalize (Manager : in out URL_Policy);
-- Setup the XML parser to read the <b>policy</b> description.
overriding
procedure Prepare_Config (Policy : in out URL_Policy;
Reader : in out Util.Serialize.IO.XML.Parser);
-- Get the URL policy associated with the given policy manager.
-- Returns the URL policy instance or null if it was not registered in the policy manager.
function Get_URL_Policy (Manager : in Security.Policies.Policy_Manager'Class)
return URL_Policy_Access;
private
use Util.Strings;
-- The <b>Access_Rule</b> represents a list of permissions to verify to grant
-- access to the resource. To make it simple, the user must have one of the
-- permission from the list. Each permission will refer to a specific permission
-- controller.
type Access_Rule (Count : Natural) is new Util.Refs.Ref_Entity with record
Permissions : Permission_Index_Array (1 .. Count);
end record;
type Access_Rule_Access is access all Access_Rule;
package Access_Rule_Refs is
new Util.Refs.Indefinite_References (Element_Type => Access_Rule,
Element_Access => Access_Rule_Access);
subtype Access_Rule_Ref is Access_Rule_Refs.Ref;
-- Find the access rule of the policy that matches the given URI.
-- Returns the No_Rule value (disable access) if no rule is found.
function Find_Access_Rule (Manager : in URL_Policy;
URI : in String) return Access_Rule_Ref;
-- The <b>Policy</b> defines the access rules that are applied on a given
-- URL, set of URLs or files.
type Policy is record
Id : Natural;
Pattern : GNAT.Regexp.Regexp;
Rule : Access_Rule_Ref;
end record;
-- The <b>Policy_Vector</b> represents the whole permission policy. The order of
-- policy in the list is important as policies can override each other.
package Policy_Vector is new Ada.Containers.Vectors (Index_Type => Positive,
Element_Type => Policy);
package Rules_Maps is new Ada.Containers.Hashed_Maps (Key_Type => String_Ref,
Element_Type => Access_Rule_Ref,
Hash => Hash,
Equivalent_Keys => Equivalent_Keys,
"=" => Access_Rule_Refs."=");
type Rules is new Util.Refs.Ref_Entity with record
Map : Rules_Maps.Map;
end record;
type Rules_Access is access all Rules;
package Rules_Ref is new Util.Refs.References (Rules, Rules_Access);
type Rules_Ref_Access is access Rules_Ref.Atomic_Ref;
type Controller_Access_Array_Access is access all Controller_Access_Array;
type URL_Policy is new Security.Policies.Policy with record
Cache : Rules_Ref_Access;
Policies : Policy_Vector.Vector;
Id : Natural := 0;
Permissions : Util.Beans.Objects.Vectors.Vector;
Patterns : Util.Beans.Objects.Vectors.Vector;
end record;
end Security.Policies.Urls;
|
-----------------------------------------------------------------------
-- security-policies-urls -- URL security policy
-- 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.Containers.Hashed_Maps;
with Ada.Containers.Vectors;
with Util.Refs;
with Util.Strings;
with Util.Serialize.IO.XML;
with GNAT.Regexp;
-- == URL Security Policy ==
-- The <tt>Security.Policies.Urls</tt> implements a security policy intended to be used
-- in web servers. It allows to protect an URL by defining permissions that must be granted
-- for a user to get access to the URL. A typical example is a web server that has a set of
-- administration pages, these pages should be accessed by users having some admin permission.
--
-- === Policy creation ===
-- An instance of the <tt>URL_Policy</tt> must be created and registered in the policy manager.
-- Get or declare the following variables:
--
-- Manager : Security.Policies.Policy_Manager;
-- Policy : Security.Policies.Urls.URL_Policy_Access;
--
-- Create the URL policy and register it in the policy manager as follows:
--
-- Policy := new URL_Policy;
-- Manager.Add_Policy (Policy.all'Access);
--
-- === Policy Configuration ===
-- Once the URL policy is registered, the policy manager can read and process the following
-- XML configuration:
--
-- <policy-rules>
-- <url-policy id='1'>
-- <permission>create-workspace</permission>
-- <permission>admin</permission>
-- <url-pattern>/workspace/create</url-pattern>
-- <url-pattern>/workspace/setup/*</url-pattern>
-- </url-policy>
-- ...
-- </policy-rules>
--
-- This policy gives access to the URL that match one of the URL pattern if the
-- security context has the permission <b>create-workspace</b> or <b>admin</b>.
-- These two permissions are checked according to another security policy.
-- The XML configuration can define several <tt>url-policy</tt>. They are checked in
-- the order defined in the XML. In other words, the first <tt>url-policy</tt> that matches
-- the URL is used to verify the permission.
--
-- The <tt>url-policy</tt> definition can contain several <tt>permission</tt>.
-- The first permission that is granted gives access to the URL.
--
-- === Checking for permission ===
-- To check a URL permission, you must declare a <tt>URL_Permission</tt> object with the URL.
--
-- URL : constant String := ...;
-- Perm : constant Policies.URLs.URL_Permission (URL'Length)
-- := URL_Permission '(Len => URI'Length, URL => URL);
--
-- Then, we can check the permission:
--
-- Result : Boolean := Security.Contexts.Has_Permission (Perm);
--
package Security.Policies.URLs is
NAME : constant String := "URL-Policy";
package P_URL is new Security.Permissions.Definition ("url");
-- ------------------------------
-- URL Permission
-- ------------------------------
-- Represents a permission to access a given URL.
type URL_Permission (Len : Natural) is new Permissions.Permission (P_URL.Permission) with record
URL : String (1 .. Len);
end record;
-- ------------------------------
-- URL policy
-- ------------------------------
type URL_Policy is new Policy with private;
type URL_Policy_Access is access all URL_Policy'Class;
Invalid_Name : exception;
-- Get the policy name.
overriding
function Get_Name (From : in URL_Policy) return String;
-- Returns True if the user has the permission to access the given URI permission.
function Has_Permission (Manager : in URL_Policy;
Context : in Security_Context_Access;
Permission : in URL_Permission'Class) return Boolean;
-- Grant the permission to access to the given <b>URI</b> to users having the <b>To</b>
-- permissions.
procedure Grant_URI_Permission (Manager : in out URL_Policy;
URI : in String;
To : in String);
-- Initialize the permission manager.
overriding
procedure Initialize (Manager : in out URL_Policy);
-- Finalize the permission manager.
overriding
procedure Finalize (Manager : in out URL_Policy);
-- Setup the XML parser to read the <b>policy</b> description.
overriding
procedure Prepare_Config (Policy : in out URL_Policy;
Reader : in out Util.Serialize.IO.XML.Parser);
-- Get the URL policy associated with the given policy manager.
-- Returns the URL policy instance or null if it was not registered in the policy manager.
function Get_URL_Policy (Manager : in Security.Policies.Policy_Manager'Class)
return URL_Policy_Access;
private
use Util.Strings;
-- The <b>Access_Rule</b> represents a list of permissions to verify to grant
-- access to the resource. To make it simple, the user must have one of the
-- permission from the list. Each permission will refer to a specific permission
-- controller.
type Access_Rule (Count : Natural) is new Util.Refs.Ref_Entity with record
Permissions : Permission_Index_Array (1 .. Count);
end record;
type Access_Rule_Access is access all Access_Rule;
package Access_Rule_Refs is
new Util.Refs.Indefinite_References (Element_Type => Access_Rule,
Element_Access => Access_Rule_Access);
subtype Access_Rule_Ref is Access_Rule_Refs.Ref;
-- Find the access rule of the policy that matches the given URI.
-- Returns the No_Rule value (disable access) if no rule is found.
function Find_Access_Rule (Manager : in URL_Policy;
URI : in String) return Access_Rule_Ref;
-- The <b>Policy</b> defines the access rules that are applied on a given
-- URL, set of URLs or files.
type Policy is record
Id : Natural;
Pattern : GNAT.Regexp.Regexp;
Rule : Access_Rule_Ref;
end record;
-- The <b>Policy_Vector</b> represents the whole permission policy. The order of
-- policy in the list is important as policies can override each other.
package Policy_Vector is new Ada.Containers.Vectors (Index_Type => Positive,
Element_Type => Policy);
package Rules_Maps is new Ada.Containers.Hashed_Maps (Key_Type => String_Ref,
Element_Type => Access_Rule_Ref,
Hash => Hash,
Equivalent_Keys => Equivalent_Keys,
"=" => Access_Rule_Refs."=");
type Rules is new Util.Refs.Ref_Entity with record
Map : Rules_Maps.Map;
end record;
type Rules_Access is access all Rules;
package Rules_Ref is new Util.Refs.References (Rules, Rules_Access);
type Rules_Ref_Access is access Rules_Ref.Atomic_Ref;
type Controller_Access_Array_Access is access all Controller_Access_Array;
type URL_Policy is new Security.Policies.Policy with record
Cache : Rules_Ref_Access;
Policies : Policy_Vector.Vector;
Id : Natural := 0;
Permissions : Util.Beans.Objects.Vectors.Vector;
Patterns : Util.Beans.Objects.Vectors.Vector;
end record;
end Security.Policies.URLs;
|
Rename package URLs and the permission URL_Permission
|
Rename package URLs and the permission URL_Permission
|
Ada
|
apache-2.0
|
Letractively/ada-security
|
d6ffc788eccaddf8b4268491094a6562048f064a
|
src/wiki-documents.ads
|
src/wiki-documents.ads
|
-----------------------------------------------------------------------
-- wiki-documents -- Wiki document
-- Copyright (C) 2011, 2015, 2016, 2018 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with 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);
-- Returns True if the current node is the root document node.
function Is_Root_Node (Doc : in Document) return Boolean;
-- 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;
-- Returns True if the document displays the table of contents by itself.
function Is_Using_TOC (Doc : in Document) return Boolean;
-- Returns True if the table of contents is visible and must be rendered.
function Is_Visible_TOC (Doc : in Document) return Boolean;
-- Hide the table of contents.
procedure Hide_TOC (Doc : in out Document);
-- 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;
Using_TOC : Boolean := False;
Visible_TOC : Boolean := True;
end record;
end Wiki.Documents;
|
-----------------------------------------------------------------------
-- wiki-documents -- Wiki document
-- Copyright (C) 2011, 2015, 2016, 2018, 2019 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Wiki.Strings;
with Wiki.Attributes;
with Wiki.Nodes.Lists;
-- === 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);
-- Returns True if the current node is the root document node.
function Is_Root_Node (Doc : in Document) return Boolean;
-- 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;
-- Returns True if the document displays the table of contents by itself.
function Is_Using_TOC (Doc : in Document) return Boolean;
-- Returns True if the table of contents is visible and must be rendered.
function Is_Visible_TOC (Doc : in Document) return Boolean;
-- Hide the table of contents.
procedure Hide_TOC (Doc : in out Document);
-- Get the table of content node associated with the document.
procedure Get_TOC (Doc : in out Document;
TOC : out Wiki.Nodes.Lists.Node_List_Ref);
-- Get the table of content node associated with the document.
function Get_TOC (Doc : in Document) return Wiki.Nodes.Lists.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.Lists.Node_List_Ref;
TOC : Wiki.Nodes.Lists.Node_List_Ref;
Current : Wiki.Nodes.Node_Type_Access;
Using_TOC : Boolean := False;
Visible_TOC : Boolean := True;
end record;
end Wiki.Documents;
|
Update to use the new Node_List_Ref reference
|
Update to use the new Node_List_Ref reference
|
Ada
|
apache-2.0
|
stcarrez/ada-wiki,stcarrez/ada-wiki
|
6f6b40a670b8286ca97d469291302136f3ef6a9a
|
src/util-beans-basic-lists.ads
|
src/util-beans-basic-lists.ads
|
-----------------------------------------------------------------------
-- util-beans-basic-lists -- List bean given access to a vector
-- Copyright (C) 2011, 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.Finalization;
with Ada.Containers;
with Ada.Containers.Vectors;
with Util.Beans.Objects;
-- The <b>Util.Beans.Basic.Lists</b> generic package implements a list of
-- elements that can be accessed through the <b>List_Bean</b> interface.
generic
type Element_Type is new Util.Beans.Basic.Readonly_Bean with private;
package Util.Beans.Basic.Lists is
-- Package that represents the vectors of elements.
-- (gcc 4.4 crashes if this package is defined as generic parameter.
package Vectors is
new Ada.Containers.Vectors (Element_Type => Element_Type,
Index_Type => Natural);
-- The list of elements is defined in a public part so that applications
-- can easily add or remove elements in the target list. The <b>List_Bean</b>
-- type holds the real implementation with the private parts.
type Abstract_List_Bean is abstract new Ada.Finalization.Controlled
and Util.Beans.Basic.List_Bean with record
List : aliased Vectors.Vector;
end record;
-- ------------------------------
-- List of objects
-- ------------------------------
-- The <b>List_Bean</b> type gives access to a list of objects.
type List_Bean is new Abstract_List_Bean with private;
type List_Bean_Access is access all List_Bean'Class;
-- Get the number of elements in the list.
overriding
function Get_Count (From : in List_Bean) return Natural;
-- Set the current row index. Valid row indexes start at 1.
overriding
procedure Set_Row_Index (From : in out List_Bean;
Index : in Natural);
-- Returns the current row index.
function Get_Row_Index (From : in List_Bean) return Natural;
-- Get the element at the current row index.
overriding
function Get_Row (From : in List_Bean) return Util.Beans.Objects.Object;
-- Get the value identified by the name.
-- If the name cannot be found, the method should return the Null object.
overriding
function Get_Value (From : in List_Bean;
Name : in String) return Util.Beans.Objects.Object;
-- Initialize the list bean.
overriding
procedure Initialize (Object : in out List_Bean);
-- Deletes the list bean
procedure Free (List : in out Util.Beans.Basic.Readonly_Bean_Access);
private
type List_Bean is new Abstract_List_Bean with record
Current : aliased Element_Type;
Current_Index : Natural := 0;
Row : Util.Beans.Objects.Object;
end record;
end Util.Beans.Basic.Lists;
|
-----------------------------------------------------------------------
-- util-beans-basic-lists -- List bean given access to a vector
-- Copyright (C) 2011, 2012, 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 Ada.Containers;
with Ada.Containers.Vectors;
with Util.Beans.Objects;
-- The <b>Util.Beans.Basic.Lists</b> generic package implements a list of
-- elements that can be accessed through the <b>List_Bean</b> interface.
generic
type Element_Type is new Util.Beans.Basic.Readonly_Bean with private;
package Util.Beans.Basic.Lists is
-- Package that represents the vectors of elements.
-- (gcc 4.4 crashes if this package is defined as generic parameter.
package Vectors is
new Ada.Containers.Vectors (Element_Type => Element_Type,
Index_Type => Positive);
-- The list of elements is defined in a public part so that applications
-- can easily add or remove elements in the target list. The <b>List_Bean</b>
-- type holds the real implementation with the private parts.
type Abstract_List_Bean is abstract new Ada.Finalization.Controlled
and Util.Beans.Basic.List_Bean with record
List : aliased Vectors.Vector;
end record;
-- ------------------------------
-- List of objects
-- ------------------------------
-- The <b>List_Bean</b> type gives access to a list of objects.
type List_Bean is new Abstract_List_Bean with private;
type List_Bean_Access is access all List_Bean'Class;
-- Get the number of elements in the list.
overriding
function Get_Count (From : in List_Bean) return Natural;
-- Set the current row index. Valid row indexes start at 1.
overriding
procedure Set_Row_Index (From : in out List_Bean;
Index : in Natural);
-- Returns the current row index.
function Get_Row_Index (From : in List_Bean) return Natural;
-- Get the element at the current row index.
overriding
function Get_Row (From : in List_Bean) return Util.Beans.Objects.Object;
-- Get the value identified by the name.
-- If the name cannot be found, the method should return the Null object.
overriding
function Get_Value (From : in List_Bean;
Name : in String) return Util.Beans.Objects.Object;
-- Initialize the list bean.
overriding
procedure Initialize (Object : in out List_Bean);
-- Deletes the list bean
procedure Free (List : in out Util.Beans.Basic.Readonly_Bean_Access);
private
type List_Bean is new Abstract_List_Bean with record
Current : aliased Element_Type;
Current_Index : Natural := 0;
Row : Util.Beans.Objects.Object;
end record;
end Util.Beans.Basic.Lists;
|
Change the Vectors package instantiation to use the Positive type index
|
Change the Vectors package instantiation to use the Positive type index
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
04fdd34b984a69ed4b9cc30753826df148794f16
|
src/base/beans/util-beans-objects-maps.adb
|
src/base/beans/util-beans-objects-maps.adb
|
-----------------------------------------------------------------------
-- util-beans-objects-maps -- Object maps
-- Copyright (C) 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.
-----------------------------------------------------------------------
package body Util.Beans.Objects.Maps is
-- ------------------------------
-- Get the value identified by the name.
-- If the name cannot be found, the method should return the Null object.
-- ------------------------------
function Get_Value (From : in Map_Bean;
Name : in String) return Object is
Pos : constant Cursor := From.Find (Name);
begin
if Has_Element (Pos) then
return Element (Pos);
else
return Null_Object;
end if;
end Get_Value;
-- ------------------------------
-- Set the value identified by the name.
-- If the map contains the given name, the value changed.
-- Otherwise name is added to the map and the value associated with it.
-- ------------------------------
procedure Set_Value (From : in out Map_Bean;
Name : in String;
Value : in Object) is
begin
From.Include (Name, Value);
end Set_Value;
-- ------------------------------
-- Iterate over the members of the map.
-- ------------------------------
procedure Iterate (From : in Object;
Process : not null access procedure (Name : in String;
Item : in Object)) is
procedure Process_One (Pos : in Maps.Cursor);
procedure Process_One (Pos : in Maps.Cursor) is
begin
Process (Maps.Key (Pos), Maps.Element (Pos));
end Process_One;
Bean : constant access Util.Beans.Basic.Readonly_Bean'Class := To_Bean (From);
begin
if Bean /= null and then Bean.all in Util.Beans.Objects.Maps.Map_Bean'Class then
Map_Bean'Class (Bean.all).Iterate (Process_One'Access);
end if;
end Iterate;
-- ------------------------------
-- Create an object that contains a <tt>Map_Bean</tt> instance.
-- ------------------------------
function Create return Object is
M : constant access Map_Bean'Class := new Map_Bean;
begin
return To_Object (Value => M, Storage => DYNAMIC);
end Create;
end Util.Beans.Objects.Maps;
|
-----------------------------------------------------------------------
-- util-beans-objects-maps -- Object maps
-- Copyright (C) 2010, 2011, 2012, 2017, 2018, 2019 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
package body Util.Beans.Objects.Maps is
-- ------------------------------
-- Get the value identified by the name.
-- If the name cannot be found, the method should return the Null object.
-- ------------------------------
function Get_Value (From : in Map_Bean;
Name : in String) return Object is
Pos : constant Cursor := From.Find (Name);
begin
if Has_Element (Pos) then
return Element (Pos);
else
return Null_Object;
end if;
end Get_Value;
-- ------------------------------
-- Set the value identified by the name.
-- If the map contains the given name, the value changed.
-- Otherwise name is added to the map and the value associated with it.
-- ------------------------------
procedure Set_Value (From : in out Map_Bean;
Name : in String;
Value : in Object) is
begin
From.Include (Name, Value);
end Set_Value;
-- ------------------------------
-- Iterate over the members of the map.
-- ------------------------------
procedure Iterate (From : in Object;
Process : not null access procedure (Name : in String;
Item : in Object)) is
procedure Process_One (Pos : in Maps.Cursor);
procedure Process_One (Pos : in Maps.Cursor) is
begin
Process (Maps.Key (Pos), Maps.Element (Pos));
end Process_One;
Bean : constant access Util.Beans.Basic.Readonly_Bean'Class := To_Bean (From);
begin
if Bean /= null and then Bean.all in Util.Beans.Objects.Maps.Map_Bean'Class then
Map_Bean'Class (Bean.all).Iterate (Process_One'Access);
end if;
end Iterate;
-- ------------------------------
-- Create an object that contains a <tt>Map_Bean</tt> instance.
-- ------------------------------
function Create return Object is
M : constant Map_Bean_Access := new Map_Bean;
begin
return To_Object (Value => M, Storage => DYNAMIC);
end Create;
end Util.Beans.Objects.Maps;
|
Use Map_Bean_Access type
|
Use Map_Bean_Access type
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
01aeb0efa251e996da329c0bd2bc9c9607862934
|
src/util-streams.ads
|
src/util-streams.ads
|
-----------------------------------------------------------------------
-- util-streams -- Stream utilities
-- Copyright (C) 2010, 2016, 2018 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Streams;
-- = Streams =
-- The `Util.Streams` package provides several types and operations to allow the
-- composition of input and output streams.
--
-- @include util-streams-buffered.ads
-- @include util-streams-texts.ads
-- @include util-streams-files.ads
-- @include util-streams-pipes.ads
-- @include util-streams-sockets.ads
-- @include util-streams-raw.ads
-- @include util-streams-buffered-encoders.ads
package Util.Streams is
pragma Preelaborate;
-- -----------------------
-- Output stream
-- -----------------------
-- The <b>Output_Stream</b> is an interface that accepts output bytes
-- and sends them to a sink.
type Output_Stream is limited interface;
type Output_Stream_Access is access all Output_Stream'Class;
-- Write the buffer array to the output stream.
procedure Write (Stream : in out Output_Stream;
Buffer : in Ada.Streams.Stream_Element_Array) is abstract;
-- Flush the buffer (if any) to the sink.
procedure Flush (Stream : in out Output_Stream) is null;
-- Close the sink.
procedure Close (Stream : in out Output_Stream) is null;
-- -----------------------
-- Input stream
-- -----------------------
-- The <b>Input_Stream</b> is the interface that reads input bytes
-- from a source and returns them.
type Input_Stream is limited interface;
type Input_Stream_Access is access all Input_Stream'Class;
-- Read into the buffer as many bytes as possible and return in
-- <b>last</b> the position of the last byte read.
procedure Read (Stream : in out Input_Stream;
Into : out Ada.Streams.Stream_Element_Array;
Last : out Ada.Streams.Stream_Element_Offset) is abstract;
-- Copy the input stream to the output stream until the end of the input stream
-- is reached.
procedure Copy (From : in out Input_Stream'Class;
Into : in out Output_Stream'Class);
-- Copy the stream array to the string.
-- The string must be large enough to hold the stream array
-- or a Constraint_Error exception is raised.
procedure Copy (From : in Ada.Streams.Stream_Element_Array;
Into : in out String);
-- Copy the string to the stream array.
-- The stream array must be large enough to hold the string
-- or a Constraint_Error exception is raised.
procedure Copy (From : in String;
Into : in out Ada.Streams.Stream_Element_Array);
-- Notes:
-- ------
-- The <b>Ada.Streams.Root_Stream_Type</b> implements the <b>Output_Stream</b>
-- and <b>Input_Stream</b>. It is however not easy to use for composing various
-- stream behaviors.
end Util.Streams;
|
-----------------------------------------------------------------------
-- util-streams -- Stream utilities
-- Copyright (C) 2010, 2016, 2018 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Streams;
-- = Streams =
-- The `Util.Streams` package provides several types and operations to allow the
-- composition of input and output streams. Input streams can be chained together so that
-- they traverse the different stream objects when the data is read from them. Similarly,
-- output streams can be chained and the data that is written will traverse the different
-- streams from the first one up to the last one in the chain. During such traversal, the
-- stream object is able to bufferize the data or make transformations on the data.
--
-- @include util-streams-buffered.ads
-- @include util-streams-texts.ads
-- @include util-streams-files.ads
-- @include util-streams-pipes.ads
-- @include util-streams-sockets.ads
-- @include util-streams-raw.ads
-- @include util-streams-buffered-encoders.ads
package Util.Streams is
pragma Preelaborate;
-- -----------------------
-- Output stream
-- -----------------------
-- The <b>Output_Stream</b> is an interface that accepts output bytes
-- and sends them to a sink.
type Output_Stream is limited interface;
type Output_Stream_Access is access all Output_Stream'Class;
-- Write the buffer array to the output stream.
procedure Write (Stream : in out Output_Stream;
Buffer : in Ada.Streams.Stream_Element_Array) is abstract;
-- Flush the buffer (if any) to the sink.
procedure Flush (Stream : in out Output_Stream) is null;
-- Close the sink.
procedure Close (Stream : in out Output_Stream) is null;
-- -----------------------
-- Input stream
-- -----------------------
-- The <b>Input_Stream</b> is the interface that reads input bytes
-- from a source and returns them.
type Input_Stream is limited interface;
type Input_Stream_Access is access all Input_Stream'Class;
-- Read into the buffer as many bytes as possible and return in
-- <b>last</b> the position of the last byte read.
procedure Read (Stream : in out Input_Stream;
Into : out Ada.Streams.Stream_Element_Array;
Last : out Ada.Streams.Stream_Element_Offset) is abstract;
-- Copy the input stream to the output stream until the end of the input stream
-- is reached.
procedure Copy (From : in out Input_Stream'Class;
Into : in out Output_Stream'Class);
-- Copy the stream array to the string.
-- The string must be large enough to hold the stream array
-- or a Constraint_Error exception is raised.
procedure Copy (From : in Ada.Streams.Stream_Element_Array;
Into : in out String);
-- Copy the string to the stream array.
-- The stream array must be large enough to hold the string
-- or a Constraint_Error exception is raised.
procedure Copy (From : in String;
Into : in out Ada.Streams.Stream_Element_Array);
-- Notes:
-- ------
-- The <b>Ada.Streams.Root_Stream_Type</b> implements the <b>Output_Stream</b>
-- and <b>Input_Stream</b>. It is however not easy to use for composing various
-- stream behaviors.
end Util.Streams;
|
Add and update the documentation
|
Add and update the documentation
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
05af2633fc2acd28730f03193c28bb823a388465
|
src/wiki-filters.ads
|
src/wiki-filters.ads
|
-----------------------------------------------------------------------
-- wiki-filters -- Wiki filters
-- Copyright (C) 2015, 2016, 2020 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Finalization;
with Wiki.Attributes;
with Wiki.Documents;
with Wiki.Nodes;
with Wiki.Strings;
-- == Filters ==
-- The `Wiki.Filters` package provides a simple filter framework that allows to plug
-- specific filters when a wiki document is parsed and processed. The `Filter_Type`
-- implements the operations that the `Wiki.Parsers` will use to populate the document.
-- A filter can do some operations while calls are made so that it can:
--
-- * Get the text content and filter it by looking at forbidden words in some dictionary,
-- * Ignore some formatting construct (for example to forbid the use of links),
-- * Verify and do some corrections on HTML content embedded in wiki text,
-- * Expand some plugins, specific links to complex content.
--
-- To implement a new filter, the `Filter_Type` type must be used as a base type
-- and some of the operations have to be overridden. The default `Filter_Type` operations
-- just propagate the call to the attached wiki document instance (ie, a kind of pass
-- through filter).
--
-- @include wiki-filters-toc.ads
-- @include wiki-filters-html.ads
-- @include wiki-filters-collectors.ads
-- @include wiki-filters-autolink.ads
-- @include wiki-filters-variables.ads
package Wiki.Filters is
pragma Preelaborate;
-- ------------------------------
-- Filter type
-- ------------------------------
type Filter_Type is limited new Ada.Finalization.Limited_Controlled with private;
type Filter_Type_Access is access all Filter_Type'Class;
-- Add a simple node such as N_LINE_BREAK, N_HORIZONTAL_RULE or N_PARAGRAPH to the document.
procedure Add_Node (Filter : in out Filter_Type;
Document : in out Wiki.Documents.Document;
Kind : in Wiki.Nodes.Simple_Node_Kind);
-- Add a text content with the given format to the document.
procedure Add_Text (Filter : in out Filter_Type;
Document : in out Wiki.Documents.Document;
Text : in Wiki.Strings.WString;
Format : in Wiki.Format_Map);
-- Add a section header with the given level in the document.
procedure Add_Header (Filter : in out Filter_Type;
Document : in out Wiki.Documents.Document;
Header : in Wiki.Strings.WString;
Level : in Natural);
-- Push a HTML node with the given tag to the document.
procedure Push_Node (Filter : in out Filter_Type;
Document : in out Wiki.Documents.Document;
Tag : in Wiki.Html_Tag;
Attributes : in out Wiki.Attributes.Attribute_List);
-- Pop a HTML node with the given tag.
procedure Pop_Node (Filter : in out Filter_Type;
Document : in out Wiki.Documents.Document;
Tag : in Wiki.Html_Tag);
-- Add a blockquote (<blockquote>). The level indicates the blockquote nested level.
-- The blockquote must be closed at the next header.
procedure Add_Blockquote (Filter : in out Filter_Type;
Document : in out Wiki.Documents.Document;
Level : in Natural);
-- Add a list item (<li>). Close the previous paragraph and list item if any.
-- The list item will be closed at the next list item, next paragraph or next header.
procedure Add_List_Item (Filter : in out Filter_Type;
Document : in out Wiki.Documents.Document;
Level : in Positive;
Ordered : in Boolean);
-- Add a link.
procedure Add_Link (Filter : in out Filter_Type;
Document : in out Wiki.Documents.Document;
Name : in Wiki.Strings.WString;
Attributes : in out Wiki.Attributes.Attribute_List);
-- Add an image.
procedure Add_Image (Filter : in out Filter_Type;
Document : in out Wiki.Documents.Document;
Name : in Wiki.Strings.WString;
Attributes : in out Wiki.Attributes.Attribute_List);
-- Add a quote.
procedure Add_Quote (Filter : in out Filter_Type;
Document : in out Wiki.Documents.Document;
Name : in Wiki.Strings.WString;
Attributes : in out Wiki.Attributes.Attribute_List);
-- Add a text block that is pre-formatted.
procedure Add_Preformatted (Filter : in out Filter_Type;
Document : in out Wiki.Documents.Document;
Text : in Wiki.Strings.WString;
Format : in Wiki.Strings.WString);
-- Add a new row to the current table.
procedure Add_Row (Filter : in out Filter_Type;
Document : in out Wiki.Documents.Document);
-- Add a column to the current table row. The column is configured with the
-- given attributes. The column content is provided through calls to Append.
procedure Add_Column (Filter : in out Filter_Type;
Document : in out Wiki.Documents.Document;
Attributes : in out Wiki.Attributes.Attribute_List);
-- Finish the creation of the table.
procedure Finish_Table (Filter : in out Filter_Type;
Document : in out Wiki.Documents.Document);
-- Finish the document after complete wiki text has been parsed.
procedure Finish (Filter : in out Filter_Type;
Document : in out Wiki.Documents.Document);
type Filter_Chain is new Filter_Type with private;
-- Add the filter at beginning of the filter chain.
procedure Add_Filter (Chain : in out Filter_Chain;
Filter : in Filter_Type_Access);
-- Internal operation to copy the filter chain.
procedure Set_Chain (Chain : in out Filter_Chain;
From : in Filter_Chain'Class);
private
type Filter_Type is limited new Ada.Finalization.Limited_Controlled with record
Next : Filter_Type_Access;
end record;
type Filter_Chain is new Filter_Type with null record;
end Wiki.Filters;
|
-----------------------------------------------------------------------
-- wiki-filters -- Wiki filters
-- Copyright (C) 2015, 2016, 2020, 2022 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Finalization;
with Wiki.Attributes;
with Wiki.Documents;
with Wiki.Nodes;
with Wiki.Strings;
-- == Filters ==
-- The `Wiki.Filters` package provides a simple filter framework that allows to plug
-- specific filters when a wiki document is parsed and processed. The `Filter_Type`
-- implements the operations that the `Wiki.Parsers` will use to populate the document.
-- A filter can do some operations while calls are made so that it can:
--
-- * Get the text content and filter it by looking at forbidden words in some dictionary,
-- * Ignore some formatting construct (for example to forbid the use of links),
-- * Verify and do some corrections on HTML content embedded in wiki text,
-- * Expand some plugins, specific links to complex content.
--
-- To implement a new filter, the `Filter_Type` type must be used as a base type
-- and some of the operations have to be overridden. The default `Filter_Type` operations
-- just propagate the call to the attached wiki document instance (ie, a kind of pass
-- through filter).
--
-- @include wiki-filters-toc.ads
-- @include wiki-filters-html.ads
-- @include wiki-filters-collectors.ads
-- @include wiki-filters-autolink.ads
-- @include wiki-filters-variables.ads
package Wiki.Filters is
pragma Preelaborate;
-- ------------------------------
-- Filter type
-- ------------------------------
type Filter_Type is limited new Ada.Finalization.Limited_Controlled with private;
type Filter_Type_Access is access all Filter_Type'Class;
-- Add a simple node such as N_LINE_BREAK, N_HORIZONTAL_RULE or N_PARAGRAPH to the document.
procedure Add_Node (Filter : in out Filter_Type;
Document : in out Wiki.Documents.Document;
Kind : in Wiki.Nodes.Simple_Node_Kind);
-- Add a text content with the given format to the document.
procedure Add_Text (Filter : in out Filter_Type;
Document : in out Wiki.Documents.Document;
Text : in Wiki.Strings.WString;
Format : in Wiki.Format_Map);
-- Add a section header with the given level in the document.
procedure Add_Header (Filter : in out Filter_Type;
Document : in out Wiki.Documents.Document;
Header : in Wiki.Strings.WString;
Level : in Natural);
-- Push a HTML node with the given tag to the document.
procedure Push_Node (Filter : in out Filter_Type;
Document : in out Wiki.Documents.Document;
Tag : in Wiki.Html_Tag;
Attributes : in out Wiki.Attributes.Attribute_List);
-- Pop a HTML node with the given tag.
procedure Pop_Node (Filter : in out Filter_Type;
Document : in out Wiki.Documents.Document;
Tag : in Wiki.Html_Tag);
-- Add a blockquote (<blockquote>). The level indicates the blockquote nested level.
-- The blockquote must be closed at the next header.
procedure Add_Blockquote (Filter : in out Filter_Type;
Document : in out Wiki.Documents.Document;
Level : in Natural);
-- Add a list (<ul> or <ol>) starting at the given number.
procedure Add_List (Filter : in out Filter_Type;
Document : in out Wiki.Documents.Document;
Level : in Positive;
Ordered : in Boolean);
-- Add a link.
procedure Add_Link (Filter : in out Filter_Type;
Document : in out Wiki.Documents.Document;
Name : in Wiki.Strings.WString;
Attributes : in out Wiki.Attributes.Attribute_List);
-- Add an image.
procedure Add_Image (Filter : in out Filter_Type;
Document : in out Wiki.Documents.Document;
Name : in Wiki.Strings.WString;
Attributes : in out Wiki.Attributes.Attribute_List);
-- Add a quote.
procedure Add_Quote (Filter : in out Filter_Type;
Document : in out Wiki.Documents.Document;
Name : in Wiki.Strings.WString;
Attributes : in out Wiki.Attributes.Attribute_List);
-- Add a text block that is pre-formatted.
procedure Add_Preformatted (Filter : in out Filter_Type;
Document : in out Wiki.Documents.Document;
Text : in Wiki.Strings.WString;
Format : in Wiki.Strings.WString);
-- Add a new row to the current table.
procedure Add_Row (Filter : in out Filter_Type;
Document : in out Wiki.Documents.Document);
-- Add a column to the current table row. The column is configured with the
-- given attributes. The column content is provided through calls to Append.
procedure Add_Column (Filter : in out Filter_Type;
Document : in out Wiki.Documents.Document;
Attributes : in out Wiki.Attributes.Attribute_List);
-- Finish the creation of the table.
procedure Finish_Table (Filter : in out Filter_Type;
Document : in out Wiki.Documents.Document);
-- Finish the document after complete wiki text has been parsed.
procedure Finish (Filter : in out Filter_Type;
Document : in out Wiki.Documents.Document);
type Filter_Chain is new Filter_Type with private;
-- Add the filter at beginning of the filter chain.
procedure Add_Filter (Chain : in out Filter_Chain;
Filter : in Filter_Type_Access);
-- Internal operation to copy the filter chain.
procedure Set_Chain (Chain : in out Filter_Chain;
From : in Filter_Chain'Class);
private
type Filter_Type is limited new Ada.Finalization.Limited_Controlled with record
Next : Filter_Type_Access;
end record;
type Filter_Chain is new Filter_Type with null record;
end Wiki.Filters;
|
Change Add_List_Item into Add_List
|
Change Add_List_Item into Add_List
|
Ada
|
apache-2.0
|
stcarrez/ada-wiki,stcarrez/ada-wiki
|
daea33934362dddcbdea8d79140c16e5e6244ea1
|
src/security-policies-urls.ads
|
src/security-policies-urls.ads
|
-----------------------------------------------------------------------
-- security-permissions -- Definition of permissions
-- Copyright (C) 2010, 2011, 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Containers.Hashed_Maps;
with Ada.Containers.Vectors;
with Util.Refs;
with Util.Beans.Objects;
with Util.Beans.Objects.Vectors;
with Util.Serialize.IO.XML;
with GNAT.Regexp;
package Security.Policies.Urls is
NAME : constant String := "URL-Policy";
-- ------------------------------
-- URI Permission
-- ------------------------------
-- Represents a permission to access a given URI.
type URI_Permission (Len : Natural) is new Permissions.Permission with record
URI : String (1 .. Len);
end record;
-- ------------------------------
-- URL policy
-- ------------------------------
type URL_Policy is new Policy with private;
type URL_Policy_Access is access all URL_Policy'Class;
Invalid_Name : exception;
-- Get the policy name.
overriding
function Get_Name (From : in URL_Policy) return String;
-- Returns True if the user has the permission to access the given URI permission.
function Has_Permission (Manager : in URL_Policy;
Context : in Security_Context_Access;
Permission : in URI_Permission'Class) return Boolean;
-- Grant the permission to access to the given <b>URI</b> to users having the <b>To</b>
-- permissions.
procedure Grant_URI_Permission (Manager : in out URL_Policy;
URI : in String;
To : in String);
-- Initialize the permission manager.
overriding
procedure Initialize (Manager : in out URL_Policy);
-- Finalize the permission manager.
overriding
procedure Finalize (Manager : in out URL_Policy);
-- Setup the XML parser to read the <b>policy</b> description.
overriding
procedure Set_Reader_Config (Policy : in out URL_Policy;
Reader : in out Util.Serialize.IO.XML.Parser);
private
-- The <b>Access_Rule</b> represents a list of permissions to verify to grant
-- access to the resource. To make it simple, the user must have one of the
-- permission from the list. Each permission will refer to a specific permission
-- controller.
type Access_Rule (Count : Natural) is new Util.Refs.Ref_Entity with record
Permissions : Permission_Index_Array (1 .. Count);
end record;
type Access_Rule_Access is access all Access_Rule;
package Access_Rule_Refs is
new Util.Refs.Indefinite_References (Element_Type => Access_Rule,
Element_Access => Access_Rule_Access);
subtype Access_Rule_Ref is Access_Rule_Refs.Ref;
-- Find the access rule of the policy that matches the given URI.
-- Returns the No_Rule value (disable access) if no rule is found.
function Find_Access_Rule (Manager : in URL_Policy;
URI : in String) return Access_Rule_Ref;
-- The <b>Policy</b> defines the access rules that are applied on a given
-- URL, set of URLs or files.
type Policy is record
Id : Natural;
Pattern : GNAT.Regexp.Regexp;
Rule : Access_Rule_Ref;
end record;
-- The <b>Policy_Vector</b> represents the whole permission policy. The order of
-- policy in the list is important as policies can override each other.
package Policy_Vector is new Ada.Containers.Vectors (Index_Type => Positive,
Element_Type => Policy);
package Rules_Maps is new Ada.Containers.Hashed_Maps (Key_Type => String_Ref,
Element_Type => Access_Rule_Ref,
Hash => Hash,
Equivalent_Keys => Equivalent_Keys,
"=" => Access_Rule_Refs."=");
type Rules is new Util.Refs.Ref_Entity with record
Map : Rules_Maps.Map;
end record;
type Rules_Access is access all Rules;
package Rules_Ref is new Util.Refs.References (Rules, Rules_Access);
type Rules_Ref_Access is access Rules_Ref.Atomic_Ref;
type Controller_Access_Array_Access is access all Controller_Access_Array;
type URL_Policy is new Security.Policies.Policy with record
Cache : Rules_Ref_Access;
Policies : Policy_Vector.Vector;
end record;
end Security.Policies.Urls;
|
-----------------------------------------------------------------------
-- security-policies-urls -- URL security policy
-- 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.Containers.Hashed_Maps;
with Ada.Containers.Vectors;
with Util.Refs;
with Util.Serialize.IO.XML;
with GNAT.Regexp;
package Security.Policies.Urls is
NAME : constant String := "URL-Policy";
-- ------------------------------
-- URI Permission
-- ------------------------------
-- Represents a permission to access a given URI.
type URI_Permission (Len : Natural) is new Permissions.Permission with record
URI : String (1 .. Len);
end record;
-- ------------------------------
-- URL policy
-- ------------------------------
type URL_Policy is new Policy with private;
type URL_Policy_Access is access all URL_Policy'Class;
Invalid_Name : exception;
-- Get the policy name.
overriding
function Get_Name (From : in URL_Policy) return String;
-- Returns True if the user has the permission to access the given URI permission.
function Has_Permission (Manager : in URL_Policy;
Context : in Security_Context_Access;
Permission : in URI_Permission'Class) return Boolean;
-- Grant the permission to access to the given <b>URI</b> to users having the <b>To</b>
-- permissions.
procedure Grant_URI_Permission (Manager : in out URL_Policy;
URI : in String;
To : in String);
-- Initialize the permission manager.
overriding
procedure Initialize (Manager : in out URL_Policy);
-- Finalize the permission manager.
overriding
procedure Finalize (Manager : in out URL_Policy);
-- Setup the XML parser to read the <b>policy</b> description.
overriding
procedure Set_Reader_Config (Policy : in out URL_Policy;
Reader : in out Util.Serialize.IO.XML.Parser);
private
-- The <b>Access_Rule</b> represents a list of permissions to verify to grant
-- access to the resource. To make it simple, the user must have one of the
-- permission from the list. Each permission will refer to a specific permission
-- controller.
type Access_Rule (Count : Natural) is new Util.Refs.Ref_Entity with record
Permissions : Permission_Index_Array (1 .. Count);
end record;
type Access_Rule_Access is access all Access_Rule;
package Access_Rule_Refs is
new Util.Refs.Indefinite_References (Element_Type => Access_Rule,
Element_Access => Access_Rule_Access);
subtype Access_Rule_Ref is Access_Rule_Refs.Ref;
-- Find the access rule of the policy that matches the given URI.
-- Returns the No_Rule value (disable access) if no rule is found.
function Find_Access_Rule (Manager : in URL_Policy;
URI : in String) return Access_Rule_Ref;
-- The <b>Policy</b> defines the access rules that are applied on a given
-- URL, set of URLs or files.
type Policy is record
Id : Natural;
Pattern : GNAT.Regexp.Regexp;
Rule : Access_Rule_Ref;
end record;
-- The <b>Policy_Vector</b> represents the whole permission policy. The order of
-- policy in the list is important as policies can override each other.
package Policy_Vector is new Ada.Containers.Vectors (Index_Type => Positive,
Element_Type => Policy);
package Rules_Maps is new Ada.Containers.Hashed_Maps (Key_Type => String_Ref,
Element_Type => Access_Rule_Ref,
Hash => Hash,
Equivalent_Keys => Equivalent_Keys,
"=" => Access_Rule_Refs."=");
type Rules is new Util.Refs.Ref_Entity with record
Map : Rules_Maps.Map;
end record;
type Rules_Access is access all Rules;
package Rules_Ref is new Util.Refs.References (Rules, Rules_Access);
type Rules_Ref_Access is access Rules_Ref.Atomic_Ref;
type Controller_Access_Array_Access is access all Controller_Access_Array;
type URL_Policy is new Security.Policies.Policy with record
Cache : Rules_Ref_Access;
Policies : Policy_Vector.Vector;
end record;
end Security.Policies.Urls;
|
Remove unused with clauses
|
Remove unused with clauses
|
Ada
|
apache-2.0
|
stcarrez/ada-security
|
afad91f399643b6a73e9be06f16eb8881b27b837
|
src/babel-stores-local.ads
|
src/babel-stores-local.ads
|
-----------------------------------------------------------------------
-- babel-stores-local -- Store to access local 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 Ada.Strings.Unbounded;
with Util.Streams.Raw;
with Babel.Files.Buffers;
package Babel.Stores.Local is
type Local_Store_Type is new Babel.Stores.Store_Type with private;
-- Get the absolute path to access the local file.
function Get_Absolute_Path (Store : in Local_Store_Type;
Path : in String) return String;
-- Open a file in the store to read its content with a stream.
overriding
procedure Open_File (Store : in out Local_Store_Type;
Path : in String;
Stream : out Babel.Streams.Stream_Access);
-- Open a file in the store to read its content with a stream.
overriding
procedure Read_File (Store : in out Local_Store_Type;
Path : in String;
Stream : out Babel.Streams.Refs.Stream_Ref);
-- Write a file in the store with a stream.
overriding
procedure Write_File (Store : in out Local_Store_Type;
Path : in String;
Stream : in Babel.Streams.Refs.Stream_Ref;
Mode : in Util.Systems.Types.mode_t);
overriding
procedure Read (Store : in out Local_Store_Type;
Path : in String;
Into : in out Babel.Files.Buffers.Buffer);
overriding
procedure Write (Store : in out Local_Store_Type;
Path : in String;
Into : in Babel.Files.Buffers.Buffer);
overriding
procedure Scan (Store : in out Local_Store_Type;
Path : in String;
Into : in out Babel.Files.File_Container'Class;
Filter : in Babel.Filters.Filter_Type'Class);
procedure Open (Store : in out Local_Store_Type;
Stream : in out Util.Streams.Raw.Raw_Stream;
Path : in String);
-- Set the root directory for the local store.
procedure Set_Root_Directory (Store : in out Local_Store_Type;
Path : in String);
-- Set the buffer pool to be used by local store.
procedure Set_Buffers (Store : in out Local_Store_Type;
Buffers : in Babel.Files.Buffers.Buffer_Pool_Access);
private
type Local_Store_Type is new Babel.Stores.Store_Type with record
Root_Dir : Ada.Strings.Unbounded.Unbounded_String;
Pool : Babel.Files.Buffers.Buffer_Pool_Access;
end record;
end Babel.Stores.Local;
|
-----------------------------------------------------------------------
-- babel-stores-local -- Store to access local 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 Ada.Strings.Unbounded;
with Util.Streams.Raw;
with Babel.Files.Buffers;
package Babel.Stores.Local is
type Local_Store_Type is new Babel.Stores.Store_Type with private;
-- Get the absolute path to access the local file.
function Get_Absolute_Path (Store : in Local_Store_Type;
Path : in String) return String;
-- Open a file in the store to read its content with a stream.
overriding
procedure Open_File (Store : in out Local_Store_Type;
Path : in String;
Stream : out Babel.Streams.Stream_Access);
-- Open a file in the store to read its content with a stream.
overriding
procedure Read_File (Store : in out Local_Store_Type;
Path : in String;
Stream : out Babel.Streams.Refs.Stream_Ref);
-- Write a file in the store with a stream.
overriding
procedure Write_File (Store : in out Local_Store_Type;
Path : in String;
Stream : in Babel.Streams.Refs.Stream_Ref;
Mode : in Babel.Files.File_Mode);
overriding
procedure Read (Store : in out Local_Store_Type;
Path : in String;
Into : in out Babel.Files.Buffers.Buffer);
overriding
procedure Write (Store : in out Local_Store_Type;
Path : in String;
Into : in Babel.Files.Buffers.Buffer);
overriding
procedure Scan (Store : in out Local_Store_Type;
Path : in String;
Into : in out Babel.Files.File_Container'Class;
Filter : in Babel.Filters.Filter_Type'Class);
procedure Open (Store : in out Local_Store_Type;
Stream : in out Util.Streams.Raw.Raw_Stream;
Path : in String);
-- Set the root directory for the local store.
procedure Set_Root_Directory (Store : in out Local_Store_Type;
Path : in String);
-- Set the buffer pool to be used by local store.
procedure Set_Buffers (Store : in out Local_Store_Type;
Buffers : in Babel.Files.Buffers.Buffer_Pool_Access);
private
type Local_Store_Type is new Babel.Stores.Store_Type with record
Root_Dir : Ada.Strings.Unbounded.Unbounded_String;
Pool : Babel.Files.Buffers.Buffer_Pool_Access;
end record;
end Babel.Stores.Local;
|
Change Write_File to use the Babel.Files.File_Mode type
|
Change Write_File to use the Babel.Files.File_Mode type
|
Ada
|
apache-2.0
|
stcarrez/babel
|
14b74c3175d2c38e76ac31cd04166ca29448454d
|
mat/src/mat-readers-files.adb
|
mat/src/mat-readers-files.adb
|
-----------------------------------------------------------------------
-- mat-readers-files -- Reader for files
-- Copyright (C) 2014 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Streams.Stream_IO;
with Util.Streams.Buffered;
with Util.Streams.Files;
with Util.Log.Loggers;
with MAT.Readers.Marshaller;
package body MAT.Readers.Files is
-- The logger
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("MAT.Readers.Files");
BUFFER_SIZE : constant Natural := 100 * 1024;
MAX_MSG_SIZE : constant Ada.Streams.Stream_Element_Offset := 2048;
-- Open the file.
procedure Open (Reader : in out File_Reader_Type;
Path : in String) is
begin
Log.Info ("Reading data stream {0}", Path);
Reader.Stream.Initialize (Size => BUFFER_SIZE,
Input => Reader.File'Unchecked_Access,
Output => null);
Reader.File.Open (Mode => Ada.Streams.Stream_IO.In_File,
Name => Path);
end Open;
procedure Read_All (Reader : in out File_Reader_Type) is
use Ada.Streams;
use type MAT.Types.Uint8;
Data : aliased Ada.Streams.Stream_Element_Array (0 .. MAX_MSG_SIZE);
Buffer : aliased Buffer_Type;
Msg : Message;
Last : Ada.Streams.Stream_Element_Offset;
Size : MAT.Types.Uint16;
Version : MAT.Types.Uint16;
Format : MAT.Types.Uint8;
begin
Msg.Buffer := Buffer'Unchecked_Access;
Msg.Buffer.Start := Data (0)'Address;
Msg.Buffer.Current := Msg.Buffer.Start;
Msg.Buffer.Last := Data (MAX_MSG_SIZE)'Address;
Msg.Buffer.Size := 3;
Reader.Stream.Read (Data (0 .. 2), Last);
Format := MAT.Readers.Marshaller.Get_Uint8 (Msg.Buffer);
if Format = 0 then
Msg.Buffer.Endian := LITTLE_ENDIAN;
Log.Debug ("Data stream is little endian");
else
Msg.Buffer.Endian := BIG_ENDIAN;
Log.Debug ("Data stream is big endian");
end if;
Msg.Size := Natural (MAT.Readers.Marshaller.Get_Uint16 (Msg.Buffer));
if Msg.Size < 2 then
Log.Error ("Invalid message size {0}", Natural'Image (Msg.Size));
end if;
-- Msg.Size := Msg.Size - 2;
Reader.Stream.Read (Data (0 .. Ada.Streams.Stream_Element_Offset (Msg.Size - 1)), Last);
Msg.Buffer.Current := Msg.Buffer.Start;
Msg.Buffer.Last := Data (Last)'Address;
Msg.Buffer.Size := Natural (Msg.Size);
Reader.Read_Headers (Msg);
while not Reader.Stream.Is_Eof loop
Reader.Stream.Read (Data (0 .. 1), Last);
exit when Last /= 2;
Msg.Buffer.Size := 2;
Msg.Buffer.Current := Msg.Buffer.Start;
Msg.Size := Natural (MAT.Readers.Marshaller.Get_Uint16 (Msg.Buffer));
if Msg.Size < 2 then
Log.Error ("Invalid message size {0}", Natural'Image (Msg.Size));
end if;
if Ada.Streams.Stream_Element_Offset (Msg.Size) >= Data'Last then
Log.Error ("Message size {0} is too big", Natural'Image (Msg.Size));
exit;
end if;
-- Msg.Size := Msg.Size - 2;
Reader.Stream.Read (Data (0 .. Ada.Streams.Stream_Element_Offset (Msg.Size - 1)), Last);
Msg.Buffer.Current := Msg.Buffer.Start;
Msg.Buffer.Last := Data (Last)'Address;
Msg.Buffer.Size := Natural (Msg.Size);
Reader.Dispatch_Message (Msg);
end loop;
end Read_All;
end MAT.Readers.Files;
|
-----------------------------------------------------------------------
-- mat-readers-files -- Reader for files
-- Copyright (C) 2014 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Streams.Stream_IO;
with Util.Log.Loggers;
with MAT.Readers.Marshaller;
package body MAT.Readers.Files is
-- The logger
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("MAT.Readers.Files");
BUFFER_SIZE : constant Natural := 100 * 1024;
MAX_MSG_SIZE : constant Ada.Streams.Stream_Element_Offset := 2048;
-- Open the file.
procedure Open (Reader : in out File_Reader_Type;
Path : in String) is
begin
Log.Info ("Reading data stream {0}", Path);
Reader.Stream.Initialize (Size => BUFFER_SIZE,
Input => Reader.File'Unchecked_Access,
Output => null);
Reader.File.Open (Mode => Ada.Streams.Stream_IO.In_File,
Name => Path);
end Open;
procedure Read_All (Reader : in out File_Reader_Type) is
use Ada.Streams;
use type MAT.Types.Uint8;
Data : aliased Ada.Streams.Stream_Element_Array (0 .. MAX_MSG_SIZE);
Buffer : aliased Buffer_Type;
Msg : Message;
Last : Ada.Streams.Stream_Element_Offset;
Format : MAT.Types.Uint8;
begin
Msg.Buffer := Buffer'Unchecked_Access;
Msg.Buffer.Start := Data (0)'Address;
Msg.Buffer.Current := Msg.Buffer.Start;
Msg.Buffer.Last := Data (MAX_MSG_SIZE)'Address;
Msg.Buffer.Size := 3;
Reader.Stream.Read (Data (0 .. 2), Last);
Format := MAT.Readers.Marshaller.Get_Uint8 (Msg.Buffer);
if Format = 0 then
Msg.Buffer.Endian := LITTLE_ENDIAN;
Log.Debug ("Data stream is little endian");
else
Msg.Buffer.Endian := BIG_ENDIAN;
Log.Debug ("Data stream is big endian");
end if;
Msg.Size := Natural (MAT.Readers.Marshaller.Get_Uint16 (Msg.Buffer));
if Msg.Size < 2 then
Log.Error ("Invalid message size {0}", Natural'Image (Msg.Size));
end if;
Reader.Stream.Read (Data (0 .. Ada.Streams.Stream_Element_Offset (Msg.Size - 1)), Last);
Msg.Buffer.Current := Msg.Buffer.Start;
Msg.Buffer.Last := Data (Last)'Address;
Msg.Buffer.Size := Msg.Size;
Reader.Read_Headers (Msg);
while not Reader.Stream.Is_Eof loop
Reader.Stream.Read (Data (0 .. 1), Last);
exit when Last /= 2;
Msg.Buffer.Size := 2;
Msg.Buffer.Current := Msg.Buffer.Start;
Msg.Size := Natural (MAT.Readers.Marshaller.Get_Uint16 (Msg.Buffer));
if Msg.Size < 2 then
Log.Error ("Invalid message size {0}", Natural'Image (Msg.Size));
end if;
if Ada.Streams.Stream_Element_Offset (Msg.Size) >= Data'Last then
Log.Error ("Message size {0} is too big", Natural'Image (Msg.Size));
exit;
end if;
Reader.Stream.Read (Data (0 .. Ada.Streams.Stream_Element_Offset (Msg.Size - 1)), Last);
Msg.Buffer.Current := Msg.Buffer.Start;
Msg.Buffer.Last := Data (Last)'Address;
Msg.Buffer.Size := Msg.Size;
Reader.Dispatch_Message (Msg);
end loop;
end Read_All;
end MAT.Readers.Files;
|
Fix compilation warnings
|
Fix compilation warnings
|
Ada
|
apache-2.0
|
stcarrez/mat,stcarrez/mat,stcarrez/mat
|
77b0a4ad84e9f68ac4bc13c3db753c5fb0cf5908
|
awa/regtests/awa-testsuite.adb
|
awa/regtests/awa-testsuite.adb
|
-----------------------------------------------------------------------
-- Util testsuite - Util Testsuite
-- Copyright (C) 2009, 2010, 2011, 2012, 2013 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with AWA.Users.Services.Tests;
with AWA.Users.Tests;
with AWA.Blogs.Services.Tests;
with AWA.Wikis.Parsers.Tests;
with AWA.Wikis.Writers.Tests;
with AWA.Helpers.Selectors.Tests;
with AWA.Storages.Services.Tests;
with AWA.Events.Services.Tests;
with AWA.Mail.Clients.Tests;
with AWA.Mail.Modules.Tests;
with AWA.Images.Services.Tests;
with AWA.Modules.Tests;
with ASF.Converters.Dates;
with AWA.Users.Modules;
with AWA.Mail.Modules;
with AWA.Blogs.Modules;
with AWA.Workspaces.Modules;
with AWA.Storages.Modules;
with AWA.Images.Modules;
with AWA.Converters.Dates;
with AWA.Tests;
with AWA.Services.Contexts;
with AWA.Jobs.Services.Tests;
with AWA.Jobs.Modules.Tests;
with ASF.Server.Web;
with ASF.Server.Tests;
package body AWA.Testsuite is
Users : aliased AWA.Users.Modules.User_Module;
Workspaces : aliased AWA.Workspaces.Modules.Workspace_Module;
Mail : aliased AWA.Mail.Modules.Mail_Module;
Jobs : aliased AWA.Jobs.Modules.Job_Module;
Blogs : aliased AWA.Blogs.Modules.Blog_Module;
Storages : aliased AWA.Storages.Modules.Storage_Module;
Images : aliased AWA.Images.Modules.Image_Module;
Date_Converter : aliased ASF.Converters.Dates.Date_Converter;
Rel_Date_Converter : aliased AWA.Converters.Dates.Relative_Date_Converter;
Tests : aliased Util.Tests.Test_Suite;
function Suite return Util.Tests.Access_Test_Suite is
Ret : constant Util.Tests.Access_Test_Suite := Tests'Access;
begin
AWA.Modules.Tests.Add_Tests (Ret);
AWA.Events.Services.Tests.Add_Tests (Ret);
AWA.Mail.Clients.Tests.Add_Tests (Ret);
AWA.Mail.Modules.Tests.Add_Tests (Ret);
AWA.Users.Services.Tests.Add_Tests (Ret);
AWA.Users.Tests.Add_Tests (Ret);
AWA.Wikis.Parsers.Tests.Add_Tests (Ret);
AWA.Wikis.Writers.Tests.Add_Tests (Ret);
AWA.Helpers.Selectors.Tests.Add_Tests (Ret);
AWA.Jobs.Modules.Tests.Add_Tests (Ret);
AWA.Jobs.Services.Tests.Add_Tests (Ret);
AWA.Blogs.Services.Tests.Add_Tests (Ret);
AWA.Storages.Services.Tests.Add_Tests (Ret);
AWA.Images.Services.Tests.Add_Tests (Ret);
return Ret;
end Suite;
procedure Initialize (Props : in Util.Properties.Manager) is
begin
Initialize (null, Props, True);
end Initialize;
-- ------------------------------
-- Initialize the AWA test framework mockup.
-- ------------------------------
procedure Initialize (App : in AWA.Applications.Application_Access;
Props : in Util.Properties.Manager;
Add_Modules : in Boolean) is
use AWA.Applications;
begin
AWA.Tests.Initialize (App, Props, Add_Modules);
if Add_Modules then
declare
Application : constant Applications.Application_Access := AWA.Tests.Get_Application;
Ctx : AWA.Services.Contexts.Service_Context;
Users : constant AWA.Users.Modules.User_Module_Access := AWA.Testsuite.Users'Access;
begin
Ctx.Set_Context (Application, null);
Register (App => Application.all'Access,
Name => AWA.Users.Modules.NAME,
URI => "user",
Module => Users.all'Access);
Register (App => Application.all'Access,
Name => "mail",
URI => "mail",
Module => Mail'Access);
Register (App => Application.all'Access,
Name => "workspaces",
URI => "workspaces",
Module => Workspaces'Access);
Register (App => Application.all'Access,
Name => AWA.Storages.Modules.NAME,
URI => "storages",
Module => Storages'Access);
Register (App => Application.all'Access,
Name => AWA.Images.Modules.NAME,
URI => "images",
Module => Images'Access);
Register (App => Application.all'Access,
Name => AWA.Jobs.Modules.NAME,
URI => "jobs",
Module => Jobs'Access);
Register (App => Application.all'Access,
Name => AWA.Blogs.Modules.NAME,
URI => "blogs",
Module => Blogs'Access);
Application.Start;
if Props.Exists ("test.server") then
declare
WS : ASF.Server.Web.AWS_Container;
begin
Application.Add_Converter (Name => "dateConverter",
Converter => Date_Converter'Access);
Application.Add_Converter (Name => "smartDateConverter",
Converter => Rel_Date_Converter'Access);
WS.Register_Application ("/asfunit", Application.all'Access);
WS.Start;
delay 6000.0;
end;
end if;
ASF.Server.Tests.Set_Context (Application.all'Access);
end;
end if;
end Initialize;
end AWA.Testsuite;
|
-----------------------------------------------------------------------
-- Util testsuite - Util Testsuite
-- Copyright (C) 2009, 2010, 2011, 2012, 2013 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with AWA.Users.Services.Tests;
with AWA.Users.Tests;
with AWA.Blogs.Services.Tests;
with AWA.Wikis.Parsers.Tests;
with AWA.Wikis.Writers.Tests;
with AWA.Helpers.Selectors.Tests;
with AWA.Storages.Services.Tests;
with AWA.Events.Services.Tests;
with AWA.Mail.Clients.Tests;
with AWA.Mail.Modules.Tests;
with AWA.Images.Services.Tests;
with AWA.Votes.Modules.Tests;
with AWA.Questions.Services.Tests;
with AWA.Modules.Tests;
with ASF.Converters.Dates;
with AWA.Users.Modules;
with AWA.Mail.Modules;
with AWA.Blogs.Modules;
with AWA.Workspaces.Modules;
with AWA.Storages.Modules;
with AWA.Images.Modules;
with AWA.Questions.Modules;
with AWA.Votes.Modules;
with AWA.Converters.Dates;
with AWA.Tests;
with AWA.Services.Contexts;
with AWA.Jobs.Services.Tests;
with AWA.Jobs.Modules.Tests;
with ASF.Server.Web;
with ASF.Server.Tests;
package body AWA.Testsuite is
Users : aliased AWA.Users.Modules.User_Module;
Workspaces : aliased AWA.Workspaces.Modules.Workspace_Module;
Mail : aliased AWA.Mail.Modules.Mail_Module;
Jobs : aliased AWA.Jobs.Modules.Job_Module;
Blogs : aliased AWA.Blogs.Modules.Blog_Module;
Storages : aliased AWA.Storages.Modules.Storage_Module;
Images : aliased AWA.Images.Modules.Image_Module;
Questions : aliased AWA.Questions.Modules.Question_Module;
Votes : aliased AWA.Votes.Modules.Vote_Module;
Date_Converter : aliased ASF.Converters.Dates.Date_Converter;
Rel_Date_Converter : aliased AWA.Converters.Dates.Relative_Date_Converter;
Tests : aliased Util.Tests.Test_Suite;
function Suite return Util.Tests.Access_Test_Suite is
Ret : constant Util.Tests.Access_Test_Suite := Tests'Access;
begin
AWA.Modules.Tests.Add_Tests (Ret);
AWA.Events.Services.Tests.Add_Tests (Ret);
AWA.Mail.Clients.Tests.Add_Tests (Ret);
AWA.Mail.Modules.Tests.Add_Tests (Ret);
AWA.Users.Services.Tests.Add_Tests (Ret);
AWA.Users.Tests.Add_Tests (Ret);
AWA.Wikis.Parsers.Tests.Add_Tests (Ret);
AWA.Wikis.Writers.Tests.Add_Tests (Ret);
AWA.Helpers.Selectors.Tests.Add_Tests (Ret);
AWA.Jobs.Modules.Tests.Add_Tests (Ret);
AWA.Jobs.Services.Tests.Add_Tests (Ret);
AWA.Blogs.Services.Tests.Add_Tests (Ret);
AWA.Storages.Services.Tests.Add_Tests (Ret);
AWA.Images.Services.Tests.Add_Tests (Ret);
AWA.Votes.Modules.Tests.Add_Tests (Ret);
AWA.Questions.Services.Tests.Add_Tests (Ret);
return Ret;
end Suite;
procedure Initialize (Props : in Util.Properties.Manager) is
begin
Initialize (null, Props, True);
end Initialize;
-- ------------------------------
-- Initialize the AWA test framework mockup.
-- ------------------------------
procedure Initialize (App : in AWA.Applications.Application_Access;
Props : in Util.Properties.Manager;
Add_Modules : in Boolean) is
use AWA.Applications;
begin
AWA.Tests.Initialize (App, Props, Add_Modules);
if Add_Modules then
declare
Application : constant Applications.Application_Access := AWA.Tests.Get_Application;
Ctx : AWA.Services.Contexts.Service_Context;
Users : constant AWA.Users.Modules.User_Module_Access := AWA.Testsuite.Users'Access;
begin
Ctx.Set_Context (Application, null);
Register (App => Application.all'Access,
Name => AWA.Users.Modules.NAME,
URI => "user",
Module => Users.all'Access);
Register (App => Application.all'Access,
Name => "mail",
URI => "mail",
Module => Mail'Access);
Register (App => Application.all'Access,
Name => "workspaces",
URI => "workspaces",
Module => Workspaces'Access);
Register (App => Application.all'Access,
Name => AWA.Storages.Modules.NAME,
URI => "storages",
Module => Storages'Access);
Register (App => Application.all'Access,
Name => AWA.Images.Modules.NAME,
URI => "images",
Module => Images'Access);
Register (App => Application.all'Access,
Name => AWA.Jobs.Modules.NAME,
URI => "jobs",
Module => Jobs'Access);
Register (App => Application.all'Access,
Name => AWA.Votes.Modules.NAME,
URI => "votes",
Module => Votes'Access);
Register (App => Application.all'Access,
Name => AWA.Blogs.Modules.NAME,
URI => "blogs",
Module => Blogs'Access);
Register (App => Application.all'Access,
Name => AWA.Questions.Modules.NAME,
URI => "questions",
Module => Questions'Access);
Application.Start;
if Props.Exists ("test.server") then
declare
WS : ASF.Server.Web.AWS_Container;
begin
Application.Add_Converter (Name => "dateConverter",
Converter => Date_Converter'Access);
Application.Add_Converter (Name => "smartDateConverter",
Converter => Rel_Date_Converter'Access);
WS.Register_Application ("/asfunit", Application.all'Access);
WS.Start;
delay 6000.0;
end;
end if;
ASF.Server.Tests.Set_Context (Application.all'Access);
end;
end if;
end Initialize;
end AWA.Testsuite;
|
Add the votes and questions plugin unit tests
|
Add the votes and questions plugin unit tests
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
5ade7f686e5cfceb7762c17727067180dea7ec20
|
awa/regtests/awa-testsuite.adb
|
awa/regtests/awa-testsuite.adb
|
-----------------------------------------------------------------------
-- Util testsuite - Util Testsuite
-- Copyright (C) 2009, 2010, 2011, 2012, 2013 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with AWA.Users.Services.Tests;
with AWA.Users.Tests;
with AWA.Blogs.Services.Tests;
with AWA.Wikis.Parsers.Tests;
with AWA.Wikis.Writers.Tests;
with AWA.Helpers.Selectors.Tests;
with AWA.Storages.Services.Tests;
with AWA.Events.Services.Tests;
with AWA.Mail.Clients.Tests;
with AWA.Mail.Modules.Tests;
with AWA.Images.Services.Tests;
with AWA.Modules.Tests;
with ASF.Converters.Dates;
with AWA.Users.Modules;
with AWA.Mail.Modules;
with AWA.Blogs.Modules;
with AWA.Workspaces.Modules;
with AWA.Storages.Modules;
with AWA.Images.Modules;
with AWA.Converters.Dates;
with AWA.Tests;
with AWA.Services.Contexts;
with AWA.Jobs.Services.Tests;
with AWA.Jobs.Modules.Tests;
with ASF.Server.Web;
with ASF.Server.Tests;
package body AWA.Testsuite is
Users : aliased AWA.Users.Modules.User_Module;
Workspaces : aliased AWA.Workspaces.Modules.Workspace_Module;
Mail : aliased AWA.Mail.Modules.Mail_Module;
Jobs : aliased AWA.Jobs.Modules.Job_Module;
Blogs : aliased AWA.Blogs.Modules.Blog_Module;
Storages : aliased AWA.Storages.Modules.Storage_Module;
Images : aliased AWA.Images.Modules.Image_Module;
Date_Converter : aliased ASF.Converters.Dates.Date_Converter;
Rel_Date_Converter : aliased AWA.Converters.Dates.Relative_Date_Converter;
Tests : aliased Util.Tests.Test_Suite;
function Suite return Util.Tests.Access_Test_Suite is
Ret : constant Util.Tests.Access_Test_Suite := Tests'Access;
begin
AWA.Modules.Tests.Add_Tests (Ret);
AWA.Events.Services.Tests.Add_Tests (Ret);
AWA.Mail.Clients.Tests.Add_Tests (Ret);
AWA.Mail.Modules.Tests.Add_Tests (Ret);
AWA.Users.Services.Tests.Add_Tests (Ret);
AWA.Users.Tests.Add_Tests (Ret);
AWA.Wikis.Parsers.Tests.Add_Tests (Ret);
AWA.Wikis.Writers.Tests.Add_Tests (Ret);
AWA.Helpers.Selectors.Tests.Add_Tests (Ret);
AWA.Jobs.Modules.Tests.Add_Tests (Ret);
AWA.Jobs.Services.Tests.Add_Tests (Ret);
AWA.Blogs.Services.Tests.Add_Tests (Ret);
AWA.Storages.Services.Tests.Add_Tests (Ret);
AWA.Images.Services.Tests.Add_Tests (Ret);
return Ret;
end Suite;
procedure Initialize (Props : in Util.Properties.Manager) is
begin
Initialize (null, Props, True);
end Initialize;
-- ------------------------------
-- Initialize the AWA test framework mockup.
-- ------------------------------
procedure Initialize (App : in AWA.Applications.Application_Access;
Props : in Util.Properties.Manager;
Add_Modules : in Boolean) is
use AWA.Applications;
begin
AWA.Tests.Initialize (App, Props, Add_Modules);
if Add_Modules then
declare
Application : constant Applications.Application_Access := AWA.Tests.Get_Application;
Ctx : AWA.Services.Contexts.Service_Context;
Users : constant AWA.Users.Modules.User_Module_Access := AWA.Testsuite.Users'Access;
begin
Ctx.Set_Context (Application, null);
Register (App => Application.all'Access,
Name => AWA.Users.Modules.NAME,
URI => "user",
Module => Users.all'Access);
Register (App => Application.all'Access,
Name => "mail",
URI => "mail",
Module => Mail'Access);
Register (App => Application.all'Access,
Name => "workspaces",
URI => "workspaces",
Module => Workspaces'Access);
Register (App => Application.all'Access,
Name => AWA.Storages.Modules.NAME,
URI => "storages",
Module => Storages'Access);
Register (App => Application.all'Access,
Name => AWA.Images.Modules.NAME,
URI => "images",
Module => Images'Access);
Register (App => Application.all'Access,
Name => AWA.Jobs.Modules.NAME,
URI => "jobs",
Module => Jobs'Access);
Register (App => Application.all'Access,
Name => AWA.Blogs.Modules.NAME,
URI => "blogs",
Module => Blogs'Access);
Application.Start;
if Props.Exists ("test.server") then
declare
WS : ASF.Server.Web.AWS_Container;
begin
Application.Add_Converter (Name => "dateConverter",
Converter => Date_Converter'Access);
Application.Add_Converter (Name => "smartDateConverter",
Converter => Rel_Date_Converter'Access);
WS.Register_Application ("/asfunit", Application.all'Access);
WS.Start;
delay 6000.0;
end;
end if;
ASF.Server.Tests.Set_Context (Application.all'Access);
end;
end if;
end Initialize;
end AWA.Testsuite;
|
-----------------------------------------------------------------------
-- Util testsuite - Util Testsuite
-- Copyright (C) 2009, 2010, 2011, 2012, 2013 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with AWA.Users.Services.Tests;
with AWA.Users.Tests;
with AWA.Blogs.Services.Tests;
with AWA.Wikis.Parsers.Tests;
with AWA.Wikis.Writers.Tests;
with AWA.Helpers.Selectors.Tests;
with AWA.Storages.Services.Tests;
with AWA.Events.Services.Tests;
with AWA.Mail.Clients.Tests;
with AWA.Mail.Modules.Tests;
with AWA.Images.Services.Tests;
with AWA.Votes.Modules.Tests;
with AWA.Questions.Services.Tests;
with AWA.Modules.Tests;
with ASF.Converters.Dates;
with AWA.Users.Modules;
with AWA.Mail.Modules;
with AWA.Blogs.Modules;
with AWA.Workspaces.Modules;
with AWA.Storages.Modules;
with AWA.Images.Modules;
with AWA.Questions.Modules;
with AWA.Votes.Modules;
with AWA.Converters.Dates;
with AWA.Tests;
with AWA.Services.Contexts;
with AWA.Jobs.Services.Tests;
with AWA.Jobs.Modules.Tests;
with ASF.Server.Web;
with ASF.Server.Tests;
package body AWA.Testsuite is
Users : aliased AWA.Users.Modules.User_Module;
Workspaces : aliased AWA.Workspaces.Modules.Workspace_Module;
Mail : aliased AWA.Mail.Modules.Mail_Module;
Jobs : aliased AWA.Jobs.Modules.Job_Module;
Blogs : aliased AWA.Blogs.Modules.Blog_Module;
Storages : aliased AWA.Storages.Modules.Storage_Module;
Images : aliased AWA.Images.Modules.Image_Module;
Questions : aliased AWA.Questions.Modules.Question_Module;
Votes : aliased AWA.Votes.Modules.Vote_Module;
Date_Converter : aliased ASF.Converters.Dates.Date_Converter;
Rel_Date_Converter : aliased AWA.Converters.Dates.Relative_Date_Converter;
Tests : aliased Util.Tests.Test_Suite;
function Suite return Util.Tests.Access_Test_Suite is
Ret : constant Util.Tests.Access_Test_Suite := Tests'Access;
begin
AWA.Modules.Tests.Add_Tests (Ret);
AWA.Events.Services.Tests.Add_Tests (Ret);
AWA.Mail.Clients.Tests.Add_Tests (Ret);
AWA.Mail.Modules.Tests.Add_Tests (Ret);
AWA.Users.Services.Tests.Add_Tests (Ret);
AWA.Users.Tests.Add_Tests (Ret);
AWA.Wikis.Parsers.Tests.Add_Tests (Ret);
AWA.Wikis.Writers.Tests.Add_Tests (Ret);
AWA.Helpers.Selectors.Tests.Add_Tests (Ret);
AWA.Jobs.Modules.Tests.Add_Tests (Ret);
AWA.Jobs.Services.Tests.Add_Tests (Ret);
AWA.Blogs.Services.Tests.Add_Tests (Ret);
AWA.Storages.Services.Tests.Add_Tests (Ret);
AWA.Images.Services.Tests.Add_Tests (Ret);
AWA.Votes.Modules.Tests.Add_Tests (Ret);
AWA.Questions.Services.Tests.Add_Tests (Ret);
return Ret;
end Suite;
procedure Initialize (Props : in Util.Properties.Manager) is
begin
Initialize (null, Props, True);
end Initialize;
-- ------------------------------
-- Initialize the AWA test framework mockup.
-- ------------------------------
procedure Initialize (App : in AWA.Applications.Application_Access;
Props : in Util.Properties.Manager;
Add_Modules : in Boolean) is
use AWA.Applications;
begin
AWA.Tests.Initialize (App, Props, Add_Modules);
if Add_Modules then
declare
Application : constant Applications.Application_Access := AWA.Tests.Get_Application;
Ctx : AWA.Services.Contexts.Service_Context;
Users : constant AWA.Users.Modules.User_Module_Access := AWA.Testsuite.Users'Access;
begin
Ctx.Set_Context (Application, null);
Register (App => Application.all'Access,
Name => AWA.Users.Modules.NAME,
URI => "user",
Module => Users.all'Access);
Register (App => Application.all'Access,
Name => "mail",
URI => "mail",
Module => Mail'Access);
Register (App => Application.all'Access,
Name => "workspaces",
URI => "workspaces",
Module => Workspaces'Access);
Register (App => Application.all'Access,
Name => AWA.Storages.Modules.NAME,
URI => "storages",
Module => Storages'Access);
Register (App => Application.all'Access,
Name => AWA.Images.Modules.NAME,
URI => "images",
Module => Images'Access);
Register (App => Application.all'Access,
Name => AWA.Jobs.Modules.NAME,
URI => "jobs",
Module => Jobs'Access);
Register (App => Application.all'Access,
Name => AWA.Votes.Modules.NAME,
URI => "votes",
Module => Votes'Access);
Register (App => Application.all'Access,
Name => AWA.Blogs.Modules.NAME,
URI => "blogs",
Module => Blogs'Access);
Register (App => Application.all'Access,
Name => AWA.Questions.Modules.NAME,
URI => "questions",
Module => Questions'Access);
Application.Start;
if Props.Exists ("test.server") then
declare
WS : ASF.Server.Web.AWS_Container;
begin
Application.Add_Converter (Name => "dateConverter",
Converter => Date_Converter'Access);
Application.Add_Converter (Name => "smartDateConverter",
Converter => Rel_Date_Converter'Access);
WS.Register_Application ("/asfunit", Application.all'Access);
WS.Start;
delay 6000.0;
end;
end if;
ASF.Server.Tests.Set_Context (Application.all'Access);
end;
end if;
end Initialize;
end AWA.Testsuite;
|
Add the votes and questions plugin unit tests
|
Add the votes and questions plugin unit tests
|
Ada
|
apache-2.0
|
tectronics/ada-awa,Letractively/ada-awa,tectronics/ada-awa,Letractively/ada-awa,tectronics/ada-awa,Letractively/ada-awa
|
13ccc71522c935b48f00e15e878a45bba47becec
|
src/util-events-timers.ads
|
src/util-events-timers.ads
|
-----------------------------------------------------------------------
-- util-events-timers -- Timer list management
-- Copyright (C) 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Real_Time;
private with Ada.Finalization;
private with Util.Concurrent.Counters;
-- == Timer Management ==
-- The <tt>Util.Events.Timers</tt> package provides a timer list that allows to have
-- operations called on regular basis when a deadline has expired. It is very close to
-- the <tt>Ada.Real_Time.Timing_Events</tt> package but it provides more flexibility
-- by allowing to have several timer lists that run independently. Unlike the GNAT
-- implementation, this timer list management does not use tasks at all. The timer list
-- can therefore be used in a mono-task environment by the main process task. Furthermore
-- you can control your own task priority by having your own task that uses the timer list.
--
-- The timer list is created by an instance of <tt>Timer_List</tt>:
--
-- Manager : Util.Events.Timers.Timer_List;
--
-- The timer list is protected against concurrent accesses so that timing events can be
-- setup by a task but the timer handler is executed by another task.
--
-- === Timer Creation ===
-- A timer handler is defined by implementing the <tt>Timer</tt> interface with the
-- <tt>Time_Handler</tt> procedure. A typical timer handler could be declared as follows:
--
-- type Timeout is new Timer with null record;
-- overriding procedure Time_Handler (T : in out Timeout);
--
-- My_Timeout : aliased Timeout;
--
-- The timer instance is represented by the <tt>Timer_Ref</tt> type that describes the handler
-- to be called as well as the deadline time. The timer instance is initialized as follows:
--
-- T : Util.Events.Timers.Timer_Ref;
-- Manager.Set_Timer (T, My_Timeout'Access, Ada.Real_Time.Seconds (1));
--
-- === Timer Main Loop ===
-- Because the implementation does not impose any execution model, the timer management must
-- be called regularly by some application's main loop. The <tt>Process</tt> procedure
-- executes the timer handler that have ellapsed and it returns the deadline to wait for the
-- next timer to execute.
--
-- Deadline : Ada.Real_Time.Time;
-- loop
-- ...
-- Manager.Process (Deadline);
-- delay until Deadline;
-- end loop;
--
package Util.Events.Timers is
type Timer_Ref is tagged private;
-- The timer interface that must be implemented by applications.
type Timer is limited interface;
type Timer_Access is access all Timer'Class;
-- The timer handler executed when the timer deadline has passed.
procedure Time_Handler (T : in out Timer;
Event : in out Timer_Ref'Class) is abstract;
-- Repeat the timer.
procedure Repeat (Event : in out Timer_Ref;
In_Time : in Ada.Real_Time.Time_Span);
-- Cancel the timer.
procedure Cancel (Event : in out Timer_Ref);
-- Check if the timer is ready to be executed.
function Is_Scheduled (Event : in Timer_Ref) return Boolean;
-- Returns the deadline time for the timer execution.
-- Returns Time'Last if the timer is not scheduled.
function Time_Of_Event (Event : in Timer_Ref) return Ada.Real_Time.Time;
type Timer_List is tagged limited private;
-- Set a timer to be called at the given time.
procedure Set_Timer (List : in out Timer_List;
Handler : in Timer_Access;
Event : in out Timer_Ref'Class;
At_Time : in Ada.Real_Time.Time);
-- Process the timer handlers that have passed the deadline and return the next
-- deadline. The <tt>Max_Count</tt> parameter allows to limit the number of timer handlers
-- that are called by operation. The default is not limited.
procedure Process (List : in out Timer_List;
Timeout : out Ada.Real_Time.Time;
Max_Count : in Natural := Natural'Last);
private
type Timer_Manager;
type Timer_Manager_Access is access all Timer_Manager;
type Timer_Node;
type Timer_Node_Access is access all Timer_Node;
type Timer_Ref is new Ada.Finalization.Controlled with record
Value : Timer_Node_Access;
end record;
overriding
procedure Adjust (Object : in out Timer_Ref);
overriding
procedure Finalize (Object : in out Timer_Ref);
type Timer_Node is limited record
Next : Timer_Node_Access;
Prev : Timer_Node_Access;
List : Timer_Manager_Access;
Counter : Util.Concurrent.Counters.Counter;
Handler : Timer_Access;
Deadline : Ada.Real_Time.Time;
end record;
protected type Timer_Manager is
-- Add a timer.
procedure Add (Timer : in Timer_Node_Access;
Deadline : in Ada.Real_Time.Time);
-- Cancel a timer.
procedure Cancel (Timer : in out Timer_Node_Access);
-- Find the next timer to be executed or return the next deadline.
procedure Find_Next (Deadline : out Ada.Real_Time.Time;
Timer : in out Timer_Ref);
private
List : Timer_Node_Access;
end Timer_Manager;
type Timer_List is new Ada.Finalization.Limited_Controlled with record
Manager : aliased Timer_Manager;
end record;
overriding
procedure Finalize (Object : in out Timer_List);
end Util.Events.Timers;
|
-----------------------------------------------------------------------
-- util-events-timers -- Timer list management
-- Copyright (C) 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Real_Time;
private with Ada.Finalization;
private with Util.Concurrent.Counters;
-- == Timer Management ==
-- The <tt>Util.Events.Timers</tt> package provides a timer list that allows to have
-- operations called on regular basis when a deadline has expired. It is very close to
-- the <tt>Ada.Real_Time.Timing_Events</tt> package but it provides more flexibility
-- by allowing to have several timer lists that run independently. Unlike the GNAT
-- implementation, this timer list management does not use tasks at all. The timer list
-- can therefore be used in a mono-task environment by the main process task. Furthermore
-- you can control your own task priority by having your own task that uses the timer list.
--
-- The timer list is created by an instance of <tt>Timer_List</tt>:
--
-- Manager : Util.Events.Timers.Timer_List;
--
-- The timer list is protected against concurrent accesses so that timing events can be
-- setup by a task but the timer handler is executed by another task.
--
-- === Timer Creation ===
-- A timer handler is defined by implementing the <tt>Timer</tt> interface with the
-- <tt>Time_Handler</tt> procedure. A typical timer handler could be declared as follows:
--
-- type Timeout is new Timer with null record;
-- overriding procedure Time_Handler (T : in out Timeout);
--
-- My_Timeout : aliased Timeout;
--
-- The timer instance is represented by the <tt>Timer_Ref</tt> type that describes the handler
-- to be called as well as the deadline time. The timer instance is initialized as follows:
--
-- T : Util.Events.Timers.Timer_Ref;
-- Manager.Set_Timer (T, My_Timeout'Access, Ada.Real_Time.Seconds (1));
--
-- === Timer Main Loop ===
-- Because the implementation does not impose any execution model, the timer management must
-- be called regularly by some application's main loop. The <tt>Process</tt> procedure
-- executes the timer handler that have ellapsed and it returns the deadline to wait for the
-- next timer to execute.
--
-- Deadline : Ada.Real_Time.Time;
-- loop
-- ...
-- Manager.Process (Deadline);
-- delay until Deadline;
-- end loop;
--
package Util.Events.Timers is
type Timer_Ref is tagged private;
-- The timer interface that must be implemented by applications.
type Timer is limited interface;
type Timer_Access is access all Timer'Class;
-- The timer handler executed when the timer deadline has passed.
procedure Time_Handler (T : in out Timer;
Event : in out Timer_Ref'Class) is abstract;
-- Repeat the timer.
procedure Repeat (Event : in out Timer_Ref;
In_Time : in Ada.Real_Time.Time_Span);
-- Cancel the timer.
procedure Cancel (Event : in out Timer_Ref);
-- Check if the timer is ready to be executed.
function Is_Scheduled (Event : in Timer_Ref) return Boolean;
-- Returns the deadline time for the timer execution.
-- Returns Time'Last if the timer is not scheduled.
function Time_Of_Event (Event : in Timer_Ref) return Ada.Real_Time.Time;
type Timer_List is tagged limited private;
-- Set a timer to be called at the given time.
procedure Set_Timer (List : in out Timer_List;
Handler : in Timer_Access;
Event : in out Timer_Ref'Class;
At_Time : in Ada.Real_Time.Time);
-- Process the timer handlers that have passed the deadline and return the next
-- deadline. The <tt>Max_Count</tt> parameter allows to limit the number of timer handlers
-- that are called by operation. The default is not limited.
procedure Process (List : in out Timer_List;
Timeout : out Ada.Real_Time.Time;
Max_Count : in Natural := Natural'Last);
private
type Timer_Manager;
type Timer_Manager_Access is access all Timer_Manager;
type Timer_Node;
type Timer_Node_Access is access all Timer_Node;
type Timer_Ref is new Ada.Finalization.Controlled with record
Value : Timer_Node_Access;
end record;
overriding
procedure Adjust (Object : in out Timer_Ref);
overriding
procedure Finalize (Object : in out Timer_Ref);
type Timer_Node is limited record
Next : Timer_Node_Access;
Prev : Timer_Node_Access;
List : Timer_Manager_Access;
Counter : Util.Concurrent.Counters.Counter := Util.Concurrent.Counters.ONE;
Handler : Timer_Access;
Deadline : Ada.Real_Time.Time;
end record;
protected type Timer_Manager is
-- Add a timer.
procedure Add (Timer : in Timer_Node_Access;
Deadline : in Ada.Real_Time.Time);
-- Cancel a timer.
procedure Cancel (Timer : in out Timer_Node_Access);
-- Find the next timer to be executed or return the next deadline.
procedure Find_Next (Deadline : out Ada.Real_Time.Time;
Timer : in out Timer_Ref);
private
List : Timer_Node_Access;
end Timer_Manager;
type Timer_List is new Ada.Finalization.Limited_Controlled with record
Manager : aliased Timer_Manager;
end record;
overriding
procedure Finalize (Object : in out Timer_List);
end Util.Events.Timers;
|
Initialize the Timer_Node counter to 1
|
Initialize the Timer_Node counter to 1
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
d4d734c17d094e22a182f1e4326540faa6ff88f5
|
src/util-streams-files.adb
|
src/util-streams-files.adb
|
-----------------------------------------------------------------------
-- Util.Streams.Files -- File Stream utilities
-- Copyright (C) 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.
-----------------------------------------------------------------------
package body Util.Streams.Files is
-- ------------------------------
-- Open the file and initialize the stream for reading or writing.
-- ------------------------------
procedure Open (Stream : in out File_Stream;
Mode : in Ada.Streams.Stream_IO.File_Mode;
Name : in String := "";
Form : in String := "") is
begin
Ada.Streams.Stream_IO.Open (Stream.File, Mode, Name, Form);
end Open;
-- ------------------------------
-- Create the file and initialize the stream for writing.
-- ------------------------------
procedure Create (Stream : in out File_Stream;
Mode : in Ada.Streams.Stream_IO.File_Mode;
Name : in String := "";
Form : in String := "") is
begin
Ada.Streams.Stream_IO.Create (Stream.File, Mode, Name, Form);
end Create;
-- ------------------------------
-- Close the stream.
-- ------------------------------
overriding
procedure Close (Stream : in out File_Stream) is
begin
Ada.Streams.Stream_IO.Close (Stream.File);
end Close;
-- ------------------------------
-- Write the buffer array to the output stream.
-- ------------------------------
overriding
procedure Write (Stream : in out File_Stream;
Buffer : in Ada.Streams.Stream_Element_Array) is
begin
Ada.Streams.Stream_IO.Write (Stream.File, Buffer);
end Write;
-- ------------------------------
-- Read into the buffer as many bytes as possible and return in
-- <b>last</b> the position of the last byte read.
-- ------------------------------
overriding
procedure Read (Stream : in out File_Stream;
Into : out Ada.Streams.Stream_Element_Array;
Last : out Ada.Streams.Stream_Element_Offset) is
begin
Ada.Streams.Stream_IO.Read (Stream.File, Into, Last);
end Read;
-- ------------------------------
-- Flush the stream and release the buffer.
-- ------------------------------
overriding
procedure Finalize (Object : in out File_Stream) is
begin
if Ada.Streams.Stream_IO.Is_Open (Object.File) then
Object.Close;
end if;
end Finalize;
end Util.Streams.Files;
|
-----------------------------------------------------------------------
-- util-streams-files -- File Stream utilities
-- Copyright (C) 2010, 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.
-----------------------------------------------------------------------
package body Util.Streams.Files is
-- ------------------------------
-- Open the file and initialize the stream for reading or writing.
-- ------------------------------
procedure Open (Stream : in out File_Stream;
Mode : in Ada.Streams.Stream_IO.File_Mode;
Name : in String := "";
Form : in String := "") is
begin
Ada.Streams.Stream_IO.Open (Stream.File, Mode, Name, Form);
end Open;
-- ------------------------------
-- Create the file and initialize the stream for writing.
-- ------------------------------
procedure Create (Stream : in out File_Stream;
Mode : in Ada.Streams.Stream_IO.File_Mode;
Name : in String := "";
Form : in String := "") is
begin
Ada.Streams.Stream_IO.Create (Stream.File, Mode, Name, Form);
end Create;
-- ------------------------------
-- Close the stream.
-- ------------------------------
overriding
procedure Close (Stream : in out File_Stream) is
begin
Ada.Streams.Stream_IO.Close (Stream.File);
end Close;
-- ------------------------------
-- Write the buffer array to the output stream.
-- ------------------------------
overriding
procedure Write (Stream : in out File_Stream;
Buffer : in Ada.Streams.Stream_Element_Array) is
begin
Ada.Streams.Stream_IO.Write (Stream.File, Buffer);
end Write;
-- ------------------------------
-- Read into the buffer as many bytes as possible and return in
-- <b>last</b> the position of the last byte read.
-- ------------------------------
overriding
procedure Read (Stream : in out File_Stream;
Into : out Ada.Streams.Stream_Element_Array;
Last : out Ada.Streams.Stream_Element_Offset) is
begin
Ada.Streams.Stream_IO.Read (Stream.File, Into, Last);
end Read;
-- ------------------------------
-- Flush the stream and release the buffer.
-- ------------------------------
overriding
procedure Finalize (Object : in out File_Stream) is
begin
if Ada.Streams.Stream_IO.Is_Open (Object.File) then
Object.Close;
end if;
end Finalize;
end Util.Streams.Files;
|
Update the header
|
Update the header
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
c38b98ff3de90ee249961b58554c4cf0b4098353
|
src/wiki-writers-builders.adb
|
src/wiki-writers-builders.adb
|
-----------------------------------------------------------------------
-- wiki-writers-builders -- Wiki writer to a string builder
-- Copyright (C) 2011, 2012, 2013, 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Characters.Conversions;
package body Wiki.Writers.Builders is
-- ------------------------------
-- Write the content to the string builder.
-- ------------------------------
overriding
procedure Write (Writer : in out Writer_Builder_Type;
Content : in Wide_Wide_String) is
begin
Wide_Wide_Builders.Append (Writer.Content, Content);
end Write;
-- ------------------------------
-- Write the content to the string builder.
-- ------------------------------
overriding
procedure Write (Writer : in out Writer_Builder_Type;
Content : in Unbounded_Wide_Wide_String) is
begin
Wide_Wide_Builders.Append (Writer.Content, To_Wide_Wide_String (Content));
end Write;
-- ------------------------------
-- Iterate over the buffer content calling the <tt>Process</tt> procedure with each
-- chunk.
-- ------------------------------
procedure Iterate (Source : in Writer_Builder_Type;
Process : not null access procedure (Chunk : in Wide_Wide_String)) is
begin
Wide_Wide_Builders.Iterate (Source.Content, Process);
end Iterate;
-- ------------------------------
-- Convert what was collected in the writer builder to a string and return it.
-- ------------------------------
function To_String (Source : in Writer_Builder_Type) return String is
Pos : Natural := 0;
Result : String (1 .. Wide_Wide_Builders.Length (Source.Content));
procedure Convert (Chunk : in Wide_Wide_String) is
begin
for I in Chunk'Range loop
Pos := Pos + 1;
Result (Pos) := Ada.Characters.Conversions.To_Character (Chunk (I));
end loop;
end Convert;
begin
Wide_Wide_Builders.Iterate (Source.Content, Convert'Access);
return Result;
end To_String;
-- ------------------------------
-- Write a single character to the string builder.
-- ------------------------------
procedure Write (Writer : in out Writer_Builder_Type;
Char : in Wide_Wide_Character) is
begin
Wide_Wide_Builders.Append (Writer.Content, Char);
end Write;
-- ------------------------------
-- Write a single character to the string builder.
-- ------------------------------
procedure Write_Char (Writer : in out Writer_Builder_Type;
Char : in Character) is
begin
Wide_Wide_Builders.Append (Writer.Content,
Ada.Characters.Conversions.To_Wide_Wide_Character (Char));
end Write_Char;
-- ------------------------------
-- Write the string to the string builder.
-- ------------------------------
procedure Write_String (Writer : in out Writer_Builder_Type;
Content : in String) is
begin
for I in Content'Range loop
Writer.Write_Char (Content (I));
end loop;
end Write_String;
type Unicode_Char is mod 2**31;
-- ------------------------------
-- Internal method to write a character on the response stream
-- and escape that character as necessary. Unlike 'Write_Char',
-- this operation does not closes the current XML entity.
-- ------------------------------
procedure Write_Escape (Stream : in out Html_Writer_Type'Class;
Char : in Wide_Wide_Character) is
Code : constant Unicode_Char := Wide_Wide_Character'Pos (Char);
begin
-- If "?" or over, no escaping is needed (this covers
-- most of the Latin alphabet)
if Code > 16#3F# or Code <= 16#20# then
Stream.Write (Char);
elsif Char = '<' then
Stream.Write ("<");
elsif Char = '>' then
Stream.Write (">");
elsif Char = '&' then
Stream.Write ("&");
else
Stream.Write (Char);
end if;
end Write_Escape;
-- ------------------------------
-- Close the current XML entity if an entity was started
-- ------------------------------
procedure Close_Current (Stream : in out Html_writer_Type'Class) is
begin
if Stream.Close_Start then
Stream.Write_Char ('>');
Stream.Close_Start := False;
end if;
end Close_Current;
procedure Write_Wide_Element (Writer : in out Html_writer_Type;
Name : in String;
Content : in Unbounded_Wide_Wide_String) is
begin
Writer.Start_Element (Name);
Writer.Write_Wide_Text (Content);
Writer.End_Element (Name);
end Write_Wide_Element;
procedure Write_Wide_Attribute (Writer : in out Html_writer_Type;
Name : in String;
Content : in Unbounded_Wide_Wide_String) is
Count : constant Natural := Length (Content);
begin
if Writer.Close_Start then
Writer.Write_Char (' ');
Writer.Write_String (Name);
Writer.Write_Char ('=');
Writer.Write_Char ('"');
for I in 1 .. Count loop
declare
C : constant Wide_Wide_Character := Element (Content, I);
begin
if C = '"' then
Writer.Write_String (""");
else
Writer.Write_Escape (C);
end if;
end;
end loop;
Writer.Write_Char ('"');
end if;
end Write_Wide_Attribute;
procedure Start_Element (Writer : in out Html_Writer_Type;
Name : in String) is
begin
Close_Current (Writer);
Writer.Write_Char ('<');
Writer.Write_String (Name);
Writer.Close_Start := True;
end Start_Element;
procedure End_Element (Writer : in out Html_Writer_Type;
Name : in String) is
begin
Close_Current (Writer);
Writer.Write_String ("</");
Writer.Write_String (Name);
Writer.Write_Char ('>');
end End_Element;
procedure Write_Wide_Text (Writer : in out Html_Writer_Type;
Content : in Unbounded_Wide_Wide_String) is
Count : constant Natural := Length (Content);
begin
Close_Current (Writer);
if Count > 0 then
for I in 1 .. Count loop
Html_Writer_Type'Class (Writer).Write_Escape (Element (Content, I));
end loop;
end if;
end Write_Wide_Text;
end Wiki.Writers.Builders;
|
-----------------------------------------------------------------------
-- wiki-writers-builders -- Wiki writer to a string builder
-- Copyright (C) 2011, 2012, 2013, 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Characters.Conversions;
package body Wiki.Writers.Builders is
-- ------------------------------
-- Write the content to the string builder.
-- ------------------------------
overriding
procedure Write (Writer : in out Writer_Builder_Type;
Content : in Wide_Wide_String) is
begin
Wide_Wide_Builders.Append (Writer.Content, Content);
end Write;
-- ------------------------------
-- Write the content to the string builder.
-- ------------------------------
overriding
procedure Write (Writer : in out Writer_Builder_Type;
Content : in Unbounded_Wide_Wide_String) is
begin
Wide_Wide_Builders.Append (Writer.Content, To_Wide_Wide_String (Content));
end Write;
-- ------------------------------
-- Iterate over the buffer content calling the <tt>Process</tt> procedure with each
-- chunk.
-- ------------------------------
procedure Iterate (Source : in Writer_Builder_Type;
Process : not null access procedure (Chunk : in Wide_Wide_String)) is
begin
Wide_Wide_Builders.Iterate (Source.Content, Process);
end Iterate;
-- ------------------------------
-- Convert what was collected in the writer builder to a string and return it.
-- ------------------------------
function To_String (Source : in Writer_Builder_Type) return String is
Pos : Natural := 0;
Result : String (1 .. Wide_Wide_Builders.Length (Source.Content));
procedure Convert (Chunk : in Wide_Wide_String) is
begin
for I in Chunk'Range loop
Pos := Pos + 1;
Result (Pos) := Ada.Characters.Conversions.To_Character (Chunk (I));
end loop;
end Convert;
begin
Wide_Wide_Builders.Iterate (Source.Content, Convert'Access);
return Result;
end To_String;
-- ------------------------------
-- Write a single character to the string builder.
-- ------------------------------
procedure Write (Writer : in out Writer_Builder_Type;
Char : in Wide_Wide_Character) is
begin
Wide_Wide_Builders.Append (Writer.Content, Char);
end Write;
-- ------------------------------
-- Write a single character to the string builder.
-- ------------------------------
procedure Write_Char (Writer : in out Writer_Builder_Type;
Char : in Character) is
begin
Wide_Wide_Builders.Append (Writer.Content,
Ada.Characters.Conversions.To_Wide_Wide_Character (Char));
end Write_Char;
-- ------------------------------
-- Write the string to the string builder.
-- ------------------------------
procedure Write_String (Writer : in out Writer_Builder_Type;
Content : in String) is
begin
for I in Content'Range loop
Writer.Write_Char (Content (I));
end loop;
end Write_String;
type Unicode_Char is mod 2**31;
-- ------------------------------
-- Internal method to write a character on the response stream
-- and escape that character as necessary. Unlike 'Write_Char',
-- this operation does not closes the current XML entity.
-- ------------------------------
procedure Write_Escape (Stream : in out Html_Writer_Type'Class;
Char : in Wide_Wide_Character) is
Code : constant Unicode_Char := Wide_Wide_Character'Pos (Char);
begin
-- If "?" or over, no escaping is needed (this covers
-- most of the Latin alphabet)
if Code > 16#3F# or Code <= 16#20# then
Stream.Write (Char);
elsif Char = '<' then
Stream.Write ("<");
elsif Char = '>' then
Stream.Write (">");
elsif Char = '&' then
Stream.Write ("&");
else
Stream.Write (Char);
end if;
end Write_Escape;
-- ------------------------------
-- Close the current XML entity if an entity was started
-- ------------------------------
procedure Close_Current (Stream : in out Html_writer_Type'Class) is
begin
if Stream.Close_Start then
Stream.Write_Char ('>');
Stream.Close_Start := False;
end if;
end Close_Current;
procedure Write_Wide_Element (Writer : in out Html_writer_Type;
Name : in String;
Content : in Unbounded_Wide_Wide_String) is
begin
Writer.Start_Element (Name);
Writer.Write_Wide_Text (Content);
Writer.End_Element (Name);
end Write_Wide_Element;
-- Write an XML attribute within an XML element.
-- The attribute value is escaped according to the XML escape rules.
procedure Write_Wide_Attribute (Writer : in out Html_Writer_Type;
Name : in String;
Content : in Wide_Wide_String) is
begin
if Writer.Close_Start then
Writer.Write_Char (' ');
Writer.Write_String (Name);
Writer.Write_Char ('=');
Writer.Write_Char ('"');
for I in Content'Range loop
declare
C : constant Wide_Wide_Character := Content (I);
begin
if C = '"' then
Writer.Write_String (""");
else
Writer.Write_Escape (C);
end if;
end;
end loop;
Writer.Write_Char ('"');
end if;
end Write_Wide_Attribute;
procedure Write_Wide_Attribute (Writer : in out Html_Writer_Type;
Name : in String;
Content : in Unbounded_Wide_Wide_String) is
Count : constant Natural := Length (Content);
begin
if Writer.Close_Start then
Writer.Write_Char (' ');
Writer.Write_String (Name);
Writer.Write_Char ('=');
Writer.Write_Char ('"');
for I in 1 .. Count loop
declare
C : constant Wide_Wide_Character := Element (Content, I);
begin
if C = '"' then
Writer.Write_String (""");
else
Writer.Write_Escape (C);
end if;
end;
end loop;
Writer.Write_Char ('"');
end if;
end Write_Wide_Attribute;
procedure Start_Element (Writer : in out Html_Writer_Type;
Name : in String) is
begin
Close_Current (Writer);
Writer.Write_Char ('<');
Writer.Write_String (Name);
Writer.Close_Start := True;
end Start_Element;
procedure End_Element (Writer : in out Html_Writer_Type;
Name : in String) is
begin
Close_Current (Writer);
Writer.Write_String ("</");
Writer.Write_String (Name);
Writer.Write_Char ('>');
end End_Element;
procedure Write_Wide_Text (Writer : in out Html_Writer_Type;
Content : in Unbounded_Wide_Wide_String) is
Count : constant Natural := Length (Content);
begin
Close_Current (Writer);
if Count > 0 then
for I in 1 .. Count loop
Html_Writer_Type'Class (Writer).Write_Escape (Element (Content, I));
end loop;
end if;
end Write_Wide_Text;
end Wiki.Writers.Builders;
|
Implement the Write_Wide_Attribute procedure
|
Implement the Write_Wide_Attribute procedure
|
Ada
|
apache-2.0
|
stcarrez/ada-wiki,stcarrez/ada-wiki
|
2206c849b0a3652ebeaa92e2eba48fafed09c5f4
|
awa/src/awa-applications.adb
|
awa/src/awa-applications.adb
|
-----------------------------------------------------------------------
-- awa -- Ada Web Application
-- Copyright (C) 2009, 2010, 2011, 2012, 2013, 2014, 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.IO_Exceptions;
with ADO.Drivers;
with EL.Contexts.Default;
with Util.Files;
with Util.Log.Loggers;
with ASF.Server;
with ASF.Servlets;
with AWA.Services.Contexts;
with AWA.Components.Factory;
with AWA.Applications.Factory;
with AWA.Applications.Configs;
with AWA.Helpers.Selectors;
with AWA.Permissions.Services;
with AWA.Permissions.Beans;
package body AWA.Applications is
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("AWA.Applications");
-- ------------------------------
-- Initialize the application
-- ------------------------------
overriding
procedure Initialize (App : in out Application;
Conf : in ASF.Applications.Config;
Factory : in out ASF.Applications.Main.Application_Factory'Class) is
Ctx : AWA.Services.Contexts.Service_Context;
begin
Log.Info ("Initializing application");
Ctx.Set_Context (App'Unchecked_Access, null);
AWA.Applications.Factory.Set_Application (Factory, App'Unchecked_Access);
ASF.Applications.Main.Application (App).Initialize (Conf, Factory);
-- Load the application configuration before any module.
Application'Class (App).Load_Configuration (App.Get_Config (P_Config_File.P));
-- Register the application modules and load their configuration.
Application'Class (App).Initialize_Modules;
-- Load the plugin application configuration after the module are configured.
Application'Class (App).Load_Configuration (App.Get_Config (P_Plugin_Config_File.P));
end Initialize;
-- ------------------------------
-- Initialize the application configuration properties. Properties defined in <b>Conf</b>
-- are expanded by using the EL expression resolver.
-- ------------------------------
overriding
procedure Initialize_Config (App : in out Application;
Conf : in out ASF.Applications.Config) is
begin
Log.Info ("Initializing configuration");
if Conf.Get ("app.modules.dir", "") = "" then
Conf.Set ("app.modules.dir", "#{fn:composePath(app_search_dirs,'config')}");
end if;
if Conf.Get ("bundle.dir", "") = "" then
Conf.Set ("bundle.dir", "#{fn:composePath(app_search_dirs,'bundles')}");
end if;
if Conf.Get ("ado.queries.paths", "") = "" then
Conf.Set ("ado.queries.paths", "#{fn:composePath(app_search_dirs,'db')}");
end if;
ASF.Applications.Main.Application (App).Initialize_Config (Conf);
ADO.Drivers.Initialize (Conf);
App.DB_Factory.Create (Conf.Get ("database"));
App.Events.Initialize (App'Unchecked_Access);
AWA.Modules.Initialize (App.Modules, Conf);
App.Register_Class ("AWA.Helpers.Selectors.Select_List_Bean",
AWA.Helpers.Selectors.Create_Select_List_Bean'Access);
App.Register_Class ("AWA.Permissions.Beans.Permission_Bean",
AWA.Permissions.Beans.Create_Permission_Bean'Access);
end Initialize_Config;
-- ------------------------------
-- Initialize the servlets provided by the application.
-- This procedure is called by <b>Initialize</b>.
-- It should register the application servlets.
-- ------------------------------
overriding
procedure Initialize_Servlets (App : in out Application) is
begin
Log.Info ("Initializing application servlets");
ASF.Applications.Main.Application (App).Initialize_Servlets;
end Initialize_Servlets;
-- ------------------------------
-- Initialize the filters provided by the application.
-- This procedure is called by <b>Initialize</b>.
-- It should register the application filters.
-- ------------------------------
overriding
procedure Initialize_Filters (App : in out Application) is
begin
Log.Info ("Initializing application filters");
ASF.Applications.Main.Application (App).Initialize_Filters;
end Initialize_Filters;
-- ------------------------------
-- Initialize the ASF components provided by the application.
-- This procedure is called by <b>Initialize</b>.
-- It should register the component factories used by the application.
-- ------------------------------
overriding
procedure Initialize_Components (App : in out Application) is
procedure Register_Functions is
new ASF.Applications.Main.Register_Functions (AWA.Permissions.Services.Set_Functions);
begin
Log.Info ("Initializing application components");
ASF.Applications.Main.Application (App).Initialize_Components;
App.Add_Components (AWA.Components.Factory.Definition);
Register_Functions (App);
end Initialize_Components;
-- ------------------------------
-- Read the application configuration file <b>awa.xml</b>. This is called after the servlets
-- and filters have been registered in the application but before the module registration.
-- ------------------------------
procedure Load_Configuration (App : in out Application;
Files : in String) is
procedure Load_Config (File : in String;
Done : out Boolean);
Paths : constant String := App.Get_Config (P_Module_Dir.P);
Ctx : aliased EL.Contexts.Default.Default_Context;
procedure Load_Config (File : in String;
Done : out Boolean) is
Path : constant String := Util.Files.Find_File_Path (File, Paths);
begin
Done := False;
AWA.Applications.Configs.Read_Configuration (App, Path, Ctx'Unchecked_Access);
exception
when Ada.IO_Exceptions.Name_Error =>
Log.Warn ("Application configuration file '{0}' does not exist", Path);
end Load_Config;
begin
Util.Files.Iterate_Path (Files, Load_Config'Access);
end Load_Configuration;
-- ------------------------------
-- Initialize the AWA modules provided by the application.
-- This procedure is called by <b>Initialize</b>.
-- It should register the modules used by the application.
-- ------------------------------
procedure Initialize_Modules (App : in out Application) is
begin
null;
end Initialize_Modules;
-- ------------------------------
-- Start the application. This is called by the server container when the server is started.
-- ------------------------------
overriding
procedure Start (App : in out Application) is
begin
-- Start the event service.
App.Events.Start;
-- Start the application.
ASF.Applications.Main.Application (App).Start;
-- Dump the route and filters to help in configuration issues.
App.Dump_Routes (Util.Log.INFO_LEVEL);
end Start;
-- ------------------------------
-- Register the module in the application
-- ------------------------------
procedure Register (App : in Application_Access;
Module : access AWA.Modules.Module'Class;
Name : in String;
URI : in String := "") is
begin
App.Register (Module.all'Unchecked_Access, Name, URI);
end Register;
-- ------------------------------
-- Get the database connection for reading
-- ------------------------------
function Get_Session (App : Application)
return ADO.Sessions.Session is
begin
return App.DB_Factory.Get_Session;
end Get_Session;
-- ------------------------------
-- Get the database connection for writing
-- ------------------------------
function Get_Master_Session (App : Application)
return ADO.Sessions.Master_Session is
begin
return App.DB_Factory.Get_Master_Session;
end Get_Master_Session;
-- ------------------------------
-- Find the module with the given name
-- ------------------------------
function Find_Module (App : in Application;
Name : in String) return AWA.Modules.Module_Access is
begin
return AWA.Modules.Find_By_Name (App.Modules, Name);
end Find_Module;
-- ------------------------------
-- Register the module in the application
-- ------------------------------
procedure Register (App : in out Application;
Module : in AWA.Modules.Module_Access;
Name : in String;
URI : in String := "") is
begin
AWA.Modules.Register (App.Modules'Unchecked_Access, App'Unchecked_Access, Module, Name, URI);
end Register;
-- ------------------------------
-- Send the event in the application event queues.
-- ------------------------------
procedure Send_Event (App : in Application;
Event : in AWA.Events.Module_Event'Class) is
begin
App.Events.Send (Event);
end Send_Event;
-- ------------------------------
-- Execute the <tt>Process</tt> procedure with the event manager used by the application.
-- ------------------------------
procedure Do_Event_Manager (App : in out Application;
Process : access procedure
(Events : in out AWA.Events.Services.Event_Manager)) is
begin
Process (App.Events);
end Do_Event_Manager;
-- ------------------------------
-- Initialize the parser represented by <b>Parser</b> to recognize the configuration
-- that are specific to the plugins that have been registered so far.
-- ------------------------------
procedure Initialize_Parser (App : in out Application'Class;
Parser : in out Util.Serialize.IO.Parser'Class) is
procedure Process (Module : in out AWA.Modules.Module'Class);
procedure Process (Module : in out AWA.Modules.Module'Class) is
begin
Module.Initialize_Parser (Parser);
end Process;
begin
AWA.Modules.Iterate (App.Modules, Process'Access);
end Initialize_Parser;
-- ------------------------------
-- Get the current application from the servlet context or service context.
-- ------------------------------
function Current return Application_Access is
use type AWA.Services.Contexts.Service_Context_Access;
Ctx : constant AWA.Services.Contexts.Service_Context_Access := AWA.Services.Contexts.Current;
begin
if Ctx /= null then
return Ctx.Get_Application;
end if;
-- If there is no service context, look in the servlet current context.
declare
use type ASF.Servlets.Servlet_Registry_Access;
Ctx : constant ASF.Servlets.Servlet_Registry_Access := ASF.Server.Current;
begin
if Ctx = null then
Log.Warn ("There is no service context");
return null;
end if;
if not (Ctx.all in AWA.Applications.Application'Class) then
Log.Warn ("The servlet context is not an application");
return null;
end if;
return AWA.Applications.Application'Class (Ctx.all)'Access;
end;
end Current;
end AWA.Applications;
|
-----------------------------------------------------------------------
-- awa -- Ada Web Application
-- Copyright (C) 2009, 2010, 2011, 2012, 2013, 2014, 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.IO_Exceptions;
with ADO.Drivers;
with EL.Contexts.Default;
with Util.Files;
with Util.Log.Loggers;
with ASF.Server;
with ASF.Servlets;
with AWA.Services.Contexts;
with AWA.Components.Factory;
with AWA.Applications.Factory;
with AWA.Applications.Configs;
with AWA.Helpers.Selectors;
with AWA.Permissions.Services;
with AWA.Permissions.Beans;
package body AWA.Applications is
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("AWA.Applications");
-- ------------------------------
-- Initialize the application
-- ------------------------------
overriding
procedure Initialize (App : in out Application;
Conf : in ASF.Applications.Config;
Factory : in out ASF.Applications.Main.Application_Factory'Class) is
Ctx : AWA.Services.Contexts.Service_Context;
begin
Log.Info ("Initializing application");
Ctx.Set_Context (App'Unchecked_Access, null);
AWA.Applications.Factory.Set_Application (Factory, App'Unchecked_Access);
ASF.Applications.Main.Application (App).Initialize (Conf, Factory);
-- Load the application configuration before any module.
Application'Class (App).Load_Configuration (App.Get_Config (P_Config_File.P));
-- Register the application modules and load their configuration.
Application'Class (App).Initialize_Modules;
-- Load the plugin application configuration after the module are configured.
Application'Class (App).Load_Configuration (App.Get_Config (P_Plugin_Config_File.P));
end Initialize;
-- ------------------------------
-- Initialize the application configuration properties. Properties defined in <b>Conf</b>
-- are expanded by using the EL expression resolver.
-- ------------------------------
overriding
procedure Initialize_Config (App : in out Application;
Conf : in out ASF.Applications.Config) is
begin
Log.Info ("Initializing configuration");
if Conf.Get ("app.modules.dir", "") = "" then
Conf.Set ("app.modules.dir", "#{fn:composePath(app_search_dirs,'config')}");
end if;
if Conf.Get ("bundle.dir", "") = "" then
Conf.Set ("bundle.dir", "#{fn:composePath(app_search_dirs,'bundles')}");
end if;
if Conf.Get ("ado.queries.paths", "") = "" then
Conf.Set ("ado.queries.paths", "#{fn:composePath(app_search_dirs,'db')}");
end if;
ASF.Applications.Main.Application (App).Initialize_Config (Conf);
ADO.Drivers.Initialize (Conf);
App.DB_Factory.Create (Conf.Get ("database"));
App.Events.Initialize (App'Unchecked_Access);
AWA.Modules.Initialize (App.Modules, Conf);
App.Register_Class ("AWA.Helpers.Selectors.Select_List_Bean",
AWA.Helpers.Selectors.Create_Select_List_Bean'Access);
App.Register_Class ("AWA.Permissions.Beans.Permission_Bean",
AWA.Permissions.Beans.Create_Permission_Bean'Access);
end Initialize_Config;
-- ------------------------------
-- Initialize the servlets provided by the application.
-- This procedure is called by <b>Initialize</b>.
-- It should register the application servlets.
-- ------------------------------
overriding
procedure Initialize_Servlets (App : in out Application) is
begin
Log.Info ("Initializing application servlets");
ASF.Applications.Main.Application (App).Initialize_Servlets;
end Initialize_Servlets;
-- ------------------------------
-- Initialize the filters provided by the application.
-- This procedure is called by <b>Initialize</b>.
-- It should register the application filters.
-- ------------------------------
overriding
procedure Initialize_Filters (App : in out Application) is
begin
Log.Info ("Initializing application filters");
ASF.Applications.Main.Application (App).Initialize_Filters;
end Initialize_Filters;
-- ------------------------------
-- Initialize the ASF components provided by the application.
-- This procedure is called by <b>Initialize</b>.
-- It should register the component factories used by the application.
-- ------------------------------
overriding
procedure Initialize_Components (App : in out Application) is
procedure Register_Functions is
new ASF.Applications.Main.Register_Functions (AWA.Permissions.Services.Set_Functions);
begin
Log.Info ("Initializing application components");
ASF.Applications.Main.Application (App).Initialize_Components;
App.Add_Components (AWA.Components.Factory.Definition);
Register_Functions (App);
end Initialize_Components;
-- ------------------------------
-- Read the application configuration file <b>awa.xml</b>. This is called after the servlets
-- and filters have been registered in the application but before the module registration.
-- ------------------------------
procedure Load_Configuration (App : in out Application;
Files : in String) is
procedure Load_Config (File : in String;
Done : out Boolean);
Paths : constant String := App.Get_Config (P_Module_Dir.P);
Ctx : aliased EL.Contexts.Default.Default_Context;
procedure Load_Config (File : in String;
Done : out Boolean) is
Path : constant String := Util.Files.Find_File_Path (File, Paths);
begin
Done := False;
AWA.Applications.Configs.Read_Configuration (App, Path, Ctx'Unchecked_Access, True);
exception
when Ada.IO_Exceptions.Name_Error =>
Log.Warn ("Application configuration file '{0}' does not exist", Path);
end Load_Config;
begin
Util.Files.Iterate_Path (Files, Load_Config'Access);
end Load_Configuration;
-- ------------------------------
-- Initialize the AWA modules provided by the application.
-- This procedure is called by <b>Initialize</b>.
-- It should register the modules used by the application.
-- ------------------------------
procedure Initialize_Modules (App : in out Application) is
begin
null;
end Initialize_Modules;
-- ------------------------------
-- Start the application. This is called by the server container when the server is started.
-- ------------------------------
overriding
procedure Start (App : in out Application) is
begin
-- Start the event service.
App.Events.Start;
-- Start the application.
ASF.Applications.Main.Application (App).Start;
-- Dump the route and filters to help in configuration issues.
App.Dump_Routes (Util.Log.INFO_LEVEL);
end Start;
-- ------------------------------
-- Register the module in the application
-- ------------------------------
procedure Register (App : in Application_Access;
Module : access AWA.Modules.Module'Class;
Name : in String;
URI : in String := "") is
begin
App.Register (Module.all'Unchecked_Access, Name, URI);
end Register;
-- ------------------------------
-- Get the database connection for reading
-- ------------------------------
function Get_Session (App : Application)
return ADO.Sessions.Session is
begin
return App.DB_Factory.Get_Session;
end Get_Session;
-- ------------------------------
-- Get the database connection for writing
-- ------------------------------
function Get_Master_Session (App : Application)
return ADO.Sessions.Master_Session is
begin
return App.DB_Factory.Get_Master_Session;
end Get_Master_Session;
-- ------------------------------
-- Find the module with the given name
-- ------------------------------
function Find_Module (App : in Application;
Name : in String) return AWA.Modules.Module_Access is
begin
return AWA.Modules.Find_By_Name (App.Modules, Name);
end Find_Module;
-- ------------------------------
-- Register the module in the application
-- ------------------------------
procedure Register (App : in out Application;
Module : in AWA.Modules.Module_Access;
Name : in String;
URI : in String := "") is
begin
AWA.Modules.Register (App.Modules'Unchecked_Access, App'Unchecked_Access, Module, Name, URI);
end Register;
-- ------------------------------
-- Send the event in the application event queues.
-- ------------------------------
procedure Send_Event (App : in Application;
Event : in AWA.Events.Module_Event'Class) is
begin
App.Events.Send (Event);
end Send_Event;
-- ------------------------------
-- Execute the <tt>Process</tt> procedure with the event manager used by the application.
-- ------------------------------
procedure Do_Event_Manager (App : in out Application;
Process : access procedure
(Events : in out AWA.Events.Services.Event_Manager)) is
begin
Process (App.Events);
end Do_Event_Manager;
-- ------------------------------
-- Initialize the parser represented by <b>Parser</b> to recognize the configuration
-- that are specific to the plugins that have been registered so far.
-- ------------------------------
procedure Initialize_Parser (App : in out Application'Class;
Parser : in out Util.Serialize.IO.Parser'Class) is
procedure Process (Module : in out AWA.Modules.Module'Class);
procedure Process (Module : in out AWA.Modules.Module'Class) is
begin
Module.Initialize_Parser (Parser);
end Process;
begin
AWA.Modules.Iterate (App.Modules, Process'Access);
end Initialize_Parser;
-- ------------------------------
-- Get the current application from the servlet context or service context.
-- ------------------------------
function Current return Application_Access is
use type AWA.Services.Contexts.Service_Context_Access;
Ctx : constant AWA.Services.Contexts.Service_Context_Access := AWA.Services.Contexts.Current;
begin
if Ctx /= null then
return Ctx.Get_Application;
end if;
-- If there is no service context, look in the servlet current context.
declare
use type ASF.Servlets.Servlet_Registry_Access;
Ctx : constant ASF.Servlets.Servlet_Registry_Access := ASF.Server.Current;
begin
if Ctx = null then
Log.Warn ("There is no service context");
return null;
end if;
if not (Ctx.all in AWA.Applications.Application'Class) then
Log.Warn ("The servlet context is not an application");
return null;
end if;
return AWA.Applications.Application'Class (Ctx.all)'Access;
end;
end Current;
end AWA.Applications;
|
Load the configuration files and allow to override the <context-param>
|
Load the configuration files and allow to override the <context-param>
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
715a511ced02c36852d38136fb539684990d3502
|
src/security-policies-roles.adb
|
src/security-policies-roles.adb
|
-----------------------------------------------------------------------
-- security-policies-roles -- Role based policies
-- Copyright (C) 2010, 2011, 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Log.Loggers;
with Util.Serialize.Mappers.Record_Mapper;
with Util.Strings.Tokenizers;
with Security.Controllers;
with Security.Controllers.Roles;
package body Security.Policies.Roles is
use Util.Log;
-- The logger
Log : constant Loggers.Logger := Loggers.Create ("Security.Policies.Roles");
-- ------------------------------
-- Set the roles which are assigned to the user in the security context.
-- The role policy will use these roles to verify a permission.
-- ------------------------------
procedure Set_Role_Context (Context : in out Security.Contexts.Security_Context'Class;
Roles : in Role_Map) is
Policy : constant Security.Policies.Policy_Access := Context.Get_Policy (NAME);
Data : Role_Policy_Context_Access;
begin
if Policy = null then
Log.Error ("There is no security policy: " & NAME);
end if;
Data := new Role_Policy_Context;
Data.Roles := Roles;
Context.Set_Policy_Context (Policy, Data.all'Access);
end Set_Role_Context;
-- ------------------------------
-- Set the roles which are assigned to the user in the security context.
-- The role policy will use these roles to verify a permission.
-- ------------------------------
procedure Set_Role_Context (Context : in out Security.Contexts.Security_Context'Class;
Roles : in String) is
Policy : constant Security.Policies.Policy_Access := Context.Get_Policy (NAME);
Data : Role_Policy_Context_Access;
Map : Role_Map;
begin
if Policy = null then
Log.Error ("There is no security policy: " & NAME);
end if;
Role_Policy'Class (Policy.all).Set_Roles (Roles, Map);
Data := new Role_Policy_Context;
Data.Roles := Map;
Context.Set_Policy_Context (Policy, Data.all'Access);
end Set_Role_Context;
-- ------------------------------
-- Get the policy name.
-- ------------------------------
overriding
function Get_Name (From : in Role_Policy) return String is
pragma Unreferenced (From);
begin
return NAME;
end Get_Name;
-- ------------------------------
-- Get the role name.
-- ------------------------------
function Get_Role_Name (Manager : in Role_Policy;
Role : in Role_Type) return String is
use type Ada.Strings.Unbounded.String_Access;
begin
if Manager.Names (Role) = null then
return "";
else
return Manager.Names (Role).all;
end if;
end Get_Role_Name;
-- ------------------------------
-- Find the role type associated with the role name identified by <b>Name</b>.
-- Raises <b>Invalid_Name</b> if there is no role type.
-- ------------------------------
function Find_Role (Manager : in Role_Policy;
Name : in String) return Role_Type is
use type Ada.Strings.Unbounded.String_Access;
begin
Log.Debug ("Searching role {0}", Name);
for I in Role_Type'First .. Manager.Next_Role loop
exit when Manager.Names (I) = null;
if Name = Manager.Names (I).all then
return I;
end if;
end loop;
Log.Debug ("Role {0} not found", Name);
raise Invalid_Name;
end Find_Role;
-- ------------------------------
-- Create a role
-- ------------------------------
procedure Create_Role (Manager : in out Role_Policy;
Name : in String;
Role : out Role_Type) is
begin
Role := Manager.Next_Role;
Log.Info ("Role {0} is {1}", Name, Role_Type'Image (Role));
if Manager.Next_Role = Role_Type'Last then
Log.Error ("Too many roles allocated. Number of roles is {0}",
Role_Type'Image (Role_Type'Last));
else
Manager.Next_Role := Manager.Next_Role + 1;
end if;
Manager.Names (Role) := new String '(Name);
end Create_Role;
-- ------------------------------
-- Get or build a permission type for the given name.
-- ------------------------------
procedure Add_Role_Type (Manager : in out Role_Policy;
Name : in String;
Result : out Role_Type) is
begin
Result := Manager.Find_Role (Name);
exception
when Invalid_Name =>
Manager.Create_Role (Name, Result);
end Add_Role_Type;
-- ------------------------------
-- Set the roles specified in the <tt>Roles</tt> parameter. Each role is represented by
-- its name and multiple roles are separated by ','.
-- Raises Invalid_Name if a role was not found.
-- ------------------------------
procedure Set_Roles (Manager : in Role_Policy;
Roles : in String;
Into : out Role_Map) is
procedure Process (Role : in String;
Done : out Boolean);
procedure Process (Role : in String;
Done : out Boolean) is
begin
Into (Manager.Find_Role (Role)) := True;
Done := False;
end Process;
begin
Into := (others => False);
Util.Strings.Tokenizers.Iterate_Tokens (Content => Roles,
Pattern => ",",
Process => Process'Access,
Going => Ada.Strings.Forward);
end Set_Roles;
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
use Security.Controllers.Roles;
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 : 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.
-- ------------------------------
procedure Prepare_Config (Policy : in out Role_Policy;
Reader : in out Util.Serialize.IO.XML.Parser) is
Config : Controller_Config_Access := new Controller_Config;
begin
Reader.Add_Mapping ("policy-rules", Mapper'Access);
Reader.Add_Mapping ("module", Mapper'Access);
Config.Manager := Policy'Unchecked_Access;
Config_Mapper.Set_Context (Reader, Config);
end Prepare_Config;
-- ------------------------------
-- Finalize the policy manager.
-- ------------------------------
overriding
procedure Finalize (Policy : in out Role_Policy) is
use type Ada.Strings.Unbounded.String_Access;
begin
for I in Policy.Names'Range loop
exit when Policy.Names (I) = null;
Ada.Strings.Unbounded.Free (Policy.Names (I));
end loop;
end Finalize;
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.Policies.Roles;
|
-----------------------------------------------------------------------
-- security-policies-roles -- Role based policies
-- Copyright (C) 2010, 2011, 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Log.Loggers;
with Util.Serialize.Mappers.Record_Mapper;
with Util.Strings.Tokenizers;
with Security.Controllers;
with Security.Controllers.Roles;
package body Security.Policies.Roles is
use Util.Log;
-- The logger
Log : constant Loggers.Logger := Loggers.Create ("Security.Policies.Roles");
-- ------------------------------
-- Set the roles which are assigned to the user in the security context.
-- The role policy will use these roles to verify a permission.
-- ------------------------------
procedure Set_Role_Context (Context : in out Security.Contexts.Security_Context'Class;
Roles : in Role_Map) is
Policy : constant Security.Policies.Policy_Access := Context.Get_Policy (NAME);
Data : Role_Policy_Context_Access;
begin
if Policy = null then
Log.Error ("There is no security policy: " & NAME);
end if;
Data := new Role_Policy_Context;
Data.Roles := Roles;
Context.Set_Policy_Context (Policy, Data.all'Access);
end Set_Role_Context;
-- ------------------------------
-- Set the roles which are assigned to the user in the security context.
-- The role policy will use these roles to verify a permission.
-- ------------------------------
procedure Set_Role_Context (Context : in out Security.Contexts.Security_Context'Class;
Roles : in String) is
Policy : constant Security.Policies.Policy_Access := Context.Get_Policy (NAME);
Data : Role_Policy_Context_Access;
Map : Role_Map;
begin
if Policy = null then
Log.Error ("There is no security policy: " & NAME);
end if;
Role_Policy'Class (Policy.all).Set_Roles (Roles, Map);
Data := new Role_Policy_Context;
Data.Roles := Map;
Context.Set_Policy_Context (Policy, Data.all'Access);
end Set_Role_Context;
-- ------------------------------
-- Get the policy name.
-- ------------------------------
overriding
function Get_Name (From : in Role_Policy) return String is
pragma Unreferenced (From);
begin
return NAME;
end Get_Name;
-- ------------------------------
-- Get the role name.
-- ------------------------------
function Get_Role_Name (Manager : in Role_Policy;
Role : in Role_Type) return String is
use type Ada.Strings.Unbounded.String_Access;
begin
if Manager.Names (Role) = null then
return "";
else
return Manager.Names (Role).all;
end if;
end Get_Role_Name;
-- ------------------------------
-- Find the role type associated with the role name identified by <b>Name</b>.
-- Raises <b>Invalid_Name</b> if there is no role type.
-- ------------------------------
function Find_Role (Manager : in Role_Policy;
Name : in String) return Role_Type is
use type Ada.Strings.Unbounded.String_Access;
begin
Log.Debug ("Searching role {0}", Name);
for I in Role_Type'First .. Manager.Next_Role loop
exit when Manager.Names (I) = null;
if Name = Manager.Names (I).all then
return I;
end if;
end loop;
Log.Debug ("Role {0} not found", Name);
raise Invalid_Name;
end Find_Role;
-- ------------------------------
-- Create a role
-- ------------------------------
procedure Create_Role (Manager : in out Role_Policy;
Name : in String;
Role : out Role_Type) is
begin
Role := Manager.Next_Role;
Log.Info ("Role {0} is {1}", Name, Role_Type'Image (Role));
if Manager.Next_Role = Role_Type'Last then
Log.Error ("Too many roles allocated. Number of roles is {0}",
Role_Type'Image (Role_Type'Last));
else
Manager.Next_Role := Manager.Next_Role + 1;
end if;
Manager.Names (Role) := new String '(Name);
end Create_Role;
-- ------------------------------
-- Get or build a permission type for the given name.
-- ------------------------------
procedure Add_Role_Type (Manager : in out Role_Policy;
Name : in String;
Result : out Role_Type) is
begin
Result := Manager.Find_Role (Name);
exception
when Invalid_Name =>
Manager.Create_Role (Name, Result);
end Add_Role_Type;
-- ------------------------------
-- Set the roles specified in the <tt>Roles</tt> parameter. Each role is represented by
-- its name and multiple roles are separated by ','.
-- Raises Invalid_Name if a role was not found.
-- ------------------------------
procedure Set_Roles (Manager : in Role_Policy;
Roles : in String;
Into : out Role_Map) is
procedure Process (Role : in String;
Done : out Boolean);
procedure Process (Role : in String;
Done : out Boolean) is
begin
Into (Manager.Find_Role (Role)) := True;
Done := False;
end Process;
begin
Into := (others => False);
Util.Strings.Tokenizers.Iterate_Tokens (Content => Roles,
Pattern => ",",
Process => Process'Access,
Going => Ada.Strings.Forward);
end Set_Roles;
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
use Security.Controllers.Roles;
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 : 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.
-- ------------------------------
procedure Prepare_Config (Policy : in out Role_Policy;
Reader : in out Util.Serialize.IO.XML.Parser) is
Config : Controller_Config_Access := new Controller_Config;
begin
Reader.Add_Mapping ("policy-rules", Mapper'Access);
Reader.Add_Mapping ("module", Mapper'Access);
Config.Manager := Policy'Unchecked_Access;
Config_Mapper.Set_Context (Reader, Config);
end Prepare_Config;
-- ------------------------------
-- Finalize the policy manager.
-- ------------------------------
overriding
procedure Finalize (Policy : in out Role_Policy) is
use type Ada.Strings.Unbounded.String_Access;
begin
for I in Policy.Names'Range loop
exit when Policy.Names (I) = null;
Ada.Strings.Unbounded.Free (Policy.Names (I));
end loop;
end Finalize;
-- ------------------------------
-- Get the role policy associated with the given policy manager.
-- Returns the role policy instance or null if it was not registered in the policy manager.
-- ------------------------------
function Get_Role_Policy (Manager : in Security.Policies.Policy_Manager'Class)
return Role_Policy_Access is
Policy : constant Security.Policies.Policy_Access := Manager.Get_Policy (NAME);
begin
if Policy = null or else not (Policy.all in Role_Policy'Class) then
return null;
else
return Role_Policy'Class (Policy.all)'Access;
end if;
end Get_Role_Policy;
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.Policies.Roles;
|
Implement the new function Get_Role_Policy
|
Implement the new function Get_Role_Policy
|
Ada
|
apache-2.0
|
Letractively/ada-security
|
a5014924e574416bad35d1d8d2615dd70f973cae
|
arch/ARM/cortex_m/src/semihosting.adb
|
arch/ARM/cortex_m/src/semihosting.adb
|
------------------------------------------------------------------------------
-- --
-- Copyright (C) 2016, AdaCore --
-- --
-- Redistribution and use in source and binary forms, with or without --
-- modification, are permitted provided that the following conditions are --
-- met: --
-- 1. Redistributions of source code must retain the above copyright --
-- notice, this list of conditions and the following disclaimer. --
-- 2. Redistributions in binary form must reproduce the above copyright --
-- notice, this list of conditions and the following disclaimer in --
-- the documentation and/or other materials provided with the --
-- distribution. --
-- 3. Neither the name of the copyright holder nor the names of its --
-- contributors may be used to endorse or promote products derived --
-- from this software without specific prior written permission. --
-- --
-- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS --
-- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT --
-- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR --
-- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT --
-- HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, --
-- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT --
-- LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, --
-- DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY --
-- THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT --
-- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE --
-- OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. --
-- --
------------------------------------------------------------------------------
with Cortex_M.Debug;
with System.Machine_Code; use System.Machine_Code;
with HAL; use HAL;
with Ada.Unchecked_Conversion;
with Interfaces.C; use Interfaces.C;
package body Semihosting is
type SH_u32_Array is array (Integer range <>) of SH_Word
with Pack, Convention => C, Volatile_Components;
function To_SH_u32 is new Ada.Unchecked_Conversion
(Source => System.Address, Target => SH_Word);
function To_SH_u32 is new Ada.Unchecked_Conversion
(Source => Integer, Target => SH_Word);
subtype Syscall is SH_Word;
SYS_OPEN : constant Syscall := 16#01#;
SYS_CLOSE : constant Syscall := 16#02#;
SYS_WRITEC : constant Syscall := 16#03#;
SYS_WRITE0 : constant Syscall := 16#04#;
SYS_WRITE : constant Syscall := 16#05#;
SYS_READ : constant Syscall := 16#06#;
-- SYS_READC : constant Syscall := 16#07#;
-- SYS_ISERROR : constant Syscall := 16#08#;
-- SYS_ISTTY : constant Syscall := 16#09#;
SYS_SEEK : constant Syscall := 16#0A#;
-- SYS_FLEN : constant Syscall := 16#0C#;
-- SYS_TMPNAM : constant Syscall := 16#0D#;
SYS_REMOVE : constant Syscall := 16#0E#;
-- SYS_RENAME : constant Syscall := 16#0E#;
-- SYS_CLOCK : constant Syscall := 16#10#;
-- SYS_TIME : constant Syscall := 16#11#;
SYS_ERRNO : constant Syscall := 16#13#;
-- SYS_GET_CMD : constant Syscall := 16#15#;
-- SYS_HEAPINFO : constant Syscall := 16#16#;
-- SYS_ELAPSED : constant Syscall := 16#30#;
-- SYS_TICKFREQ : constant Syscall := 16#31#;
function Semihosting_Enabled return Boolean is
(Cortex_M.Debug.Halting_Debug_Enabled);
function Generic_SH_Call (R0, R1 : SH_Word) return SH_Word;
function Generic_SH_Call (R0 : SH_Word; R1 : System.Address) return SH_Word;
---------------------
-- Generic_SH_Call --
---------------------
function Generic_SH_Call (R0, R1 : SH_Word) return SH_Word is
Ret : SH_Word;
begin
Asm ("mov r0, %1" & ASCII.LF & ASCII.HT &
"mov r1, %2" & ASCII.LF & ASCII.HT &
"bkpt #0xAB" & ASCII.LF & ASCII.HT &
"mov %0, r0",
Outputs => (SH_Word'Asm_Output ("=r", Ret)),
Inputs => (SH_Word'Asm_Input ("r", R0),
SH_Word'Asm_Input ("r", R1)),
Volatile => True,
Clobber => ("r1, r0"));
return Ret;
end Generic_SH_Call;
---------------------
-- Generic_SH_Call --
---------------------
function Generic_SH_Call (R0 : SH_Word; R1 : System.Address) return SH_Word is
begin
return Generic_SH_Call (R0, To_SH_u32 (R1));
end Generic_SH_Call;
-----------
-- Close --
-----------
function Close (File_Handle : SH_Word) return SH_Word is
Block : SH_u32_Array (0 .. 0);
begin
if not Semihosting_Enabled then
-- No debugger attached
return SH_Word'Last;
end if;
Block (0) := File_Handle;
return Generic_SH_Call (SYS_CLOSE, Block'Address);
end Close;
----------
-- Open --
----------
function Open (Filename : String; Mode : Flag) return SH_Word is
Block : SH_u32_Array (0 .. 2);
C_Name : char_array (0 .. Filename'Length) with Volatile;
begin
if not Semihosting_Enabled then
-- No debugger attached
return SH_Word'Last;
end if;
for J in Filename'Range loop
C_Name (size_t (J - Filename'First)) :=
char'Val (Character'Pos (Filename (J)));
end loop;
C_Name (C_Name'Last) := nul;
Block (0) := To_SH_u32 (C_Name'Address);
Block (1) := Mode;
Block (2) := Filename'Length;
return Generic_SH_Call (SYS_OPEN, Block'Address);
end Open;
----------
-- Read --
----------
function Read (File_Handle : SH_Word;
Buffer_Address : System.Address;
Buffer_Size : SH_Word) return SH_Word
is
Block : SH_u32_Array (0 .. 2);
begin
if not Semihosting_Enabled then
-- No debugger attached
return Buffer_Size;
end if;
Block (0) := File_Handle;
Block (1) := To_SH_u32 (Buffer_Address);
Block (2) := Buffer_Size;
return Generic_SH_Call (SYS_READ, Block'Address);
end Read;
-----------
-- Write --
-----------
function Write (File_Handle : SH_Word;
Buffer_Address : System.Address;
Buffer_Size : SH_Word) return SH_Word
is
Block : SH_u32_Array (0 .. 3);
begin
if not Semihosting_Enabled then
-- No debugger attached
return Buffer_Size;
end if;
Block (0) := File_Handle;
Block (1) := To_SH_u32 (Buffer_Address);
Block (2) := Buffer_Size;
return Generic_SH_Call (SYS_WRITE, Block'Address);
end Write;
------------
-- Remove --
------------
function Remove (Filename : String) return SH_Word is
Block : SH_u32_Array (0 .. 1);
C_Name : char_array (0 .. Filename'Length) with Volatile;
begin
if not Semihosting_Enabled then
-- No debugger attached
return SH_Word'Last;
end if;
for J in Filename'Range loop
C_Name (size_t (J - Filename'First)) :=
char'Val (Character'Pos (Filename (J)));
end loop;
C_Name (C_Name'Last) := nul;
Block (0) := To_SH_u32 (C_Name'Address);
Block (1) := To_SH_u32 (Filename'Length);
return Generic_SH_Call (SYS_REMOVE, Block'Address);
end Remove;
----------
-- Seek --
----------
function Seek (File_Handle : SH_Word;
Absolute_Position : SH_Word) return SH_Word
is
Block : SH_u32_Array (0 .. 1);
begin
if not Semihosting_Enabled then
-- No debugger attached
return SH_Word'Last;
end if;
Block (0) := File_Handle;
Block (1) := Absolute_Position;
return Generic_SH_Call (SYS_SEEK, Block'Address);
end Seek;
-----------
-- Errno --
-----------
function Errno return SH_Word is
begin
return Generic_SH_Call (SYS_ERRNO, 0);
end Errno;
-------------
-- Write_C --
-------------
procedure Write_C (C : Character) is
Ret : SH_Word with Unreferenced;
begin
if not Semihosting_Enabled then
-- No debugger attached
return;
end if;
Ret := Generic_SH_Call (SYS_WRITEC, C'Address);
end Write_C;
-------------
-- Write_0 --
-------------
procedure Write_0 (Str : String) is
Data : UInt8_Array (Str'First .. Str'Last + 1);
Ret : SH_Word with Unreferenced;
begin
if not Semihosting_Enabled then
-- No debugger attached
return;
end if;
for Index in Str'Range loop
Data (Index) := Character'Pos (Str (Index));
end loop;
-- Add trailing zero
Data (Str'Last + 1) := 0;
Ret := Generic_SH_Call (SYS_WRITE0, Data'Address);
end Write_0;
--------------
-- Log_Line --
--------------
procedure Log_Line (Str : String) is
begin
Log (Str);
Log_New_Line;
end Log_Line;
------------------
-- Log_New_Line --
------------------
procedure Log_New_Line is
begin
Write_C (ASCII.LF);
end Log_New_Line;
end Semihosting;
|
------------------------------------------------------------------------------
-- --
-- Copyright (C) 2016-2020, AdaCore --
-- --
-- Redistribution and use in source and binary forms, with or without --
-- modification, are permitted provided that the following conditions are --
-- met: --
-- 1. Redistributions of source code must retain the above copyright --
-- notice, this list of conditions and the following disclaimer. --
-- 2. Redistributions in binary form must reproduce the above copyright --
-- notice, this list of conditions and the following disclaimer in --
-- the documentation and/or other materials provided with the --
-- distribution. --
-- 3. Neither the name of the copyright holder nor the names of its --
-- contributors may be used to endorse or promote products derived --
-- from this software without specific prior written permission. --
-- --
-- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS --
-- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT --
-- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR --
-- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT --
-- HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, --
-- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT --
-- LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, --
-- DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY --
-- THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT --
-- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE --
-- OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. --
-- --
------------------------------------------------------------------------------
with Cortex_M.Debug;
with System.Machine_Code; use System.Machine_Code;
with HAL; use HAL;
with Ada.Unchecked_Conversion;
with Interfaces.C; use Interfaces.C;
package body Semihosting is
type SH_u32_Array is array (Integer range <>) of SH_Word
with Pack, Convention => C, Volatile_Components;
function To_SH_u32 is new Ada.Unchecked_Conversion
(Source => System.Address, Target => SH_Word);
function To_SH_u32 is new Ada.Unchecked_Conversion
(Source => Integer, Target => SH_Word);
subtype Syscall is SH_Word;
SYS_OPEN : constant Syscall := 16#01#;
SYS_CLOSE : constant Syscall := 16#02#;
SYS_WRITEC : constant Syscall := 16#03#;
SYS_WRITE0 : constant Syscall := 16#04#;
SYS_WRITE : constant Syscall := 16#05#;
SYS_READ : constant Syscall := 16#06#;
-- SYS_READC : constant Syscall := 16#07#;
-- SYS_ISERROR : constant Syscall := 16#08#;
-- SYS_ISTTY : constant Syscall := 16#09#;
SYS_SEEK : constant Syscall := 16#0A#;
-- SYS_FLEN : constant Syscall := 16#0C#;
-- SYS_TMPNAM : constant Syscall := 16#0D#;
SYS_REMOVE : constant Syscall := 16#0E#;
-- SYS_RENAME : constant Syscall := 16#0E#;
-- SYS_CLOCK : constant Syscall := 16#10#;
-- SYS_TIME : constant Syscall := 16#11#;
SYS_ERRNO : constant Syscall := 16#13#;
-- SYS_GET_CMD : constant Syscall := 16#15#;
-- SYS_HEAPINFO : constant Syscall := 16#16#;
-- SYS_ELAPSED : constant Syscall := 16#30#;
-- SYS_TICKFREQ : constant Syscall := 16#31#;
function Semihosting_Enabled return Boolean is
(Cortex_M.Debug.Halting_Debug_Enabled);
function Generic_SH_Call (R0, R1 : SH_Word) return SH_Word;
function Generic_SH_Call (R0 : SH_Word; R1 : System.Address) return SH_Word;
---------------------
-- Generic_SH_Call --
---------------------
function Generic_SH_Call (R0, R1 : SH_Word) return SH_Word is
Ret : SH_Word;
begin
Asm ("mov r0, %1" & ASCII.LF & ASCII.HT &
"mov r1, %2" & ASCII.LF & ASCII.HT &
"bkpt #0xAB" & ASCII.LF & ASCII.HT &
"mov %0, r0",
Outputs => (SH_Word'Asm_Output ("=r", Ret)),
Inputs => (SH_Word'Asm_Input ("r", R0),
SH_Word'Asm_Input ("r", R1)),
Volatile => True,
Clobber => ("r1, r0"));
return Ret;
end Generic_SH_Call;
---------------------
-- Generic_SH_Call --
---------------------
function Generic_SH_Call (R0 : SH_Word; R1 : System.Address) return SH_Word is
begin
return Generic_SH_Call (R0, To_SH_u32 (R1));
end Generic_SH_Call;
-----------
-- Close --
-----------
function Close (File_Handle : SH_Word) return SH_Word is
Block : SH_u32_Array (0 .. 0);
begin
if not Semihosting_Enabled then
-- No debugger attached
return SH_Word'Last;
end if;
Block (0) := File_Handle;
return Generic_SH_Call (SYS_CLOSE, Block'Address);
end Close;
----------
-- Open --
----------
function Open (Filename : String; Mode : Flag) return SH_Word is
Block : SH_u32_Array (0 .. 2);
C_Name : char_array (0 .. Filename'Length) with Volatile;
begin
if not Semihosting_Enabled then
-- No debugger attached
return SH_Word'Last;
end if;
for J in Filename'Range loop
C_Name (size_t (J - Filename'First)) :=
char'Val (Character'Pos (Filename (J)));
end loop;
C_Name (C_Name'Last) := nul;
Block (0) := To_SH_u32 (C_Name'Address);
Block (1) := Mode;
Block (2) := Filename'Length;
return Generic_SH_Call (SYS_OPEN, Block'Address);
end Open;
----------
-- Read --
----------
function Read (File_Handle : SH_Word;
Buffer_Address : System.Address;
Buffer_Size : SH_Word) return SH_Word
is
Block : SH_u32_Array (0 .. 2);
begin
if not Semihosting_Enabled then
-- No debugger attached
return Buffer_Size;
end if;
Block (0) := File_Handle;
Block (1) := To_SH_u32 (Buffer_Address);
Block (2) := Buffer_Size;
return Generic_SH_Call (SYS_READ, Block'Address);
end Read;
-----------
-- Write --
-----------
function Write (File_Handle : SH_Word;
Buffer_Address : System.Address;
Buffer_Size : SH_Word) return SH_Word
is
Block : SH_u32_Array (0 .. 3);
begin
if not Semihosting_Enabled then
-- No debugger attached
return Buffer_Size;
end if;
Block (0) := File_Handle;
Block (1) := To_SH_u32 (Buffer_Address);
Block (2) := Buffer_Size;
return Generic_SH_Call (SYS_WRITE, Block'Address);
end Write;
------------
-- Remove --
------------
function Remove (Filename : String) return SH_Word is
Block : SH_u32_Array (0 .. 1);
C_Name : char_array (0 .. Filename'Length) with Volatile;
begin
if not Semihosting_Enabled then
-- No debugger attached
return SH_Word'Last;
end if;
for J in Filename'Range loop
C_Name (size_t (J - Filename'First)) :=
char'Val (Character'Pos (Filename (J)));
end loop;
C_Name (C_Name'Last) := nul;
Block (0) := To_SH_u32 (C_Name'Address);
Block (1) := To_SH_u32 (Filename'Length);
return Generic_SH_Call (SYS_REMOVE, Block'Address);
end Remove;
----------
-- Seek --
----------
function Seek (File_Handle : SH_Word;
Absolute_Position : SH_Word) return SH_Word
is
Block : SH_u32_Array (0 .. 1);
begin
if not Semihosting_Enabled then
-- No debugger attached
return SH_Word'Last;
end if;
Block (0) := File_Handle;
Block (1) := Absolute_Position;
return Generic_SH_Call (SYS_SEEK, Block'Address);
end Seek;
-----------
-- Errno --
-----------
function Errno return SH_Word is
begin
return Generic_SH_Call (SYS_ERRNO, 0);
end Errno;
-------------
-- Write_C --
-------------
procedure Write_C (C : Character) is
Ret : SH_Word with Unreferenced;
begin
if not Semihosting_Enabled then
-- No debugger attached
return;
end if;
Ret := Generic_SH_Call (SYS_WRITEC, C'Address);
end Write_C;
-------------
-- Write_0 --
-------------
procedure Write_0 (Str : String) is
type Byte_Array is new UInt8_Array with Volatile_Components;
Data : Byte_Array (Str'First .. Str'Last + 1);
Ret : SH_Word with Unreferenced;
begin
if not Semihosting_Enabled then
-- No debugger attached
return;
end if;
for Index in Str'Range loop
Data (Index) := Character'Pos (Str (Index));
end loop;
-- Add trailing zero
Data (Str'Last + 1) := 0;
Ret := Generic_SH_Call (SYS_WRITE0, Data'Address);
end Write_0;
--------------
-- Log_Line --
--------------
procedure Log_Line (Str : String) is
begin
Log (Str);
Log_New_Line;
end Log_Line;
------------------
-- Log_New_Line --
------------------
procedure Log_New_Line is
begin
Write_C (ASCII.LF);
end Log_New_Line;
end Semihosting;
|
Reduce optimization opportunities in Semihosting.
|
Reduce optimization opportunities in Semihosting.
* arch/ARM/cortex_m/src/semihosting.adb (Write_0): Data is of new
type Byte_Array, which is a new UInt8_Array with volatile
components (FSF GCC was miscompiling at -O3).
|
Ada
|
bsd-3-clause
|
AdaCore/Ada_Drivers_Library,AdaCore/Ada_Drivers_Library,simonjwright/Ada_Drivers_Library,simonjwright/Ada_Drivers_Library
|
e88f7695b11bbb1b5a860ed8ca41242dc142d21c
|
awa/plugins/awa-tags/src/awa-tags-beans.ads
|
awa/plugins/awa-tags/src/awa-tags-beans.ads
|
-----------------------------------------------------------------------
-- awa-tags-beans -- Beans for the tags module
-- Copyright (C) 2013 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Ada.Containers.Hashed_Maps;
with Ada.Containers.Ordered_Sets;
with Ada.Finalization;
with Util.Beans.Basic;
with Util.Beans.Objects.Lists;
with Util.Beans.Lists.Strings;
with Util.Strings.Vectors;
with ADO;
with ADO.Utils;
with ADO.Schemas;
with ADO.Sessions;
with AWA.Tags.Models;
with AWA.Tags.Modules;
-- == Tag Beans ==
-- Several bean types are provided to represent and manage a list of tags.
--
-- === Tag_List_Bean ===
-- The <tt>Tag_List_Bean</tt> holds a list of tags and provides operations used by the
-- <tt>awa:tagList</tt> component to add or remove tags within a <tt>h:form</tt> component.
-- A bean can be declared and configured as follows in the XML application configuration file:
--
-- <managed-bean>
-- <managed-bean-name>questionTags</managed-bean-name>
-- <managed-bean-class>AWA.Tags.Beans.Tag_List_Bean</managed-bean-class>
-- <managed-bean-scope>Request</managed-bean-scope>
-- <managed-property>
-- <property-name>entity_type</property-name>
-- <property-class>String</property-class>
-- <value>Awa_Question</value>
-- </managed-property>
-- <managed-property>
-- <property-name>permission</property-name>
-- <property-class>String</property-class>
-- <value>question-edit</value>
-- </managed-property>
-- </managed-bean>
--
-- The <tt>entity_type</tt> property defines the name of the database table to which the tags
-- are assigned. The <tt>permission</tt> property defines the permission name that must be used
-- to verify that the user has the permission do add or remove the tag. Such permission is
-- verified only when the <tt>awa:tagList</tt> component is used within a form.
--
-- === Tag_Search_Bean ===
-- The <tt>Tag_Search_Bean</tt> is dedicated to searching for tags that start with a given
-- pattern. The auto complete feature of the <tt>awa:tagList</tt> component can use this
-- bean type to look in the database for tags matching a start pattern. The declaration of the
-- bean should define the database table to search for tags associated with a given database
-- table. This is done in the XML configuration with the <tt>entity_type</tt> property.
--
-- <managed-bean>
-- <managed-bean-name>questionTagSearch</managed-bean-name>
-- <managed-bean-class>AWA.Tags.Beans.Tag_Search_Bean</managed-bean-class>
-- <managed-bean-scope>Request</managed-bean-scope>
-- <managed-property>
-- <property-name>entity_type</property-name>
-- <property-class>String</property-class>
-- <value>awa_question</value>
-- </managed-property>
-- </managed-bean>
--
-- === Tag_Info_List_Bean ===
-- The <tt>Tag_Info_List_Bean</tt> holds a collection of tags with their weight. It is used
-- by the <tt>awa:tagCloud</tt> component.
--
--
-- <managed-bean>
-- <managed-bean-name>QuestionTagList</managed-bean-name>
-- <managed-bean-class>AWA.Tags.Beans.Tag_Info_List_Bean</managed-bean-class>
-- <managed-bean-scope>Request</managed-bean-scope>
-- <managed-property>
-- <property-name>Entity_Type</property-name>
-- <property-class>String</property-class>
-- <value>Awa_Question</value>
-- </managed-property>
-- </managed-bean>
package AWA.Tags.Beans is
-- Compare two tags on their count and name.
function "<" (Left, Right : in AWA.Tags.Models.Tag_Info) return Boolean;
package Tag_Ordered_Sets is
new Ada.Containers.Ordered_Sets (Element_Type => AWA.Tags.Models.Tag_Info,
"=" => AWA.Tags.Models."=");
type Tag_List_Bean is
new Util.Beans.Objects.Lists.List_Bean and Util.Beans.Basic.Bean with private;
type Tag_List_Bean_Access is access all Tag_List_Bean'Class;
-- Set the value identified by the name.
-- If the name cannot be found, the method should raise the No_Value
-- exception.
overriding
procedure Set_Value (From : in out Tag_List_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object);
-- Set the entity type (database table) onto which the tags are associated.
procedure Set_Entity_Type (Into : in out Tag_List_Bean;
Table : in ADO.Schemas.Class_Mapping_Access);
-- Set the permission to check before removing or adding a tag on the entity.
procedure Set_Permission (Into : in out Tag_List_Bean;
Permission : in String);
-- Load the tags associated with the given database identifier.
procedure Load_Tags (Into : in out Tag_List_Bean;
Session : in ADO.Sessions.Session;
For_Entity_Id : in ADO.Identifier);
-- Set the list of tags to add.
procedure Set_Added (Into : in out Tag_List_Bean;
Tags : in Util.Strings.Vectors.Vector);
-- Set the list of tags to remove.
procedure Set_Deleted (Into : in out Tag_List_Bean;
Tags : in Util.Strings.Vectors.Vector);
-- Update the tags associated with the tag entity represented by <tt>For_Entity_Id</tt>.
-- The list of tags defined by <tt>Set_Deleted</tt> are removed first and the list of
-- tags defined by <tt>Set_Added</tt> are associated with the database entity.
procedure Update_Tags (From : in Tag_List_Bean;
For_Entity_Id : in ADO.Identifier);
-- Create the tag list bean instance.
function Create_Tag_List_Bean (Module : in AWA.Tags.Modules.Tag_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access;
type Tag_Search_Bean is
new Util.Beans.Objects.Lists.List_Bean and Util.Beans.Basic.Bean with private;
type Tag_Search_Bean_Access is access all Tag_Search_Bean'Class;
-- Set the value identified by the name.
-- If the name cannot be found, the method should raise the No_Value
-- exception.
overriding
procedure Set_Value (From : in out Tag_Search_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object);
-- Search the tags that match the search string.
procedure Search_Tags (Into : in out Tag_Search_Bean;
Session : in ADO.Sessions.Session;
Search : in String);
-- Set the entity type (database table) onto which the tags are associated.
procedure Set_Entity_Type (Into : in out Tag_Search_Bean;
Table : in ADO.Schemas.Class_Mapping_Access);
-- Create the tag search bean instance.
function Create_Tag_Search_Bean (Module : in AWA.Tags.Modules.Tag_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access;
type Tag_Info_List_Bean is
new AWA.Tags.Models.Tag_Info_List_Bean and Util.Beans.Basic.Bean with private;
type Tag_Info_List_Bean_Access is access all Tag_Info_List_Bean'Class;
-- Set the value identified by the name.
-- If the name cannot be found, the method should raise the No_Value
-- exception.
overriding
procedure Set_Value (From : in out Tag_Info_List_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object);
-- Load the list of tags.
procedure Load_Tags (Into : in out Tag_Info_List_Bean;
Session : in out ADO.Sessions.Session);
-- Create the tag info list bean instance.
function Create_Tag_Info_List_Bean (Module : in AWA.Tags.Modules.Tag_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access;
-- The <tt>Entity_Tag_Map</tt> contains a list of tags associated with some entities.
-- It allows to retrieve from the database all the tags associated with several entities
-- and get the list of tags for a given entity.
type Entity_Tag_Map is new Ada.Finalization.Limited_Controlled with private;
-- Get the list of tags associated with the given entity.
-- Returns null if the entity does not have any tag.
function Get_Tags (From : in Entity_Tag_Map;
For_Entity : in ADO.Identifier)
return Util.Beans.Lists.Strings.List_Bean_Access;
-- Get the list of tags associated with the given entity.
-- Returns a null object if the entity does not have any tag.
function Get_Tags (From : in Entity_Tag_Map;
For_Entity : in ADO.Identifier)
return Util.Beans.Objects.Object;
-- Release the list of tags.
procedure Clear (List : in out Entity_Tag_Map);
-- Load the list of tags associated with a list of entities.
procedure Load_Tags (Into : in out Entity_Tag_Map;
Session : in out ADO.Sessions.Session'Class;
Entity_Type : in String;
List : in ADO.Utils.Identifier_Vector);
-- Release the list of tags.
overriding
procedure Finalize (List : in out Entity_Tag_Map);
private
type Tag_List_Bean is
new Util.Beans.Objects.Lists.List_Bean and Util.Beans.Basic.Bean with record
Module : AWA.Tags.Modules.Tag_Module_Access;
Entity_Type : Ada.Strings.Unbounded.Unbounded_String;
Permission : Ada.Strings.Unbounded.Unbounded_String;
Current : Natural := 0;
Added : Util.Strings.Vectors.Vector;
Deleted : Util.Strings.Vectors.Vector;
end record;
type Tag_Search_Bean is
new Util.Beans.Objects.Lists.List_Bean and Util.Beans.Basic.Bean with record
Module : AWA.Tags.Modules.Tag_Module_Access;
Entity_Type : Ada.Strings.Unbounded.Unbounded_String;
end record;
type Tag_Info_List_Bean is
new AWA.Tags.Models.Tag_Info_List_Bean and Util.Beans.Basic.Bean with record
Module : AWA.Tags.Modules.Tag_Module_Access;
Entity_Type : Ada.Strings.Unbounded.Unbounded_String;
end record;
package Entity_Tag_Maps is
new Ada.Containers.Hashed_Maps (Key_Type => ADO.Identifier,
Element_Type => Util.Beans.Lists.Strings.List_Bean_Access,
Hash => ADO.Utils.Hash,
Equivalent_Keys => ADO."=",
"=" => Util.Beans.Lists.Strings."=");
type Entity_Tag_Map is new Ada.Finalization.Limited_Controlled with record
Tags : Entity_Tag_Maps.Map;
end record;
end AWA.Tags.Beans;
|
-----------------------------------------------------------------------
-- awa-tags-beans -- Beans for the tags module
-- Copyright (C) 2013 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Ada.Containers.Hashed_Maps;
with Ada.Containers.Ordered_Sets;
with Ada.Finalization;
with Util.Beans.Basic;
with Util.Beans.Objects.Lists;
with Util.Beans.Lists.Strings;
with Util.Strings.Vectors;
with ADO;
with ADO.Utils;
with ADO.Schemas;
with ADO.Sessions;
with AWA.Tags.Models;
with AWA.Tags.Modules;
-- == Tag Beans ==
-- Several bean types are provided to represent and manage a list of tags.
--
-- === Tag_List_Bean ===
-- The <tt>Tag_List_Bean</tt> holds a list of tags and provides operations used by the
-- <tt>awa:tagList</tt> component to add or remove tags within a <tt>h:form</tt> component.
-- A bean can be declared and configured as follows in the XML application configuration file:
--
-- <managed-bean>
-- <managed-bean-name>questionTags</managed-bean-name>
-- <managed-bean-class>AWA.Tags.Beans.Tag_List_Bean</managed-bean-class>
-- <managed-bean-scope>request</managed-bean-scope>
-- <managed-property>
-- <property-name>entity_type</property-name>
-- <property-class>String</property-class>
-- <value>Awa_Question</value>
-- </managed-property>
-- <managed-property>
-- <property-name>permission</property-name>
-- <property-class>String</property-class>
-- <value>question-edit</value>
-- </managed-property>
-- </managed-bean>
--
-- The <tt>entity_type</tt> property defines the name of the database table to which the tags
-- are assigned. The <tt>permission</tt> property defines the permission name that must be used
-- to verify that the user has the permission do add or remove the tag. Such permission is
-- verified only when the <tt>awa:tagList</tt> component is used within a form.
--
-- === Tag_Search_Bean ===
-- The <tt>Tag_Search_Bean</tt> is dedicated to searching for tags that start with a given
-- pattern. The auto complete feature of the <tt>awa:tagList</tt> component can use this
-- bean type to look in the database for tags matching a start pattern. The declaration of the
-- bean should define the database table to search for tags associated with a given database
-- table. This is done in the XML configuration with the <tt>entity_type</tt> property.
--
-- <managed-bean>
-- <managed-bean-name>questionTagSearch</managed-bean-name>
-- <managed-bean-class>AWA.Tags.Beans.Tag_Search_Bean</managed-bean-class>
-- <managed-bean-scope>request</managed-bean-scope>
-- <managed-property>
-- <property-name>entity_type</property-name>
-- <property-class>String</property-class>
-- <value>awa_question</value>
-- </managed-property>
-- </managed-bean>
--
-- === Tag_Info_List_Bean ===
-- The <tt>Tag_Info_List_Bean</tt> holds a collection of tags with their weight. It is used
-- by the <tt>awa:tagCloud</tt> component.
--
-- <managed-bean>
-- <managed-bean-name>questionTagList</managed-bean-name>
-- <managed-bean-class>AWA.Tags.Beans.Tag_Info_List_Bean</managed-bean-class>
-- <managed-bean-scope>request</managed-bean-scope>
-- <managed-property>
-- <property-name>entity_type</property-name>
-- <property-class>String</property-class>
-- <value>awa_question</value>
-- </managed-property>
-- </managed-bean>
--
package AWA.Tags.Beans is
-- Compare two tags on their count and name.
function "<" (Left, Right : in AWA.Tags.Models.Tag_Info) return Boolean;
package Tag_Ordered_Sets is
new Ada.Containers.Ordered_Sets (Element_Type => AWA.Tags.Models.Tag_Info,
"=" => AWA.Tags.Models."=");
type Tag_List_Bean is
new Util.Beans.Objects.Lists.List_Bean and Util.Beans.Basic.Bean with private;
type Tag_List_Bean_Access is access all Tag_List_Bean'Class;
-- Set the value identified by the name.
-- If the name cannot be found, the method should raise the No_Value
-- exception.
overriding
procedure Set_Value (From : in out Tag_List_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object);
-- Set the entity type (database table) onto which the tags are associated.
procedure Set_Entity_Type (Into : in out Tag_List_Bean;
Table : in ADO.Schemas.Class_Mapping_Access);
-- Set the permission to check before removing or adding a tag on the entity.
procedure Set_Permission (Into : in out Tag_List_Bean;
Permission : in String);
-- Load the tags associated with the given database identifier.
procedure Load_Tags (Into : in out Tag_List_Bean;
Session : in ADO.Sessions.Session;
For_Entity_Id : in ADO.Identifier);
-- Set the list of tags to add.
procedure Set_Added (Into : in out Tag_List_Bean;
Tags : in Util.Strings.Vectors.Vector);
-- Set the list of tags to remove.
procedure Set_Deleted (Into : in out Tag_List_Bean;
Tags : in Util.Strings.Vectors.Vector);
-- Update the tags associated with the tag entity represented by <tt>For_Entity_Id</tt>.
-- The list of tags defined by <tt>Set_Deleted</tt> are removed first and the list of
-- tags defined by <tt>Set_Added</tt> are associated with the database entity.
procedure Update_Tags (From : in Tag_List_Bean;
For_Entity_Id : in ADO.Identifier);
-- Create the tag list bean instance.
function Create_Tag_List_Bean (Module : in AWA.Tags.Modules.Tag_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access;
type Tag_Search_Bean is
new Util.Beans.Objects.Lists.List_Bean and Util.Beans.Basic.Bean with private;
type Tag_Search_Bean_Access is access all Tag_Search_Bean'Class;
-- Set the value identified by the name.
-- If the name cannot be found, the method should raise the No_Value
-- exception.
overriding
procedure Set_Value (From : in out Tag_Search_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object);
-- Search the tags that match the search string.
procedure Search_Tags (Into : in out Tag_Search_Bean;
Session : in ADO.Sessions.Session;
Search : in String);
-- Set the entity type (database table) onto which the tags are associated.
procedure Set_Entity_Type (Into : in out Tag_Search_Bean;
Table : in ADO.Schemas.Class_Mapping_Access);
-- Create the tag search bean instance.
function Create_Tag_Search_Bean (Module : in AWA.Tags.Modules.Tag_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access;
type Tag_Info_List_Bean is
new AWA.Tags.Models.Tag_Info_List_Bean and Util.Beans.Basic.Bean with private;
type Tag_Info_List_Bean_Access is access all Tag_Info_List_Bean'Class;
-- Set the value identified by the name.
-- If the name cannot be found, the method should raise the No_Value
-- exception.
overriding
procedure Set_Value (From : in out Tag_Info_List_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object);
-- Load the list of tags.
procedure Load_Tags (Into : in out Tag_Info_List_Bean;
Session : in out ADO.Sessions.Session);
-- Create the tag info list bean instance.
function Create_Tag_Info_List_Bean (Module : in AWA.Tags.Modules.Tag_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access;
-- The <tt>Entity_Tag_Map</tt> contains a list of tags associated with some entities.
-- It allows to retrieve from the database all the tags associated with several entities
-- and get the list of tags for a given entity.
type Entity_Tag_Map is new Ada.Finalization.Limited_Controlled with private;
-- Get the list of tags associated with the given entity.
-- Returns null if the entity does not have any tag.
function Get_Tags (From : in Entity_Tag_Map;
For_Entity : in ADO.Identifier)
return Util.Beans.Lists.Strings.List_Bean_Access;
-- Get the list of tags associated with the given entity.
-- Returns a null object if the entity does not have any tag.
function Get_Tags (From : in Entity_Tag_Map;
For_Entity : in ADO.Identifier)
return Util.Beans.Objects.Object;
-- Release the list of tags.
procedure Clear (List : in out Entity_Tag_Map);
-- Load the list of tags associated with a list of entities.
procedure Load_Tags (Into : in out Entity_Tag_Map;
Session : in out ADO.Sessions.Session'Class;
Entity_Type : in String;
List : in ADO.Utils.Identifier_Vector);
-- Release the list of tags.
overriding
procedure Finalize (List : in out Entity_Tag_Map);
private
type Tag_List_Bean is
new Util.Beans.Objects.Lists.List_Bean and Util.Beans.Basic.Bean with record
Module : AWA.Tags.Modules.Tag_Module_Access;
Entity_Type : Ada.Strings.Unbounded.Unbounded_String;
Permission : Ada.Strings.Unbounded.Unbounded_String;
Current : Natural := 0;
Added : Util.Strings.Vectors.Vector;
Deleted : Util.Strings.Vectors.Vector;
end record;
type Tag_Search_Bean is
new Util.Beans.Objects.Lists.List_Bean and Util.Beans.Basic.Bean with record
Module : AWA.Tags.Modules.Tag_Module_Access;
Entity_Type : Ada.Strings.Unbounded.Unbounded_String;
end record;
type Tag_Info_List_Bean is
new AWA.Tags.Models.Tag_Info_List_Bean and Util.Beans.Basic.Bean with record
Module : AWA.Tags.Modules.Tag_Module_Access;
Entity_Type : Ada.Strings.Unbounded.Unbounded_String;
end record;
package Entity_Tag_Maps is
new Ada.Containers.Hashed_Maps (Key_Type => ADO.Identifier,
Element_Type => Util.Beans.Lists.Strings.List_Bean_Access,
Hash => ADO.Utils.Hash,
Equivalent_Keys => ADO."=",
"=" => Util.Beans.Lists.Strings."=");
type Entity_Tag_Map is new Ada.Finalization.Limited_Controlled with record
Tags : Entity_Tag_Maps.Map;
end record;
end AWA.Tags.Beans;
|
Document the tag beans
|
Document the tag beans
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
327e4cbcdba6723c6f623f013308014d8dafecd7
|
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 MAT.Readers;
with MAT.Memory.Tools;
with MAT.Expressions;
package MAT.Memory.Targets is
-- Define some global statistics about the memory slots.
type Memory_Stat is record
Thread_Count : Natural;
Total_Alloc : MAT.Types.Target_Size;
Total_Free : MAT.Types.Target_Size;
Malloc_Count : Natural;
Free_Count : Natural;
Realloc_Count : Natural;
end record;
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);
-- Collect the information about threads and the memory allocations they've made.
procedure Thread_Information (Memory : in out Target_Memory;
Threads : in out Memory_Info_Map);
-- Collect the information about frames and the memory allocations they've made.
procedure Frame_Information (Memory : in out Target_Memory;
Level : in Natural;
Frames : in out Frame_Info_Map);
-- Get the global memory and allocation statistics.
procedure Stat_Information (Memory : in out Target_Memory;
Result : out Memory_Stat);
-- Find from the <tt>Memory</tt> map the memory slots whose address intersects
-- the region [From .. To] and which is selected by the given filter expression.
-- Add the memory slot in the <tt>Into</tt> list if it does not already contains
-- the memory slot.
procedure Find (Memory : in out Target_Memory;
From : in MAT.Types.Target_Addr;
To : in MAT.Types.Target_Addr;
Filter : in MAT.Expressions.Expression_Type;
Into : in out MAT.Memory.Allocation_Map);
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);
-- Collect the information about threads and the memory allocations they've made.
procedure Thread_Information (Threads : in out Memory_Info_Map);
-- Collect the information about frames and the memory allocations they've made.
procedure Frame_Information (Level : in Natural;
Frames : in out Frame_Info_Map);
-- Find from the <tt>Memory</tt> map the memory slots whose address intersects
-- the region [From .. To] and which is selected by the given filter expression.
-- Add the memory slot in the <tt>Into</tt> list if it does not already contains
-- the memory slot.
procedure Find (From : in MAT.Types.Target_Addr;
To : in MAT.Types.Target_Addr;
Filter : in MAT.Expressions.Expression_Type;
Into : in out MAT.Memory.Allocation_Map);
-- Get the global memory and allocation statistics.
procedure Stat_Information (Result : out Memory_Stat);
private
Used_Slots : Allocation_Map;
Freed_Slots : Allocation_Map;
Stats : Memory_Stat;
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 MAT.Frames;
with MAT.Readers;
with MAT.Memory.Tools;
with MAT.Expressions;
package MAT.Memory.Targets is
-- Define some global statistics about the memory slots.
type Memory_Stat is record
Thread_Count : Natural := 0;
Total_Alloc : MAT.Types.Target_Size := 0;
Total_Free : MAT.Types.Target_Size := 0;
Malloc_Count : Natural := 0;
Free_Count : Natural := 0;
Realloc_Count : Natural := 0;
end record;
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);
-- Collect the information about threads and the memory allocations they've made.
procedure Thread_Information (Memory : in out Target_Memory;
Threads : in out Memory_Info_Map);
-- Collect the information about frames and the memory allocations they've made.
procedure Frame_Information (Memory : in out Target_Memory;
Level : in Natural;
Frames : in out Frame_Info_Map);
-- Get the global memory and allocation statistics.
procedure Stat_Information (Memory : in out Target_Memory;
Result : out Memory_Stat);
-- Find from the <tt>Memory</tt> map the memory slots whose address intersects
-- the region [From .. To] and which is selected by the given filter expression.
-- Add the memory slot in the <tt>Into</tt> list if it does not already contains
-- the memory slot.
procedure Find (Memory : in out Target_Memory;
From : in MAT.Types.Target_Addr;
To : in MAT.Types.Target_Addr;
Filter : in MAT.Expressions.Expression_Type;
Into : in out MAT.Memory.Allocation_Map);
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);
-- Collect the information about threads and the memory allocations they've made.
procedure Thread_Information (Threads : in out Memory_Info_Map);
-- Collect the information about frames and the memory allocations they've made.
procedure Frame_Information (Level : in Natural;
Frames : in out Frame_Info_Map);
-- Find from the <tt>Memory</tt> map the memory slots whose address intersects
-- the region [From .. To] and which is selected by the given filter expression.
-- Add the memory slot in the <tt>Into</tt> list if it does not already contains
-- the memory slot.
procedure Find (From : in MAT.Types.Target_Addr;
To : in MAT.Types.Target_Addr;
Filter : in MAT.Expressions.Expression_Type;
Into : in out MAT.Memory.Allocation_Map);
-- Get the global memory and allocation statistics.
procedure Stat_Information (Result : out Memory_Stat);
private
Used_Slots : Allocation_Map;
Freed_Slots : Allocation_Map;
Stats : Memory_Stat;
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;
|
Add initializer in the Memory_Stat type
|
Add initializer in the Memory_Stat type
|
Ada
|
apache-2.0
|
stcarrez/mat,stcarrez/mat,stcarrez/mat
|
ce4bb60b99bc969300e110525b97eaa271579d0e
|
matp/src/events/mat-events-probes.adb
|
matp/src/events/mat-events-probes.adb
|
-----------------------------------------------------------------------
-- mat-readers -- Reader
-- Copyright (C) 2014, 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Log.Loggers;
with MAT.Readers.Marshaller;
package body MAT.Events.Probes is
-- The logger
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("MAT.Events.Probes");
procedure Read_Probe (Client : in out Probe_Manager_Type;
Msg : in out MAT.Readers.Message_Type);
P_TIME_SEC : constant MAT.Events.Internal_Reference := 0;
P_TIME_USEC : constant MAT.Events.Internal_Reference := 1;
P_THREAD_ID : constant MAT.Events.Internal_Reference := 2;
P_THREAD_SP : constant MAT.Events.Internal_Reference := 3;
P_RUSAGE_MINFLT : constant MAT.Events.Internal_Reference := 4;
P_RUSAGE_MAJFLT : constant MAT.Events.Internal_Reference := 5;
P_RUSAGE_NVCSW : constant MAT.Events.Internal_Reference := 6;
P_RUSAGE_NIVCSW : constant MAT.Events.Internal_Reference := 7;
P_FRAME : constant MAT.Events.Internal_Reference := 8;
P_FRAME_PC : constant MAT.Events.Internal_Reference := 9;
TIME_SEC_NAME : aliased constant String := "time-sec";
TIME_USEC_NAME : aliased constant String := "time-usec";
THREAD_ID_NAME : aliased constant String := "thread-id";
THREAD_SP_NAME : aliased constant String := "thread-sp";
RUSAGE_MINFLT_NAME : aliased constant String := "ru-minflt";
RUSAGE_MAJFLT_NAME : aliased constant String := "ru-majflt";
RUSAGE_NVCSW_NAME : aliased constant String := "ru-nvcsw";
RUSAGE_NIVCSW_NAME : aliased constant String := "ru-nivcsw";
FRAME_NAME : aliased constant String := "frame";
FRAME_PC_NAME : aliased constant String := "frame-pc";
Probe_Attributes : aliased constant MAT.Events.Attribute_Table :=
(1 => (Name => TIME_SEC_NAME'Access,
Size => 0,
Kind => MAT.Events.T_SIZE_T,
Ref => P_TIME_SEC),
2 => (Name => TIME_USEC_NAME'Access,
Size => 0,
Kind => MAT.Events.T_SIZE_T,
Ref => P_TIME_USEC),
3 => (Name => THREAD_ID_NAME'Access,
Size => 0,
Kind => MAT.Events.T_SIZE_T,
Ref => P_THREAD_ID),
4 => (Name => THREAD_SP_NAME'Access,
Size => 0,
Kind => MAT.Events.T_SIZE_T,
Ref => P_THREAD_SP),
5 => (Name => FRAME_NAME'Access,
Size => 0,
Kind => MAT.Events.T_SIZE_T,
Ref => P_FRAME),
6 => (Name => FRAME_PC_NAME'Access,
Size => 0,
Kind => MAT.Events.T_SIZE_T,
Ref => P_FRAME_PC),
7 => (Name => RUSAGE_MINFLT_NAME'Access,
Size => 0,
Kind => MAT.Events.T_SIZE_T,
Ref => P_RUSAGE_MINFLT),
8 => (Name => RUSAGE_MAJFLT_NAME'Access,
Size => 0,
Kind => MAT.Events.T_SIZE_T,
Ref => P_RUSAGE_MAJFLT),
9 => (Name => RUSAGE_NVCSW_NAME'Access,
Size => 0,
Kind => MAT.Events.T_SIZE_T,
Ref => P_RUSAGE_NVCSW),
10 => (Name => RUSAGE_NIVCSW_NAME'Access,
Size => 0,
Kind => MAT.Events.T_SIZE_T,
Ref => P_RUSAGE_NIVCSW)
);
function Hash (Key : in MAT.Types.Uint16) return Ada.Containers.Hash_Type is
begin
return Ada.Containers.Hash_Type (Key);
end Hash;
-- ------------------------------
-- Update the Size and Prev_Id information in the event identified by <tt>Id</tt>.
-- Update the event represented by <tt>Prev_Id</tt> so that its Next_Id refers
-- to the <tt>Id</tt> event.
-- ------------------------------
procedure Update_Event (Probe : in Probe_Type;
Id : in MAT.Events.Event_Id_Type;
Size : in MAT.Types.Target_Size;
Prev_Id : in MAT.Events.Event_Id_Type) is
begin
Probe.Owner.Get_Target_Events.Update_Event (Id, Size, Prev_Id);
end Update_Event;
-- ------------------------------
-- Initialize the manager instance.
-- ------------------------------
overriding
procedure Initialize (Manager : in out Probe_Manager_Type) is
begin
Manager.Events := new MAT.Events.Targets.Target_Events;
end Initialize;
-- ------------------------------
-- Register the probe to handle the event identified by the given name.
-- The event is mapped to the given id and the attributes table is used
-- to setup the mapping from the data stream attributes.
-- ------------------------------
procedure Register_Probe (Into : in out Probe_Manager_Type;
Probe : in Probe_Type_Access;
Name : in String;
Id : in MAT.Events.Probe_Index_Type;
Model : in MAT.Events.Const_Attribute_Table_Access) is
Handler : Probe_Handler;
begin
Handler.Probe := Probe;
Handler.Id := Id;
Handler.Attributes := Model;
Handler.Mapping := null;
Into.Probes.Insert (Name, Handler);
Probe.Owner := Into'Unchecked_Access;
end Register_Probe;
-- ------------------------------
-- Get the target events.
-- ------------------------------
function Get_Target_Events (Client : in Probe_Manager_Type)
return MAT.Events.Targets.Target_Events_Access is
begin
return Client.Events;
end Get_Target_Events;
procedure Read_Probe (Client : in out Probe_Manager_Type;
Msg : in out MAT.Readers.Message) is
use type MAT.Types.Target_Tick_Ref;
Count : Natural := 0;
Time_Sec : MAT.Types.Uint32 := 0;
Time_Usec : MAT.Types.Uint32 := 0;
Frame : constant access MAT.Events.Frame_Info := Client.Frame;
begin
Client.Event.Thread := 0;
Frame.Stack := 0;
Frame.Cur_Depth := 0;
for I in Client.Probe'Range loop
declare
Def : MAT.Events.Attribute renames Client.Probe (I);
begin
case Def.Ref is
when P_TIME_SEC =>
Time_Sec := MAT.Readers.Marshaller.Get_Target_Uint32 (Msg, Def.Kind);
when P_TIME_USEC =>
Time_Usec := MAT.Readers.Marshaller.Get_Target_Uint32 (Msg, Def.Kind);
when P_THREAD_ID =>
Client.Event.Thread := MAT.Types.Target_Thread_Ref
(MAT.Readers.Marshaller.Get_Target_Uint32 (Msg, Def.Kind));
when P_THREAD_SP =>
Frame.Stack := MAT.Readers.Marshaller.Get_Target_Addr (Msg, Def.Kind);
when P_FRAME =>
Count := Natural (MAT.Readers.Marshaller.Get_Target_Uint32 (Msg,
Def.Kind));
when P_FRAME_PC =>
for I in 1 .. Count loop -- reverse Count .. 1 loop
if Count < Frame.Depth then
Frame.Frame (Count - I + 1) := MAT.Readers.Marshaller.Get_Target_Addr (Msg,
Def.Kind);
end if;
end loop;
when others =>
null;
end case;
end;
end loop;
-- Convert the time in usec to make computation easier.
Client.Event.Time := MAT.Types.Target_Tick_Ref (Time_Sec) * 1_000_000;
Client.Event.Time := Client.Event.Time + MAT.Types.Target_Tick_Ref (Time_Usec);
Frame.Cur_Depth := Count;
exception
when E : others =>
Log.Error ("Marshaling error, frame count {0}", Natural'Image (Count));
raise;
end Read_Probe;
procedure Dispatch_Message (Client : in out Probe_Manager_Type;
Msg : in out MAT.Readers.Message_Type) is
use type MAT.Events.Attribute_Table_Ptr;
use type MAT.Events.Targets.Target_Events_Access;
Event : constant MAT.Types.Uint16 := MAT.Readers.Marshaller.Get_Uint16 (Msg.Buffer);
Pos : constant Handler_Maps.Cursor := Client.Handlers.Find (Event);
begin
if Log.Get_Level = Util.Log.DEBUG_LEVEL then
Log.Debug ("Dispatch message {0} - size {1}",
MAT.Types.Uint16'Image (Event),
Natural'Image (Msg.Size));
end if;
if not Handler_Maps.Has_Element (Pos) then
-- Message is not handled, skip it.
null;
else
if Client.Probe /= null then
Read_Probe (Client, Msg);
end if;
declare
Handler : constant Probe_Handler := Handler_Maps.Element (Pos);
begin
Client.Event.Prev_Id := 0;
Client.Event.Old_Size := 0;
Client.Event.Event := Event;
Client.Event.Index := Handler.Id;
Handler.Probe.Extract (Handler.Mapping.all'Access, Msg, Client.Event);
Client.Frames.Insert (Pc => Client.Frame.Frame (1 .. Client.Frame.Cur_Depth),
Result => Client.Event.Frame);
Client.Events.Insert (Client.Event);
Handler.Probe.Execute (Client.Event);
end;
end if;
exception
when E : others =>
Log.Error ("Exception while processing event " & MAT.Types.Uint16'Image (Event), E, True);
end Dispatch_Message;
-- ------------------------------
-- Read an event definition from the stream and configure the reader.
-- ------------------------------
procedure Read_Definition (Client : in out Probe_Manager_Type;
Msg : in out MAT.Readers.Message_Type) is
Name : constant String := MAT.Readers.Marshaller.Get_String (Msg);
Event : constant MAT.Types.Uint16 := MAT.Readers.Marshaller.Get_Uint16 (Msg.Buffer);
Count : constant MAT.Types.Uint16 := MAT.Readers.Marshaller.Get_Uint16 (Msg.Buffer);
Pos : constant Probe_Maps.Cursor := Client.Probes.Find (Name);
Frame : Probe_Handler;
procedure Add_Handler (Key : in String;
Element : in out Probe_Handler);
procedure Add_Handler (Key : in String;
Element : in out Probe_Handler) is
pragma Unreferenced (Key);
begin
Client.Handlers.Insert (Event, Element);
end Add_Handler;
begin
Log.Debug ("Read event definition {0} with {1} attributes",
Name, MAT.Types.Uint16'Image (Count));
if Name = "start" then
Frame.Mapping := new MAT.Events.Attribute_Table (1 .. Natural (Count));
Frame.Attributes := Probe_Attributes'Access;
Client.Probe := Frame.Mapping;
else
Frame.Mapping := null;
end if;
for I in 1 .. Natural (Count) loop
declare
Name : constant String := MAT.Readers.Marshaller.Get_String (Msg);
Size : constant MAT.Types.Uint16 := MAT.Readers.Marshaller.Get_Uint16 (Msg.Buffer);
procedure Read_Attribute (Key : in String;
Element : in out Probe_Handler);
procedure Read_Attribute (Key : in String;
Element : in out Probe_Handler) is
pragma Unreferenced (Key);
use type MAT.Events.Attribute_Table_Ptr;
begin
if Element.Mapping = null then
Element.Mapping := new MAT.Events.Attribute_Table (1 .. Natural (Count));
end if;
for J in Element.Attributes'Range loop
if Element.Attributes (J).Name.all = Name then
Element.Mapping (I) := Element.Attributes (J);
if Size = 1 then
Element.Mapping (I).Kind := MAT.Events.T_UINT8;
elsif Size = 2 then
Element.Mapping (I).Kind := MAT.Events.T_UINT16;
elsif Size = 4 then
Element.Mapping (I).Kind := MAT.Events.T_UINT32;
elsif Size = 8 then
Element.Mapping (I).Kind := MAT.Events.T_UINT64;
else
Element.Mapping (I).Kind := MAT.Events.T_UINT32;
end if;
end if;
end loop;
end Read_Attribute;
use type MAT.Events.Attribute_Table_Ptr;
begin
if Probe_Maps.Has_Element (Pos) then
Client.Probes.Update_Element (Pos, Read_Attribute'Access);
end if;
if Frame.Mapping /= null then
Read_Attribute ("start", Frame);
end if;
end;
end loop;
if Probe_Maps.Has_Element (Pos) then
Client.Probes.Update_Element (Pos, Add_Handler'Access);
end if;
end Read_Definition;
-- ------------------------------
-- Read a list of event definitions from the stream and configure the reader.
-- ------------------------------
procedure Read_Event_Definitions (Client : in out Probe_Manager_Type;
Msg : in out MAT.Readers.Message) is
Count : MAT.Types.Uint16;
begin
if Client.Frame = null then
Client.Frame := new MAT.Events.Frame_Info (512);
end if;
Client.Version := MAT.Readers.Marshaller.Get_Uint16 (Msg.Buffer);
Count := MAT.Readers.Marshaller.Get_Uint16 (Msg.Buffer);
Log.Info ("Read event stream version {0} with {1} definitions",
MAT.Types.Uint16'Image (Client.Version),
MAT.Types.Uint16'Image (Count));
for I in 1 .. Count loop
Read_Definition (Client, Msg);
end loop;
-- Look at the probe definition to gather the target address size.
Client.Addr_Size := MAT.Events.T_UINT32;
for I in Client.Probe'Range loop
declare
Def : MAT.Events.Attribute renames Client.Probe (I);
begin
if Def.Ref = P_THREAD_SP or Def.Ref = P_FRAME_PC then
Client.Addr_Size := Def.Kind;
exit;
end if;
end;
end loop;
exception
when E : MAT.Readers.Marshaller.Buffer_Underflow_Error =>
Log.Error ("Not enough data in the message", E, True);
end Read_Event_Definitions;
-- ------------------------------
-- Get the size of a target address (4 or 8 bytes).
-- ------------------------------
function Get_Address_Size (Client : in Probe_Manager_Type) return MAT.Events.Attribute_Type is
begin
return Client.Addr_Size;
end Get_Address_Size;
end MAT.Events.Probes;
|
-----------------------------------------------------------------------
-- mat-readers -- Reader
-- Copyright (C) 2014, 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Log.Loggers;
with MAT.Readers.Marshaller;
package body MAT.Events.Probes is
-- The logger
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("MAT.Events.Probes");
procedure Read_Probe (Client : in out Probe_Manager_Type;
Msg : in out MAT.Readers.Message_Type);
P_TIME_SEC : constant MAT.Events.Internal_Reference := 0;
P_TIME_USEC : constant MAT.Events.Internal_Reference := 1;
P_THREAD_ID : constant MAT.Events.Internal_Reference := 2;
P_THREAD_SP : constant MAT.Events.Internal_Reference := 3;
P_RUSAGE_MINFLT : constant MAT.Events.Internal_Reference := 4;
P_RUSAGE_MAJFLT : constant MAT.Events.Internal_Reference := 5;
P_RUSAGE_NVCSW : constant MAT.Events.Internal_Reference := 6;
P_RUSAGE_NIVCSW : constant MAT.Events.Internal_Reference := 7;
P_FRAME : constant MAT.Events.Internal_Reference := 8;
P_FRAME_PC : constant MAT.Events.Internal_Reference := 9;
TIME_SEC_NAME : aliased constant String := "time-sec";
TIME_USEC_NAME : aliased constant String := "time-usec";
THREAD_ID_NAME : aliased constant String := "thread-id";
THREAD_SP_NAME : aliased constant String := "thread-sp";
RUSAGE_MINFLT_NAME : aliased constant String := "ru-minflt";
RUSAGE_MAJFLT_NAME : aliased constant String := "ru-majflt";
RUSAGE_NVCSW_NAME : aliased constant String := "ru-nvcsw";
RUSAGE_NIVCSW_NAME : aliased constant String := "ru-nivcsw";
FRAME_NAME : aliased constant String := "frame";
FRAME_PC_NAME : aliased constant String := "frame-pc";
Probe_Attributes : aliased constant MAT.Events.Attribute_Table :=
(1 => (Name => TIME_SEC_NAME'Access,
Size => 0,
Kind => MAT.Events.T_SIZE_T,
Ref => P_TIME_SEC),
2 => (Name => TIME_USEC_NAME'Access,
Size => 0,
Kind => MAT.Events.T_SIZE_T,
Ref => P_TIME_USEC),
3 => (Name => THREAD_ID_NAME'Access,
Size => 0,
Kind => MAT.Events.T_SIZE_T,
Ref => P_THREAD_ID),
4 => (Name => THREAD_SP_NAME'Access,
Size => 0,
Kind => MAT.Events.T_SIZE_T,
Ref => P_THREAD_SP),
5 => (Name => FRAME_NAME'Access,
Size => 0,
Kind => MAT.Events.T_SIZE_T,
Ref => P_FRAME),
6 => (Name => FRAME_PC_NAME'Access,
Size => 0,
Kind => MAT.Events.T_SIZE_T,
Ref => P_FRAME_PC),
7 => (Name => RUSAGE_MINFLT_NAME'Access,
Size => 0,
Kind => MAT.Events.T_SIZE_T,
Ref => P_RUSAGE_MINFLT),
8 => (Name => RUSAGE_MAJFLT_NAME'Access,
Size => 0,
Kind => MAT.Events.T_SIZE_T,
Ref => P_RUSAGE_MAJFLT),
9 => (Name => RUSAGE_NVCSW_NAME'Access,
Size => 0,
Kind => MAT.Events.T_SIZE_T,
Ref => P_RUSAGE_NVCSW),
10 => (Name => RUSAGE_NIVCSW_NAME'Access,
Size => 0,
Kind => MAT.Events.T_SIZE_T,
Ref => P_RUSAGE_NIVCSW)
);
function Hash (Key : in MAT.Types.Uint16) return Ada.Containers.Hash_Type is
begin
return Ada.Containers.Hash_Type (Key);
end Hash;
-- ------------------------------
-- Update the Size and Prev_Id information in the event identified by <tt>Id</tt>.
-- Update the event represented by <tt>Prev_Id</tt> so that its Next_Id refers
-- to the <tt>Id</tt> event.
-- ------------------------------
procedure Update_Event (Probe : in Probe_Type;
Id : in MAT.Events.Event_Id_Type;
Size : in MAT.Types.Target_Size;
Prev_Id : in MAT.Events.Event_Id_Type) is
begin
Probe.Owner.Get_Target_Events.Update_Event (Id, Size, Prev_Id);
end Update_Event;
-- ------------------------------
-- Initialize the manager instance.
-- ------------------------------
overriding
procedure Initialize (Manager : in out Probe_Manager_Type) is
begin
Manager.Events := new MAT.Events.Targets.Target_Events;
Manager.Frames := new MAT.Frames.Targets.Target_Frames;
end Initialize;
-- ------------------------------
-- Register the probe to handle the event identified by the given name.
-- The event is mapped to the given id and the attributes table is used
-- to setup the mapping from the data stream attributes.
-- ------------------------------
procedure Register_Probe (Into : in out Probe_Manager_Type;
Probe : in Probe_Type_Access;
Name : in String;
Id : in MAT.Events.Probe_Index_Type;
Model : in MAT.Events.Const_Attribute_Table_Access) is
Handler : Probe_Handler;
begin
Handler.Probe := Probe;
Handler.Id := Id;
Handler.Attributes := Model;
Handler.Mapping := null;
Into.Probes.Insert (Name, Handler);
Probe.Owner := Into'Unchecked_Access;
end Register_Probe;
-- ------------------------------
-- Get the target events.
-- ------------------------------
function Get_Target_Events (Client : in Probe_Manager_Type)
return MAT.Events.Targets.Target_Events_Access is
begin
return Client.Events;
end Get_Target_Events;
-- ------------------------------
-- Get the target frames.
-- ------------------------------
function Get_Target_Frames (Client : in Probe_Manager_Type)
return MAT.Frames.Targets.Target_Frames_Access is
begin
return Client.Frames;
end Get_Target_Frames;
procedure Read_Probe (Client : in out Probe_Manager_Type;
Msg : in out MAT.Readers.Message) is
use type MAT.Types.Target_Tick_Ref;
Count : Natural := 0;
Time_Sec : MAT.Types.Uint32 := 0;
Time_Usec : MAT.Types.Uint32 := 0;
Frame : constant access MAT.Events.Frame_Info := Client.Frame;
begin
Client.Event.Thread := 0;
Frame.Stack := 0;
Frame.Cur_Depth := 0;
for I in Client.Probe'Range loop
declare
Def : MAT.Events.Attribute renames Client.Probe (I);
begin
case Def.Ref is
when P_TIME_SEC =>
Time_Sec := MAT.Readers.Marshaller.Get_Target_Uint32 (Msg, Def.Kind);
when P_TIME_USEC =>
Time_Usec := MAT.Readers.Marshaller.Get_Target_Uint32 (Msg, Def.Kind);
when P_THREAD_ID =>
Client.Event.Thread := MAT.Types.Target_Thread_Ref
(MAT.Readers.Marshaller.Get_Target_Uint32 (Msg, Def.Kind));
when P_THREAD_SP =>
Frame.Stack := MAT.Readers.Marshaller.Get_Target_Addr (Msg, Def.Kind);
when P_FRAME =>
Count := Natural (MAT.Readers.Marshaller.Get_Target_Uint32 (Msg,
Def.Kind));
when P_FRAME_PC =>
for I in 1 .. Count loop -- reverse Count .. 1 loop
if Count < Frame.Depth then
Frame.Frame (Count - I + 1) := MAT.Readers.Marshaller.Get_Target_Addr (Msg,
Def.Kind);
end if;
end loop;
when others =>
null;
end case;
end;
end loop;
-- Convert the time in usec to make computation easier.
Client.Event.Time := MAT.Types.Target_Tick_Ref (Time_Sec) * 1_000_000;
Client.Event.Time := Client.Event.Time + MAT.Types.Target_Tick_Ref (Time_Usec);
Frame.Cur_Depth := Count;
exception
when E : others =>
Log.Error ("Marshaling error, frame count {0}", Natural'Image (Count));
raise;
end Read_Probe;
procedure Dispatch_Message (Client : in out Probe_Manager_Type;
Msg : in out MAT.Readers.Message_Type) is
use type MAT.Events.Attribute_Table_Ptr;
use type MAT.Events.Targets.Target_Events_Access;
Event : constant MAT.Types.Uint16 := MAT.Readers.Marshaller.Get_Uint16 (Msg.Buffer);
Pos : constant Handler_Maps.Cursor := Client.Handlers.Find (Event);
begin
if Log.Get_Level = Util.Log.DEBUG_LEVEL then
Log.Debug ("Dispatch message {0} - size {1}",
MAT.Types.Uint16'Image (Event),
Natural'Image (Msg.Size));
end if;
if not Handler_Maps.Has_Element (Pos) then
-- Message is not handled, skip it.
null;
else
if Client.Probe /= null then
Read_Probe (Client, Msg);
end if;
declare
Handler : constant Probe_Handler := Handler_Maps.Element (Pos);
begin
Client.Event.Prev_Id := 0;
Client.Event.Old_Size := 0;
Client.Event.Event := Event;
Client.Event.Index := Handler.Id;
Handler.Probe.Extract (Handler.Mapping.all'Access, Msg, Client.Event);
Client.Frames.Insert (Pc => Client.Frame.Frame (1 .. Client.Frame.Cur_Depth),
Result => Client.Event.Frame);
Client.Events.Insert (Client.Event);
Handler.Probe.Execute (Client.Event);
end;
end if;
exception
when E : others =>
Log.Error ("Exception while processing event " & MAT.Types.Uint16'Image (Event), E, True);
end Dispatch_Message;
-- ------------------------------
-- Read an event definition from the stream and configure the reader.
-- ------------------------------
procedure Read_Definition (Client : in out Probe_Manager_Type;
Msg : in out MAT.Readers.Message_Type) is
Name : constant String := MAT.Readers.Marshaller.Get_String (Msg);
Event : constant MAT.Types.Uint16 := MAT.Readers.Marshaller.Get_Uint16 (Msg.Buffer);
Count : constant MAT.Types.Uint16 := MAT.Readers.Marshaller.Get_Uint16 (Msg.Buffer);
Pos : constant Probe_Maps.Cursor := Client.Probes.Find (Name);
Frame : Probe_Handler;
procedure Add_Handler (Key : in String;
Element : in out Probe_Handler);
procedure Add_Handler (Key : in String;
Element : in out Probe_Handler) is
pragma Unreferenced (Key);
begin
Client.Handlers.Insert (Event, Element);
end Add_Handler;
begin
Log.Debug ("Read event definition {0} with {1} attributes",
Name, MAT.Types.Uint16'Image (Count));
if Name = "start" then
Frame.Mapping := new MAT.Events.Attribute_Table (1 .. Natural (Count));
Frame.Attributes := Probe_Attributes'Access;
Client.Probe := Frame.Mapping;
else
Frame.Mapping := null;
end if;
for I in 1 .. Natural (Count) loop
declare
Name : constant String := MAT.Readers.Marshaller.Get_String (Msg);
Size : constant MAT.Types.Uint16 := MAT.Readers.Marshaller.Get_Uint16 (Msg.Buffer);
procedure Read_Attribute (Key : in String;
Element : in out Probe_Handler);
procedure Read_Attribute (Key : in String;
Element : in out Probe_Handler) is
pragma Unreferenced (Key);
use type MAT.Events.Attribute_Table_Ptr;
begin
if Element.Mapping = null then
Element.Mapping := new MAT.Events.Attribute_Table (1 .. Natural (Count));
end if;
for J in Element.Attributes'Range loop
if Element.Attributes (J).Name.all = Name then
Element.Mapping (I) := Element.Attributes (J);
if Size = 1 then
Element.Mapping (I).Kind := MAT.Events.T_UINT8;
elsif Size = 2 then
Element.Mapping (I).Kind := MAT.Events.T_UINT16;
elsif Size = 4 then
Element.Mapping (I).Kind := MAT.Events.T_UINT32;
elsif Size = 8 then
Element.Mapping (I).Kind := MAT.Events.T_UINT64;
else
Element.Mapping (I).Kind := MAT.Events.T_UINT32;
end if;
end if;
end loop;
end Read_Attribute;
use type MAT.Events.Attribute_Table_Ptr;
begin
if Probe_Maps.Has_Element (Pos) then
Client.Probes.Update_Element (Pos, Read_Attribute'Access);
end if;
if Frame.Mapping /= null then
Read_Attribute ("start", Frame);
end if;
end;
end loop;
if Probe_Maps.Has_Element (Pos) then
Client.Probes.Update_Element (Pos, Add_Handler'Access);
end if;
end Read_Definition;
-- ------------------------------
-- Read a list of event definitions from the stream and configure the reader.
-- ------------------------------
procedure Read_Event_Definitions (Client : in out Probe_Manager_Type;
Msg : in out MAT.Readers.Message) is
Count : MAT.Types.Uint16;
begin
if Client.Frame = null then
Client.Frame := new MAT.Events.Frame_Info (512);
end if;
Client.Version := MAT.Readers.Marshaller.Get_Uint16 (Msg.Buffer);
Count := MAT.Readers.Marshaller.Get_Uint16 (Msg.Buffer);
Log.Info ("Read event stream version {0} with {1} definitions",
MAT.Types.Uint16'Image (Client.Version),
MAT.Types.Uint16'Image (Count));
for I in 1 .. Count loop
Read_Definition (Client, Msg);
end loop;
-- Look at the probe definition to gather the target address size.
Client.Addr_Size := MAT.Events.T_UINT32;
for I in Client.Probe'Range loop
declare
Def : MAT.Events.Attribute renames Client.Probe (I);
begin
if Def.Ref = P_THREAD_SP or Def.Ref = P_FRAME_PC then
Client.Addr_Size := Def.Kind;
exit;
end if;
end;
end loop;
exception
when E : MAT.Readers.Marshaller.Buffer_Underflow_Error =>
Log.Error ("Not enough data in the message", E, True);
end Read_Event_Definitions;
-- ------------------------------
-- Get the size of a target address (4 or 8 bytes).
-- ------------------------------
function Get_Address_Size (Client : in Probe_Manager_Type) return MAT.Events.Attribute_Type is
begin
return Client.Addr_Size;
end Get_Address_Size;
end MAT.Events.Probes;
|
Implement Get_Target_Frames to retrieve the allocated target frames Allocate the target frames when the probe manager is created but do not release it when the probe manager is destroyed because the target process instance needs it
|
Implement Get_Target_Frames to retrieve the allocated target frames
Allocate the target frames when the probe manager is created but
do not release it when the probe manager is destroyed because the
target process instance needs it
|
Ada
|
apache-2.0
|
stcarrez/mat,stcarrez/mat,stcarrez/mat
|
762188acbda6d7394ceeaeebce4052c58728185b
|
src/gen-commands-generate.adb
|
src/gen-commands-generate.adb
|
-----------------------------------------------------------------------
-- gen-commands-generate -- Generate command for dynamo
-- Copyright (C) 2011, 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with GNAT.Command_Line;
with Ada.Directories;
with Ada.Text_IO;
package body Gen.Commands.Generate is
use GNAT.Command_Line;
use Ada.Directories;
-- ------------------------------
-- Execute the command with the arguments.
-- ------------------------------
procedure Execute (Cmd : in Command;
Generator : in out Gen.Generator.Handler) is
pragma Unreferenced (Cmd);
File_Count : Natural := 0;
begin
Generator.Read_Project ("dynamo.xml", True);
Gen.Generator.Read_Mappings (Generator);
-- Parse the command line for the --package option.
loop
case Getopt ("p: ? -package:") is
when ASCII.NUL => exit;
when '-' =>
if Full_Switch = "-package" then
Generator.Enable_Package_Generation (Parameter);
end if;
when 'p' =>
Generator.Enable_Package_Generation (Parameter);
when others =>
null;
end case;
end loop;
-- Read the model files.
loop
declare
Model_File : constant String := Get_Argument;
begin
exit when Model_File'Length = 0;
File_Count := File_Count + 1;
if Ada.Directories.Exists (Model_File)
and then Ada.Directories.Kind (Model_File) = Ada.Directories.Directory then
Gen.Generator.Read_Models (Generator, Model_File);
else
Gen.Generator.Read_Model (Generator, Model_File, False);
end if;
end;
end loop;
if File_Count = 0 then
Gen.Generator.Read_Models (Generator, "db");
end if;
-- Run the generation.
Gen.Generator.Prepare (Generator);
Gen.Generator.Generate_All (Generator);
Gen.Generator.Finish (Generator);
Generator.Save_Project;
end Execute;
-- ------------------------------
-- Write the help associated with the command.
-- ------------------------------
procedure Help (Cmd : in Command;
Generator : in out Gen.Generator.Handler) is
pragma Unreferenced (Cmd, Generator);
use Ada.Text_IO;
begin
Put_Line ("generate: Generate the Ada files for the database model or queries");
Put_Line ("Usage: generate [--package NAME] [MODEL ...]");
New_Line;
Put_Line (" Read the XML/XMI model description (Hibernate mapping, query mapping, ...)");
Put_Line (" and generate the Ada model files that correspond to the mapping.");
Put_Line (" The --package option allows to generate only the package with the given name.");
Put_Line (" The default is to generate all the packages that are recognized.");
end Help;
end Gen.Commands.Generate;
|
-----------------------------------------------------------------------
-- gen-commands-generate -- Generate command for dynamo
-- Copyright (C) 2011, 2012, 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with GNAT.Command_Line;
with Ada.Directories;
with Ada.Text_IO;
package body Gen.Commands.Generate is
use GNAT.Command_Line;
use Ada.Directories;
-- ------------------------------
-- Execute the command with the arguments.
-- ------------------------------
procedure Execute (Cmd : in Command;
Generator : in out Gen.Generator.Handler) is
pragma Unreferenced (Cmd);
File_Count : Natural := 0;
begin
Generator.Read_Project ("dynamo.xml", True);
Gen.Generator.Read_Mappings (Generator);
-- Parse the command line for the --package option.
loop
case Getopt ("p: ? -package:") is
when ASCII.NUL => exit;
when '-' =>
if Full_Switch = "-package" then
Generator.Enable_Package_Generation (Parameter);
end if;
when 'p' =>
Generator.Enable_Package_Generation (Parameter);
when others =>
null;
end case;
end loop;
-- Read the model files.
loop
declare
Model_File : constant String := Get_Argument;
begin
exit when Model_File'Length = 0;
File_Count := File_Count + 1;
if Ada.Directories.Exists (Model_File)
and then Ada.Directories.Kind (Model_File) = Ada.Directories.Directory
then
Gen.Generator.Read_Models (Generator, Model_File);
else
Gen.Generator.Read_Model (Generator, Model_File, False);
end if;
end;
end loop;
if File_Count = 0 then
Gen.Generator.Read_Models (Generator, "db");
end if;
-- Run the generation.
Gen.Generator.Prepare (Generator);
Gen.Generator.Generate_All (Generator);
Gen.Generator.Finish (Generator);
Generator.Save_Project;
end Execute;
-- ------------------------------
-- Write the help associated with the command.
-- ------------------------------
procedure Help (Cmd : in Command;
Generator : in out Gen.Generator.Handler) is
pragma Unreferenced (Cmd, Generator);
use Ada.Text_IO;
begin
Put_Line ("generate: Generate the Ada files for the database model or queries");
Put_Line ("Usage: generate [--package NAME] [MODEL ...]");
New_Line;
Put_Line (" Read the XML/XMI model description (Hibernate mapping, query mapping, ...)");
Put_Line (" and generate the Ada model files that correspond to the mapping.");
Put_Line (" The --package option allows to generate only the package with the given name.");
Put_Line (" The default is to generate all the packages that are recognized.");
end Help;
end Gen.Commands.Generate;
|
Fix compilation warnings
|
Fix compilation warnings
|
Ada
|
apache-2.0
|
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
|
bd58c2ebdc681dc7534b80a4a8ae386e93678ca1
|
src/asf-sessions-factory.adb
|
src/asf-sessions-factory.adb
|
-----------------------------------------------------------------------
-- asf.sessions.factory -- ASF Sessions factory
-- Copyright (C) 2010, 2011, 2012, 2014, 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Encoders.Base64;
with Util.Log.Loggers;
-- The <b>ASF.Sessions.Factory</b> package is a factory for creating, searching
-- and deleting sessions.
package body ASF.Sessions.Factory is
use Ada.Finalization;
use Ada.Strings.Unbounded;
-- The logger
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("ASF.Sessions.Factory");
-- ------------------------------
-- Allocate a unique and random session identifier. The default implementation
-- generates a 256 bit random number that it serializes as base64 in the string.
-- Upon successful completion, the sequence string buffer is allocated and
-- returned in <b>Id</b>. The buffer will be freed when the session is removed.
-- ------------------------------
procedure Allocate_Session_Id (Factory : in out Session_Factory;
Id : out Ada.Strings.Unbounded.String_Access) is
use Ada.Streams;
Rand : Stream_Element_Array (0 .. 4 * Factory.Id_Size - 1);
Buffer : Stream_Element_Array (0 .. 4 * 3 * Factory.Id_Size);
Encoder : Util.Encoders.Base64.Encoder;
Last : Stream_Element_Offset;
Encoded : Stream_Element_Offset;
begin
Factory.Sessions.Generate_Id (Rand);
-- Encode the random stream in base64 and save it into the Id string.
Encoder.Transform (Data => Rand, Into => Buffer,
Last => Last, Encoded => Encoded);
Id := new String (1 .. Natural (Encoded + 1));
for I in 0 .. Encoded loop
Id (Natural (I + 1)) := Character'Val (Buffer (I));
end loop;
Log.Info ("Allocated session {0}", Id.all);
end Allocate_Session_Id;
-- ------------------------------
-- Create a new session
-- ------------------------------
procedure Create_Session (Factory : in out Session_Factory;
Result : out Session) is
Sess : Session;
Impl : constant Session_Record_Access
:= new Session_Record '(Ada.Finalization.Limited_Controlled with
Ref_Counter => Util.Concurrent.Counters.ONE,
Create_Time => Ada.Calendar.Clock,
Max_Inactive => Factory.Max_Inactive,
others => <>);
begin
Impl.Access_Time := Impl.Create_Time;
Sess.Impl := Impl;
Session_Factory'Class (Factory).Allocate_Session_Id (Impl.Id);
Factory.Sessions.Insert (Sess);
Result := Sess;
end Create_Session;
-- ------------------------------
-- Deletes the session.
-- ------------------------------
procedure Delete_Session (Factory : in out Session_Factory;
Sess : in out Session) is
begin
null;
end Delete_Session;
-- ------------------------------
-- Finds the session knowing the session identifier.
-- If the session is found, the last access time is updated.
-- Otherwise, the null session object is returned.
-- ------------------------------
procedure Find_Session (Factory : in out Session_Factory;
Id : in String;
Result : out Session) is
begin
Result := Factory.Sessions.Find (Id);
if Result.Is_Valid then
Result.Impl.Access_Time := Ada.Calendar.Clock;
Log.Info ("Found active session {0}", Id);
else
Log.Info ("Invalid session {0}", Id);
end if;
end Find_Session;
-- ------------------------------
-- Returns the maximum time interval, in seconds, that the servlet container will
-- keep this session open between client accesses. After this interval, the servlet
-- container will invalidate the session. The maximum time interval can be set with
-- the Set_Max_Inactive_Interval method.
-- A negative time indicates the session should never timeout.
-- ------------------------------
function Get_Max_Inactive_Interval (Factory : in Session_Factory) return Duration is
begin
return Factory.Max_Inactive;
end Get_Max_Inactive_Interval;
-- ------------------------------
-- Specifies the time, in seconds, between client requests before the servlet
-- container will invalidate this session. A negative time indicates the session
-- should never timeout.
-- ------------------------------
procedure Set_Max_Inactive_Interval (Factory : in out Session_Factory;
Interval : in Duration) is
begin
Factory.Max_Inactive := Interval;
end Set_Max_Inactive_Interval;
-- ------------------------------
-- Initialize the session factory.
-- ------------------------------
overriding
procedure Initialize (Factory : in out Session_Factory) is
begin
Factory.Sessions.Initialize;
end Initialize;
protected body Session_Cache is
-- ------------------------------
-- Find the session in the session cache.
-- ------------------------------
function Find (Id : in String) return Session is
Pos : constant Session_Maps.Cursor := Sessions.Find (Id'Unrestricted_Access);
begin
if Session_Maps.Has_Element (Pos) then
return Session_Maps.Element (Pos);
else
return Null_Session;
end if;
end Find;
-- ------------------------------
-- Insert the session in the session cache.
-- ------------------------------
procedure Insert (Sess : in Session) is
begin
Sessions.Insert (Sess.Impl.Id.all'Access, Sess);
end Insert;
-- ------------------------------
-- Generate a random bitstream.
-- ------------------------------
procedure Generate_Id (Rand : out Ada.Streams.Stream_Element_Array) is
use Ada.Streams;
use Interfaces;
Size : constant Stream_Element_Offset := Rand'Length / 4;
begin
-- Generate the random sequence.
for I in 0 .. Size - 1 loop
declare
Value : constant Unsigned_32 := Id_Random.Random (Random);
begin
Rand (4 * I) := Stream_Element (Value and 16#0FF#);
Rand (4 * I + 1) := Stream_Element (Shift_Right (Value, 8) and 16#0FF#);
Rand (4 * I + 2) := Stream_Element (Shift_Right (Value, 16) and 16#0FF#);
Rand (4 * I + 3) := Stream_Element (Shift_Right (Value, 24) and 16#0FF#);
end;
end loop;
end Generate_Id;
-- ------------------------------
-- Initialize the random generator.
-- ------------------------------
procedure Initialize is
begin
Id_Random.Reset (Random);
end Initialize;
end Session_Cache;
end ASF.Sessions.Factory;
|
-----------------------------------------------------------------------
-- asf.sessions.factory -- ASF Sessions factory
-- Copyright (C) 2010, 2011, 2012, 2014, 2015, 2016 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Encoders.Base64;
with Util.Log.Loggers;
-- The <b>ASF.Sessions.Factory</b> package is a factory for creating, searching
-- and deleting sessions.
package body ASF.Sessions.Factory is
use Ada.Finalization;
use Ada.Strings.Unbounded;
-- The logger
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("ASF.Sessions.Factory");
-- ------------------------------
-- Allocate a unique and random session identifier. The default implementation
-- generates a 256 bit random number that it serializes as base64 in the string.
-- Upon successful completion, the sequence string buffer is allocated and
-- returned in <b>Id</b>. The buffer will be freed when the session is removed.
-- ------------------------------
procedure Allocate_Session_Id (Factory : in out Session_Factory;
Id : out Ada.Strings.Unbounded.String_Access) is
use Ada.Streams;
Rand : Stream_Element_Array (0 .. 4 * Factory.Id_Size - 1);
Buffer : Stream_Element_Array (0 .. 4 * 3 * Factory.Id_Size);
Encoder : Util.Encoders.Base64.Encoder;
Last : Stream_Element_Offset;
Encoded : Stream_Element_Offset;
begin
Factory.Sessions.Generate_Id (Rand);
-- Encode the random stream in base64 and save it into the Id string.
Encoder.Transform (Data => Rand, Into => Buffer,
Last => Last, Encoded => Encoded);
Id := new String (1 .. Natural (Encoded + 1));
for I in 0 .. Encoded loop
Id (Natural (I + 1)) := Character'Val (Buffer (I));
end loop;
Log.Info ("Allocated session {0}", Id.all);
end Allocate_Session_Id;
-- ------------------------------
-- Create a new session
-- ------------------------------
procedure Create_Session (Factory : in out Session_Factory;
Result : out Session) is
Sess : Session;
Impl : constant Session_Record_Access
:= new Session_Record '(Ada.Finalization.Limited_Controlled with
Ref_Counter => Util.Concurrent.Counters.ONE,
Create_Time => Ada.Calendar.Clock,
Max_Inactive => Factory.Max_Inactive,
others => <>);
begin
Impl.Access_Time := Impl.Create_Time;
Sess.Impl := Impl;
Session_Factory'Class (Factory).Allocate_Session_Id (Impl.Id);
Factory.Sessions.Insert (Sess);
Result := Sess;
end Create_Session;
-- ------------------------------
-- Deletes the session.
-- ------------------------------
procedure Delete_Session (Factory : in out Session_Factory;
Sess : in out Session) is
begin
Factory.Sessions.Delete (Sess);
end Delete_Session;
-- ------------------------------
-- Finds the session knowing the session identifier.
-- If the session is found, the last access time is updated.
-- Otherwise, the null session object is returned.
-- ------------------------------
procedure Find_Session (Factory : in out Session_Factory;
Id : in String;
Result : out Session) is
begin
Result := Factory.Sessions.Find (Id);
if Result.Is_Valid then
Result.Impl.Access_Time := Ada.Calendar.Clock;
Log.Info ("Found active session {0}", Id);
else
Log.Info ("Invalid session {0}", Id);
end if;
end Find_Session;
-- ------------------------------
-- Returns the maximum time interval, in seconds, that the servlet container will
-- keep this session open between client accesses. After this interval, the servlet
-- container will invalidate the session. The maximum time interval can be set with
-- the Set_Max_Inactive_Interval method.
-- A negative time indicates the session should never timeout.
-- ------------------------------
function Get_Max_Inactive_Interval (Factory : in Session_Factory) return Duration is
begin
return Factory.Max_Inactive;
end Get_Max_Inactive_Interval;
-- ------------------------------
-- Specifies the time, in seconds, between client requests before the servlet
-- container will invalidate this session. A negative time indicates the session
-- should never timeout.
-- ------------------------------
procedure Set_Max_Inactive_Interval (Factory : in out Session_Factory;
Interval : in Duration) is
begin
Factory.Max_Inactive := Interval;
end Set_Max_Inactive_Interval;
-- ------------------------------
-- Initialize the session factory.
-- ------------------------------
overriding
procedure Initialize (Factory : in out Session_Factory) is
begin
Factory.Sessions.Initialize;
end Initialize;
protected body Session_Cache is
-- ------------------------------
-- Find the session in the session cache.
-- ------------------------------
function Find (Id : in String) return Session is
Pos : constant Session_Maps.Cursor := Sessions.Find (Id'Unrestricted_Access);
begin
if Session_Maps.Has_Element (Pos) then
return Session_Maps.Element (Pos);
else
return Null_Session;
end if;
end Find;
-- ------------------------------
-- Insert the session in the session cache.
-- ------------------------------
procedure Insert (Sess : in Session) is
begin
Sessions.Insert (Sess.Impl.Id.all'Access, Sess);
end Insert;
-- ------------------------------
-- Remove the session from the session cache.
-- ------------------------------
procedure Delete (Sess : in out Session) is
Pos : Session_Maps.Cursor := Sessions.Find (Sess.Impl.Id.all'Access);
begin
if Session_Maps.Has_Element (Pos) then
Session_Maps.Delete (Sessions, Pos);
end if;
Finalize (Sess);
end Delete;
-- ------------------------------
-- Generate a random bitstream.
-- ------------------------------
procedure Generate_Id (Rand : out Ada.Streams.Stream_Element_Array) is
use Ada.Streams;
use Interfaces;
Size : constant Stream_Element_Offset := Rand'Length / 4;
begin
-- Generate the random sequence.
for I in 0 .. Size - 1 loop
declare
Value : constant Unsigned_32 := Id_Random.Random (Random);
begin
Rand (4 * I) := Stream_Element (Value and 16#0FF#);
Rand (4 * I + 1) := Stream_Element (Shift_Right (Value, 8) and 16#0FF#);
Rand (4 * I + 2) := Stream_Element (Shift_Right (Value, 16) and 16#0FF#);
Rand (4 * I + 3) := Stream_Element (Shift_Right (Value, 24) and 16#0FF#);
end;
end loop;
end Generate_Id;
-- ------------------------------
-- Initialize the random generator.
-- ------------------------------
procedure Initialize is
begin
Id_Random.Reset (Random);
end Initialize;
end Session_Cache;
end ASF.Sessions.Factory;
|
Implement the Delete protected procedure and update Delete_Session to use it
|
Implement the Delete protected procedure and update Delete_Session to use it
|
Ada
|
apache-2.0
|
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
|
a7f3c6921531e5f6fbfd87bbd8d4b2b9f23174e0
|
src/aws/asf-requests-web.ads
|
src/aws/asf-requests-web.ads
|
-----------------------------------------------------------------------
-- asf.requests -- ASF Requests
-- 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 AWS.Status;
with AWS.Headers;
with AWS.Attachments;
package ASF.Requests.Web is
type Request is new ASF.Requests.Request with private;
type Request_Access is access all Request'Class;
function Get_Parameter (R : Request; Name : String) return String;
-- Set the AWS data received to initialize the request object.
procedure Set_Request (Req : in out Request;
Data : access AWS.Status.Data);
-- Returns the name of the HTTP method with which this request was made,
-- for example, GET, POST, or PUT. Same as the value of the CGI variable
-- REQUEST_METHOD.
function Get_Method (Req : in Request) return String;
-- Returns the name and version of the protocol the request uses in the form
-- protocol/majorVersion.minorVersion, for example, HTTP/1.1. For HTTP servlets,
-- the value returned is the same as the value of the CGI variable SERVER_PROTOCOL.
function Get_Protocol (Req : in Request) return String;
-- Returns the part of this request's URL from the protocol name up to the query
-- string in the first line of the HTTP request. The web container does not decode
-- this String. For example:
-- First line of HTTP request Returned Value
-- POST /some/path.html HTTP/1.1 /some/path.html
-- GET http://foo.bar/a.html HTTP/1.0 /a.html
-- HEAD /xyz?a=b HTTP/1.1 /xyz
function Get_Request_URI (Req : in Request) return String;
-- Returns the value of the specified request header as a String. If the request
-- did not include a header of the specified name, this method returns null.
-- If there are multiple headers with the same name, this method returns the
-- first head in the request. The header name is case insensitive. You can use
-- this method with any request header.
function Get_Header (Req : in Request;
Name : in String) return String;
-- Returns all the values of the specified request header as an Enumeration
-- of String objects.
--
-- Some headers, such as Accept-Language can be sent by clients as several headers
-- each with a different value rather than sending the header as a comma
-- separated list.
--
-- If the request did not include any headers of the specified name, this method
-- returns an empty Enumeration. The header name is case insensitive. You can use
-- this method with any request header.
function Get_Headers (Req : in Request;
Name : in String) return String;
-- Iterate over the request headers and executes the <b>Process</b> procedure.
procedure Iterate_Headers (Req : in Request;
Process : not null access
procedure (Name : in String;
Value : in String));
-- Returns the Internet Protocol (IP) address of the client or last proxy that
-- sent the request. For HTTP servlets, same as the value of the CGI variable
-- REMOTE_ADDR.
function Get_Remote_Addr (Req : in Request) return String;
-- Get the number of parts included in the request.
function Get_Part_Count (Req : in Request) return Natural;
-- Process the part at the given position and executes the <b>Process</b> operation
-- with the part object.
procedure Process_Part (Req : in out Request;
Position : in Positive;
Process : not null access
procedure (Data : in ASF.Parts.Part'Class));
-- Process the part identifed by <b>Id</b> and executes the <b>Process</b> operation
-- with the part object.
procedure Process_Part (Req : in out Request;
Id : in String;
Process : not null access
procedure (Data : in ASF.Parts.Part'Class));
private
type Request is new ASF.Requests.Request with record
Data : access AWS.Status.Data;
Headers : AWS.Headers.List;
end record;
end ASF.Requests.Web;
|
-----------------------------------------------------------------------
-- asf.requests -- ASF Requests
-- Copyright (C) 2009, 2010, 2011, 2012, 2013 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with AWS.Status;
with AWS.Headers;
package ASF.Requests.Web is
type Request is new ASF.Requests.Request with private;
type Request_Access is access all Request'Class;
function Get_Parameter (R : Request; Name : String) return String;
-- Set the AWS data received to initialize the request object.
procedure Set_Request (Req : in out Request;
Data : access AWS.Status.Data);
-- Returns the name of the HTTP method with which this request was made,
-- for example, GET, POST, or PUT. Same as the value of the CGI variable
-- REQUEST_METHOD.
function Get_Method (Req : in Request) return String;
-- Returns the name and version of the protocol the request uses in the form
-- protocol/majorVersion.minorVersion, for example, HTTP/1.1. For HTTP servlets,
-- the value returned is the same as the value of the CGI variable SERVER_PROTOCOL.
function Get_Protocol (Req : in Request) return String;
-- Returns the part of this request's URL from the protocol name up to the query
-- string in the first line of the HTTP request. The web container does not decode
-- this String. For example:
-- First line of HTTP request Returned Value
-- POST /some/path.html HTTP/1.1 /some/path.html
-- GET http://foo.bar/a.html HTTP/1.0 /a.html
-- HEAD /xyz?a=b HTTP/1.1 /xyz
function Get_Request_URI (Req : in Request) return String;
-- Returns the value of the specified request header as a String. If the request
-- did not include a header of the specified name, this method returns null.
-- If there are multiple headers with the same name, this method returns the
-- first head in the request. The header name is case insensitive. You can use
-- this method with any request header.
function Get_Header (Req : in Request;
Name : in String) return String;
-- Returns all the values of the specified request header as an Enumeration
-- of String objects.
--
-- Some headers, such as Accept-Language can be sent by clients as several headers
-- each with a different value rather than sending the header as a comma
-- separated list.
--
-- If the request did not include any headers of the specified name, this method
-- returns an empty Enumeration. The header name is case insensitive. You can use
-- this method with any request header.
function Get_Headers (Req : in Request;
Name : in String) return String;
-- Iterate over the request headers and executes the <b>Process</b> procedure.
procedure Iterate_Headers (Req : in Request;
Process : not null access
procedure (Name : in String;
Value : in String));
-- Returns the Internet Protocol (IP) address of the client or last proxy that
-- sent the request. For HTTP servlets, same as the value of the CGI variable
-- REMOTE_ADDR.
function Get_Remote_Addr (Req : in Request) return String;
-- Get the number of parts included in the request.
function Get_Part_Count (Req : in Request) return Natural;
-- Process the part at the given position and executes the <b>Process</b> operation
-- with the part object.
procedure Process_Part (Req : in out Request;
Position : in Positive;
Process : not null access
procedure (Data : in ASF.Parts.Part'Class));
-- Process the part identifed by <b>Id</b> and executes the <b>Process</b> operation
-- with the part object.
procedure Process_Part (Req : in out Request;
Id : in String;
Process : not null access
procedure (Data : in ASF.Parts.Part'Class));
private
type Request is new ASF.Requests.Request with record
Data : access AWS.Status.Data;
Headers : AWS.Headers.List;
end record;
end ASF.Requests.Web;
|
Fix compilation warning
|
Fix compilation warning
|
Ada
|
apache-2.0
|
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
|
de78e82d7889eb3a78c2f720f2328b33a71b3782
|
src/gen-commands-project.adb
|
src/gen-commands-project.adb
|
-----------------------------------------------------------------------
-- gen-commands-project -- Project creation command for dynamo
-- Copyright (C) 2011, 2012, 2013, 2014, 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Directories;
with Ada.Text_IO;
with Gen.Artifacts;
with GNAT.Command_Line;
with GNAT.OS_Lib;
with Util.Log.Loggers;
with Util.Strings.Transforms;
package body Gen.Commands.Project is
use Util.Log;
Log : constant Loggers.Logger := Loggers.Create ("Gen.Commands.Project");
-- ------------------------------
-- Generator Command
-- ------------------------------
function Get_Name_From_Email (Email : in String) return String;
-- ------------------------------
-- Get the user name from the email address.
-- Returns the possible user name from his email address.
-- ------------------------------
function Get_Name_From_Email (Email : in String) return String is
Pos : Natural := Util.Strings.Index (Email, '<');
begin
if Pos > 0 then
return Email (Email'First .. Pos - 1);
end if;
Pos := Util.Strings.Index (Email, '@');
if Pos > 0 then
return Email (Email'First .. Pos - 1);
else
return Email;
end if;
end Get_Name_From_Email;
-- ------------------------------
-- Execute the command with the arguments.
-- ------------------------------
overriding
procedure Execute (Cmd : in Command;
Name : in String;
Args : in Argument_List'Class;
Generator : in out Gen.Generator.Handler) is
pragma Unreferenced (Name, Args);
use GNAT.Command_Line;
Web_Flag : aliased Boolean := False;
Tool_Flag : aliased Boolean := False;
Ado_Flag : aliased Boolean := False;
Gtk_Flag : aliased Boolean := False;
begin
-- If a dynamo.xml file exists, read it.
if Ada.Directories.Exists ("dynamo.xml") then
Generator.Read_Project ("dynamo.xml");
else
Generator.Set_Project_Property ("license", "apache");
Generator.Set_Project_Property ("author", "unknown");
Generator.Set_Project_Property ("author_email", "[email protected]");
end if;
-- Parse the command line
loop
case Getopt ("l: ? -web -tool -ado -gtk") is
when ASCII.NUL => exit;
when '-' =>
if Full_Switch = "-web" then
Web_Flag := True;
elsif Full_Switch = "-tool" then
Tool_Flag := True;
elsif Full_Switch = "-ado" then
Ado_Flag := True;
elsif Full_Switch = "-gtk" then
Gtk_Flag := True;
end if;
when 'l' =>
declare
L : constant String := Util.Strings.Transforms.To_Lower_Case (Parameter);
begin
Log.Info ("License {0}", L);
if L = "apache" then
Generator.Set_Project_Property ("license", "apache");
elsif L = "gpl" then
Generator.Set_Project_Property ("license", "gpl");
elsif L = "gpl3" then
Generator.Set_Project_Property ("license", "gpl3");
elsif L = "mit" then
Generator.Set_Project_Property ("license", "mit");
elsif L = "bsd3" then
Generator.Set_Project_Property ("license", "bsd3");
elsif L = "proprietary" then
Generator.Set_Project_Property ("license", "proprietary");
else
Generator.Error ("Invalid license: {0}", L);
Generator.Error ("Valid licenses: apache, gpl, gpl3, mit, bsd3, proprietary");
return;
end if;
end;
when others =>
null;
end case;
end loop;
if not Web_Flag and not Ado_Flag and not Tool_Flag and not Gtk_Flag then
Web_Flag := True;
end if;
declare
Name : constant String := Get_Argument;
Arg2 : constant String := Get_Argument;
Arg3 : constant String := Get_Argument;
begin
if Name'Length = 0 then
Generator.Error ("Missing project name");
Cmd.Usage;
return;
end if;
if Util.Strings.Index (Arg2, '@') > Arg2'First then
Generator.Set_Project_Property ("author_email", Arg2);
if Arg3'Length = 0 then
Generator.Set_Project_Property ("author", Get_Name_From_Email (Arg2));
else
Generator.Set_Project_Property ("author", Arg3);
end if;
elsif Util.Strings.Index (Arg3, '@') > Arg3'First then
Generator.Set_Project_Property ("author", Arg2);
Generator.Set_Project_Property ("author_email", Arg3);
elsif Arg3'Length > 0 then
Generator.Error ("The last argument should be the author's email address.");
Cmd.Usage;
return;
end if;
Generator.Set_Project_Property ("is_web", Boolean'Image (Web_Flag));
Generator.Set_Project_Property ("is_tool", Boolean'Image (Tool_Flag));
Generator.Set_Project_Property ("is_ado", Boolean'Image (Ado_Flag));
Generator.Set_Project_Property ("is_gtk", Boolean'Image (Gtk_Flag));
Generator.Set_Project_Name (Name);
Generator.Set_Force_Save (False);
if Ado_Flag then
Gen.Generator.Generate_All (Generator, Gen.Artifacts.ITERATION_TABLE, "project-ado");
elsif Gtk_Flag then
Gen.Generator.Generate_All (Generator, Gen.Artifacts.ITERATION_TABLE, "project-gtk");
else
Gen.Generator.Generate_All (Generator, Gen.Artifacts.ITERATION_TABLE, "project");
end if;
Generator.Save_Project;
declare
use type GNAT.OS_Lib.String_Access;
Path : constant GNAT.OS_Lib.String_Access
:= GNAT.OS_Lib.Locate_Exec_On_Path ("autoconf");
Args : GNAT.OS_Lib.Argument_List (1 .. 0);
Status : Boolean;
begin
if Path = null then
Generator.Error ("The 'autoconf' tool was not found. It is necessary to "
& "generate the configure script.");
Generator.Error ("Install 'autoconf' or launch it manually.");
else
Ada.Directories.Set_Directory (Generator.Get_Result_Directory);
Log.Info ("Executing {0}", Path.all);
GNAT.OS_Lib.Spawn (Path.all, Args, Status);
if not Status then
Generator.Error ("Execution of {0} failed", Path.all);
end if;
end if;
end;
end;
end Execute;
-- ------------------------------
-- Write the help associated with the command.
-- ------------------------------
overriding
procedure Help (Cmd : in Command;
Generator : in out Gen.Generator.Handler) is
pragma Unreferenced (Cmd, Generator);
use Ada.Text_IO;
begin
Put_Line ("create-project: Create a new Ada Web Application project");
Put_Line ("Usage: create-project [-l apache|gpl|gpl3|mit|bsd3|proprietary] [--web] [--tool]"
& "[--ado] [--gtk] NAME [AUTHOR] [EMAIL]");
New_Line;
Put_Line (" Creates a new AWA application with the name passed in NAME.");
Put_Line (" The application license is controlled with the -l option. ");
Put_Line (" License headers can use either the Apache, the MIT license, the BSD 3 clauses");
Put_Line (" license, the GNU licenses or a proprietary license.");
Put_Line (" The author's name and email addresses are also reported in generated files.");
New_Line;
Put_Line (" --web Generate a Web application (the default)");
Put_Line (" --tool Generate a command line tool");
Put_Line (" --ado Generate a database tool operation for ADO");
Put_Line (" --gtk Generate a GtkAda project");
end Help;
end Gen.Commands.Project;
|
-----------------------------------------------------------------------
-- gen-commands-project -- Project creation command for dynamo
-- Copyright (C) 2011, 2012, 2013, 2014, 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Directories;
with Ada.Text_IO;
with Gen.Artifacts;
with GNAT.Command_Line;
with GNAT.OS_Lib;
with Util.Log.Loggers;
with Util.Strings.Transforms;
package body Gen.Commands.Project is
use Util.Log;
Log : constant Loggers.Logger := Loggers.Create ("Gen.Commands.Project");
-- ------------------------------
-- Generator Command
-- ------------------------------
function Get_Name_From_Email (Email : in String) return String;
-- ------------------------------
-- Get the user name from the email address.
-- Returns the possible user name from his email address.
-- ------------------------------
function Get_Name_From_Email (Email : in String) return String is
Pos : Natural := Util.Strings.Index (Email, '<');
begin
if Pos > 0 then
return Email (Email'First .. Pos - 1);
end if;
Pos := Util.Strings.Index (Email, '@');
if Pos > 0 then
return Email (Email'First .. Pos - 1);
else
return Email;
end if;
end Get_Name_From_Email;
-- ------------------------------
-- Execute the command with the arguments.
-- ------------------------------
overriding
procedure Execute (Cmd : in Command;
Name : in String;
Args : in Argument_List'Class;
Generator : in out Gen.Generator.Handler) is
pragma Unreferenced (Name, Args);
use GNAT.Command_Line;
Web_Flag : aliased Boolean := False;
Tool_Flag : aliased Boolean := False;
Ado_Flag : aliased Boolean := False;
Gtk_Flag : aliased Boolean := False;
Lib_Flag : aliased Boolean := False;
begin
-- If a dynamo.xml file exists, read it.
if Ada.Directories.Exists ("dynamo.xml") then
Generator.Read_Project ("dynamo.xml");
else
Generator.Set_Project_Property ("license", "apache");
Generator.Set_Project_Property ("author", "unknown");
Generator.Set_Project_Property ("author_email", "[email protected]");
end if;
-- Parse the command line
loop
case Getopt ("l: ? -web -tool -ado -gtk") is
when ASCII.NUL => exit;
when '-' =>
if Full_Switch = "-web" then
Web_Flag := True;
elsif Full_Switch = "-tool" then
Tool_Flag := True;
elsif Full_Switch = "-ado" then
Ado_Flag := True;
elsif Full_Switch = "-lib" then
Lib_Flag := True;
elsif Full_Switch = "-gtk" then
Gtk_Flag := True;
end if;
when 'l' =>
declare
L : constant String := Util.Strings.Transforms.To_Lower_Case (Parameter);
begin
Log.Info ("License {0}", L);
if L = "apache" then
Generator.Set_Project_Property ("license", "apache");
elsif L = "gpl" then
Generator.Set_Project_Property ("license", "gpl");
elsif L = "gpl3" then
Generator.Set_Project_Property ("license", "gpl3");
elsif L = "mit" then
Generator.Set_Project_Property ("license", "mit");
elsif L = "bsd3" then
Generator.Set_Project_Property ("license", "bsd3");
elsif L = "proprietary" then
Generator.Set_Project_Property ("license", "proprietary");
else
Generator.Error ("Invalid license: {0}", L);
Generator.Error ("Valid licenses: apache, gpl, gpl3, mit, bsd3, proprietary");
return;
end if;
end;
when others =>
null;
end case;
end loop;
if not Web_Flag and not Ado_Flag and not Tool_Flag and not Gtk_Flag then
Web_Flag := True;
end if;
declare
Name : constant String := Get_Argument;
Arg2 : constant String := Get_Argument;
Arg3 : constant String := Get_Argument;
begin
if Name'Length = 0 then
Generator.Error ("Missing project name");
Cmd.Usage;
return;
end if;
if Util.Strings.Index (Arg2, '@') > Arg2'First then
Generator.Set_Project_Property ("author_email", Arg2);
if Arg3'Length = 0 then
Generator.Set_Project_Property ("author", Get_Name_From_Email (Arg2));
else
Generator.Set_Project_Property ("author", Arg3);
end if;
elsif Util.Strings.Index (Arg3, '@') > Arg3'First then
Generator.Set_Project_Property ("author", Arg2);
Generator.Set_Project_Property ("author_email", Arg3);
elsif Arg3'Length > 0 then
Generator.Error ("The last argument should be the author's email address.");
Cmd.Usage;
return;
end if;
Generator.Set_Project_Property ("is_web", Boolean'Image (Web_Flag));
Generator.Set_Project_Property ("is_tool", Boolean'Image (Tool_Flag));
Generator.Set_Project_Property ("is_ado", Boolean'Image (Ado_Flag));
Generator.Set_Project_Property ("is_gtk", Boolean'Image (Gtk_Flag));
Generator.Set_Project_Property ("is_lib", Boolean'Image (Lib_Flag));
Generator.Set_Project_Name (Name);
Generator.Set_Force_Save (False);
if Ado_Flag then
Gen.Generator.Generate_All (Generator, Gen.Artifacts.ITERATION_TABLE, "project-ado");
elsif Gtk_Flag then
Gen.Generator.Generate_All (Generator, Gen.Artifacts.ITERATION_TABLE, "project-gtk");
elsif Lib_Flag then
Gen.Generator.Generate_All (Generator, Gen.Artifacts.ITERATION_TABLE, "project-lib");
else
Gen.Generator.Generate_All (Generator, Gen.Artifacts.ITERATION_TABLE, "project");
end if;
Generator.Save_Project;
declare
use type GNAT.OS_Lib.String_Access;
Path : constant GNAT.OS_Lib.String_Access
:= GNAT.OS_Lib.Locate_Exec_On_Path ("autoconf");
Args : GNAT.OS_Lib.Argument_List (1 .. 0);
Status : Boolean;
begin
if Path = null then
Generator.Error ("The 'autoconf' tool was not found. It is necessary to "
& "generate the configure script.");
Generator.Error ("Install 'autoconf' or launch it manually.");
else
Ada.Directories.Set_Directory (Generator.Get_Result_Directory);
Log.Info ("Executing {0}", Path.all);
GNAT.OS_Lib.Spawn (Path.all, Args, Status);
if not Status then
Generator.Error ("Execution of {0} failed", Path.all);
end if;
end if;
end;
end;
end Execute;
-- ------------------------------
-- Write the help associated with the command.
-- ------------------------------
overriding
procedure Help (Cmd : in Command;
Generator : in out Gen.Generator.Handler) is
pragma Unreferenced (Cmd, Generator);
use Ada.Text_IO;
begin
Put_Line ("create-project: Create a new Ada Web Application project");
Put_Line ("Usage: create-project [-l apache|gpl|gpl3|mit|bsd3|proprietary] [--web] [--tool]"
& "[--lib] [--ado] [--gtk] NAME [AUTHOR] [EMAIL]");
New_Line;
Put_Line (" Creates a new AWA application with the name passed in NAME.");
Put_Line (" The application license is controlled with the -l option. ");
Put_Line (" License headers can use either the Apache, the MIT license, the BSD 3 clauses");
Put_Line (" license, the GNU licenses or a proprietary license.");
Put_Line (" The author's name and email addresses are also reported in generated files.");
New_Line;
Put_Line (" --web Generate a Web application (the default)");
Put_Line (" --tool Generate a command line tool");
Put_Line (" --ado Generate a database tool operation for ADO");
Put_Line (" --gtk Generate a GtkAda project");
Put_Line (" --lib Generate a library project");
end Help;
end Gen.Commands.Project;
|
Add --lib option to the create-project command
|
Add --lib option to the create-project command
|
Ada
|
apache-2.0
|
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
|
7e3a404cf37e4779c345017f6bd77dcdade57b9a
|
awa/regtests/awa-testsuite.adb
|
awa/regtests/awa-testsuite.adb
|
-----------------------------------------------------------------------
-- Util testsuite - Util Testsuite
-- Copyright (C) 2009, 2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with AWA.Users.Services.Tests;
with AWA.Users.Tests;
with AWA.Blogs.Modules.Tests;
with AWA.Blogs.Tests;
with AWA.Helpers.Selectors.Tests;
with AWA.Storages.Services.Tests;
with AWA.Events.Services.Tests;
with AWA.Mail.Clients.Tests;
with AWA.Mail.Modules.Tests;
with AWA.Images.Services.Tests;
with AWA.Votes.Modules.Tests;
with AWA.Tags.Modules.Tests;
with AWA.Questions.Modules.Tests;
with AWA.Counters.Modules.Tests;
with AWA.Modules.Tests;
with ASF.Converters.Dates;
with AWA.Users.Modules;
with AWA.Mail.Modules;
with AWA.Blogs.Modules;
with AWA.Workspaces.Modules;
with AWA.Storages.Modules;
with AWA.Images.Modules;
with AWA.Questions.Modules;
with AWA.Votes.Modules;
with AWA.Tags.Modules;
with AWA.Changelogs.Modules;
with AWA.Counters.Modules;
with AWA.Converters.Dates;
with AWA.Tests;
with AWA.Services.Contexts;
with AWA.Jobs.Services.Tests;
with AWA.Jobs.Modules.Tests;
with AWA.Settings.Modules.Tests;
with AWA.Comments.Modules.Tests;
with AWA.Changelogs.Modules.Tests;
with AWA.Wikis.Modules.Tests;
-- with ASF.Server.Web;
with ASF.Server.Tests;
package body AWA.Testsuite is
Users : aliased AWA.Users.Modules.User_Module;
Workspaces : aliased AWA.Workspaces.Modules.Workspace_Module;
Mail : aliased AWA.Mail.Modules.Mail_Module;
Jobs : aliased AWA.Jobs.Modules.Job_Module;
Comments : aliased AWA.Comments.Modules.Comment_Module;
Blogs : aliased AWA.Blogs.Modules.Blog_Module;
Storages : aliased AWA.Storages.Modules.Storage_Module;
Images : aliased AWA.Images.Modules.Image_Module;
Questions : aliased AWA.Questions.Modules.Question_Module;
Votes : aliased AWA.Votes.Modules.Vote_Module;
Tags : aliased AWA.Tags.Modules.Tag_Module;
Settings : aliased AWA.Settings.Modules.Setting_Module;
Changelogs : aliased AWA.Changelogs.Modules.Changelog_Module;
Wikis : aliased AWA.Wikis.Modules.Wiki_Module;
Counters : aliased AWA.Counters.Modules.Counter_Module;
Date_Converter : aliased ASF.Converters.Dates.Date_Converter;
Rel_Date_Converter : aliased AWA.Converters.Dates.Relative_Date_Converter;
Tests : aliased Util.Tests.Test_Suite;
function Suite return Util.Tests.Access_Test_Suite is
Ret : constant Util.Tests.Access_Test_Suite := Tests'Access;
begin
AWA.Modules.Tests.Add_Tests (Ret);
AWA.Events.Services.Tests.Add_Tests (Ret);
AWA.Mail.Clients.Tests.Add_Tests (Ret);
AWA.Mail.Modules.Tests.Add_Tests (Ret);
AWA.Users.Services.Tests.Add_Tests (Ret);
AWA.Users.Tests.Add_Tests (Ret);
AWA.Counters.Modules.Tests.Add_Tests (Ret);
AWA.Helpers.Selectors.Tests.Add_Tests (Ret);
AWA.Jobs.Modules.Tests.Add_Tests (Ret);
AWA.Jobs.Services.Tests.Add_Tests (Ret);
AWA.Settings.Modules.Tests.Add_Tests (Ret);
AWA.Comments.Modules.Tests.Add_Tests (Ret);
AWA.Blogs.Modules.Tests.Add_Tests (Ret);
AWA.Blogs.Tests.Add_Tests (Ret);
AWA.Storages.Services.Tests.Add_Tests (Ret);
AWA.Images.Services.Tests.Add_Tests (Ret);
AWA.Changelogs.Modules.Tests.Add_Tests (Ret);
AWA.Votes.Modules.Tests.Add_Tests (Ret);
AWA.Tags.Modules.Tests.Add_Tests (Ret);
AWA.Questions.Modules.Tests.Add_Tests (Ret);
AWA.Wikis.Modules.Tests.Add_Tests (Ret);
return Ret;
end Suite;
procedure Initialize (Props : in Util.Properties.Manager) is
begin
Initialize (null, Props, True);
end Initialize;
-- ------------------------------
-- Initialize the AWA test framework mockup.
-- ------------------------------
procedure Initialize (App : in AWA.Applications.Application_Access;
Props : in Util.Properties.Manager;
Add_Modules : in Boolean) is
use AWA.Applications;
begin
AWA.Tests.Initialize (App, Props, Add_Modules);
if Add_Modules then
declare
Application : constant Applications.Application_Access := AWA.Tests.Get_Application;
Ctx : AWA.Services.Contexts.Service_Context;
Users : constant AWA.Users.Modules.User_Module_Access := AWA.Testsuite.Users'Access;
begin
Ctx.Set_Context (Application, null);
Register (App => Application.all'Access,
Name => AWA.Users.Modules.NAME,
URI => "user",
Module => Users.all'Access);
Register (App => Application.all'Access,
Name => "mail",
URI => "mail",
Module => Mail'Access);
Register (App => Application.all'Access,
Name => "workspaces",
URI => "workspaces",
Module => Workspaces'Access);
Register (App => Application.all'Access,
Name => AWA.Counters.Modules.NAME,
URI => "counters",
Module => Counters'Access);
Register (App => Application.all'Access,
Name => AWA.Comments.Modules.NAME,
URI => "comments",
Module => Comments'Access);
Register (App => Application.all'Access,
Name => AWA.Storages.Modules.NAME,
URI => "storages",
Module => Storages'Access);
Register (App => Application.all'Access,
Name => AWA.Jobs.Modules.NAME,
URI => "jobs",
Module => Jobs'Access);
Register (App => Application.all'Access,
Name => AWA.Images.Modules.NAME,
URI => "images",
Module => Images'Access);
Register (App => Application.all'Access,
Name => AWA.Settings.Modules.NAME,
URI => "settings",
Module => Settings'Access);
Register (App => Application.all'Access,
Name => AWA.Votes.Modules.NAME,
URI => "votes",
Module => Votes'Access);
Register (App => Application.all'Access,
Name => AWA.Changelogs.Modules.NAME,
URI => "changelogs",
Module => Changelogs'Access);
Register (App => Application.all'Access,
Name => AWA.Tags.Modules.NAME,
URI => "tags",
Module => Tags'Access);
Register (App => Application.all'Access,
Name => AWA.Blogs.Modules.NAME,
URI => "blogs",
Module => Blogs'Access);
Register (App => Application.all'Access,
Name => AWA.Questions.Modules.NAME,
URI => "questions",
Module => Questions'Access);
Register (App => Application.all'Access,
Name => AWA.Wikis.Modules.NAME,
URI => "wikis",
Module => Wikis'Access);
Application.Add_Converter (Name => "dateConverter",
Converter => Date_Converter'Access);
Application.Add_Converter (Name => "smartDateConverter",
Converter => Rel_Date_Converter'Access);
Application.Start;
-- if Props.Exists ("test.server") then
-- declare
-- WS : ASF.Server.Web.AWS_Container;
-- begin
-- Application.Add_Converter (Name => "dateConverter",
-- Converter => Date_Converter'Access);
-- Application.Add_Converter (Name => "smartDateConverter",
-- Converter => Rel_Date_Converter'Access);
--
-- WS.Register_Application ("/asfunit", Application.all'Access);
--
-- WS.Start;
-- delay 6000.0;
-- end;
-- end if;
ASF.Server.Tests.Set_Context (Application.all'Access);
end;
end if;
end Initialize;
end AWA.Testsuite;
|
-----------------------------------------------------------------------
-- Util testsuite - Util Testsuite
-- Copyright (C) 2009, 2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with AWA.Users.Services.Tests;
with AWA.Users.Tests;
with AWA.Blogs.Modules.Tests;
with AWA.Blogs.Tests;
with AWA.Helpers.Selectors.Tests;
with AWA.Storages.Services.Tests;
with AWA.Events.Services.Tests;
with AWA.Mail.Clients.Tests;
with AWA.Mail.Modules.Tests;
with AWA.Images.Services.Tests;
with AWA.Votes.Modules.Tests;
with AWA.Tags.Modules.Tests;
with AWA.Questions.Modules.Tests;
with AWA.Counters.Modules.Tests;
with AWA.Workspaces.Tests;
with AWA.Modules.Tests;
with ASF.Converters.Dates;
with AWA.Users.Modules;
with AWA.Mail.Modules;
with AWA.Blogs.Modules;
with AWA.Workspaces.Modules;
with AWA.Storages.Modules;
with AWA.Images.Modules;
with AWA.Questions.Modules;
with AWA.Votes.Modules;
with AWA.Tags.Modules;
with AWA.Changelogs.Modules;
with AWA.Counters.Modules;
with AWA.Converters.Dates;
with AWA.Tests;
with AWA.Services.Contexts;
with AWA.Jobs.Services.Tests;
with AWA.Jobs.Modules.Tests;
with AWA.Settings.Modules.Tests;
with AWA.Comments.Modules.Tests;
with AWA.Changelogs.Modules.Tests;
with AWA.Wikis.Modules.Tests;
-- with ASF.Server.Web;
with ASF.Server.Tests;
package body AWA.Testsuite is
Users : aliased AWA.Users.Modules.User_Module;
Workspaces : aliased AWA.Workspaces.Modules.Workspace_Module;
Mail : aliased AWA.Mail.Modules.Mail_Module;
Jobs : aliased AWA.Jobs.Modules.Job_Module;
Comments : aliased AWA.Comments.Modules.Comment_Module;
Blogs : aliased AWA.Blogs.Modules.Blog_Module;
Storages : aliased AWA.Storages.Modules.Storage_Module;
Images : aliased AWA.Images.Modules.Image_Module;
Questions : aliased AWA.Questions.Modules.Question_Module;
Votes : aliased AWA.Votes.Modules.Vote_Module;
Tags : aliased AWA.Tags.Modules.Tag_Module;
Settings : aliased AWA.Settings.Modules.Setting_Module;
Changelogs : aliased AWA.Changelogs.Modules.Changelog_Module;
Wikis : aliased AWA.Wikis.Modules.Wiki_Module;
Counters : aliased AWA.Counters.Modules.Counter_Module;
Date_Converter : aliased ASF.Converters.Dates.Date_Converter;
Rel_Date_Converter : aliased AWA.Converters.Dates.Relative_Date_Converter;
Tests : aliased Util.Tests.Test_Suite;
function Suite return Util.Tests.Access_Test_Suite is
Ret : constant Util.Tests.Access_Test_Suite := Tests'Access;
begin
AWA.Modules.Tests.Add_Tests (Ret);
AWA.Events.Services.Tests.Add_Tests (Ret);
AWA.Mail.Clients.Tests.Add_Tests (Ret);
AWA.Mail.Modules.Tests.Add_Tests (Ret);
AWA.Users.Services.Tests.Add_Tests (Ret);
AWA.Users.Tests.Add_Tests (Ret);
AWA.Workspaces.Tests.Add_Tests (Ret);
AWA.Counters.Modules.Tests.Add_Tests (Ret);
AWA.Helpers.Selectors.Tests.Add_Tests (Ret);
AWA.Jobs.Modules.Tests.Add_Tests (Ret);
AWA.Jobs.Services.Tests.Add_Tests (Ret);
AWA.Settings.Modules.Tests.Add_Tests (Ret);
AWA.Comments.Modules.Tests.Add_Tests (Ret);
AWA.Blogs.Modules.Tests.Add_Tests (Ret);
AWA.Blogs.Tests.Add_Tests (Ret);
AWA.Storages.Services.Tests.Add_Tests (Ret);
AWA.Images.Services.Tests.Add_Tests (Ret);
AWA.Changelogs.Modules.Tests.Add_Tests (Ret);
AWA.Votes.Modules.Tests.Add_Tests (Ret);
AWA.Tags.Modules.Tests.Add_Tests (Ret);
AWA.Questions.Modules.Tests.Add_Tests (Ret);
AWA.Wikis.Modules.Tests.Add_Tests (Ret);
return Ret;
end Suite;
procedure Initialize (Props : in Util.Properties.Manager) is
begin
Initialize (null, Props, True);
end Initialize;
-- ------------------------------
-- Initialize the AWA test framework mockup.
-- ------------------------------
procedure Initialize (App : in AWA.Applications.Application_Access;
Props : in Util.Properties.Manager;
Add_Modules : in Boolean) is
use AWA.Applications;
begin
AWA.Tests.Initialize (App, Props, Add_Modules);
if Add_Modules then
declare
Application : constant Applications.Application_Access := AWA.Tests.Get_Application;
Ctx : AWA.Services.Contexts.Service_Context;
Users : constant AWA.Users.Modules.User_Module_Access := AWA.Testsuite.Users'Access;
begin
Ctx.Set_Context (Application, null);
Register (App => Application.all'Access,
Name => AWA.Users.Modules.NAME,
URI => "user",
Module => Users.all'Access);
Register (App => Application.all'Access,
Name => "mail",
URI => "mail",
Module => Mail'Access);
Register (App => Application.all'Access,
Name => "workspaces",
URI => "workspaces",
Module => Workspaces'Access);
Register (App => Application.all'Access,
Name => AWA.Counters.Modules.NAME,
URI => "counters",
Module => Counters'Access);
Register (App => Application.all'Access,
Name => AWA.Comments.Modules.NAME,
URI => "comments",
Module => Comments'Access);
Register (App => Application.all'Access,
Name => AWA.Storages.Modules.NAME,
URI => "storages",
Module => Storages'Access);
Register (App => Application.all'Access,
Name => AWA.Jobs.Modules.NAME,
URI => "jobs",
Module => Jobs'Access);
Register (App => Application.all'Access,
Name => AWA.Images.Modules.NAME,
URI => "images",
Module => Images'Access);
Register (App => Application.all'Access,
Name => AWA.Settings.Modules.NAME,
URI => "settings",
Module => Settings'Access);
Register (App => Application.all'Access,
Name => AWA.Votes.Modules.NAME,
URI => "votes",
Module => Votes'Access);
Register (App => Application.all'Access,
Name => AWA.Changelogs.Modules.NAME,
URI => "changelogs",
Module => Changelogs'Access);
Register (App => Application.all'Access,
Name => AWA.Tags.Modules.NAME,
URI => "tags",
Module => Tags'Access);
Register (App => Application.all'Access,
Name => AWA.Blogs.Modules.NAME,
URI => "blogs",
Module => Blogs'Access);
Register (App => Application.all'Access,
Name => AWA.Questions.Modules.NAME,
URI => "questions",
Module => Questions'Access);
Register (App => Application.all'Access,
Name => AWA.Wikis.Modules.NAME,
URI => "wikis",
Module => Wikis'Access);
Application.Add_Converter (Name => "dateConverter",
Converter => Date_Converter'Access);
Application.Add_Converter (Name => "smartDateConverter",
Converter => Rel_Date_Converter'Access);
Application.Start;
-- if Props.Exists ("test.server") then
-- declare
-- WS : ASF.Server.Web.AWS_Container;
-- begin
-- Application.Add_Converter (Name => "dateConverter",
-- Converter => Date_Converter'Access);
-- Application.Add_Converter (Name => "smartDateConverter",
-- Converter => Rel_Date_Converter'Access);
--
-- WS.Register_Application ("/asfunit", Application.all'Access);
--
-- WS.Start;
-- delay 6000.0;
-- end;
-- end if;
ASF.Server.Tests.Set_Context (Application.all'Access);
end;
end if;
end Initialize;
end AWA.Testsuite;
|
Add the workspace unit tests
|
Add the workspace unit tests
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
16d17474da5dae32bebd55aa0fbae42b0cb876a3
|
src/asf-components-widgets-inputs.adb
|
src/asf-components-widgets-inputs.adb
|
-----------------------------------------------------------------------
-- asf-components-widgets-inputs -- Input 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 Ada.Strings.Unbounded;
with Ada.Characters.Conversions;
with ASF.Models.Selects;
with ASF.Components.Utils;
with ASF.Components.Html.Messages;
with ASF.Events.Faces.Actions;
with ASF.Applications.Messages.Vectors;
with Util.Beans.Basic;
with Util.Strings.Transforms;
package body ASF.Components.Widgets.Inputs is
-- ------------------------------
-- Render the input field title.
-- ------------------------------
procedure Render_Title (UI : in UIInput;
Name : in String;
Writer : in Response_Writer_Access;
Context : in out Faces_Context'Class) is
Title : constant Util.Beans.Objects.Object := UI.Get_Attribute (Context, "title");
begin
Writer.Start_Element ("dt");
Writer.Start_Element ("label");
Writer.Write_Attribute ("for", Name);
Writer.Write_Text (Title);
Writer.End_Element ("label");
Writer.End_Element ("dt");
end Render_Title;
-- ------------------------------
-- Render the input component. Starts the DL/DD list and write the input
-- component with the possible associated error message.
-- ------------------------------
overriding
procedure Encode_Begin (UI : in UIInput;
Context : in out Faces_Context'Class) is
begin
if not UI.Is_Rendered (Context) then
return;
end if;
declare
Id : constant String := To_String (UI.Get_Client_Id);
Writer : constant Response_Writer_Access := Context.Get_Response_Writer;
Messages : constant ASF.Applications.Messages.Vectors.Cursor := Context.Get_Messages (Id);
Style : constant String := UI.Get_Attribute ("styleClass", Context);
begin
Writer.Start_Element ("dl");
Writer.Write_Attribute ("id", Id);
if ASF.Applications.Messages.Vectors.Has_Element (Messages) then
Writer.Write_Attribute ("class", Style & " asf-error");
elsif Style'Length > 0 then
Writer.Write_Attribute ("class", Style);
end if;
UI.Render_Title (Id, Writer, Context);
Writer.Start_Element ("dd");
UI.Render_Input (Context, Write_Id => False);
end;
end Encode_Begin;
-- ------------------------------
-- Render the end of the input component. Closes the DL/DD list.
-- ------------------------------
overriding
procedure Encode_End (UI : in UIInput;
Context : in out Faces_Context'Class) is
use ASF.Components.Html.Messages;
begin
if not UI.Is_Rendered (Context) then
return;
end if;
-- Render the error message associated with the input field.
declare
Id : constant String := To_String (UI.Get_Client_Id);
Writer : constant Response_Writer_Access := Context.Get_Response_Writer;
Messages : constant ASF.Applications.Messages.Vectors.Cursor := Context.Get_Messages (Id);
begin
if ASF.Applications.Messages.Vectors.Has_Element (Messages) then
Write_Message (UI, ASF.Applications.Messages.Vectors.Element (Messages),
SPAN_NO_STYLE, False, True, Context);
end if;
Writer.End_Element ("dd");
Writer.End_Element ("dl");
end;
end Encode_End;
-- ------------------------------
-- Render the end of the input component. Closes the DL/DD list.
-- ------------------------------
overriding
procedure Encode_End (UI : in UIComplete;
Context : in out Faces_Context'Class) is
begin
if not UI.Is_Rendered (Context) then
return;
end if;
-- Render the autocomplete script and finish the input component.
declare
Id : constant String := To_String (UI.Get_Client_Id);
Writer : constant Response_Writer_Access := Context.Get_Response_Writer;
begin
Writer.Queue_Script ("$('#");
Writer.Queue_Script (Id);
Writer.Queue_Script (" input').complete({");
Writer.Queue_Script ("});");
UIInput (UI).Encode_End (Context);
end;
end Encode_End;
overriding
procedure Process_Decodes (UI : in out UIComplete;
Context : in out Faces_Context'Class) is
begin
if not UI.Is_Rendered (Context) then
return;
end if;
declare
Id : constant String := To_String (UI.Get_Client_Id);
Val : constant String := Context.Get_Parameter (Id & ".match");
begin
if Val'Length > 0 then
UI.Match_Value := Util.Beans.Objects.To_Object (Val);
else
ASF.Components.Html.Forms.UIInput (UI).Process_Decodes (Context);
end if;
end;
end Process_Decodes;
procedure Render_List (UI : in UIComplete;
Match : in String;
Context : in out Faces_Context'Class) is
use type Util.Beans.Basic.List_Bean_Access;
procedure Render_Item (Label : in String);
List : constant Util.Beans.Basic.List_Bean_Access
:= ASF.Components.Utils.Get_List_Bean (UI, "autocompleteList", Context);
Writer : constant Response_Writer_Access := Context.Get_Response_Writer;
Need_Comma : Boolean := False;
Count : Natural;
procedure Render_Item (Label : in String) is
Result : Ada.Strings.Unbounded.Unbounded_String;
begin
if Match'Length = 0 or else
(Match'Length <= Label'Length
and then Match = Label (Label'First .. Label'First + Match'Length - 1)) then
if Need_Comma then
Writer.Write (",");
end if;
Writer.Write ('"');
Util.Strings.Transforms.Escape_Java (Content => Label,
Into => Result);
Writer.Write (Result);
Writer.Write ('"');
Need_Comma := True;
end if;
end Render_Item;
begin
Writer.Write ('[');
if List /= null then
Count := List.Get_Count;
if List.all in ASF.Models.Selects.Select_Item_List'Class then
declare
S : constant access ASF.Models.Selects.Select_Item_List'Class
:= ASF.Models.Selects.Select_Item_List'Class (List.all)'Access;
begin
for I in 1 .. Count loop
Render_Item (Ada.Characters.Conversions.To_String (S.Get_Select_Item (I).Get_Label));
end loop;
end;
else
for I in 1 .. Count loop
List.Set_Row_Index (I);
declare
Value : constant Util.Beans.Objects.Object := List.Get_Row;
Label : constant String := Util.Beans.Objects.To_String (Value);
begin
Render_Item (Label);
end;
end loop;
end if;
end if;
Writer.Write (']');
end Render_List;
overriding
procedure Process_Updates (UI : in out UIComplete;
Context : in out Faces_Context'Class) is
begin
if not Util.Beans.Objects.Is_Empty (UI.Match_Value) then
declare
Value : constant access ASF.Views.Nodes.Tag_Attribute := UI.Get_Attribute ("match");
ME : EL.Expressions.Method_Expression;
begin
if Value /= null then
declare
VE : constant EL.Expressions.Value_Expression
:= ASF.Views.Nodes.Get_Value_Expression (Value.all);
begin
VE.Set_Value (Value => UI.Match_Value, Context => Context.Get_ELContext.all);
end;
end if;
-- Post an event on this component to trigger the rendering of the completion
-- list as part of an application/json output. The rendering is made by Broadcast.
ASF.Events.Faces.Actions.Post_Event (UI => UI,
Method => ME);
end;
else
ASF.Components.Html.Forms.UIInput (UI).Process_Updates (Context);
end if;
-- exception
-- when E : others =>
-- UI.Is_Valid := False;
-- UI.Add_Message (CONVERTER_MESSAGE_NAME, "convert", Context);
-- Log.Info (Utils.Get_Line_Info (UI)
-- & ": Exception raised when updating value {0} for component {1}: {2}",
-- EL.Objects.To_String (UI.Submitted_Value),
-- To_String (UI.Get_Client_Id), Ada.Exceptions.Exception_Name (E));
end Process_Updates;
-- ------------------------------
-- Broadcast the event to the event listeners installed on this component.
-- Listeners are called in the order in which they were added.
-- ------------------------------
overriding
procedure Broadcast (UI : in out UIComplete;
Event : not null access ASF.Events.Faces.Faces_Event'Class;
Context : in out Faces_Context'Class) is
pragma Unreferenced (Event);
Match : constant String := Util.Beans.Objects.To_String (UI.Match_Value);
begin
Context.Get_Response.Set_Content_Type ("application/json; charset=UTF-8");
UI.Render_List (Match, Context);
Context.Response_Completed;
end Broadcast;
-- ------------------------------
-- Render the end of the input date component.
-- Generate the javascript code to activate the input date selector
-- and closes the DL/DD list.
-- ------------------------------
overriding
procedure Encode_End (UI : in UIInputDate;
Context : in out Faces_Context'Class) is
use ASF.Components.Html.Messages;
begin
if not UI.Is_Rendered (Context) then
return;
end if;
-- Render the input date script and finish the input component.
declare
Id : constant String := To_String (UI.Get_Client_Id);
Writer : constant Response_Writer_Access := Context.Get_Response_Writer;
Format : constant String := UI.Get_Attribute ("dateFormat", Context);
begin
Writer.Queue_Script ("$('#");
Writer.Queue_Script (Id);
Writer.Queue_Script (" input').datepicker({");
if Format'Length > 0 then
Writer.Queue_Script ("dateFormat: """);
Writer.Queue_Script (Format);
Writer.Queue_Script ("""");
end if;
Writer.Queue_Script ("});");
UIInput (UI).Encode_End (Context);
end;
end Encode_End;
end ASF.Components.Widgets.Inputs;
|
-----------------------------------------------------------------------
-- asf-components-widgets-inputs -- Input 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 Ada.Strings.Unbounded;
with Ada.Characters.Conversions;
with ASF.Models.Selects;
with ASF.Components.Utils;
with ASF.Components.Html.Messages;
with ASF.Events.Faces.Actions;
with ASF.Applications.Messages.Vectors;
with Util.Beans.Basic;
with Util.Strings.Transforms;
package body ASF.Components.Widgets.Inputs is
-- ------------------------------
-- Render the input field title.
-- ------------------------------
procedure Render_Title (UI : in UIInput;
Name : in String;
Writer : in Response_Writer_Access;
Context : in out Faces_Context'Class) is
Title : constant Util.Beans.Objects.Object := UI.Get_Attribute (Context, "title");
begin
Writer.Start_Element ("dt");
Writer.Start_Element ("label");
Writer.Write_Attribute ("for", Name);
Writer.Write_Text (Title);
Writer.End_Element ("label");
Writer.End_Element ("dt");
end Render_Title;
-- ------------------------------
-- Render the input component. Starts the DL/DD list and write the input
-- component with the possible associated error message.
-- ------------------------------
overriding
procedure Encode_Begin (UI : in UIInput;
Context : in out Faces_Context'Class) is
begin
if not UI.Is_Rendered (Context) then
return;
end if;
declare
Id : constant String := To_String (UI.Get_Client_Id);
Writer : constant Response_Writer_Access := Context.Get_Response_Writer;
Messages : constant ASF.Applications.Messages.Vectors.Cursor := Context.Get_Messages (Id);
Style : constant String := UI.Get_Attribute ("styleClass", Context);
begin
Writer.Start_Element ("dl");
Writer.Write_Attribute ("id", Id);
if ASF.Applications.Messages.Vectors.Has_Element (Messages) then
Writer.Write_Attribute ("class", Style & " asf-error");
elsif Style'Length > 0 then
Writer.Write_Attribute ("class", Style);
end if;
UI.Render_Title (Id, Writer, Context);
Writer.Start_Element ("dd");
UI.Render_Input (Context, Write_Id => False);
end;
end Encode_Begin;
-- ------------------------------
-- Render the end of the input component. Closes the DL/DD list.
-- ------------------------------
overriding
procedure Encode_End (UI : in UIInput;
Context : in out Faces_Context'Class) is
use ASF.Components.Html.Messages;
begin
if not UI.Is_Rendered (Context) then
return;
end if;
-- Render the error message associated with the input field.
declare
Id : constant String := To_String (UI.Get_Client_Id);
Writer : constant Response_Writer_Access := Context.Get_Response_Writer;
Messages : constant ASF.Applications.Messages.Vectors.Cursor := Context.Get_Messages (Id);
begin
if ASF.Applications.Messages.Vectors.Has_Element (Messages) then
Write_Message (UI, ASF.Applications.Messages.Vectors.Element (Messages),
SPAN_NO_STYLE, False, True, Context);
end if;
Writer.End_Element ("dd");
Writer.End_Element ("dl");
end;
end Encode_End;
-- ------------------------------
-- Render the end of the input component. Closes the DL/DD list.
-- ------------------------------
overriding
procedure Encode_End (UI : in UIComplete;
Context : in out Faces_Context'Class) is
begin
if not UI.Is_Rendered (Context) then
return;
end if;
-- Render the autocomplete script and finish the input component.
declare
Id : constant String := To_String (UI.Get_Client_Id);
Writer : constant Response_Writer_Access := Context.Get_Response_Writer;
begin
Writer.Queue_Script ("$('#");
Writer.Queue_Script (Id);
Writer.Queue_Script (" input').complete({");
Writer.Queue_Script ("});");
UIInput (UI).Encode_End (Context);
end;
end Encode_End;
overriding
procedure Process_Decodes (UI : in out UIComplete;
Context : in out Faces_Context'Class) is
begin
if not UI.Is_Rendered (Context) then
return;
end if;
declare
Id : constant String := To_String (UI.Get_Client_Id);
Val : constant String := Context.Get_Parameter (Id & ".match");
begin
if Val'Length > 0 then
UI.Match_Value := Util.Beans.Objects.To_Object (Val);
else
ASF.Components.Html.Forms.UIInput (UI).Process_Decodes (Context);
end if;
end;
end Process_Decodes;
procedure Render_List (UI : in UIComplete;
Match : in String;
Context : in out Faces_Context'Class) is
use type Util.Beans.Basic.List_Bean_Access;
procedure Render_Item (Label : in String);
List : constant Util.Beans.Basic.List_Bean_Access
:= ASF.Components.Utils.Get_List_Bean (UI, "autocompleteList", Context);
Writer : constant Response_Writer_Access := Context.Get_Response_Writer;
Need_Comma : Boolean := False;
Count : Natural;
procedure Render_Item (Label : in String) is
Result : Ada.Strings.Unbounded.Unbounded_String;
begin
if Match'Length = 0 or else
(Match'Length <= Label'Length
and then Match = Label (Label'First .. Label'First + Match'Length - 1)) then
if Need_Comma then
Writer.Write (",");
end if;
Writer.Write ('"');
Util.Strings.Transforms.Escape_Java (Content => Label,
Into => Result);
Writer.Write (Result);
Writer.Write ('"');
Need_Comma := True;
end if;
end Render_Item;
begin
Writer.Write ('[');
if List /= null then
Count := List.Get_Count;
if List.all in ASF.Models.Selects.Select_Item_List'Class then
declare
S : constant access ASF.Models.Selects.Select_Item_List'Class
:= ASF.Models.Selects.Select_Item_List'Class (List.all)'Access;
begin
for I in 1 .. Count loop
declare
Value : constant ASF.Models.Selects.Select_Item := S.Get_Select_Item (I);
begin
Render_Item (Ada.Characters.Conversions.To_String (Value.Get_Label));
end;
end loop;
end;
else
for I in 1 .. Count loop
List.Set_Row_Index (I);
declare
Value : constant Util.Beans.Objects.Object := List.Get_Row;
Label : constant String := Util.Beans.Objects.To_String (Value);
begin
Render_Item (Label);
end;
end loop;
end if;
end if;
Writer.Write (']');
end Render_List;
overriding
procedure Process_Updates (UI : in out UIComplete;
Context : in out Faces_Context'Class) is
begin
if not Util.Beans.Objects.Is_Empty (UI.Match_Value) then
declare
Value : constant access ASF.Views.Nodes.Tag_Attribute := UI.Get_Attribute ("match");
ME : EL.Expressions.Method_Expression;
begin
if Value /= null then
declare
VE : constant EL.Expressions.Value_Expression
:= ASF.Views.Nodes.Get_Value_Expression (Value.all);
begin
VE.Set_Value (Value => UI.Match_Value, Context => Context.Get_ELContext.all);
end;
end if;
-- Post an event on this component to trigger the rendering of the completion
-- list as part of an application/json output. The rendering is made by Broadcast.
ASF.Events.Faces.Actions.Post_Event (UI => UI,
Method => ME);
end;
else
ASF.Components.Html.Forms.UIInput (UI).Process_Updates (Context);
end if;
-- exception
-- when E : others =>
-- UI.Is_Valid := False;
-- UI.Add_Message (CONVERTER_MESSAGE_NAME, "convert", Context);
-- Log.Info (Utils.Get_Line_Info (UI)
-- & ": Exception raised when updating value {0} for component {1}: {2}",
-- EL.Objects.To_String (UI.Submitted_Value),
-- To_String (UI.Get_Client_Id), Ada.Exceptions.Exception_Name (E));
end Process_Updates;
-- ------------------------------
-- Broadcast the event to the event listeners installed on this component.
-- Listeners are called in the order in which they were added.
-- ------------------------------
overriding
procedure Broadcast (UI : in out UIComplete;
Event : not null access ASF.Events.Faces.Faces_Event'Class;
Context : in out Faces_Context'Class) is
pragma Unreferenced (Event);
Match : constant String := Util.Beans.Objects.To_String (UI.Match_Value);
begin
Context.Get_Response.Set_Content_Type ("application/json; charset=UTF-8");
UI.Render_List (Match, Context);
Context.Response_Completed;
end Broadcast;
-- ------------------------------
-- Render the end of the input date component.
-- Generate the javascript code to activate the input date selector
-- and closes the DL/DD list.
-- ------------------------------
overriding
procedure Encode_End (UI : in UIInputDate;
Context : in out Faces_Context'Class) is
use ASF.Components.Html.Messages;
begin
if not UI.Is_Rendered (Context) then
return;
end if;
-- Render the input date script and finish the input component.
declare
Id : constant String := To_String (UI.Get_Client_Id);
Writer : constant Response_Writer_Access := Context.Get_Response_Writer;
Format : constant String := UI.Get_Attribute ("dateFormat", Context);
begin
Writer.Queue_Script ("$('#");
Writer.Queue_Script (Id);
Writer.Queue_Script (" input').datepicker({");
if Format'Length > 0 then
Writer.Queue_Script ("dateFormat: """);
Writer.Queue_Script (Format);
Writer.Queue_Script ("""");
end if;
Writer.Queue_Script ("});");
UIInput (UI).Encode_End (Context);
end;
end Encode_End;
end ASF.Components.Widgets.Inputs;
|
Fix compilation warning (line too long)
|
Fix compilation warning (line too long)
|
Ada
|
apache-2.0
|
Letractively/ada-asf,Letractively/ada-asf,Letractively/ada-asf
|
e7e319f648358f8269e27d6f8fed0019ed7dbd09
|
mat/src/mat-formats.ads
|
mat/src/mat-formats.ads
|
-----------------------------------------------------------------------
-- mat-formats - Format various types for the console or GUI interface
-- Copyright (C) 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with MAT.Types;
with MAT.Events.Targets;
package MAT.Formats is
-- Format the address into a string.
function Addr (Value : in MAT.Types.Target_Addr) return String;
-- Format the size into a string.
function Size (Value : in MAT.Types.Target_Size) return String;
-- Format the time relative to the start time.
function Time (Value : in MAT.Types.Target_Tick_Ref;
Start : in MAT.Types.Target_Tick_Ref) return String;
-- Format the duration in seconds, milliseconds or microseconds.
function Duration (Value : in MAT.Types.Target_Tick_Ref) return String;
-- Format a file, line, function information into a string.
function Location (File : in Ada.Strings.Unbounded.Unbounded_String;
Line : in Natural;
Func : in Ada.Strings.Unbounded.Unbounded_String) return String;
-- Format a short description of the event.
function Event (Item : in MAT.Events.Targets.Probe_Event_Type;
Related : in MAT.Events.Targets.Target_Event_Vector) return String;
end MAT.Formats;
|
-----------------------------------------------------------------------
-- mat-formats - Format various types for the console or GUI interface
-- Copyright (C) 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with MAT.Types;
with MAT.Events.Targets;
package MAT.Formats is
-- Format the address into a string.
function Addr (Value : in MAT.Types.Target_Addr) return String;
-- Format the size into a string.
function Size (Value : in MAT.Types.Target_Size) return String;
-- Format the time relative to the start time.
function Time (Value : in MAT.Types.Target_Tick_Ref;
Start : in MAT.Types.Target_Tick_Ref) return String;
-- Format the duration in seconds, milliseconds or microseconds.
function Duration (Value : in MAT.Types.Target_Tick_Ref) return String;
-- Format a file, line, function information into a string.
function Location (File : in Ada.Strings.Unbounded.Unbounded_String;
Line : in Natural;
Func : in Ada.Strings.Unbounded.Unbounded_String) return String;
-- Format a short description of the event.
function Event (Item : in MAT.Events.Targets.Probe_Event_Type;
Related : in MAT.Events.Targets.Target_Event_Vector;
Start_Time : in MAT.Types.Target_Tick_Ref) return String;
end MAT.Formats;
|
Add a Start_Time to the Event function to print relative time
|
Add a Start_Time to the Event function to print relative time
|
Ada
|
apache-2.0
|
stcarrez/mat,stcarrez/mat,stcarrez/mat
|
65d77bc7c2151782a53935089befcb5993490652
|
tests/natools-s_expressions-cache_tests.adb
|
tests/natools-s_expressions-cache_tests.adb
|
------------------------------------------------------------------------------
-- Copyright (c) 2014, Natacha Porté --
-- --
-- Permission to use, copy, modify, and distribute this software for any --
-- purpose with or without fee is hereby granted, provided that the above --
-- copyright notice and this permission notice appear in all copies. --
-- --
-- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES --
-- WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF --
-- MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR --
-- ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES --
-- WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN --
-- ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF --
-- OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. --
------------------------------------------------------------------------------
with System.Storage_Pools;
with GNAT.Debug_Pools;
with Natools.S_Expressions.Atom_Buffers;
with Natools.S_Expressions.Caches;
with Natools.S_Expressions.Generic_Caches;
with Natools.S_Expressions.Printers;
with Natools.S_Expressions.Test_Tools;
package body Natools.S_Expressions.Cache_Tests is
Pool : GNAT.Debug_Pools.Debug_Pool;
package Debug_Caches is new Generic_Caches
(System.Storage_Pools.Root_Storage_Pool'Class (Pool),
System.Storage_Pools.Root_Storage_Pool'Class (Pool),
System.Storage_Pools.Root_Storage_Pool'Class (Pool));
procedure Inject_Test (Printer : in out Printers.Printer'Class);
-- Inject test S-expression into Pr
function Canonical_Test return Atom;
-- Return canonical encoding of test S-expression above
------------------------
-- Helper Subprograms --
------------------------
function Canonical_Test return Atom is
begin
return To_Atom ("5:begin(()(4:head4:tail))3:end");
end Canonical_Test;
procedure Inject_Test (Printer : in out Printers.Printer'Class) is
begin
Printer.Append_Atom (To_Atom ("begin"));
Printer.Open_List;
Printer.Open_List;
Printer.Close_List;
Printer.Open_List;
Printer.Append_Atom (To_Atom ("head"));
Printer.Append_Atom (To_Atom ("tail"));
Printer.Close_List;
Printer.Close_List;
Printer.Append_Atom (To_Atom ("end"));
end Inject_Test;
-------------------------
-- Complete Test Suite --
-------------------------
procedure All_Tests (Report : in out NT.Reporter'Class) is
begin
Default_Instantiation (Report);
Debug_Instantiation (Report);
Descriptor_Interface (Report);
end All_Tests;
-----------------------
-- Inidividual Tests --
-----------------------
procedure Debug_Instantiation (Report : in out NT.Reporter'Class) is
Test : NT.Test := Report.Item ("Debug instantiation");
Buffer : Atom_Buffers.Atom_Buffer;
procedure Put (S : in String);
procedure Put_Line (S : in String);
procedure Flush;
procedure Info_Pool;
procedure Put (S : in String) is
begin
Buffer.Append (To_Atom (S));
end Put;
procedure Put_Line (S : in String) is
begin
Test.Info (To_String (Buffer.Data) & S);
Buffer.Soft_Reset;
end Put_Line;
procedure Flush is
begin
if Buffer.Length > 0 then
Test.Info (To_String (Buffer.Data));
end if;
Buffer.Hard_Reset;
end Flush;
procedure Info_Pool is
procedure Print_Info is new GNAT.Debug_Pools.Print_Info;
begin
Print_Info (Pool);
Flush;
end Info_Pool;
begin
declare
Cache, Deep, Shallow : Debug_Caches.Reference;
begin
Inject_Test (Cache);
declare
First : Debug_Caches.Cursor := Cache.First;
Output : aliased Test_Tools.Memory_Stream;
Pr : Printers.Canonical (Output'Access);
begin
Output.Set_Expected (Canonical_Test);
Printers.Transfer (First, Pr);
Output.Check_Stream (Test);
end;
Deep := Cache.Duplicate;
Shallow := Deep;
Deep.Append_Atom (To_Atom ("more"));
declare
Other : Debug_Caches.Cursor := Deep.First;
Output : aliased Test_Tools.Memory_Stream;
Pr : Printers.Canonical (Output'Access);
begin
Output.Set_Expected (Canonical_Test & To_Atom ("4:more"));
Printers.Transfer (Other, Pr);
Output.Check_Stream (Test);
end;
declare
Second : Debug_Caches.Cursor := Cache.First;
Output : aliased Test_Tools.Memory_Stream;
Pr : Printers.Canonical (Output'Access);
begin
Output.Set_Expected (Canonical_Test);
Printers.Transfer (Second, Pr);
Output.Check_Stream (Test);
end;
declare
Second_Other : Debug_Caches.Cursor := Shallow.First;
Output : aliased Test_Tools.Memory_Stream;
Pr : Printers.Canonical (Output'Access);
begin
Output.Set_Expected (Canonical_Test & To_Atom ("4:more"));
Printers.Transfer (Second_Other, Pr);
Output.Check_Stream (Test);
end;
end;
Info_Pool;
exception
when Error : others => Test.Report_Exception (Error);
end Debug_Instantiation;
procedure Default_Instantiation (Report : in out NT.Reporter'Class) is
Test : NT.Test := Report.Item ("Default instantiation");
begin
declare
Cache, Deep, Shallow : Caches.Reference;
begin
Inject_Test (Cache);
declare
First : Caches.Cursor := Cache.First;
Output : aliased Test_Tools.Memory_Stream;
Pr : Printers.Canonical (Output'Access);
begin
Output.Set_Expected (Canonical_Test);
Printers.Transfer (First, Pr);
Output.Check_Stream (Test);
end;
Deep := Cache.Duplicate;
Shallow := Deep;
Deep.Append_Atom (To_Atom ("more"));
declare
Other : Caches.Cursor := Deep.First;
Output : aliased Test_Tools.Memory_Stream;
Pr : Printers.Canonical (Output'Access);
begin
Output.Set_Expected (Canonical_Test & To_Atom ("4:more"));
Printers.Transfer (Other, Pr);
Output.Check_Stream (Test);
end;
declare
Second : Caches.Cursor := Cache.First;
Output : aliased Test_Tools.Memory_Stream;
Pr : Printers.Canonical (Output'Access);
begin
Output.Set_Expected (Canonical_Test);
Printers.Transfer (Second, Pr);
Output.Check_Stream (Test);
end;
declare
Second_Other : Caches.Cursor := Shallow.First;
Output : aliased Test_Tools.Memory_Stream;
Pr : Printers.Canonical (Output'Access);
begin
Output.Set_Expected (Canonical_Test & To_Atom ("4:more"));
Printers.Transfer (Second_Other, Pr);
Output.Check_Stream (Test);
end;
end;
exception
when Error : others => Test.Report_Exception (Error);
end Default_Instantiation;
procedure Descriptor_Interface (Report : in out NT.Reporter'Class) is
Test : NT.Test := Report.Item ("Descriptor insterface");
begin
declare
Cache : Caches.Reference;
First, Second : Caches.Cursor;
begin
Cache.Append_Atom (To_Atom ("begin"));
Cache.Open_List;
Cache.Append_Atom (To_Atom ("command"));
Cache.Open_List;
Cache.Append_Atom (To_Atom ("first"));
Cache.Append_Atom (To_Atom ("second"));
Cache.Close_List;
Cache.Close_List;
Cache.Append_Atom (To_Atom ("end"));
First := Cache.First;
Second := First;
Test_Tools.Test_Atom_Accessors (Test, First, To_Atom ("begin"), 0);
Test_Tools.Test_Atom_Accessors (Test, Second, To_Atom ("begin"), 0);
Test_Tools.Next_And_Check (Test, First, Events.Open_List, 1);
Test_Tools.Test_Atom_Accessor_Exceptions (Test, First);
Test_Tools.Next_And_Check (Test, First, To_Atom ("command"), 1);
Test_Tools.Next_And_Check (Test, First, Events.Open_List, 2);
Test_Tools.Next_And_Check (Test, Second, Events.Open_List, 1);
Test_Tools.Next_And_Check (Test, First, To_Atom ("first"), 2);
Test_Tools.Next_And_Check (Test, Second, To_Atom ("command"), 1);
Test_Tools.Next_And_Check (Test, First, To_Atom ("second"), 2);
Test_Tools.Next_And_Check (Test, First, Events.Close_List, 1);
Test_Tools.Next_And_Check (Test, Second, Events.Open_List, 2);
Test_Tools.Next_And_Check (Test, Second, To_Atom ("first"), 2);
Test_Tools.Next_And_Check (Test, Second, To_Atom ("second"), 2);
Test_Tools.Next_And_Check (Test, First, Events.Close_List, 0);
Test_Tools.Next_And_Check (Test, Second, Events.Close_List, 1);
Test_Tools.Test_Atom_Accessor_Exceptions (Test, Second);
Test_Tools.Next_And_Check (Test, Second, Events.Close_List, 0);
Test_Tools.Next_And_Check (Test, Second, To_Atom ("end"), 0);
Test_Tools.Next_And_Check (Test, First, To_Atom ("end"), 0);
Test_Tools.Next_And_Check (Test, First, Events.End_Of_Input, 0);
Test_Tools.Next_And_Check (Test, Second, Events.End_Of_Input, 0);
end;
exception
when Error : others => Test.Report_Exception (Error);
end Descriptor_Interface;
end Natools.S_Expressions.Cache_Tests;
|
------------------------------------------------------------------------------
-- Copyright (c) 2014, Natacha Porté --
-- --
-- Permission to use, copy, modify, and distribute this software for any --
-- purpose with or without fee is hereby granted, provided that the above --
-- copyright notice and this permission notice appear in all copies. --
-- --
-- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES --
-- WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF --
-- MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR --
-- ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES --
-- WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN --
-- ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF --
-- OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. --
------------------------------------------------------------------------------
with System.Storage_Pools;
with GNAT.Debug_Pools;
with Natools.S_Expressions.Atom_Buffers;
with Natools.S_Expressions.Caches;
with Natools.S_Expressions.Generic_Caches;
with Natools.S_Expressions.Printers;
with Natools.S_Expressions.Test_Tools;
package body Natools.S_Expressions.Cache_Tests is
Pool : GNAT.Debug_Pools.Debug_Pool;
package Debug_Caches is new Generic_Caches
(System.Storage_Pools.Root_Storage_Pool'Class (Pool),
System.Storage_Pools.Root_Storage_Pool'Class (Pool),
System.Storage_Pools.Root_Storage_Pool'Class (Pool));
procedure Inject_Test (Printer : in out Printers.Printer'Class);
-- Inject test S-expression into Pr
function Canonical_Test return Atom;
-- Return canonical encoding of test S-expression above
------------------------
-- Helper Subprograms --
------------------------
function Canonical_Test return Atom is
begin
return To_Atom ("5:begin(()(4:head4:tail))3:end");
end Canonical_Test;
procedure Inject_Test (Printer : in out Printers.Printer'Class) is
begin
Printer.Append_Atom (To_Atom ("begin"));
Printer.Open_List;
Printer.Open_List;
Printer.Close_List;
Printer.Open_List;
Printer.Append_Atom (To_Atom ("head"));
Printer.Append_Atom (To_Atom ("tail"));
Printer.Close_List;
Printer.Close_List;
Printer.Append_Atom (To_Atom ("end"));
end Inject_Test;
-------------------------
-- Complete Test Suite --
-------------------------
procedure All_Tests (Report : in out NT.Reporter'Class) is
begin
Default_Instantiation (Report);
Debug_Instantiation (Report);
Descriptor_Interface (Report);
end All_Tests;
-----------------------
-- Inidividual Tests --
-----------------------
procedure Debug_Instantiation (Report : in out NT.Reporter'Class) is
Test : NT.Test := Report.Item ("Debug instantiation");
Buffer : Atom_Buffers.Atom_Buffer;
procedure Put (S : in String);
procedure Put_Line (S : in String);
procedure Flush;
procedure Info_Pool;
procedure Put (S : in String) is
begin
Buffer.Append (To_Atom (S));
end Put;
procedure Put_Line (S : in String) is
begin
Test.Info (To_String (Buffer.Data) & S);
Buffer.Soft_Reset;
end Put_Line;
procedure Flush is
begin
if Buffer.Length > 0 then
Test.Info (To_String (Buffer.Data));
end if;
Buffer.Hard_Reset;
end Flush;
procedure Info_Pool is
procedure Print_Info is new GNAT.Debug_Pools.Print_Info;
begin
Print_Info (Pool);
Flush;
end Info_Pool;
begin
declare
Cache, Deep, Shallow : Debug_Caches.Reference;
begin
declare
Empty_Cursor : Debug_Caches.Cursor := Deep.First;
Event : Events.Event;
begin
Event := Empty_Cursor.Current_Event;
if Event /= Events.End_Of_Input then
Test.Fail ("Unexpected Empty_Cursor.Current_Event "
& Events.Event'Image (Event)
& " (expected End_Of_Input)");
end if;
Test_Tools.Next_And_Check
(Test, Empty_Cursor, Events.End_Of_Input, 0);
end;
Inject_Test (Cache);
declare
First : Debug_Caches.Cursor := Cache.First;
Output : aliased Test_Tools.Memory_Stream;
Pr : Printers.Canonical (Output'Access);
begin
Output.Set_Expected (Canonical_Test);
Printers.Transfer (First, Pr);
Output.Check_Stream (Test);
end;
Deep := Cache.Duplicate;
Shallow := Deep;
Deep.Append_Atom (To_Atom ("more"));
declare
Other : Debug_Caches.Cursor := Deep.First;
Output : aliased Test_Tools.Memory_Stream;
Pr : Printers.Canonical (Output'Access);
begin
Output.Set_Expected (Canonical_Test & To_Atom ("4:more"));
Printers.Transfer (Other, Pr);
Output.Check_Stream (Test);
end;
declare
Second : Debug_Caches.Cursor := Cache.First;
Output : aliased Test_Tools.Memory_Stream;
Pr : Printers.Canonical (Output'Access);
begin
Output.Set_Expected (Canonical_Test);
Printers.Transfer (Second, Pr);
Output.Check_Stream (Test);
end;
declare
Second_Other : Debug_Caches.Cursor := Shallow.First;
Output : aliased Test_Tools.Memory_Stream;
Pr : Printers.Canonical (Output'Access);
begin
Output.Set_Expected (Canonical_Test & To_Atom ("4:more"));
Printers.Transfer (Second_Other, Pr);
Output.Check_Stream (Test);
end;
end;
Info_Pool;
exception
when Error : others => Test.Report_Exception (Error);
end Debug_Instantiation;
procedure Default_Instantiation (Report : in out NT.Reporter'Class) is
Test : NT.Test := Report.Item ("Default instantiation");
begin
declare
Cache, Deep, Shallow : Caches.Reference;
begin
declare
Empty_Cursor : Caches.Cursor := Deep.First;
Event : Events.Event;
begin
Event := Empty_Cursor.Current_Event;
if Event /= Events.End_Of_Input then
Test.Fail ("Unexpected Empty_Cursor.Current_Event "
& Events.Event'Image (Event)
& " (expected End_Of_Input)");
end if;
Test_Tools.Next_And_Check
(Test, Empty_Cursor, Events.End_Of_Input, 0);
end;
Inject_Test (Cache);
declare
First : Caches.Cursor := Cache.First;
Output : aliased Test_Tools.Memory_Stream;
Pr : Printers.Canonical (Output'Access);
begin
Output.Set_Expected (Canonical_Test);
Printers.Transfer (First, Pr);
Output.Check_Stream (Test);
end;
Deep := Cache.Duplicate;
Shallow := Deep;
Deep.Append_Atom (To_Atom ("more"));
declare
Other : Caches.Cursor := Deep.First;
Output : aliased Test_Tools.Memory_Stream;
Pr : Printers.Canonical (Output'Access);
begin
Output.Set_Expected (Canonical_Test & To_Atom ("4:more"));
Printers.Transfer (Other, Pr);
Output.Check_Stream (Test);
end;
declare
Second : Caches.Cursor := Cache.First;
Output : aliased Test_Tools.Memory_Stream;
Pr : Printers.Canonical (Output'Access);
begin
Output.Set_Expected (Canonical_Test);
Printers.Transfer (Second, Pr);
Output.Check_Stream (Test);
end;
declare
Second_Other : Caches.Cursor := Shallow.First;
Output : aliased Test_Tools.Memory_Stream;
Pr : Printers.Canonical (Output'Access);
begin
Output.Set_Expected (Canonical_Test & To_Atom ("4:more"));
Printers.Transfer (Second_Other, Pr);
Output.Check_Stream (Test);
end;
end;
exception
when Error : others => Test.Report_Exception (Error);
end Default_Instantiation;
procedure Descriptor_Interface (Report : in out NT.Reporter'Class) is
Test : NT.Test := Report.Item ("Descriptor insterface");
begin
declare
Cache : Caches.Reference;
First, Second : Caches.Cursor;
begin
Cache.Append_Atom (To_Atom ("begin"));
Cache.Open_List;
Cache.Append_Atom (To_Atom ("command"));
Cache.Open_List;
Cache.Append_Atom (To_Atom ("first"));
Cache.Append_Atom (To_Atom ("second"));
Cache.Close_List;
Cache.Close_List;
Cache.Append_Atom (To_Atom ("end"));
First := Cache.First;
Second := First;
Test_Tools.Test_Atom_Accessors (Test, First, To_Atom ("begin"), 0);
Test_Tools.Test_Atom_Accessors (Test, Second, To_Atom ("begin"), 0);
Test_Tools.Next_And_Check (Test, First, Events.Open_List, 1);
Test_Tools.Test_Atom_Accessor_Exceptions (Test, First);
Test_Tools.Next_And_Check (Test, First, To_Atom ("command"), 1);
Test_Tools.Next_And_Check (Test, First, Events.Open_List, 2);
Test_Tools.Next_And_Check (Test, Second, Events.Open_List, 1);
Test_Tools.Next_And_Check (Test, First, To_Atom ("first"), 2);
Test_Tools.Next_And_Check (Test, Second, To_Atom ("command"), 1);
Test_Tools.Next_And_Check (Test, First, To_Atom ("second"), 2);
Test_Tools.Next_And_Check (Test, First, Events.Close_List, 1);
Test_Tools.Next_And_Check (Test, Second, Events.Open_List, 2);
Test_Tools.Next_And_Check (Test, Second, To_Atom ("first"), 2);
Test_Tools.Next_And_Check (Test, Second, To_Atom ("second"), 2);
Test_Tools.Next_And_Check (Test, First, Events.Close_List, 0);
Test_Tools.Next_And_Check (Test, Second, Events.Close_List, 1);
Test_Tools.Test_Atom_Accessor_Exceptions (Test, Second);
Test_Tools.Next_And_Check (Test, Second, Events.Close_List, 0);
Test_Tools.Next_And_Check (Test, Second, To_Atom ("end"), 0);
Test_Tools.Next_And_Check (Test, First, To_Atom ("end"), 0);
Test_Tools.Next_And_Check (Test, First, Events.End_Of_Input, 0);
Test_Tools.Next_And_Check (Test, Second, Events.End_Of_Input, 0);
end;
exception
when Error : others => Test.Report_Exception (Error);
end Descriptor_Interface;
end Natools.S_Expressions.Cache_Tests;
|
add checks using empty reference and cursor
|
s_expressions-cache_tests: add checks using empty reference and cursor
|
Ada
|
isc
|
faelys/natools
|
0aec6cdb76d5c4ae9b5c70c95a8157d0c89820d6
|
src/security-policies-urls.ads
|
src/security-policies-urls.ads
|
-----------------------------------------------------------------------
-- security-policies-urls -- URL security policy
-- 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.Containers.Hashed_Maps;
with Ada.Containers.Vectors;
with Util.Refs;
with Util.Strings;
with Util.Serialize.IO.XML;
with GNAT.Regexp;
-- == URL Security Policy ==
-- The <tt>Security.Policies.Urls</tt> implements a security policy intended to be used
-- in web servers. It allows to protect an URL by defining permissions that must be granted
-- for a user to get access to the URL. A typical example is a web server that has a set of
-- administration pages, these pages should be accessed by users having some admin permission.
--
-- === Policy creation ===
-- An instance of the <tt>URL_Policy</tt> must be created and registered in the policy manager.
-- Get or declare the following variables:
--
-- Manager : Security.Policies.Policy_Manager;
-- Policy : Security.Policies.Urls.URL_Policy_Access;
--
-- Create the URL policy and register it in the policy manager as follows:
--
-- Policy := new URL_Policy;
-- Manager.Add_Policy (Policy.all'Access);
--
-- === Policy Configuration ===
-- Once the URL policy is registered, the policy manager can read and process the following
-- XML configuration:
--
-- <policy-rules>
-- <url-policy id='1'>
-- <permission>create-workspace</permission>
-- <permission>admin</permission>
-- <url-pattern>/workspace/create</url-pattern>
-- <url-pattern>/workspace/setup/*</url-pattern>
-- </url-policy>
-- ...
-- </policy-rules>
--
-- This policy gives access to the URL that match one of the URL pattern if the
-- security context has the permission <b>create-workspace</b> or <b>admin</b>.
-- These two permissions are checked according to another security policy.
-- The XML configuration can define several <tt>url-policy</tt>. They are checked in
-- the order defined in the XML. In other words, the first <tt>url-policy</tt> that matches
-- the URL is used to verify the permission.
--
-- The <tt>url-policy</tt> definition can contain several <tt>permission</tt>.
-- The first permission that is granted gives access to the URL.
--
-- === Checking for permission ===
-- To check a URL permission, you must declare a <tt>URL_Permission</tt> object with the URL.
--
-- URL : constant String := ...;
-- Perm : constant Policies.URLs.URL_Permission (URL'Length)
-- := URL_Permission '(Len => URI'Length, URL => URL);
--
-- Then, we can check the permission:
--
-- Result : Boolean := Security.Contexts.Has_Permission (Perm);
--
package Security.Policies.URLs is
NAME : constant String := "URL-Policy";
package P_URL is new Security.Permissions.Definition ("url");
-- ------------------------------
-- URL Permission
-- ------------------------------
-- Represents a permission to access a given URL.
type URL_Permission (Len : Natural) is new Permissions.Permission (P_URL.Permission) with record
URL : String (1 .. Len);
end record;
-- ------------------------------
-- URL policy
-- ------------------------------
type URL_Policy is new Policy with private;
type URL_Policy_Access is access all URL_Policy'Class;
Invalid_Name : exception;
-- Get the policy name.
overriding
function Get_Name (From : in URL_Policy) return String;
-- Returns True if the user has the permission to access the given URI permission.
function Has_Permission (Manager : in URL_Policy;
Context : in Security_Context_Access;
Permission : in URL_Permission'Class) return Boolean;
-- Grant the permission to access to the given <b>URI</b> to users having the <b>To</b>
-- permissions.
procedure Grant_URI_Permission (Manager : in out URL_Policy;
URI : in String;
To : in String);
-- Initialize the permission manager.
overriding
procedure Initialize (Manager : in out URL_Policy);
-- Finalize the permission manager.
overriding
procedure Finalize (Manager : in out URL_Policy);
-- Setup the XML parser to read the <b>policy</b> description.
overriding
procedure Prepare_Config (Policy : in out URL_Policy;
Reader : in out Util.Serialize.IO.XML.Parser);
-- Get the URL policy associated with the given policy manager.
-- Returns the URL policy instance or null if it was not registered in the policy manager.
function Get_URL_Policy (Manager : in Security.Policies.Policy_Manager'Class)
return URL_Policy_Access;
private
use Util.Strings;
-- The <b>Access_Rule</b> represents a list of permissions to verify to grant
-- access to the resource. To make it simple, the user must have one of the
-- permission from the list. Each permission will refer to a specific permission
-- controller.
type Access_Rule (Count : Natural) is new Util.Refs.Ref_Entity with record
Permissions : Permission_Index_Array (1 .. Count);
end record;
type Access_Rule_Access is access all Access_Rule;
package Access_Rule_Refs is
new Util.Refs.Indefinite_References (Element_Type => Access_Rule,
Element_Access => Access_Rule_Access);
subtype Access_Rule_Ref is Access_Rule_Refs.Ref;
-- Find the access rule of the policy that matches the given URI.
-- Returns the No_Rule value (disable access) if no rule is found.
function Find_Access_Rule (Manager : in URL_Policy;
URI : in String) return Access_Rule_Ref;
-- The <b>Policy</b> defines the access rules that are applied on a given
-- URL, set of URLs or files.
type Policy is record
Id : Natural;
Pattern : GNAT.Regexp.Regexp;
Rule : Access_Rule_Ref;
end record;
-- The <b>Policy_Vector</b> represents the whole permission policy. The order of
-- policy in the list is important as policies can override each other.
package Policy_Vector is new Ada.Containers.Vectors (Index_Type => Positive,
Element_Type => Policy);
package Rules_Maps is new Ada.Containers.Hashed_Maps (Key_Type => String_Ref,
Element_Type => Access_Rule_Ref,
Hash => Hash,
Equivalent_Keys => Equivalent_Keys,
"=" => Access_Rule_Refs."=");
type Rules is new Util.Refs.Ref_Entity with record
Map : Rules_Maps.Map;
end record;
type Rules_Access is access all Rules;
package Rules_Ref is new Util.Refs.References (Rules, Rules_Access);
type Rules_Ref_Access is access Rules_Ref.Atomic_Ref;
type Controller_Access_Array_Access is access all Controller_Access_Array;
type URL_Policy is new Security.Policies.Policy with record
Cache : Rules_Ref_Access;
Policies : Policy_Vector.Vector;
Id : Natural := 0;
Permissions : Util.Beans.Objects.Vectors.Vector;
Patterns : Util.Beans.Objects.Vectors.Vector;
end record;
end Security.Policies.URLs;
|
-----------------------------------------------------------------------
-- security-policies-urls -- URL security policy
-- 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.Containers.Hashed_Maps;
with Ada.Containers.Vectors;
with Util.Refs;
with Util.Strings;
with Util.Serialize.IO.XML;
with GNAT.Regexp;
with Security.Contexts;
-- == URL Security Policy ==
-- The <tt>Security.Policies.Urls</tt> implements a security policy intended to be used
-- in web servers. It allows to protect an URL by defining permissions that must be granted
-- for a user to get access to the URL. A typical example is a web server that has a set of
-- administration pages, these pages should be accessed by users having some admin permission.
--
-- === Policy creation ===
-- An instance of the <tt>URL_Policy</tt> must be created and registered in the policy manager.
-- Get or declare the following variables:
--
-- Manager : Security.Policies.Policy_Manager;
-- Policy : Security.Policies.Urls.URL_Policy_Access;
--
-- Create the URL policy and register it in the policy manager as follows:
--
-- Policy := new URL_Policy;
-- Manager.Add_Policy (Policy.all'Access);
--
-- === Policy Configuration ===
-- Once the URL policy is registered, the policy manager can read and process the following
-- XML configuration:
--
-- <policy-rules>
-- <url-policy id='1'>
-- <permission>create-workspace</permission>
-- <permission>admin</permission>
-- <url-pattern>/workspace/create</url-pattern>
-- <url-pattern>/workspace/setup/*</url-pattern>
-- </url-policy>
-- ...
-- </policy-rules>
--
-- This policy gives access to the URL that match one of the URL pattern if the
-- security context has the permission <b>create-workspace</b> or <b>admin</b>.
-- These two permissions are checked according to another security policy.
-- The XML configuration can define several <tt>url-policy</tt>. They are checked in
-- the order defined in the XML. In other words, the first <tt>url-policy</tt> that matches
-- the URL is used to verify the permission.
--
-- The <tt>url-policy</tt> definition can contain several <tt>permission</tt>.
-- The first permission that is granted gives access to the URL.
--
-- === Checking for permission ===
-- To check a URL permission, you must declare a <tt>URL_Permission</tt> object with the URL.
--
-- URL : constant String := ...;
-- Perm : constant Policies.URLs.URL_Permission (URL'Length)
-- := URL_Permission '(Len => URI'Length, URL => URL);
--
-- Then, we can check the permission:
--
-- Result : Boolean := Security.Contexts.Has_Permission (Perm);
--
package Security.Policies.URLs is
NAME : constant String := "URL-Policy";
package P_URL is new Security.Permissions.Definition ("url");
-- ------------------------------
-- URL Permission
-- ------------------------------
-- Represents a permission to access a given URL.
type URL_Permission (Len : Natural) is new Permissions.Permission (P_URL.Permission) with record
URL : String (1 .. Len);
end record;
-- ------------------------------
-- URL policy
-- ------------------------------
type URL_Policy is new Policy with private;
type URL_Policy_Access is access all URL_Policy'Class;
Invalid_Name : exception;
-- Get the policy name.
overriding
function Get_Name (From : in URL_Policy) return String;
-- Returns True if the user has the permission to access the given URI permission.
function Has_Permission (Manager : in URL_Policy;
Context : in Contexts.Security_Context'Class;
Permission : in URL_Permission'Class) return Boolean;
-- Grant the permission to access to the given <b>URI</b> to users having the <b>To</b>
-- permissions.
procedure Grant_URI_Permission (Manager : in out URL_Policy;
URI : in String;
To : in String);
-- Initialize the permission manager.
overriding
procedure Initialize (Manager : in out URL_Policy);
-- Finalize the permission manager.
overriding
procedure Finalize (Manager : in out URL_Policy);
-- Setup the XML parser to read the <b>policy</b> description.
overriding
procedure Prepare_Config (Policy : in out URL_Policy;
Reader : in out Util.Serialize.IO.XML.Parser);
-- Get the URL policy associated with the given policy manager.
-- Returns the URL policy instance or null if it was not registered in the policy manager.
function Get_URL_Policy (Manager : in Security.Policies.Policy_Manager'Class)
return URL_Policy_Access;
private
use Util.Strings;
-- The <b>Access_Rule</b> represents a list of permissions to verify to grant
-- access to the resource. To make it simple, the user must have one of the
-- permission from the list. Each permission will refer to a specific permission
-- controller.
type Access_Rule (Count : Natural) is new Util.Refs.Ref_Entity with record
Permissions : Permission_Index_Array (1 .. Count);
end record;
type Access_Rule_Access is access all Access_Rule;
package Access_Rule_Refs is
new Util.Refs.Indefinite_References (Element_Type => Access_Rule,
Element_Access => Access_Rule_Access);
subtype Access_Rule_Ref is Access_Rule_Refs.Ref;
-- Find the access rule of the policy that matches the given URI.
-- Returns the No_Rule value (disable access) if no rule is found.
function Find_Access_Rule (Manager : in URL_Policy;
URI : in String) return Access_Rule_Ref;
-- The <b>Policy</b> defines the access rules that are applied on a given
-- URL, set of URLs or files.
type Policy is record
Id : Natural;
Pattern : GNAT.Regexp.Regexp;
Rule : Access_Rule_Ref;
end record;
-- The <b>Policy_Vector</b> represents the whole permission policy. The order of
-- policy in the list is important as policies can override each other.
package Policy_Vector is new Ada.Containers.Vectors (Index_Type => Positive,
Element_Type => Policy);
package Rules_Maps is new Ada.Containers.Hashed_Maps (Key_Type => String_Ref,
Element_Type => Access_Rule_Ref,
Hash => Hash,
Equivalent_Keys => Equivalent_Keys,
"=" => Access_Rule_Refs."=");
type Rules is new Util.Refs.Ref_Entity with record
Map : Rules_Maps.Map;
end record;
type Rules_Access is access all Rules;
package Rules_Ref is new Util.Refs.References (Rules, Rules_Access);
type Rules_Ref_Access is access Rules_Ref.Atomic_Ref;
type Controller_Access_Array_Access is access all Controller_Access_Array;
type URL_Policy is new Security.Policies.Policy with record
Cache : Rules_Ref_Access;
Policies : Policy_Vector.Vector;
Id : Natural := 0;
Permissions : Util.Beans.Objects.Vectors.Vector;
Patterns : Util.Beans.Objects.Vectors.Vector;
end record;
end Security.Policies.URLs;
|
Change Has_Permission to get a Security Context class as parameter
|
Change Has_Permission to get a Security Context class as parameter
|
Ada
|
apache-2.0
|
Letractively/ada-security
|
ab5dd6dc3ccb88e57d48fd96cb7ee4f3e125ad53
|
src/port_specification-json.adb
|
src/port_specification-json.adb
|
-- This file is covered by the Internet Software Consortium (ISC) License
-- Reference: ../License.txt
with Utilities;
with Ada.Characters.Latin_1;
with HelperText;
package body Port_Specification.Json is
package LAT renames Ada.Characters.Latin_1;
package UTL renames Utilities;
package HT renames HelperText;
--------------------------------------------------------------------------------------------
-- describe_port
--------------------------------------------------------------------------------------------
procedure describe_port
(specs : Portspecs;
dossier : TIO.File_Type;
bucket : String;
index : Positive)
is
fpcval : constant String := fpc_value (specs.generated, specs.equivalent_fpc_port);
nvar : constant Natural := specs.get_number_of_variants;
begin
TIO.Put
(dossier,
UTL.json_object (True, 3, index) &
UTL.json_nvpair_string ("bucket", bucket, 1, pad) &
UTL.json_nvpair_string ("namebase", specs.get_namebase, 2, pad) &
UTL.json_nvpair_string ("version", specs.get_field_value (sp_version), 3, pad) &
homepage_line (specs) &
UTL.json_nvpair_string ("FPC", fpcval, 3, pad) &
UTL.json_nvpair_complex ("keywords", describe_keywords (specs), 3, pad) &
UTL.json_nvpair_complex ("distfile", describe_distfiles (specs), 3, pad) &
specs.get_json_contacts &
describe_Common_Platform_Enumeration (specs) &
UTL.json_name_complex ("variants", 4, pad) &
UTL.json_array (True, pad + 1)
);
for x in 1 .. nvar loop
declare
varstr : constant String := specs.get_list_item (Port_Specification.sp_variants, x);
sdesc : constant String := specs.get_tagline (varstr);
spray : constant String := describe_subpackages (specs, varstr);
begin
TIO.Put
(dossier,
UTL.json_object (True, pad + 2, x) &
UTL.json_nvpair_string ("label", varstr, 1, pad + 3) &
UTL.json_nvpair_string ("sdesc", sdesc, 2, pad + 3) &
UTL.json_nvpair_complex ("spkgs", spray, 3, pad + 3) &
UTL.json_object (False, pad + 2, x)
);
end;
end loop;
TIO.Put
(dossier,
UTL.json_array (False, pad + 1) &
UTL.json_object (False, 3, index)
);
end describe_port;
--------------------------------------------------------------------------------------------
-- fpc_value
--------------------------------------------------------------------------------------------
function fpc_value (is_generated : Boolean; raw_value : String) return String is
begin
if is_generated then
return "generated";
else
return raw_value;
end if;
end fpc_value;
--------------------------------------------------------------------------------------------
-- describe_keywords
--------------------------------------------------------------------------------------------
function describe_keywords (specs : Portspecs) return String
is
raw : constant String := specs.get_field_value (Port_Specification.sp_keywords);
innerquote : constant String :=
HT.replace_char
(S => HT.replace_char (raw, LAT.Comma, LAT.Quotation & LAT.Comma),
focus => LAT.Space,
substring => LAT.Space & LAT.Quotation);
begin
return "[ " & LAT.Quotation & innerquote & LAT.Quotation & " ]";
end describe_keywords;
--------------------------------------------------------------------------------------------
-- describe_distfiles
--------------------------------------------------------------------------------------------
function describe_distfiles (specs : Portspecs) return String
is
numfiles : constant Natural := specs.get_list_length (Port_Specification.sp_distfiles);
result : HT.Text := HT.SUS ("[ ");
begin
for x in 1 .. numfiles loop
if x > 1 then
HT.SU.Append (result, ", ");
end if;
HT.SU.Append (result, LAT.Quotation & specs.get_repology_distfile (x) & LAT.Quotation);
end loop;
return HT.USS (result) & " ]";
end describe_distfiles;
--------------------------------------------------------------------------------------------
-- describe_subpackages
--------------------------------------------------------------------------------------------
function describe_subpackages (specs : Portspecs; variant : String) return String
is
numpkg : constant Natural := specs.get_subpackage_length (variant);
result : HT.Text := HT.SUS ("[ ");
begin
for x in 1 .. numpkg loop
if x > 1 then
HT.SU.Append (result, ", ");
end if;
HT.SU.Append (result, LAT.Quotation &
specs.get_subpackage_item (variant, x) & LAT.Quotation);
end loop;
return HT.USS (result) & " ]";
end describe_subpackages;
--------------------------------------------------------------------------------------------
-- homepage_line
--------------------------------------------------------------------------------------------
function homepage_line (specs : Portspecs) return String
is
homepage : constant String := specs.get_field_value (sp_homepage);
begin
if homepage = homepage_none or else
specs.repology_sucks
then
return "";
end if;
return UTL.json_nvpair_string ("homepage", specs.get_field_value (sp_homepage), 3, pad);
end homepage_line;
--------------------------------------------------------------------------------------------
-- describe_Common_Platform_Enumeration
--------------------------------------------------------------------------------------------
function describe_Common_Platform_Enumeration (specs : Portspecs) return String
is
function retrieve (key : String; default_value : String) return String;
function form_object return String;
procedure maybe_push (json_key, cpe_key, default_value : String);
procedure always_push (json_key, value : String);
pairs : string_crate.Vector;
function retrieve (key : String; default_value : String) return String
is
key_text : HT.Text := HT.SUS (key);
begin
if specs.catch_all.Contains (key_text) then
return HT.USS (specs.catch_all.Element (key_text).list.First_Element);
else
return default_value;
end if;
end retrieve;
procedure always_push (json_key, value : String) is
begin
pairs.Append (HT.SUS (json_key & "=" & value));
end always_push;
procedure maybe_push (json_key, cpe_key, default_value : String)
is
cpe_key_text : HT.Text := HT.SUS (cpe_key);
cpe_value : HT.Text;
begin
if specs.catch_all.Contains (cpe_key_text) then
cpe_value := specs.catch_all.Element (cpe_key_text).list.First_Element;
if not HT.equivalent (cpe_value, default_value) then
pairs.Append (HT.SUS (json_key & "=" & HT.USS (cpe_value)));
end if;
end if;
end maybe_push;
function form_object return String
is
procedure dump (position : string_crate.Cursor);
tracker : Natural := 0;
guts : HT.Text;
procedure dump (position : string_crate.Cursor)
is
both : String := HT.USS (string_crate.Element (position));
key : String := HT.part_1 (both, "=");
value : String := HT.part_2 (both, "=");
data : String := UTL.json_nvpair_string (key, value, 1, 0); -- trailing LF
begin
tracker := tracker + 1;
if tracker > 1 then
HT.SU.Append (guts, LAT.Comma);
end if;
HT.SU.Append (guts, data (data'First .. data'Last - 1));
end dump;
begin
pairs.Iterate (dump'Access);
return "{" & HT.USS (guts) & " }";
end form_object;
begin
if not specs.uses.Contains (HT.SUS ("cpe")) then
return "";
end if;
maybe_push ("part", "CPE_PART", "a");
declare
cpe_product : String := retrieve ("CPE_PRODUCT", HT.lowercase (specs.get_namebase));
cpe_vendor : String := retrieve ("CPE_VENDOR", cpe_product);
begin
-- probably should be vendor then product, but this was the original order
-- of repology json. Maintain order to avoid massive diff.
always_push ("product", cpe_product);
always_push ("vendor", cpe_vendor);
end;
maybe_push ("version", "CPE_VERSION", HT.USS (specs.version));
maybe_push ("update", "CPE_UPDATE", "");
maybe_push ("edition", "CPE_EDITION", "");
maybe_push ("lang", "CPE_LANG", "");
maybe_push ("sw_edition", "CPE_SW_EDITION", "");
maybe_push ("target_sw", "CPE_TARGET_SW", "take-anything");
maybe_push ("target_hw", "CPE_TARGET_HW", "x86-x86-arm64");
maybe_push ("other", "CPE_OTHER", HT.USS (specs.version));
return UTL.json_nvpair_complex ("cpe", form_object, 3, pad);
end describe_Common_Platform_Enumeration;
end Port_Specification.Json;
|
-- This file is covered by the Internet Software Consortium (ISC) License
-- Reference: ../License.txt
with Utilities;
with Ada.Characters.Latin_1;
with HelperText;
package body Port_Specification.Json is
package LAT renames Ada.Characters.Latin_1;
package UTL renames Utilities;
package HT renames HelperText;
--------------------------------------------------------------------------------------------
-- describe_port
--------------------------------------------------------------------------------------------
procedure describe_port
(specs : Portspecs;
dossier : TIO.File_Type;
bucket : String;
index : Positive)
is
fpcval : constant String := fpc_value (specs.generated, specs.equivalent_fpc_port);
nvar : constant Natural := specs.get_number_of_variants;
begin
TIO.Put
(dossier,
UTL.json_object (True, 3, index) &
UTL.json_nvpair_string ("bucket", bucket, 1, pad) &
UTL.json_nvpair_string ("namebase", specs.get_namebase, 2, pad) &
UTL.json_nvpair_string ("version", specs.get_field_value (sp_version), 3, pad) &
homepage_line (specs) &
UTL.json_nvpair_string ("FPC", fpcval, 3, pad) &
UTL.json_nvpair_complex ("keywords", describe_keywords (specs), 3, pad) &
UTL.json_nvpair_complex ("distfile", describe_distfiles (specs), 3, pad) &
specs.get_json_contacts &
describe_Common_Platform_Enumeration (specs) &
UTL.json_name_complex ("variants", 4, pad) &
UTL.json_array (True, pad + 1)
);
for x in 1 .. nvar loop
declare
varstr : constant String := specs.get_list_item (Port_Specification.sp_variants, x);
sdesc : constant String := specs.get_tagline (varstr);
spray : constant String := describe_subpackages (specs, varstr);
begin
TIO.Put
(dossier,
UTL.json_object (True, pad + 2, x) &
UTL.json_nvpair_string ("label", varstr, 1, pad + 3) &
UTL.json_nvpair_string ("sdesc", sdesc, 2, pad + 3) &
UTL.json_nvpair_complex ("spkgs", spray, 3, pad + 3) &
UTL.json_object (False, pad + 2, x)
);
end;
end loop;
TIO.Put
(dossier,
UTL.json_array (False, pad + 1) &
UTL.json_object (False, 3, index)
);
end describe_port;
--------------------------------------------------------------------------------------------
-- fpc_value
--------------------------------------------------------------------------------------------
function fpc_value (is_generated : Boolean; raw_value : String) return String is
begin
if is_generated then
return "generated";
else
return raw_value;
end if;
end fpc_value;
--------------------------------------------------------------------------------------------
-- describe_keywords
--------------------------------------------------------------------------------------------
function describe_keywords (specs : Portspecs) return String
is
raw : constant String := specs.get_field_value (Port_Specification.sp_keywords);
innerquote : constant String :=
HT.replace_char
(S => HT.replace_char (raw, LAT.Comma, LAT.Quotation & LAT.Comma),
focus => LAT.Space,
substring => LAT.Space & LAT.Quotation);
begin
return "[ " & LAT.Quotation & innerquote & LAT.Quotation & " ]";
end describe_keywords;
--------------------------------------------------------------------------------------------
-- describe_distfiles
--------------------------------------------------------------------------------------------
function describe_distfiles (specs : Portspecs) return String
is
numfiles : constant Natural := specs.get_list_length (Port_Specification.sp_distfiles);
result : HT.Text := HT.SUS ("[ ");
begin
for x in 1 .. numfiles loop
if x > 1 then
HT.SU.Append (result, ", ");
end if;
HT.SU.Append (result, LAT.Quotation & specs.get_repology_distfile (x) & LAT.Quotation);
end loop;
return HT.USS (result) & " ]";
end describe_distfiles;
--------------------------------------------------------------------------------------------
-- describe_subpackages
--------------------------------------------------------------------------------------------
function describe_subpackages (specs : Portspecs; variant : String) return String
is
numpkg : constant Natural := specs.get_subpackage_length (variant);
result : HT.Text := HT.SUS ("[ ");
begin
for x in 1 .. numpkg loop
if x > 1 then
HT.SU.Append (result, ", ");
end if;
HT.SU.Append (result, LAT.Quotation &
specs.get_subpackage_item (variant, x) & LAT.Quotation);
end loop;
return HT.USS (result) & " ]";
end describe_subpackages;
--------------------------------------------------------------------------------------------
-- homepage_line
--------------------------------------------------------------------------------------------
function homepage_line (specs : Portspecs) return String
is
homepage : constant String := specs.get_field_value (sp_homepage);
begin
if homepage = homepage_none or else
specs.repology_sucks
then
return "";
end if;
return UTL.json_nvpair_string ("homepage", specs.get_field_value (sp_homepage), 3, pad);
end homepage_line;
--------------------------------------------------------------------------------------------
-- describe_Common_Platform_Enumeration
--------------------------------------------------------------------------------------------
function describe_Common_Platform_Enumeration (specs : Portspecs) return String
is
function retrieve (key : String; default_value : String) return String;
function form_object return String;
procedure maybe_push (json_key, cpe_key, default_value : String);
procedure always_push (json_key, value : String);
pairs : string_crate.Vector;
function retrieve (key : String; default_value : String) return String
is
key_text : HT.Text := HT.SUS (key);
begin
if specs.catch_all.Contains (key_text) then
return HT.USS (specs.catch_all.Element (key_text).list.First_Element);
else
return default_value;
end if;
end retrieve;
procedure always_push (json_key, value : String) is
begin
pairs.Append (HT.SUS (json_key & "=" & value));
end always_push;
procedure maybe_push (json_key, cpe_key, default_value : String)
is
cpe_key_text : HT.Text := HT.SUS (cpe_key);
cpe_value : HT.Text;
begin
if specs.catch_all.Contains (cpe_key_text) then
cpe_value := specs.catch_all.Element (cpe_key_text).list.First_Element;
if not HT.equivalent (cpe_value, default_value) then
pairs.Append (HT.SUS (json_key & "=" & HT.USS (cpe_value)));
end if;
end if;
end maybe_push;
function form_object return String
is
procedure dump (position : string_crate.Cursor);
tracker : Natural := 0;
guts : HT.Text;
procedure dump (position : string_crate.Cursor)
is
both : String := HT.USS (string_crate.Element (position));
key : String := HT.part_1 (both, "=");
value : String := HT.part_2 (both, "=");
data : String := UTL.json_nvpair_string (key, value, 1, 0); -- trailing LF
begin
tracker := tracker + 1;
if tracker > 1 then
HT.SU.Append (guts, LAT.Comma);
end if;
HT.SU.Append (guts, data (data'First .. data'Last - 1));
end dump;
begin
pairs.Iterate (dump'Access);
return "{" & HT.USS (guts) & " }";
end form_object;
begin
if not specs.uses.Contains (HT.SUS ("cpe")) then
return "";
end if;
-- maybe_push ("part", "CPE_PART", "a");
declare
cpe_product : String := retrieve ("CPE_PRODUCT", HT.lowercase (specs.get_namebase));
cpe_vendor : String := retrieve ("CPE_VENDOR", cpe_product);
begin
-- probably should be vendor then product, but this was the original order
-- of repology json. Maintain order to avoid massive diff.
always_push ("product", cpe_product);
always_push ("vendor", cpe_vendor);
end;
-- maybe_push ("version", "CPE_VERSION", HT.USS (specs.version));
-- maybe_push ("update", "CPE_UPDATE", "");
maybe_push ("edition", "CPE_EDITION", "");
maybe_push ("lang", "CPE_LANG", "");
maybe_push ("sw_edition", "CPE_SW_EDITION", "");
maybe_push ("target_sw", "CPE_TARGET_SW", "take-anything");
maybe_push ("target_hw", "CPE_TARGET_HW", "x86-x86-arm64");
maybe_push ("other", "CPE_OTHER", HT.USS (specs.version));
return UTL.json_nvpair_complex ("cpe", form_object, 3, pad);
end describe_Common_Platform_Enumeration;
end Port_Specification.Json;
|
Disable 3 CPE fields from repology.json
|
Disable 3 CPE fields from repology.json
These are not parsed by repology so there is no need to publish them.
|
Ada
|
isc
|
jrmarino/ravenadm,jrmarino/ravenadm,jrmarino/ravenadm
|
848caf64677d6f4198d029fd5513db80ee1b46ad
|
src/security-policies-roles.ads
|
src/security-policies-roles.ads
|
-----------------------------------------------------------------------
-- security-policies-roles -- Role based policies
-- Copyright (C) 2010, 2011, 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
-- == Role Based Security Policy ==
-- The <tt>Security.Policies.Roles</tt> package implements a role based security policy.
--
-- A role is represented by a name in security configuration files.
package Security.Policies.Roles is
-- Each role is represented by a <b>Role_Type</b> number to provide a fast
-- and efficient role check.
type Role_Type is new Natural range 0 .. 63;
for Role_Type'Size use 8;
type Role_Type_Array is array (Positive range <>) of Role_Type;
-- The <b>Role_Map</b> represents a set of roles which are assigned to a user.
-- Each role is represented by a boolean in the map. The implementation is limited
-- to 64 roles (the number of different permissions can be higher).
type Role_Map is array (Role_Type'Range) of Boolean;
pragma Pack (Role_Map);
-- ------------------------------
-- Role based policy
-- ------------------------------
type Role_Policy is new Policy with private;
Invalid_Name : exception;
-- 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);
-- ------------------------------
-- Permission Manager
-- ------------------------------
-- The <b>Permission_Manager</b> verifies through some policy that a permission
-- is granted to a user.
-- Find the role type associated with the role name identified by <b>Name</b>.
-- Raises <b>Invalid_Name</b> if there is no role type.
function Find_Role (Manager : in Role_Policy;
Name : in String) return Role_Type;
-- Get the role name.
function Get_Role_Name (Manager : in Role_Policy;
Role : in Role_Type) return String;
-- Create a role
procedure Create_Role (Manager : in out Role_Policy;
Name : in String;
Role : out Role_Type);
-- Get or add a role type for the given name.
procedure Add_Role_Type (Manager : in out Role_Policy;
Name : in String;
Result : out Role_Type);
private
type Role_Name_Array is
array (Role_Type'Range) of Ada.Strings.Unbounded.String_Access;
type Role_Policy is new Policy with record
Names : Role_Name_Array;
Next_Role : Role_Type := Role_Type'First;
end record;
type Controller_Config is record
Name : Util.Beans.Objects.Object;
Roles : Permissions.Role_Type_Array (1 .. Integer (Permissions.Role_Type'Last));
Count : Natural := 0;
Manager : Security.Permissions.Permission_Manager_Access;
end record;
-- Setup the XML parser to read the <b>role-permission</b> description. For example:
--
-- <security-role>
-- <role-name>admin</role-name>
-- </security-role>
-- <role-permission>
-- <name>create-workspace</name>
-- <role>admin</role>
-- <role>manager</role>
-- </role-permission>
--
-- This defines a permission <b>create-workspace</b> that will be granted if the
-- user has either the <b>admin</b> or the <b>manager</b> role.
overriding
procedure Set_Reader_Config (Pol : in out Policy;
Reader : in out Util.Serialize.IO.XML.Parser);
end Security.Policies.Roles;
|
-----------------------------------------------------------------------
-- security-policies-roles -- Role based policies
-- Copyright (C) 2010, 2011, 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
-- == Role Based Security Policy ==
-- The <tt>Security.Policies.Roles</tt> package implements a role based security policy.
--
-- A role is represented by a name in security configuration files.
package Security.Policies.Roles is
-- Each role is represented by a <b>Role_Type</b> number to provide a fast
-- and efficient role check.
type Role_Type is new Natural range 0 .. 63;
for Role_Type'Size use 8;
type Role_Type_Array is array (Positive range <>) of Role_Type;
-- The <b>Role_Map</b> represents a set of roles which are assigned to a user.
-- Each role is represented by a boolean in the map. The implementation is limited
-- to 64 roles (the number of different permissions can be higher).
type Role_Map is array (Role_Type'Range) of Boolean;
pragma Pack (Role_Map);
-- ------------------------------
-- Role based policy
-- ------------------------------
type Role_Policy is new Policy with private;
Invalid_Name : exception;
-- ------------------------------
-- Permission Manager
-- ------------------------------
-- The <b>Permission_Manager</b> verifies through some policy that a permission
-- is granted to a user.
-- Find the role type associated with the role name identified by <b>Name</b>.
-- Raises <b>Invalid_Name</b> if there is no role type.
function Find_Role (Manager : in Role_Policy;
Name : in String) return Role_Type;
-- Get the role name.
function Get_Role_Name (Manager : in Role_Policy;
Role : in Role_Type) return String;
-- Create a role
procedure Create_Role (Manager : in out Role_Policy;
Name : in String;
Role : out Role_Type);
-- Get or add a role type for the given name.
procedure Add_Role_Type (Manager : in out Role_Policy;
Name : in String;
Result : out Role_Type);
private
type Role_Name_Array is
array (Role_Type'Range) of Ada.Strings.Unbounded.String_Access;
type Role_Policy is new Policy with record
Names : Role_Name_Array;
Next_Role : Role_Type := Role_Type'First;
end record;
type Controller_Config is record
Name : Util.Beans.Objects.Object;
Roles : Permissions.Role_Type_Array (1 .. Integer (Permissions.Role_Type'Last));
Count : Natural := 0;
Manager : Security.Permissions.Permission_Manager_Access;
end record;
-- Setup the XML parser to read the <b>role-permission</b> description. For example:
--
-- <security-role>
-- <role-name>admin</role-name>
-- </security-role>
-- <role-permission>
-- <name>create-workspace</name>
-- <role>admin</role>
-- <role>manager</role>
-- </role-permission>
--
-- This defines a permission <b>create-workspace</b> that will be granted if the
-- user has either the <b>admin</b> or the <b>manager</b> role.
overriding
procedure Set_Reader_Config (Pol : in out Policy;
Reader : in out Util.Serialize.IO.XML.Parser);
end Security.Policies.Roles;
|
Remove Permission_Type and Permission_Map
|
Remove Permission_Type and Permission_Map
|
Ada
|
apache-2.0
|
Letractively/ada-security
|
210d73c3b779f1568daf80f23ca6bd280a3e65cc
|
awa/regtests/awa_harness.adb
|
awa/regtests/awa_harness.adb
|
-----------------------------------------------------------------------
-- AWA - Unit tests
-- Copyright (C) 2009, 2010, 2011 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with AWA.Testsuite;
with Util.Tests;
with AWA.Tests;
procedure AWA_Harness is
procedure Harness is new Util.Tests.Harness (AWA.Testsuite.Suite,
AWA.Tests.Initialize);
begin
Harness ("awa-tests.xml");
end AWA_Harness;
|
-----------------------------------------------------------------------
-- AWA - Unit tests
-- Copyright (C) 2009, 2010, 2011, 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with AWA.Testsuite;
with Util.Tests;
with AWA.Tests;
procedure AWA_Harness is
procedure Harness is new Util.Tests.Harness (AWA.Testsuite.Suite,
AWA.Tests.Initialize,
AWA.Tests.Finish);
begin
Harness ("awa-tests.xml");
end AWA_Harness;
|
Call the Finish procedure after executing the testsuite Finish will destroy the AWA application that was allocated dynamically
|
Call the Finish procedure after executing the testsuite
Finish will destroy the AWA application that was allocated dynamically
|
Ada
|
apache-2.0
|
Letractively/ada-awa,tectronics/ada-awa,Letractively/ada-awa,tectronics/ada-awa,Letractively/ada-awa,tectronics/ada-awa
|
e8e22fd9ad186a4fac4b444a6a18a20bca28d36f
|
regtests/ado-schemas-tests.adb
|
regtests/ado-schemas-tests.adb
|
-----------------------------------------------------------------------
-- ado-schemas-tests -- Test loading of database schema
-- Copyright (C) 2009, 2010, 2011, 2012, 2015, 2017, 2018, 2019 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Directories;
with Util.Test_Caller;
with Util.Strings.Vectors;
with Util.Strings.Transforms;
with ADO.Parameters;
with ADO.Schemas.Databases;
with ADO.Sessions.Sources;
with ADO.Sessions.Entities;
with ADO.Schemas.Entities;
with Regtests;
with Regtests.Audits.Model;
with Regtests.Simple.Model;
package body ADO.Schemas.Tests is
use Util.Tests;
function To_Lower_Case (S : in String) return String
renames Util.Strings.Transforms.To_Lower_Case;
package Caller is new Util.Test_Caller (Test, "ADO.Schemas");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test ADO.Schemas.Entities.Find_Entity_Type",
Test_Find_Entity_Type'Access);
Caller.Add_Test (Suite, "Test ADO.Schemas.Entities.Find_Entity_Type (error)",
Test_Find_Entity_Type_Error'Access);
Caller.Add_Test (Suite, "Test ADO.Sessions.Load_Schema",
Test_Load_Schema'Access);
Caller.Add_Test (Suite, "Test ADO.Schemas.Get_Table",
Test_Table_Iterator'Access);
Caller.Add_Test (Suite, "Test ADO.Schemas.Get_Table (Empty schema)",
Test_Empty_Schema'Access);
Caller.Add_Test (Suite, "Test ADO.Schemas.Databases.Create_Database",
Test_Create_Schema'Access);
end Add_Tests;
-- ------------------------------
-- Test reading the entity cache and the Find_Entity_Type operation
-- ------------------------------
procedure Test_Find_Entity_Type (T : in out Test) is
S : ADO.Sessions.Session := Regtests.Get_Database;
C : ADO.Schemas.Entities.Entity_Cache;
begin
ADO.Schemas.Entities.Initialize (Cache => C,
Session => S);
declare
T4 : constant ADO.Entity_Type
:= Entities.Find_Entity_Type (Cache => C,
Table => Regtests.Simple.Model.ALLOCATE_TABLE);
T5 : constant ADO.Entity_Type
:= Entities.Find_Entity_Type (Cache => C,
Table => Regtests.Simple.Model.USER_TABLE);
T1 : constant ADO.Entity_Type
:= Sessions.Entities.Find_Entity_Type (Session => S,
Table => Regtests.Audits.Model.AUDIT_TABLE);
T2 : constant ADO.Entity_Type
:= Sessions.Entities.Find_Entity_Type (Session => S,
Table => Regtests.Audits.Model.EMAIL_TABLE);
T3 : constant ADO.Entity_Type
:= Sessions.Entities.Find_Entity_Type (Session => S,
Name => "audit_property");
begin
T.Assert (T1 > 0, "T1 must be positive");
T.Assert (T2 > 0, "T2 must be positive");
T.Assert (T3 > 0, "T3 must be positive");
T.Assert (T4 > 0, "T4 must be positive");
T.Assert (T5 > 0, "T5 must be positive");
T.Assert (T1 /= T2, "Two distinct tables have different entity types (T1, T2)");
T.Assert (T2 /= T3, "Two distinct tables have different entity types (T2, T3)");
T.Assert (T3 /= T4, "Two distinct tables have different entity types (T3, T4)");
T.Assert (T4 /= T5, "Two distinct tables have different entity types (T4, T5)");
T.Assert (T5 /= T1, "Two distinct tables have different entity types (T5, T1)");
end;
end Test_Find_Entity_Type;
-- ------------------------------
-- Test calling Find_Entity_Type with an invalid table.
-- ------------------------------
procedure Test_Find_Entity_Type_Error (T : in out Test) is
C : ADO.Schemas.Entities.Entity_Cache;
begin
declare
R : ADO.Entity_Type;
pragma Unreferenced (R);
begin
R := Entities.Find_Entity_Type (Cache => C,
Table => Regtests.Simple.Model.USER_TABLE);
T.Assert (False, "Find_Entity_Type did not raise the No_Entity_Type exception");
exception
when ADO.Schemas.Entities.No_Entity_Type =>
null;
end;
declare
P : ADO.Parameters.Parameter
:= ADO.Parameters.Parameter'(T => ADO.Parameters.T_INTEGER, Num => 0,
Len => 0, Value_Len => 0, Position => 0, Name => "");
begin
P := C.Expand ("something");
T.Assert (False, "Expand did not raise the No_Entity_Type exception");
exception
when ADO.Schemas.Entities.No_Entity_Type =>
null;
end;
end Test_Find_Entity_Type_Error;
-- ------------------------------
-- Test the Load_Schema operation and check the result schema.
-- ------------------------------
procedure Test_Load_Schema (T : in out Test) is
S : constant ADO.Sessions.Session := Regtests.Get_Database;
Schema : Schema_Definition;
Table : Table_Definition;
begin
S.Load_Schema (Schema);
Table := ADO.Schemas.Find_Table (Schema, "allocate");
T.Assert (Table /= null, "Table schema for test_allocate not found");
Assert_Equals (T, "allocate", Get_Name (Table));
declare
C : Column_Cursor := Get_Columns (Table);
Nb_Columns : Integer := 0;
begin
while Has_Element (C) loop
Nb_Columns := Nb_Columns + 1;
Next (C);
end loop;
Assert_Equals (T, 3, Nb_Columns, "Invalid number of columns");
end;
declare
C : constant Column_Definition := Find_Column (Table, "ID");
begin
T.Assert (C /= null, "Cannot find column 'id' in table schema");
Assert_Equals (T, "id", To_Lower_Case (Get_Name (C)), "Invalid column name");
T.Assert (Get_Type (C) = T_LONG_INTEGER, "Invalid column type");
T.Assert (not Is_Null (C), "Column is null");
T.Assert (Is_Primary (C), "Column must be a primary key");
end;
declare
C : constant Column_Definition := Find_Column (Table, "NAME");
begin
T.Assert (C /= null, "Cannot find column 'NAME' in table schema");
Assert_Equals (T, "name", To_Lower_Case (Get_Name (C)), "Invalid column name");
T.Assert (Get_Type (C) = T_VARCHAR, "Invalid column type");
T.Assert (Is_Null (C), "Column is null");
T.Assert (not Is_Primary (C), "Column must not be a primary key");
Assert_Equals (T, 255, Get_Size (C), "Column has invalid size");
end;
declare
C : constant Column_Definition := Find_Column (Table, "version");
begin
T.Assert (C /= null, "Cannot find column 'version' in table schema");
Assert_Equals (T, "version", To_Lower_Case (Get_Name (C)), "Invalid column name");
T.Assert (Get_Type (C) = T_INTEGER, "Invalid column type");
T.Assert (not Is_Null (C), "Column is null");
end;
declare
C : constant Column_Definition := Find_Column (Table, "this_column_does_not_exist");
begin
T.Assert (C = null, "Find_Column must return null for an unknown column");
end;
end Test_Load_Schema;
-- ------------------------------
-- Test the Table_Cursor operations and check the result schema.
-- ------------------------------
procedure Test_Table_Iterator (T : in out Test) is
S : constant ADO.Sessions.Session := Regtests.Get_Database;
Schema : Schema_Definition;
Table : Table_Definition;
Driver : constant String := S.Get_Driver.Get_Driver_Name;
begin
S.Load_Schema (Schema);
declare
Iter : Table_Cursor := Schema.Get_Tables;
Count : Natural := 0;
begin
T.Assert (Has_Element (Iter), "The Get_Tables returns an empty iterator");
while Has_Element (Iter) loop
Table := Element (Iter);
T.Assert (Table /= null, "Element function must not return null");
declare
Col_Iter : Column_Cursor := Get_Columns (Table);
begin
-- T.Assert (Has_Element (Col_Iter), "Table has a column");
while Has_Element (Col_Iter) loop
T.Assert (Element (Col_Iter) /= null, "Element function must not return null");
Next (Col_Iter);
end loop;
end;
Count := Count + 1;
Next (Iter);
end loop;
if Driver = "sqlite" then
Util.Tests.Assert_Equals (T, 21, Count,
"Invalid number of tables found in the schema");
elsif Driver = "mysql" then
Util.Tests.Assert_Equals (T, 11, Count,
"Invalid number of tables found in the schema");
elsif Driver = "postgresql" then
Util.Tests.Assert_Equals (T, 11, Count,
"Invalid number of tables found in the schema");
end if;
end;
end Test_Table_Iterator;
-- ------------------------------
-- Test the Table_Cursor operations on an empty schema.
-- ------------------------------
procedure Test_Empty_Schema (T : in out Test) is
Schema : Schema_Definition;
Iter : constant Table_Cursor := Schema.Get_Tables;
begin
T.Assert (not Has_Element (Iter), "The Get_Tables must return an empty iterator");
T.Assert (Schema.Find_Table ("test") = null, "The Find_Table must return null");
end Test_Empty_Schema;
-- ------------------------------
-- Test the creation of database.
-- ------------------------------
procedure Test_Create_Schema (T : in out Test) is
use ADO.Sessions.Sources;
Msg : Util.Strings.Vectors.Vector;
Cfg : Data_Source := Data_Source (Regtests.Get_Controller);
Driver : constant String := Cfg.Get_Driver;
Database : constant String := Cfg.Get_Database;
Path : constant String :=
"db/regtests/" & Cfg.Get_Driver & "/create-ado-" & Driver & ".sql";
pragma Unreferenced (Msg);
begin
if Driver = "sqlite" then
if Ada.Directories.Exists (Database & ".test") then
Ada.Directories.Delete_File (Database & ".test");
end if;
Cfg.Set_Database (Database & ".test");
ADO.Schemas.Databases.Create_Database (Admin => Cfg,
Config => Cfg,
Schema_Path => Path,
Messages => Msg);
T.Assert (Ada.Directories.Exists (Database & ".test"),
"The sqlite database was not created");
else
ADO.Schemas.Databases.Create_Database (Admin => Cfg,
Config => Cfg,
Schema_Path => Path,
Messages => Msg);
end if;
end Test_Create_Schema;
end ADO.Schemas.Tests;
|
-----------------------------------------------------------------------
-- ado-schemas-tests -- Test loading of database schema
-- Copyright (C) 2009 - 2020 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Directories;
with Util.Test_Caller;
with Util.Strings.Vectors;
with Util.Strings.Transforms;
with ADO.Parameters;
with ADO.Schemas.Databases;
with ADO.Sessions.Sources;
with ADO.Sessions.Entities;
with ADO.Schemas.Entities;
with Regtests;
with Regtests.Audits.Model;
with Regtests.Simple.Model;
package body ADO.Schemas.Tests is
use Util.Tests;
function To_Lower_Case (S : in String) return String
renames Util.Strings.Transforms.To_Lower_Case;
package Caller is new Util.Test_Caller (Test, "ADO.Schemas");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test ADO.Schemas.Entities.Find_Entity_Type",
Test_Find_Entity_Type'Access);
Caller.Add_Test (Suite, "Test ADO.Schemas.Entities.Find_Entity_Type (error)",
Test_Find_Entity_Type_Error'Access);
Caller.Add_Test (Suite, "Test ADO.Sessions.Load_Schema",
Test_Load_Schema'Access);
Caller.Add_Test (Suite, "Test ADO.Schemas.Get_Table",
Test_Table_Iterator'Access);
Caller.Add_Test (Suite, "Test ADO.Schemas.Get_Table (Empty schema)",
Test_Empty_Schema'Access);
Caller.Add_Test (Suite, "Test ADO.Schemas.Databases.Create_Database",
Test_Create_Schema'Access);
end Add_Tests;
-- ------------------------------
-- Test reading the entity cache and the Find_Entity_Type operation
-- ------------------------------
procedure Test_Find_Entity_Type (T : in out Test) is
S : ADO.Sessions.Session := Regtests.Get_Database;
C : ADO.Schemas.Entities.Entity_Cache;
begin
ADO.Schemas.Entities.Initialize (Cache => C,
Session => S);
declare
T4 : constant ADO.Entity_Type
:= Entities.Find_Entity_Type (Cache => C,
Table => Regtests.Simple.Model.ALLOCATE_TABLE);
T5 : constant ADO.Entity_Type
:= Entities.Find_Entity_Type (Cache => C,
Table => Regtests.Simple.Model.USER_TABLE);
T1 : constant ADO.Entity_Type
:= Sessions.Entities.Find_Entity_Type (Session => S,
Table => Regtests.Audits.Model.AUDIT_TABLE);
T2 : constant ADO.Entity_Type
:= Sessions.Entities.Find_Entity_Type (Session => S,
Table => Regtests.Audits.Model.EMAIL_TABLE);
T3 : constant ADO.Entity_Type
:= Sessions.Entities.Find_Entity_Type (Session => S,
Name => "audit_property");
begin
T.Assert (T1 > 0, "T1 must be positive");
T.Assert (T2 > 0, "T2 must be positive");
T.Assert (T3 > 0, "T3 must be positive");
T.Assert (T4 > 0, "T4 must be positive");
T.Assert (T5 > 0, "T5 must be positive");
T.Assert (T1 /= T2, "Two distinct tables have different entity types (T1, T2)");
T.Assert (T2 /= T3, "Two distinct tables have different entity types (T2, T3)");
T.Assert (T3 /= T4, "Two distinct tables have different entity types (T3, T4)");
T.Assert (T4 /= T5, "Two distinct tables have different entity types (T4, T5)");
T.Assert (T5 /= T1, "Two distinct tables have different entity types (T5, T1)");
end;
end Test_Find_Entity_Type;
-- ------------------------------
-- Test calling Find_Entity_Type with an invalid table.
-- ------------------------------
procedure Test_Find_Entity_Type_Error (T : in out Test) is
C : ADO.Schemas.Entities.Entity_Cache;
begin
declare
R : ADO.Entity_Type;
pragma Unreferenced (R);
begin
R := Entities.Find_Entity_Type (Cache => C,
Table => Regtests.Simple.Model.USER_TABLE);
T.Assert (False, "Find_Entity_Type did not raise the No_Entity_Type exception");
exception
when ADO.Schemas.Entities.No_Entity_Type =>
null;
end;
declare
P : ADO.Parameters.Parameter
:= ADO.Parameters.Parameter'(T => ADO.Parameters.T_INTEGER, Num => 0,
Len => 0, Value_Len => 0, Position => 0, Name => "");
begin
P := C.Expand ("something");
T.Assert (False, "Expand did not raise the No_Entity_Type exception");
exception
when ADO.Schemas.Entities.No_Entity_Type =>
null;
end;
end Test_Find_Entity_Type_Error;
-- ------------------------------
-- Test the Load_Schema operation and check the result schema.
-- ------------------------------
procedure Test_Load_Schema (T : in out Test) is
S : constant ADO.Sessions.Session := Regtests.Get_Database;
Schema : Schema_Definition;
Table : Table_Definition;
begin
S.Load_Schema (Schema);
Table := ADO.Schemas.Find_Table (Schema, "allocate");
T.Assert (Table /= null, "Table schema for test_allocate not found");
Assert_Equals (T, "allocate", Get_Name (Table));
declare
C : Column_Cursor := Get_Columns (Table);
Nb_Columns : Integer := 0;
begin
while Has_Element (C) loop
Nb_Columns := Nb_Columns + 1;
Next (C);
end loop;
Assert_Equals (T, 3, Nb_Columns, "Invalid number of columns");
end;
declare
C : constant Column_Definition := Find_Column (Table, "ID");
begin
T.Assert (C /= null, "Cannot find column 'id' in table schema");
Assert_Equals (T, "id", To_Lower_Case (Get_Name (C)), "Invalid column name");
T.Assert (Get_Type (C) = T_LONG_INTEGER, "Invalid column type");
T.Assert (not Is_Null (C), "Column is null");
T.Assert (Is_Primary (C), "Column must be a primary key");
end;
declare
C : constant Column_Definition := Find_Column (Table, "NAME");
begin
T.Assert (C /= null, "Cannot find column 'NAME' in table schema");
Assert_Equals (T, "name", To_Lower_Case (Get_Name (C)), "Invalid column name");
T.Assert (Get_Type (C) = T_VARCHAR, "Invalid column type");
T.Assert (Is_Null (C), "Column is null");
T.Assert (not Is_Primary (C), "Column must not be a primary key");
Assert_Equals (T, 255, Get_Size (C), "Column has invalid size");
end;
declare
C : constant Column_Definition := Find_Column (Table, "version");
begin
T.Assert (C /= null, "Cannot find column 'version' in table schema");
Assert_Equals (T, "version", To_Lower_Case (Get_Name (C)), "Invalid column name");
T.Assert (Get_Type (C) = T_INTEGER, "Invalid column type");
T.Assert (not Is_Null (C), "Column is null");
end;
declare
C : constant Column_Definition := Find_Column (Table, "this_column_does_not_exist");
begin
T.Assert (C = null, "Find_Column must return null for an unknown column");
end;
end Test_Load_Schema;
-- ------------------------------
-- Test the Table_Cursor operations and check the result schema.
-- ------------------------------
procedure Test_Table_Iterator (T : in out Test) is
S : constant ADO.Sessions.Session := Regtests.Get_Database;
Schema : Schema_Definition;
Table : Table_Definition;
Driver : constant String := S.Get_Driver.Get_Driver_Name;
begin
S.Load_Schema (Schema);
declare
Iter : Table_Cursor := Schema.Get_Tables;
Count : Natural := 0;
begin
T.Assert (Has_Element (Iter), "The Get_Tables returns an empty iterator");
while Has_Element (Iter) loop
Table := Element (Iter);
T.Assert (Table /= null, "Element function must not return null");
declare
Col_Iter : Column_Cursor := Get_Columns (Table);
begin
-- T.Assert (Has_Element (Col_Iter), "Table has a column");
while Has_Element (Col_Iter) loop
T.Assert (Element (Col_Iter) /= null, "Element function must not return null");
Next (Col_Iter);
end loop;
end;
Count := Count + 1;
Next (Iter);
end loop;
if Driver = "sqlite" then
Util.Tests.Assert_Equals (T, 11, Count,
"Invalid number of tables found in the schema");
elsif Driver = "mysql" then
Util.Tests.Assert_Equals (T, 11, Count,
"Invalid number of tables found in the schema");
elsif Driver = "postgresql" then
Util.Tests.Assert_Equals (T, 11, Count,
"Invalid number of tables found in the schema");
end if;
end;
end Test_Table_Iterator;
-- ------------------------------
-- Test the Table_Cursor operations on an empty schema.
-- ------------------------------
procedure Test_Empty_Schema (T : in out Test) is
Schema : Schema_Definition;
Iter : constant Table_Cursor := Schema.Get_Tables;
begin
T.Assert (not Has_Element (Iter), "The Get_Tables must return an empty iterator");
T.Assert (Schema.Find_Table ("test") = null, "The Find_Table must return null");
end Test_Empty_Schema;
-- ------------------------------
-- Test the creation of database.
-- ------------------------------
procedure Test_Create_Schema (T : in out Test) is
use ADO.Sessions.Sources;
Msg : Util.Strings.Vectors.Vector;
Cfg : Data_Source := Data_Source (Regtests.Get_Controller);
Driver : constant String := Cfg.Get_Driver;
Database : constant String := Cfg.Get_Database;
Path : constant String :=
"db/regtests/" & Cfg.Get_Driver & "/create-ado-" & Driver & ".sql";
pragma Unreferenced (Msg);
begin
if Driver = "sqlite" then
if Ada.Directories.Exists (Database & ".test") then
Ada.Directories.Delete_File (Database & ".test");
end if;
Cfg.Set_Database (Database & ".test");
ADO.Schemas.Databases.Create_Database (Admin => Cfg,
Config => Cfg,
Schema_Path => Path,
Messages => Msg);
T.Assert (Ada.Directories.Exists (Database & ".test"),
"The sqlite database was not created");
else
ADO.Schemas.Databases.Create_Database (Admin => Cfg,
Config => Cfg,
Schema_Path => Path,
Messages => Msg);
end if;
end Test_Create_Schema;
end ADO.Schemas.Tests;
|
Fix Load_Schema unit test for SQLite after corrections in SQLite driver
|
Fix Load_Schema unit test for SQLite after corrections in SQLite driver
|
Ada
|
apache-2.0
|
stcarrez/ada-ado
|
b45b132a1c4c3871696f1e12835fa625fd8bf998
|
tools/timekey.adb
|
tools/timekey.adb
|
------------------------------------------------------------------------------
-- 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;
Subsecond_Digits : Natural := Duration'Aft;
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), Subsecond_Digits, 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, Subsecond_Digits, 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;
Subsecond_Digits : Natural := Duration'Aft;
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), Subsecond_Digits, 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;
elsif Arg'Length = 2
and then Arg (Arg'First) = '-'
and then Arg (Arg'Last) in '0' .. '9'
then
Subsecond_Digits := Character'Pos (Arg (Arg'Last))
- Character'Pos ('0');
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, Subsecond_Digits, False)
& " => ");
end if;
Ada.Text_IO.Put_Line (Natools.Time_Keys.To_Key (Now));
end;
end if;
end Timekey;
|
add CLI option to configure numer of subsecond digits
|
tools/timekey: add CLI option to configure numer of subsecond digits
|
Ada
|
isc
|
faelys/natools
|
759f93a9712f13afed950710f1b1572881b488e6
|
src/asf-server.adb
|
src/asf-server.adb
|
-----------------------------------------------------------------------
-- asf.server -- ASF Server
-- Copyright (C) 2009, 2010, 2011, 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Strings;
with Ada.Unchecked_Deallocation;
with Ada.Task_Attributes;
package body ASF.Server is
Null_Context : constant Request_Context := Request_Context'(null, null, null);
package Task_Context is new Ada.Task_Attributes
(Request_Context, Null_Context);
procedure Free is
new Ada.Unchecked_Deallocation (Object => Binding_Array,
Name => Binding_Array_Access);
-- ------------------------------
-- Get the current registry associated with the current request being processed
-- by the current thread. Returns null if there is no current request.
-- ------------------------------
function Current return ASF.Servlets.Servlet_Registry_Access is
begin
return Task_Context.Value.Application;
end Current;
-- ------------------------------
-- Set the current registry. This is called by <b>Service</b> once the
-- registry is identified from the URI.
-- ------------------------------
procedure Set_Context (Context : in Request_Context) is
begin
Task_Context.Set_Value (Context);
end Set_Context;
-- ------------------------------
-- Give access to the current request and response object to the <b>Process</b>
-- procedure. If there is no current request for the thread, do nothing.
-- ------------------------------
procedure Update_Context (Process : not null access
procedure (Request : in out Requests.Request'Class;
Response : in out Responses.Response'Class)) is
Ctx : constant Request_Context := Task_Context.Value;
begin
Process (Ctx.Request.all, Ctx.Response.all);
end Update_Context;
-- ------------------------------
-- Register the application to serve requests
-- ------------------------------
procedure Register_Application (Server : in out Container;
URI : in String;
Context : in ASF.Servlets.Servlet_Registry_Access) is
Count : constant Natural := Server.Nb_Bindings;
Apps : constant Binding_Array_Access := new Binding_Array (1 .. Count + 1);
begin
if Server.Applications /= null then
Apps (1 .. Count) := Server.Applications (1 .. Count);
Free (Server.Applications);
end if;
Server.Nb_Bindings := Count + 1;
Apps (Apps'Last).Context := Context;
Apps (Apps'Last).Base_URI := Ada.Strings.Unbounded.To_Unbounded_String (URI);
Server.Applications := Apps;
-- Inform the servlet registry about the base URI.
Context.Register_Application (URI);
end Register_Application;
-- ------------------------------
-- Start the applications that have been registered.
-- ------------------------------
procedure Start (Server : in out Container) is
begin
if Server.Applications /= null then
for I in Server.Applications'Range loop
Server.Applications (I).Context.Start;
end loop;
end if;
end Start;
-- ------------------------------
-- 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.
-- ------------------------------
procedure Service (Server : in Container;
Request : in out Requests.Request'Class;
Response : in out Responses.Response'Class) is
use Servlets;
use Util.Strings;
use type Ada.Strings.Unbounded.Unbounded_String;
URI : constant String := Request.Get_Request_URI;
Slash_Pos : constant Natural := Index (URI, '/', URI'First + 1);
Apps : constant Binding_Array_Access := Server.Applications;
Prefix_End : Natural;
begin
if Apps = null then
Response.Set_Status (Responses.SC_NOT_FOUND);
Server.Default.Send_Error_Page (Request, Response);
return;
end if;
-- Find the module and action to invoke
if Slash_Pos > 1 then
Prefix_End := Slash_Pos - 1;
else
Prefix_End := URI'Last;
end if;
for I in Apps.all'Range loop
if Apps (I).Base_URI = URI (URI'First .. Prefix_End) then
declare
Req : Request_Context;
Context : constant Servlet_Registry_Access := Apps (I).Context;
Page : constant String := URI (Prefix_End + 1 .. URI'Last);
Dispatcher : constant Request_Dispatcher := Context.Get_Request_Dispatcher (Page);
begin
Req.Request := Request'Unchecked_Access;
Req.Response := Response'Unchecked_Access;
Req.Application := Context;
Set_Context (Req);
Forward (Dispatcher, Request, Response);
case Response.Get_Status / 100 is
when 2 | 3 =>
null;
when others =>
Context.Send_Error_Page (Request, Response);
end case;
Set_Context (Null_Context);
return;
exception
when E : others =>
Context.Error (Request, Response, E);
Set_Context (Null_Context);
return;
end;
end if;
end loop;
Response.Set_Status (Responses.SC_NOT_FOUND);
Server.Default.Send_Error_Page (Request, Response);
exception
when E : others =>
Server.Default.Error (Request, Response, E);
end Service;
-- ------------------------------
-- Release the storage.
-- ------------------------------
overriding
procedure Finalize (Server : in out Container) is
begin
Free (Server.Applications);
end Finalize;
end ASF.Server;
|
-----------------------------------------------------------------------
-- asf.server -- ASF Server
-- Copyright (C) 2009, 2010, 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 Util.Strings;
with Ada.Unchecked_Deallocation;
with Ada.Task_Attributes;
package body ASF.Server is
Null_Context : constant Request_Context := Request_Context'(null, null, null);
package Task_Context is new Ada.Task_Attributes
(Request_Context, Null_Context);
procedure Free is
new Ada.Unchecked_Deallocation (Object => Binding_Array,
Name => Binding_Array_Access);
-- ------------------------------
-- Get the current registry associated with the current request being processed
-- by the current thread. Returns null if there is no current request.
-- ------------------------------
function Current return ASF.Servlets.Servlet_Registry_Access is
begin
return Task_Context.Value.Application;
end Current;
-- ------------------------------
-- Set the current registry. This is called by <b>Service</b> once the
-- registry is identified from the URI.
-- ------------------------------
procedure Set_Context (Context : in Request_Context) is
begin
Task_Context.Set_Value (Context);
end Set_Context;
-- ------------------------------
-- Give access to the current request and response object to the <b>Process</b>
-- procedure. If there is no current request for the thread, do nothing.
-- ------------------------------
procedure Update_Context (Process : not null access
procedure (Request : in out Requests.Request'Class;
Response : in out Responses.Response'Class)) is
Ctx : constant Request_Context := Task_Context.Value;
begin
Process (Ctx.Request.all, Ctx.Response.all);
end Update_Context;
-- ------------------------------
-- Register the application to serve requests
-- ------------------------------
procedure Register_Application (Server : in out Container;
URI : in String;
Context : in ASF.Servlets.Servlet_Registry_Access) is
Count : constant Natural := Server.Nb_Bindings;
Apps : constant Binding_Array_Access := new Binding_Array (1 .. Count + 1);
begin
if Server.Applications /= null then
Apps (1 .. Count) := Server.Applications (1 .. Count);
Free (Server.Applications);
end if;
Server.Nb_Bindings := Count + 1;
Apps (Count + 1).Context := Context;
Apps (Count + 1).Base_URI := Ada.Strings.Unbounded.To_Unbounded_String (URI);
Server.Applications := Apps;
-- Inform the servlet registry about the base URI.
Context.Register_Application (URI);
end Register_Application;
-- ------------------------------
-- Remove the application
-- ------------------------------
procedure Remove_Application (Server : in out Container;
Context : in ASF.Servlets.Servlet_Registry_Access) is
use type ASF.Servlets.Servlet_Registry_Access;
Count : constant Natural := Server.Nb_Bindings;
Apps : constant Binding_Array_Access := Server.Applications;
begin
for I in 1 .. Count loop
if Apps (I).Context = Context then
Server.Nb_Bindings := Count - 1;
if I < Count then
Apps (I) := Apps (Count);
end if;
return;
end if;
end loop;
end Remove_Application;
-- ------------------------------
-- Start the applications that have been registered.
-- ------------------------------
procedure Start (Server : in out Container) is
begin
if Server.Applications /= null then
for I in Server.Applications'Range loop
Server.Applications (I).Context.Start;
end loop;
end if;
end Start;
-- ------------------------------
-- 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.
-- ------------------------------
procedure Service (Server : in Container;
Request : in out Requests.Request'Class;
Response : in out Responses.Response'Class) is
use Servlets;
use Util.Strings;
use type Ada.Strings.Unbounded.Unbounded_String;
URI : constant String := Request.Get_Request_URI;
Slash_Pos : constant Natural := Index (URI, '/', URI'First + 1);
Apps : constant Binding_Array_Access := Server.Applications;
Prefix_End : Natural;
begin
if Apps = null then
Response.Set_Status (Responses.SC_NOT_FOUND);
Server.Default.Send_Error_Page (Request, Response);
return;
end if;
-- Find the module and action to invoke
if Slash_Pos > 1 then
Prefix_End := Slash_Pos - 1;
else
Prefix_End := URI'Last;
end if;
for I in Apps.all'Range loop
if Apps (I).Base_URI = URI (URI'First .. Prefix_End) then
declare
Req : Request_Context;
Context : constant Servlet_Registry_Access := Apps (I).Context;
Page : constant String := URI (Prefix_End + 1 .. URI'Last);
Dispatcher : constant Request_Dispatcher := Context.Get_Request_Dispatcher (Page);
begin
Req.Request := Request'Unchecked_Access;
Req.Response := Response'Unchecked_Access;
Req.Application := Context;
Set_Context (Req);
Forward (Dispatcher, Request, Response);
case Response.Get_Status / 100 is
when 2 | 3 =>
null;
when others =>
Context.Send_Error_Page (Request, Response);
end case;
Set_Context (Null_Context);
return;
exception
when E : others =>
Context.Error (Request, Response, E);
Set_Context (Null_Context);
return;
end;
end if;
end loop;
Response.Set_Status (Responses.SC_NOT_FOUND);
Server.Default.Send_Error_Page (Request, Response);
exception
when E : others =>
Server.Default.Error (Request, Response, E);
end Service;
-- ------------------------------
-- Release the storage.
-- ------------------------------
overriding
procedure Finalize (Server : in out Container) is
begin
Free (Server.Applications);
end Finalize;
end ASF.Server;
|
Implement Remove_Application procedure
|
Implement Remove_Application procedure
|
Ada
|
apache-2.0
|
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
|
e40402895375a8cf68659fc66c380f5f408e21f4
|
awa/plugins/awa-images/src/awa-images-beans.ads
|
awa/plugins/awa-images/src/awa-images-beans.ads
|
-----------------------------------------------------------------------
-- awa-images-beans -- Image Ada Beans
-- Copyright (C) 2016 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with ADO;
with Util.Beans.Objects;
with Util.Beans.Basic;
with AWA.Storages.Beans;
with AWA.Images.Models;
with AWA.Images.Modules;
package AWA.Images.Beans is
FOLDER_ID_PARAMETER : constant String := "folderId";
-- ------------------------------
-- Image List Bean
-- ------------------------------
-- This bean represents a list of images for a given folder.
type Image_List_Bean is new AWA.Storages.Beans.Storage_List_Bean with record
-- List of images.
Image_List : aliased AWA.Images.Models.Image_Info_List_Bean;
Image_List_Bean : AWA.Images.Models.Image_Info_List_Bean_Access;
end record;
type Image_List_Bean_Access is access all Image_List_Bean'Class;
-- Load the list of images associated with the current folder.
overriding
procedure Load_Files (Storage : in Image_List_Bean);
overriding
function Get_Value (List : in Image_List_Bean;
Name : in String) return Util.Beans.Objects.Object;
-- Create the Image_List_Bean bean instance.
function Create_Image_List_Bean (Module : in AWA.Images.Modules.Image_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access;
end AWA.Images.Beans;
|
-----------------------------------------------------------------------
-- awa-images-beans -- Image Ada Beans
-- Copyright (C) 2016 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with ADO;
with Util.Beans.Objects;
with Util.Beans.Basic;
with AWA.Storages.Beans;
with AWA.Images.Models;
with AWA.Images.Modules;
package AWA.Images.Beans is
-- ------------------------------
-- Image List Bean
-- ------------------------------
-- This bean represents a list of images for a given folder.
type Image_List_Bean is new AWA.Storages.Beans.Storage_List_Bean with record
-- List of images.
Image_List : aliased AWA.Images.Models.Image_Info_List_Bean;
Image_List_Bean : AWA.Images.Models.Image_Info_List_Bean_Access;
end record;
type Image_List_Bean_Access is access all Image_List_Bean'Class;
-- Load the list of images associated with the current folder.
overriding
procedure Load_Files (Storage : in Image_List_Bean);
overriding
function Get_Value (List : in Image_List_Bean;
Name : in String) return Util.Beans.Objects.Object;
-- Create the Image_List_Bean bean instance.
function Create_Image_List_Bean (Module : in AWA.Images.Modules.Image_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access;
end AWA.Images.Beans;
|
Remove FOLDER_ID_PARAMETER constant
|
Remove FOLDER_ID_PARAMETER constant
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
8495f8b93f886b0039d329288269006a5e44ec6c
|
awa/plugins/awa-wikis/src/awa-wikis-modules.ads
|
awa/plugins/awa-wikis/src/awa-wikis-modules.ads
|
-----------------------------------------------------------------------
-- awa-wikis-modules -- Module wikis
-- Copyright (C) 2015, 2016 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with ASF.Applications;
with ADO;
with ADO.Sessions;
with AWA.Events;
with AWA.Modules;
with AWA.Modules.Lifecycles;
with AWA.Wikis.Models;
with AWA.Tags.Beans;
with AWA.Counters.Definition;
with Security.Permissions;
-- == Events ==
-- The <tt>wikis</tt> exposes a number of events which are posted when some action
-- are performed at the service level.
--
-- === wiki-create-page ===
-- This event is posted when a new wiki page is created.
--
-- === wiki-create-content ===
-- This event is posted when a new wiki page content is created. Each time a wiki page is
-- modified, a new wiki page content is created and this event is posted.
--
package AWA.Wikis.Modules is
-- The name under which the module is registered.
NAME : constant String := "wikis";
-- The configuration parameter that defines the image link prefix in rendered HTML content.
PARAM_IMAGE_PREFIX : constant String := "image_prefix";
package ACL_Create_Wiki_Pages is new Security.Permissions.Definition ("wiki-page-create");
package ACL_Delete_Wiki_Pages is new Security.Permissions.Definition ("wiki-page-delete");
package ACL_Update_Wiki_Pages is new Security.Permissions.Definition ("wiki-page-update");
package ACL_View_Wiki_Page is new Security.Permissions.Definition ("wiki-page-view");
-- Define the permissions.
package ACL_Create_Wiki_Space is new Security.Permissions.Definition ("wiki-space-create");
package ACL_Delete_Wiki_Space is new Security.Permissions.Definition ("wiki-space-delete");
package ACL_Update_Wiki_Space is new Security.Permissions.Definition ("wiki-space-update");
-- Event posted when a new wiki page is created.
package Create_Page_Event is new AWA.Events.Definition (Name => "wiki-create-page");
-- Event posted when a new wiki content is created.
package Create_Content_Event is new AWA.Events.Definition (Name => "wiki-create-content");
-- Define the read wiki page counter.
package Read_Counter is new AWA.Counters.Definition (Models.WIKI_PAGE_TABLE, "read_count");
package Wiki_Lifecycle is
new AWA.Modules.Lifecycles (Element_Type => AWA.Wikis.Models.Wiki_Page_Ref'Class);
subtype Listener is Wiki_Lifecycle.Listener;
-- The configuration parameter that defines a list of wiki page ID to copy when a new
-- wiki space is created.
PARAM_WIKI_COPY_LIST : constant String := "wiki_copy_list";
-- Exception raised when a wiki page name is already used for the wiki space.
Name_Used : exception;
-- ------------------------------
-- Module wikis
-- ------------------------------
type Wiki_Module is new AWA.Modules.Module with private;
type Wiki_Module_Access is access all Wiki_Module'Class;
-- Initialize the wikis module.
overriding
procedure Initialize (Plugin : in out Wiki_Module;
App : in AWA.Modules.Application_Access;
Props : in ASF.Applications.Config);
-- Configures the module after its initialization and after having read its XML configuration.
overriding
procedure Configure (Plugin : in out Wiki_Module;
Props : in ASF.Applications.Config);
-- Get the image prefix that was configured for the Wiki module.
function Get_Image_Prefix (Module : in Wiki_Module)
return Ada.Strings.Unbounded.Unbounded_String;
-- Get the wikis module.
function Get_Wiki_Module return Wiki_Module_Access;
-- Create the wiki space.
procedure Create_Wiki_Space (Module : in Wiki_Module;
Wiki : in out AWA.Wikis.Models.Wiki_Space_Ref'Class);
-- Save the wiki space.
procedure Save_Wiki_Space (Module : in Wiki_Module;
Wiki : in out AWA.Wikis.Models.Wiki_Space_Ref'Class);
-- 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);
-- Create the wiki page into the wiki space.
procedure Create_Wiki_Page (Model : in Wiki_Module;
Into : in AWA.Wikis.Models.Wiki_Space_Ref'Class;
Page : in out AWA.Wikis.Models.Wiki_Page_Ref'Class;
Content : in out AWA.Wikis.Models.Wiki_Content_Ref'Class);
-- Save the wiki page.
procedure Save (Model : in Wiki_Module;
Page : in out AWA.Wikis.Models.Wiki_Page_Ref'Class);
-- Delete the wiki page as well as all its versions.
procedure Delete (Model : in Wiki_Module;
Page : in out AWA.Wikis.Models.Wiki_Page_Ref'Class);
-- Load the wiki page and its content.
procedure Load_Page (Model : in Wiki_Module;
Page : in out AWA.Wikis.Models.Wiki_Page_Ref'Class;
Content : in out AWA.Wikis.Models.Wiki_Content_Ref'Class;
Tags : in out AWA.Tags.Beans.Tag_List_Bean;
Id : in ADO.Identifier);
-- Load the wiki page and its content from the wiki space Id and the page name.
procedure Load_Page (Model : in Wiki_Module;
Page : in out AWA.Wikis.Models.Wiki_Page_Ref'Class;
Content : in out AWA.Wikis.Models.Wiki_Content_Ref'Class;
Tags : in out AWA.Tags.Beans.Tag_List_Bean;
Wiki : in ADO.Identifier;
Name : in String);
-- Create a new wiki content for the wiki page.
procedure Create_Wiki_Content (Model : in Wiki_Module;
Page : in out AWA.Wikis.Models.Wiki_Page_Ref'Class;
Content : in out AWA.Wikis.Models.Wiki_Content_Ref'Class);
-- Save a new wiki content for the wiki page.
procedure Save_Wiki_Content (Model : in Wiki_Module;
Page : in out AWA.Wikis.Models.Wiki_Page_Ref'Class;
Content : in out AWA.Wikis.Models.Wiki_Content_Ref'Class);
private
-- Copy the wiki page with its last version to the wiki space.
procedure Copy_Page (Module : in Wiki_Module;
DB : in out ADO.Sessions.Master_Session;
Wiki : in AWA.Wikis.Models.Wiki_Space_Ref'Class;
Page_Id : in ADO.Identifier);
-- Copy the wiki page with its last version to the wiki space.
procedure Copy_Page (Module : in Wiki_Module;
DB : in out ADO.Sessions.Master_Session;
Wiki : in AWA.Wikis.Models.Wiki_Space_Ref'Class;
Page : in AWA.Wikis.Models.Wiki_Page_Ref'Class);
-- Save a new wiki content for the wiki page.
procedure Save_Wiki_Content (Model : in Wiki_Module;
DB : in out ADO.Sessions.Master_Session;
Page : in out AWA.Wikis.Models.Wiki_Page_Ref'Class;
Content : in out AWA.Wikis.Models.Wiki_Content_Ref'Class);
type Wiki_Module is new AWA.Modules.Module with record
Image_Prefix : Ada.Strings.Unbounded.Unbounded_String;
end record;
end AWA.Wikis.Modules;
|
-----------------------------------------------------------------------
-- awa-wikis-modules -- Module wikis
-- Copyright (C) 2015, 2016 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with ASF.Applications;
with ADO;
with ADO.Sessions;
with AWA.Events;
with AWA.Modules;
with AWA.Modules.Lifecycles;
with AWA.Wikis.Models;
with AWA.Tags.Beans;
with AWA.Counters.Definition;
with Security.Permissions;
with Wiki.Strings;
-- == Events ==
-- The <tt>wikis</tt> exposes a number of events which are posted when some action
-- are performed at the service level.
--
-- === wiki-create-page ===
-- This event is posted when a new wiki page is created.
--
-- === wiki-create-content ===
-- This event is posted when a new wiki page content is created. Each time a wiki page is
-- modified, a new wiki page content is created and this event is posted.
--
package AWA.Wikis.Modules is
-- The name under which the module is registered.
NAME : constant String := "wikis";
-- The configuration parameter that defines the image link prefix in rendered HTML content.
PARAM_IMAGE_PREFIX : constant String := "image_prefix";
package ACL_Create_Wiki_Pages is new Security.Permissions.Definition ("wiki-page-create");
package ACL_Delete_Wiki_Pages is new Security.Permissions.Definition ("wiki-page-delete");
package ACL_Update_Wiki_Pages is new Security.Permissions.Definition ("wiki-page-update");
package ACL_View_Wiki_Page is new Security.Permissions.Definition ("wiki-page-view");
-- Define the permissions.
package ACL_Create_Wiki_Space is new Security.Permissions.Definition ("wiki-space-create");
package ACL_Delete_Wiki_Space is new Security.Permissions.Definition ("wiki-space-delete");
package ACL_Update_Wiki_Space is new Security.Permissions.Definition ("wiki-space-update");
-- Event posted when a new wiki page is created.
package Create_Page_Event is new AWA.Events.Definition (Name => "wiki-create-page");
-- Event posted when a new wiki content is created.
package Create_Content_Event is new AWA.Events.Definition (Name => "wiki-create-content");
-- Define the read wiki page counter.
package Read_Counter is new AWA.Counters.Definition (Models.WIKI_PAGE_TABLE, "read_count");
package Wiki_Lifecycle is
new AWA.Modules.Lifecycles (Element_Type => AWA.Wikis.Models.Wiki_Page_Ref'Class);
subtype Listener is Wiki_Lifecycle.Listener;
-- The configuration parameter that defines a list of wiki page ID to copy when a new
-- wiki space is created.
PARAM_WIKI_COPY_LIST : constant String := "wiki_copy_list";
-- Exception raised when a wiki page name is already used for the wiki space.
Name_Used : exception;
-- ------------------------------
-- Module wikis
-- ------------------------------
type Wiki_Module is new AWA.Modules.Module with private;
type Wiki_Module_Access is access all Wiki_Module'Class;
-- Initialize the wikis module.
overriding
procedure Initialize (Plugin : in out Wiki_Module;
App : in AWA.Modules.Application_Access;
Props : in ASF.Applications.Config);
-- Configures the module after its initialization and after having read its XML configuration.
overriding
procedure Configure (Plugin : in out Wiki_Module;
Props : in ASF.Applications.Config);
-- Get the image prefix that was configured for the Wiki module.
function Get_Image_Prefix (Module : in Wiki_Module)
return Wiki.Strings.UString;
-- Get the wikis module.
function Get_Wiki_Module return Wiki_Module_Access;
-- Create the wiki space.
procedure Create_Wiki_Space (Module : in Wiki_Module;
Wiki : in out AWA.Wikis.Models.Wiki_Space_Ref'Class);
-- Save the wiki space.
procedure Save_Wiki_Space (Module : in Wiki_Module;
Wiki : in out AWA.Wikis.Models.Wiki_Space_Ref'Class);
-- 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);
-- Create the wiki page into the wiki space.
procedure Create_Wiki_Page (Model : in Wiki_Module;
Into : in AWA.Wikis.Models.Wiki_Space_Ref'Class;
Page : in out AWA.Wikis.Models.Wiki_Page_Ref'Class;
Content : in out AWA.Wikis.Models.Wiki_Content_Ref'Class);
-- Save the wiki page.
procedure Save (Model : in Wiki_Module;
Page : in out AWA.Wikis.Models.Wiki_Page_Ref'Class);
-- Delete the wiki page as well as all its versions.
procedure Delete (Model : in Wiki_Module;
Page : in out AWA.Wikis.Models.Wiki_Page_Ref'Class);
-- Load the wiki page and its content.
procedure Load_Page (Model : in Wiki_Module;
Page : in out AWA.Wikis.Models.Wiki_Page_Ref'Class;
Content : in out AWA.Wikis.Models.Wiki_Content_Ref'Class;
Tags : in out AWA.Tags.Beans.Tag_List_Bean;
Id : in ADO.Identifier);
-- Load the wiki page and its content from the wiki space Id and the page name.
procedure Load_Page (Model : in Wiki_Module;
Page : in out AWA.Wikis.Models.Wiki_Page_Ref'Class;
Content : in out AWA.Wikis.Models.Wiki_Content_Ref'Class;
Tags : in out AWA.Tags.Beans.Tag_List_Bean;
Wiki : in ADO.Identifier;
Name : in String);
-- Create a new wiki content for the wiki page.
procedure Create_Wiki_Content (Model : in Wiki_Module;
Page : in out AWA.Wikis.Models.Wiki_Page_Ref'Class;
Content : in out AWA.Wikis.Models.Wiki_Content_Ref'Class);
-- Save a new wiki content for the wiki page.
procedure Save_Wiki_Content (Model : in Wiki_Module;
Page : in out AWA.Wikis.Models.Wiki_Page_Ref'Class;
Content : in out AWA.Wikis.Models.Wiki_Content_Ref'Class);
private
-- Copy the wiki page with its last version to the wiki space.
procedure Copy_Page (Module : in Wiki_Module;
DB : in out ADO.Sessions.Master_Session;
Wiki : in AWA.Wikis.Models.Wiki_Space_Ref'Class;
Page_Id : in ADO.Identifier);
-- Copy the wiki page with its last version to the wiki space.
procedure Copy_Page (Module : in Wiki_Module;
DB : in out ADO.Sessions.Master_Session;
Wiki : in AWA.Wikis.Models.Wiki_Space_Ref'Class;
Page : in AWA.Wikis.Models.Wiki_Page_Ref'Class);
-- Save a new wiki content for the wiki page.
procedure Save_Wiki_Content (Model : in Wiki_Module;
DB : in out ADO.Sessions.Master_Session;
Page : in out AWA.Wikis.Models.Wiki_Page_Ref'Class;
Content : in out AWA.Wikis.Models.Wiki_Content_Ref'Class);
type Wiki_Module is new AWA.Modules.Module with record
Image_Prefix : Wiki.Strings.UString;
end record;
end AWA.Wikis.Modules;
|
Use the Wiki.Strings.UString type for the image prefix
|
Use the Wiki.Strings.UString type for the image prefix
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
82d370b52b4d337d68d6634be9f58d3072fdaa76
|
src/security-oauth-clients.adb
|
src/security-oauth-clients.adb
|
-----------------------------------------------------------------------
-- security-oauth-clients -- OAuth Client Security
-- Copyright (C) 2012, 2013, 2017, 2018 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Exceptions;
with Util.Log.Loggers;
with Util.Strings;
with Util.Http.Clients;
with Util.Properties.JSON;
with Util.Encoders.HMAC.SHA1;
with Security.Random;
package body Security.OAuth.Clients is
use Ada.Strings.Unbounded;
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Security.OAuth.Clients");
-- ------------------------------
-- Access Token
-- ------------------------------
Random_Generator : Security.Random.Generator;
-- ------------------------------
-- Generate a random nonce with at last the number of random bits.
-- The number of bits is rounded up to a multiple of 32.
-- The random bits are then converted to base64url in the returned string.
-- ------------------------------
function Create_Nonce (Bits : in Positive := 256) return String is
begin
-- Generate the random sequence.
return Random_Generator.Generate (Bits);
end Create_Nonce;
-- ------------------------------
-- Get the principal name. This is the OAuth access token.
-- ------------------------------
function Get_Name (From : in Access_Token) return String is
begin
return From.Access_Id;
end Get_Name;
-- ------------------------------
-- Get the id_token that was returned by the authentication process.
-- ------------------------------
function Get_Id_Token (From : in OpenID_Token) return String is
begin
return From.Id_Token;
end Get_Id_Token;
-- ------------------------------
-- Get the principal name. This is the OAuth access token.
-- ------------------------------
function Get_Name (From : in Grant_Type) return String is
begin
return To_String (From.Access_Token);
end Get_Name;
-- ------------------------------
-- Get the Authorization header to be used for accessing a protected resource.
-- (See RFC 6749 7. Accessing Protected Resources)
-- ------------------------------
function Get_Authorization (From : in Grant_Type) return String is
begin
return "Bearer " & To_String (From.Access_Token);
end Get_Authorization;
-- ------------------------------
-- Set the OAuth authorization server URI that the application must use
-- to exchange the OAuth code into an access token.
-- ------------------------------
procedure Set_Provider_URI (App : in out Application;
URI : in String) is
begin
App.Request_URI := Ada.Strings.Unbounded.To_Unbounded_String (URI);
end Set_Provider_URI;
-- ------------------------------
-- Build a unique opaque value used to prevent cross-site request forgery.
-- The <b>Nonce</b> parameters is an optional but recommended unique value
-- used only once. The state value will be returned back by the OAuth provider.
-- This protects the <tt>client_id</tt> and <tt>redirect_uri</tt> parameters.
-- ------------------------------
function Get_State (App : in Application;
Nonce : in String) return String is
use Ada.Strings.Unbounded;
Data : constant String := Nonce & To_String (App.Client_Id) & To_String (App.Callback);
Hmac : String := Util.Encoders.HMAC.SHA1.Sign_Base64 (Key => To_String (App.Secret),
Data => Data,
URL => True);
begin
-- Avoid the '=' at end of HMAC since it could be replaced by %C20 which is annoying...
Hmac (Hmac'Last) := '.';
return Hmac;
end Get_State;
-- ------------------------------
-- Get the authenticate parameters to build the URI to redirect the user to
-- the OAuth authorization form.
-- ------------------------------
function Get_Auth_Params (App : in Application;
State : in String;
Scope : in String := "") return String is
begin
return Security.OAuth.CLIENT_ID
& "=" & Ada.Strings.Unbounded.To_String (App.Client_Id)
& "&"
& Security.OAuth.REDIRECT_URI
& "=" & Ada.Strings.Unbounded.To_String (App.Callback)
& "&"
& Security.OAuth.SCOPE
& "=" & Scope
& "&"
& Security.OAuth.STATE
& "=" & State;
end Get_Auth_Params;
-- ------------------------------
-- Verify that the <b>State</b> opaque value was created by the <b>Get_State</b>
-- operation with the given client and redirect URL.
-- ------------------------------
function Is_Valid_State (App : in Application;
Nonce : in String;
State : in String) return Boolean is
Hmac : constant String := Application'Class (App).Get_State (Nonce);
begin
return Hmac = State;
end Is_Valid_State;
-- ------------------------------
-- Exchange the OAuth code into an access token.
-- ------------------------------
function Request_Access_Token (App : in Application;
Code : in String) return Access_Token_Access is
Client : Util.Http.Clients.Client;
Response : Util.Http.Clients.Response;
Data : constant String
:= Security.OAuth.GRANT_TYPE & "=authorization_code"
& "&"
& Security.OAuth.CODE & "=" & Code
& "&"
& Security.OAuth.REDIRECT_URI & "=" & Ada.Strings.Unbounded.To_String (App.Callback)
& "&"
& Security.OAuth.CLIENT_ID & "=" & Ada.Strings.Unbounded.To_String (App.Client_Id)
& "&"
& Security.OAuth.CLIENT_SECRET & "=" & Ada.Strings.Unbounded.To_String (App.Secret);
URI : constant String := Ada.Strings.Unbounded.To_String (App.Request_URI);
begin
Log.Info ("Getting access token from {0}", URI);
begin
Client.Post (URL => URI,
Data => Data,
Reply => Response);
if Response.Get_Status /= Util.Http.SC_OK then
Log.Warn ("Cannot get access token from {0}: status is {1} Body {2}",
URI, Natural'Image (Response.Get_Status), Response.Get_Body);
return null;
end if;
exception
-- Handle a Program_Error exception that could be raised by AWS when SSL
-- is not supported. Emit a log error so that we can trouble this kins of
-- problem more easily.
when E : Program_Error =>
Log.Error ("Cannot get access token from {0}: program error: {1}",
URI, Ada.Exceptions.Exception_Message (E));
raise;
end;
-- Decode the response.
declare
Content : constant String := Response.Get_Body;
Content_Type : constant String := Response.Get_Header ("Content-Type");
Pos : Natural := Util.Strings.Index (Content_Type, ';');
Last : Natural;
Expires : Natural;
begin
if Pos = 0 then
Pos := Content_Type'Last;
else
Pos := Pos - 1;
end if;
Log.Debug ("Content type: {0}", Content_Type);
Log.Debug ("Data: {0}", Content);
-- Facebook sends the access token as a 'text/plain' content.
if Content_Type (Content_Type'First .. Pos) = "text/plain" then
Pos := Util.Strings.Index (Content, '=');
if Pos = 0 then
Log.Error ("Invalid access token response: '{0}'", Content);
return null;
end if;
if Content (Content'First .. Pos) /= "access_token=" then
Log.Error ("The 'access_token' parameter is missing in response: '{0}'", Content);
return null;
end if;
Last := Util.Strings.Index (Content, '&', Pos + 1);
if Last = 0 then
Log.Error ("Invalid 'access_token' parameter: '{0}'", Content);
return null;
end if;
if Content (Last .. Last + 8) /= "&expires=" then
Log.Error ("Invalid 'expires' parameter: '{0}'", Content);
return null;
end if;
Expires := Natural'Value (Content (Last + 9 .. Content'Last));
return Application'Class (App).Create_Access_Token (Content (Pos + 1 .. Last - 1),
"", "",
Expires);
elsif Content_Type (Content_Type'First .. Pos) = "application/json" then
declare
P : Util.Properties.Manager;
begin
Util.Properties.JSON.Parse_JSON (P, Content);
Expires := Natural'Value (P.Get ("expires_in"));
return Application'Class (App).Create_Access_Token (P.Get ("access_token"),
P.Get ("refresh_token", ""),
P.Get ("id_token", ""),
Expires);
end;
else
Log.Error ("Content type {0} not supported for access token response", Content_Type);
Log.Error ("Response: {0}", Content);
return null;
end if;
end;
end Request_Access_Token;
-- ------------------------------
-- Exchange the OAuth code into an access token.
-- ------------------------------
procedure Do_Request_Token (App : in Application;
URI : in String;
Data : in String;
Cred : in out Grant_Type'Class) is
Client : Util.Http.Clients.Client;
Response : Util.Http.Clients.Response;
begin
Log.Info ("Getting access token from {0}", URI);
Client.Post (URL => URI,
Data => Data,
Reply => Response);
if Response.Get_Status /= Util.Http.SC_OK then
Log.Warn ("Cannot get access token from {0}: status is {1} Body {2}",
URI, Natural'Image (Response.Get_Status), Response.Get_Body);
return;
end if;
-- Decode the response.
declare
Content : constant String := Response.Get_Body;
Content_Type : constant String := Response.Get_Header ("Content-Type");
Pos : Natural := Util.Strings.Index (Content_Type, ';');
Last : Natural;
Expires : Natural;
begin
if Pos = 0 then
Pos := Content_Type'Last;
else
Pos := Pos - 1;
end if;
Log.Debug ("Content type: {0}", Content_Type);
Log.Debug ("Data: {0}", Content);
-- Facebook sends the access token as a 'text/plain' content.
if Content_Type (Content_Type'First .. Pos) = "text/plain" then
Pos := Util.Strings.Index (Content, '=');
if Pos = 0 then
Log.Error ("Invalid access token response: '{0}'", Content);
return;
end if;
if Content (Content'First .. Pos) /= "access_token=" then
Log.Error ("The 'access_token' parameter is missing in response: '{0}'", Content);
return;
end if;
Last := Util.Strings.Index (Content, '&', Pos + 1);
if Last = 0 then
Log.Error ("Invalid 'access_token' parameter: '{0}'", Content);
return;
end if;
if Content (Last .. Last + 8) /= "&expires=" then
Log.Error ("Invalid 'expires' parameter: '{0}'", Content);
return;
end if;
Expires := Natural'Value (Content (Last + 9 .. Content'Last));
Cred.Access_Token := To_Unbounded_String (Content (Pos + 1 .. Last - 1));
elsif Content_Type (Content_Type'First .. Pos) = "application/json" then
declare
P : Util.Properties.Manager;
begin
Util.Properties.JSON.Parse_JSON (P, Content);
Expires := Natural'Value (P.Get ("expires_in"));
Cred.Access_Token := P.Get ("access_token");
Cred.Refresh_Token := To_Unbounded_String (P.Get ("refresh_token", ""));
Cred.Id_Token := To_Unbounded_String (P.Get ("id_token", ""));
end;
else
Log.Error ("Content type {0} not supported for access token response", Content_Type);
Log.Error ("Response: {0}", Content);
return;
end if;
end;
exception
-- Handle a Program_Error exception that could be raised by AWS when SSL
-- is not supported. Emit a log error so that we can trouble this kins of
-- problem more easily.
when E : Program_Error =>
Log.Error ("Cannot get access token from {0}: program error: {1}",
URI, Ada.Exceptions.Exception_Message (E));
raise;
end Do_Request_Token;
-- ------------------------------
-- Get a request token with username and password.
-- RFC 6749: 4.3. Resource Owner Password Credentials Grant
-- ------------------------------
procedure Request_Token (App : in Application;
Username : in String;
Password : in String;
Scope : in String;
Token : in out Grant_Type'Class) is
Client : Util.Http.Clients.Client;
Data : constant String
:= Security.OAuth.GRANT_TYPE & "=password"
& "&"
& Security.OAuth.USERNAME & "=" & Username
& "&"
& Security.OAuth.PASSWORD & "=" & Password
& "&"
& Security.OAuth.CLIENT_ID & "=" & Ada.Strings.Unbounded.To_String (App.Client_Id)
& "&"
& Security.OAuth.SCOPE & "=" & Scope
& "&"
& Security.OAuth.CLIENT_SECRET & "=" & Ada.Strings.Unbounded.To_String (App.Secret);
URI : constant String := Ada.Strings.Unbounded.To_String (App.Request_URI);
begin
Log.Info ("Getting access token from {0} - resource owner password", URI);
Do_Request_Token (App, URI, Data, Token);
end Request_Token;
-- ------------------------------
-- Create the access token
-- ------------------------------
function Create_Access_Token (App : in Application;
Token : in String;
Refresh : in String;
Id_Token : in String;
Expires : in Natural) return Access_Token_Access is
pragma Unreferenced (App, Expires);
begin
if Id_Token'Length > 0 then
declare
Result : constant OpenID_Token_Access
:= new OpenID_Token '(Len => Token'Length,
Id_Len => Id_Token'Length,
Refresh_Len => Refresh'Length,
Access_Id => Token,
Id_Token => Id_Token,
Refresh_Token => Refresh);
begin
return Result.all'Access;
end;
else
return new Access_Token '(Len => Token'Length,
Access_Id => Token);
end if;
end Create_Access_Token;
end Security.OAuth.Clients;
|
-----------------------------------------------------------------------
-- security-oauth-clients -- OAuth Client Security
-- Copyright (C) 2012, 2013, 2017, 2018 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Exceptions;
with Util.Log.Loggers;
with Util.Strings;
with Util.Http.Clients;
with Util.Properties.JSON;
with Util.Encoders.HMAC.SHA1;
with Security.Random;
package body Security.OAuth.Clients is
use Ada.Strings.Unbounded;
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Security.OAuth.Clients");
-- ------------------------------
-- Access Token
-- ------------------------------
Random_Generator : Security.Random.Generator;
-- ------------------------------
-- Generate a random nonce with at last the number of random bits.
-- The number of bits is rounded up to a multiple of 32.
-- The random bits are then converted to base64url in the returned string.
-- ------------------------------
function Create_Nonce (Bits : in Positive := 256) return String is
begin
-- Generate the random sequence.
return Random_Generator.Generate (Bits);
end Create_Nonce;
-- ------------------------------
-- Get the principal name. This is the OAuth access token.
-- ------------------------------
function Get_Name (From : in Access_Token) return String is
begin
return From.Access_Id;
end Get_Name;
-- ------------------------------
-- Get the id_token that was returned by the authentication process.
-- ------------------------------
function Get_Id_Token (From : in OpenID_Token) return String is
begin
return From.Id_Token;
end Get_Id_Token;
-- ------------------------------
-- Get the principal name. This is the OAuth access token.
-- ------------------------------
function Get_Name (From : in Grant_Type) return String is
begin
return To_String (From.Access_Token);
end Get_Name;
-- ------------------------------
-- Get the Authorization header to be used for accessing a protected resource.
-- (See RFC 6749 7. Accessing Protected Resources)
-- ------------------------------
function Get_Authorization (From : in Grant_Type) return String is
begin
return "Bearer " & To_String (From.Access_Token);
end Get_Authorization;
-- ------------------------------
-- Set the OAuth authorization server URI that the application must use
-- to exchange the OAuth code into an access token.
-- ------------------------------
procedure Set_Provider_URI (App : in out Application;
URI : in String) is
begin
App.Request_URI := Ada.Strings.Unbounded.To_Unbounded_String (URI);
end Set_Provider_URI;
-- ------------------------------
-- Build a unique opaque value used to prevent cross-site request forgery.
-- The <b>Nonce</b> parameters is an optional but recommended unique value
-- used only once. The state value will be returned back by the OAuth provider.
-- This protects the <tt>client_id</tt> and <tt>redirect_uri</tt> parameters.
-- ------------------------------
function Get_State (App : in Application;
Nonce : in String) return String is
use Ada.Strings.Unbounded;
Data : constant String := Nonce & To_String (App.Client_Id) & To_String (App.Callback);
Hmac : String := Util.Encoders.HMAC.SHA1.Sign_Base64 (Key => To_String (App.Secret),
Data => Data,
URL => True);
begin
-- Avoid the '=' at end of HMAC since it could be replaced by %C20 which is annoying...
Hmac (Hmac'Last) := '.';
return Hmac;
end Get_State;
-- ------------------------------
-- Get the authenticate parameters to build the URI to redirect the user to
-- the OAuth authorization form.
-- ------------------------------
function Get_Auth_Params (App : in Application;
State : in String;
Scope : in String := "") return String is
begin
return Security.OAuth.CLIENT_ID
& "=" & Ada.Strings.Unbounded.To_String (App.Client_Id)
& "&"
& Security.OAuth.REDIRECT_URI
& "=" & Ada.Strings.Unbounded.To_String (App.Callback)
& "&"
& Security.OAuth.SCOPE
& "=" & Scope
& "&"
& Security.OAuth.STATE
& "=" & State;
end Get_Auth_Params;
-- ------------------------------
-- Verify that the <b>State</b> opaque value was created by the <b>Get_State</b>
-- operation with the given client and redirect URL.
-- ------------------------------
function Is_Valid_State (App : in Application;
Nonce : in String;
State : in String) return Boolean is
Hmac : constant String := Application'Class (App).Get_State (Nonce);
begin
return Hmac = State;
end Is_Valid_State;
-- ------------------------------
-- Exchange the OAuth code into an access token.
-- ------------------------------
function Request_Access_Token (App : in Application;
Code : in String) return Access_Token_Access is
Client : Util.Http.Clients.Client;
Response : Util.Http.Clients.Response;
Data : constant String
:= Security.OAuth.GRANT_TYPE & "=authorization_code"
& "&"
& Security.OAuth.CODE & "=" & Code
& "&"
& Security.OAuth.REDIRECT_URI & "=" & Ada.Strings.Unbounded.To_String (App.Callback)
& "&"
& Security.OAuth.CLIENT_ID & "=" & Ada.Strings.Unbounded.To_String (App.Client_Id)
& "&"
& Security.OAuth.CLIENT_SECRET & "=" & Ada.Strings.Unbounded.To_String (App.Secret);
URI : constant String := Ada.Strings.Unbounded.To_String (App.Request_URI);
begin
Log.Info ("Getting access token from {0}", URI);
begin
Client.Post (URL => URI,
Data => Data,
Reply => Response);
if Response.Get_Status /= Util.Http.SC_OK then
Log.Warn ("Cannot get access token from {0}: status is {1} Body {2}",
URI, Natural'Image (Response.Get_Status), Response.Get_Body);
return null;
end if;
exception
-- Handle a Program_Error exception that could be raised by AWS when SSL
-- is not supported. Emit a log error so that we can trouble this kins of
-- problem more easily.
when E : Program_Error =>
Log.Error ("Cannot get access token from {0}: program error: {1}",
URI, Ada.Exceptions.Exception_Message (E));
raise;
end;
-- Decode the response.
declare
Content : constant String := Response.Get_Body;
Content_Type : constant String := Response.Get_Header ("Content-Type");
Pos : Natural := Util.Strings.Index (Content_Type, ';');
Last : Natural;
Expires : Natural;
begin
if Pos = 0 then
Pos := Content_Type'Last;
else
Pos := Pos - 1;
end if;
Log.Debug ("Content type: {0}", Content_Type);
Log.Debug ("Data: {0}", Content);
-- Facebook sends the access token as a 'text/plain' content.
if Content_Type (Content_Type'First .. Pos) = "text/plain" then
Pos := Util.Strings.Index (Content, '=');
if Pos = 0 then
Log.Error ("Invalid access token response: '{0}'", Content);
return null;
end if;
if Content (Content'First .. Pos) /= "access_token=" then
Log.Error ("The 'access_token' parameter is missing in response: '{0}'", Content);
return null;
end if;
Last := Util.Strings.Index (Content, '&', Pos + 1);
if Last = 0 then
Log.Error ("Invalid 'access_token' parameter: '{0}'", Content);
return null;
end if;
if Content (Last .. Last + 8) /= "&expires=" then
Log.Error ("Invalid 'expires' parameter: '{0}'", Content);
return null;
end if;
Expires := Natural'Value (Content (Last + 9 .. Content'Last));
return Application'Class (App).Create_Access_Token (Content (Pos + 1 .. Last - 1),
"", "",
Expires);
elsif Content_Type (Content_Type'First .. Pos) = "application/json" then
declare
P : Util.Properties.Manager;
begin
Util.Properties.JSON.Parse_JSON (P, Content);
Expires := Natural'Value (P.Get ("expires_in"));
return Application'Class (App).Create_Access_Token (P.Get ("access_token"),
P.Get ("refresh_token", ""),
P.Get ("id_token", ""),
Expires);
end;
else
Log.Error ("Content type {0} not supported for access token response", Content_Type);
Log.Error ("Response: {0}", Content);
return null;
end if;
end;
end Request_Access_Token;
-- ------------------------------
-- Exchange the OAuth code into an access token.
-- ------------------------------
procedure Do_Request_Token (App : in Application;
URI : in String;
Data : in String;
Cred : in out Grant_Type'Class) is
Client : Util.Http.Clients.Client;
Response : Util.Http.Clients.Response;
begin
Log.Info ("Getting access token from {0}", URI);
Client.Post (URL => URI,
Data => Data,
Reply => Response);
if Response.Get_Status /= Util.Http.SC_OK then
Log.Warn ("Cannot get access token from {0}: status is {1} Body {2}",
URI, Natural'Image (Response.Get_Status), Response.Get_Body);
return;
end if;
-- Decode the response.
declare
Content : constant String := Response.Get_Body;
Content_Type : constant String := Response.Get_Header ("Content-Type");
Pos : Natural := Util.Strings.Index (Content_Type, ';');
Last : Natural;
Expires : Natural;
begin
if Pos = 0 then
Pos := Content_Type'Last;
else
Pos := Pos - 1;
end if;
Log.Debug ("Content type: {0}", Content_Type);
Log.Debug ("Data: {0}", Content);
-- Facebook sends the access token as a 'text/plain' content.
if Content_Type (Content_Type'First .. Pos) = "text/plain" then
Pos := Util.Strings.Index (Content, '=');
if Pos = 0 then
Log.Error ("Invalid access token response: '{0}'", Content);
return;
end if;
if Content (Content'First .. Pos) /= "access_token=" then
Log.Error ("The 'access_token' parameter is missing in response: '{0}'", Content);
return;
end if;
Last := Util.Strings.Index (Content, '&', Pos + 1);
if Last = 0 then
Log.Error ("Invalid 'access_token' parameter: '{0}'", Content);
return;
end if;
if Content (Last .. Last + 8) /= "&expires=" then
Log.Error ("Invalid 'expires' parameter: '{0}'", Content);
return;
end if;
Expires := Natural'Value (Content (Last + 9 .. Content'Last));
Cred.Access_Token := To_Unbounded_String (Content (Pos + 1 .. Last - 1));
elsif Content_Type (Content_Type'First .. Pos) = "application/json" then
declare
P : Util.Properties.Manager;
begin
Util.Properties.JSON.Parse_JSON (P, Content);
Expires := Natural'Value (P.Get ("expires_in"));
Cred.Access_Token := P.Get ("access_token");
Cred.Refresh_Token := To_Unbounded_String (P.Get ("refresh_token", ""));
Cred.Id_Token := To_Unbounded_String (P.Get ("id_token", ""));
end;
else
Log.Error ("Content type {0} not supported for access token response", Content_Type);
Log.Error ("Response: {0}", Content);
return;
end if;
end;
exception
-- Handle a Program_Error exception that could be raised by AWS when SSL
-- is not supported. Emit a log error so that we can trouble this kins of
-- problem more easily.
when E : Program_Error =>
Log.Error ("Cannot get access token from {0}: program error: {1}",
URI, Ada.Exceptions.Exception_Message (E));
raise;
end Do_Request_Token;
-- ------------------------------
-- Get a request token with username and password.
-- RFC 6749: 4.3. Resource Owner Password Credentials Grant
-- ------------------------------
procedure Request_Token (App : in Application;
Username : in String;
Password : in String;
Scope : in String;
Token : in out Grant_Type'Class) is
Client : Util.Http.Clients.Client;
Data : constant String
:= Security.OAuth.GRANT_TYPE & "=password"
& "&"
& Security.OAuth.USERNAME & "=" & Username
& "&"
& Security.OAuth.PASSWORD & "=" & Password
& "&"
& Security.OAuth.CLIENT_ID & "=" & Ada.Strings.Unbounded.To_String (App.Client_Id)
& "&"
& Security.OAuth.SCOPE & "=" & Scope
& "&"
& Security.OAuth.CLIENT_SECRET & "=" & Ada.Strings.Unbounded.To_String (App.Secret);
URI : constant String := Ada.Strings.Unbounded.To_String (App.Request_URI);
begin
Log.Info ("Getting access token from {0} - resource owner password", URI);
Do_Request_Token (App, URI, Data, Token);
end Request_Token;
-- ------------------------------
-- Refresh the access token.
-- RFC 6749: 6. Refreshing an Access Token
-- ------------------------------
procedure Refresh_Token (App : in Application;
Scope : in String;
Token : in out Grant_Type'Class) is
Client : Util.Http.Clients.Client;
Data : constant String
:= Security.OAuth.GRANT_TYPE & "=refresh_token"
& "&"
& Security.OAuth.REFRESH_TOKEN & "=" & To_String (Token.Refresh_Token)
& "&"
& Security.OAuth.CLIENT_ID & "=" & Ada.Strings.Unbounded.To_String (App.Client_Id)
& "&"
& Security.OAuth.SCOPE & "=" & Scope
& "&"
& Security.OAuth.CLIENT_SECRET & "=" & Ada.Strings.Unbounded.To_String (App.Secret);
URI : constant String := Ada.Strings.Unbounded.To_String (App.Request_URI);
begin
Log.Info ("Refresh access token from {0}", URI);
Do_Request_Token (App, URI, Data, Token);
end Refresh_Token;
-- ------------------------------
-- Create the access token
-- ------------------------------
function Create_Access_Token (App : in Application;
Token : in String;
Refresh : in String;
Id_Token : in String;
Expires : in Natural) return Access_Token_Access is
pragma Unreferenced (App, Expires);
begin
if Id_Token'Length > 0 then
declare
Result : constant OpenID_Token_Access
:= new OpenID_Token '(Len => Token'Length,
Id_Len => Id_Token'Length,
Refresh_Len => Refresh'Length,
Access_Id => Token,
Id_Token => Id_Token,
Refresh_Token => Refresh);
begin
return Result.all'Access;
end;
else
return new Access_Token '(Len => Token'Length,
Access_Id => Token);
end if;
end Create_Access_Token;
end Security.OAuth.Clients;
|
Implement the Refresh_Token procedure
|
Implement the Refresh_Token procedure
|
Ada
|
apache-2.0
|
stcarrez/ada-security
|
ebfc27458ab7abaea92cecfc5a88722a0be6cfcc
|
src/http/util-http-clients.ads
|
src/http/util-http-clients.ads
|
-----------------------------------------------------------------------
-- util-http-clients -- HTTP Clients
-- Copyright (C) 2011, 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Finalization;
with Util.Http.Cookies;
-- == Client ==
-- The <tt>Util.Http.Clients</tt> package defines a set of API for an HTTP client to send
-- requests to an HTTP server.
--
-- === GET request ===
-- To retrieve a content using the HTTP GET operation, a client instance must be created.
-- The response is returned in a specific object that must therefore be declared:
--
-- Http : Util.Http.Clients.Client;
-- Response : Util.Http.Clients.Response;
--
-- Before invoking the GET operation, the client can setup a number of HTTP headers.
--
-- Http.Add_Header ("X-Requested-By", "wget");
--
-- The GET operation is performed when the <tt>Get</tt> procedure is called:
--
-- Http.Get ("http://www.google.com", Response);
--
-- Once the response is received, the <tt>Response</tt> object contains the status of the
-- HTTP response, the HTTP reply headers and the body. A response header can be obtained
-- by using the <tt>Get_Header</tt> function and the body using <tt>Get_Body</tt>:
--
-- Body : constant String := Response.Get_Body;
--
package Util.Http.Clients is
Connection_Error : exception;
-- ------------------------------
-- Http response
-- ------------------------------
-- The <b>Response</b> type represents a response returned by an HTTP request.
type Response is limited new Abstract_Response with private;
-- Returns a boolean indicating whether the named response header has already
-- been set.
overriding
function Contains_Header (Reply : in Response;
Name : in String) return Boolean;
-- Returns the value of the specified response header as a String. If the response
-- did not include a header of the specified name, this method returns null.
-- If there are multiple headers with the same name, this method returns the
-- first head in the request. The header name is case insensitive. You can use
-- this method with any response header.
overriding
function Get_Header (Reply : in Response;
Name : in String) return String;
-- Sets a message header with the given name and value. If the header had already
-- been set, the new value overwrites the previous one. The containsHeader
-- method can be used to test for the presence of a header before setting its value.
overriding
procedure Set_Header (Reply : in out Response;
Name : in String;
Value : in String);
-- Adds a request header with the given name and value.
-- This method allows request headers to have multiple values.
overriding
procedure Add_Header (Reply : in out Response;
Name : in String;
Value : in String);
-- Iterate over the response headers and executes the <b>Process</b> procedure.
overriding
procedure Iterate_Headers (Reply : in Response;
Process : not null access
procedure (Name : in String;
Value : in String));
-- Get the response body as a string.
overriding
function Get_Body (Reply : in Response) return String;
-- Get the response status code.
overriding
function Get_Status (Reply : in Response) return Natural;
-- ------------------------------
-- Http client
-- ------------------------------
-- The <b>Client</b> type allows to execute HTTP GET/POST requests.
type Client is limited new Abstract_Request with private;
type Client_Access is access all Client;
-- Returns a boolean indicating whether the named response header has already
-- been set.
overriding
function Contains_Header (Request : in Client;
Name : in String) return Boolean;
-- Returns the value of the specified request header as a String. If the request
-- did not include a header of the specified name, this method returns null.
-- If there are multiple headers with the same name, this method returns the
-- first head in the request. The header name is case insensitive. You can use
-- this method with any response header.
overriding
function Get_Header (Request : in Client;
Name : in String) return String;
-- Sets a header with the given name and value. If the header had already
-- been set, the new value overwrites the previous one. The containsHeader
-- method can be used to test for the presence of a header before setting its value.
overriding
procedure Set_Header (Request : in out Client;
Name : in String;
Value : in String);
-- Adds a header with the given name and value.
-- This method allows headers to have multiple values.
overriding
procedure Add_Header (Request : in out Client;
Name : in String;
Value : in String);
-- Iterate over the request headers and executes the <b>Process</b> procedure.
overriding
procedure Iterate_Headers (Request : in Client;
Process : not null access
procedure (Name : in String;
Value : in String));
-- Removes all headers with the given name.
procedure Remove_Header (Request : in out Client;
Name : in String);
-- Adds the specified cookie to the request. This method can be called multiple
-- times to set more than one cookie.
procedure Add_Cookie (Http : in out Client;
Cookie : in Util.Http.Cookies.Cookie);
-- Execute an http GET request on the given URL. Additional request parameters,
-- cookies and headers should have been set on the client object.
procedure Get (Request : in out Client;
URL : in String;
Reply : out Response'Class);
-- Execute an http POST request on the given URL. The post data is passed in <b>Data</b>.
-- Additional request cookies and headers should have been set on the client object.
procedure Post (Request : in out Client;
URL : in String;
Data : in String;
Reply : out Response'Class);
private
subtype Http_Request is Abstract_Request;
subtype Http_Request_Access is Abstract_Request_Access;
subtype Http_Response is Abstract_Response;
subtype Http_Response_Access is Abstract_Response_Access;
type Http_Manager is interface;
type Http_Manager_Access is access all Http_Manager'Class;
procedure Create (Manager : in Http_Manager;
Http : in out Client'Class) is abstract;
procedure Do_Get (Manager : in Http_Manager;
Http : in Client'Class;
URI : in String;
Reply : out Response'Class) is abstract;
procedure Do_Post (Manager : in Http_Manager;
Http : in Client'Class;
URI : in String;
Data : in String;
Reply : out Response'Class) is abstract;
Default_Http_Manager : Http_Manager_Access;
type Response is new Ada.Finalization.Limited_Controlled and Abstract_Response with record
Delegate : Abstract_Response_Access;
end record;
-- Free the resource used by the response.
overriding
procedure Finalize (Reply : in out Response);
type Client is new Ada.Finalization.Limited_Controlled and Abstract_Request with record
Manager : Http_Manager_Access;
Delegate : Http_Request_Access;
end record;
-- Initialize the client
overriding
procedure Initialize (Http : in out Client);
overriding
procedure Finalize (Http : in out Client);
end Util.Http.Clients;
|
-----------------------------------------------------------------------
-- util-http-clients -- HTTP Clients
-- Copyright (C) 2011, 2012, 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Finalization;
with Util.Http.Cookies;
-- == Client ==
-- The <tt>Util.Http.Clients</tt> package defines a set of API for an HTTP client to send
-- requests to an HTTP server.
--
-- === GET request ===
-- To retrieve a content using the HTTP GET operation, a client instance must be created.
-- The response is returned in a specific object that must therefore be declared:
--
-- Http : Util.Http.Clients.Client;
-- Response : Util.Http.Clients.Response;
--
-- Before invoking the GET operation, the client can setup a number of HTTP headers.
--
-- Http.Add_Header ("X-Requested-By", "wget");
--
-- The GET operation is performed when the <tt>Get</tt> procedure is called:
--
-- Http.Get ("http://www.google.com", Response);
--
-- Once the response is received, the <tt>Response</tt> object contains the status of the
-- HTTP response, the HTTP reply headers and the body. A response header can be obtained
-- by using the <tt>Get_Header</tt> function and the body using <tt>Get_Body</tt>:
--
-- Body : constant String := Response.Get_Body;
--
package Util.Http.Clients is
Connection_Error : exception;
-- ------------------------------
-- Http response
-- ------------------------------
-- The <b>Response</b> type represents a response returned by an HTTP request.
type Response is limited new Abstract_Response with private;
-- Returns a boolean indicating whether the named response header has already
-- been set.
overriding
function Contains_Header (Reply : in Response;
Name : in String) return Boolean;
-- Returns the value of the specified response header as a String. If the response
-- did not include a header of the specified name, this method returns null.
-- If there are multiple headers with the same name, this method returns the
-- first head in the request. The header name is case insensitive. You can use
-- this method with any response header.
overriding
function Get_Header (Reply : in Response;
Name : in String) return String;
-- Sets a message header with the given name and value. If the header had already
-- been set, the new value overwrites the previous one. The containsHeader
-- method can be used to test for the presence of a header before setting its value.
overriding
procedure Set_Header (Reply : in out Response;
Name : in String;
Value : in String);
-- Adds a request header with the given name and value.
-- This method allows request headers to have multiple values.
overriding
procedure Add_Header (Reply : in out Response;
Name : in String;
Value : in String);
-- Iterate over the response headers and executes the <b>Process</b> procedure.
overriding
procedure Iterate_Headers (Reply : in Response;
Process : not null access
procedure (Name : in String;
Value : in String));
-- Get the response body as a string.
overriding
function Get_Body (Reply : in Response) return String;
-- Get the response status code.
overriding
function Get_Status (Reply : in Response) return Natural;
-- ------------------------------
-- Http client
-- ------------------------------
-- The <b>Client</b> type allows to execute HTTP GET/POST requests.
type Client is limited new Abstract_Request with private;
type Client_Access is access all Client;
-- Returns a boolean indicating whether the named response header has already
-- been set.
overriding
function Contains_Header (Request : in Client;
Name : in String) return Boolean;
-- Returns the value of the specified request header as a String. If the request
-- did not include a header of the specified name, this method returns null.
-- If there are multiple headers with the same name, this method returns the
-- first head in the request. The header name is case insensitive. You can use
-- this method with any response header.
overriding
function Get_Header (Request : in Client;
Name : in String) return String;
-- Sets a header with the given name and value. If the header had already
-- been set, the new value overwrites the previous one. The containsHeader
-- method can be used to test for the presence of a header before setting its value.
overriding
procedure Set_Header (Request : in out Client;
Name : in String;
Value : in String);
-- Adds a header with the given name and value.
-- This method allows headers to have multiple values.
overriding
procedure Add_Header (Request : in out Client;
Name : in String;
Value : in String);
-- Iterate over the request headers and executes the <b>Process</b> procedure.
overriding
procedure Iterate_Headers (Request : in Client;
Process : not null access
procedure (Name : in String;
Value : in String));
-- Removes all headers with the given name.
procedure Remove_Header (Request : in out Client;
Name : in String);
-- Adds the specified cookie to the request. This method can be called multiple
-- times to set more than one cookie.
procedure Add_Cookie (Http : in out Client;
Cookie : in Util.Http.Cookies.Cookie);
-- Execute an http GET request on the given URL. Additional request parameters,
-- cookies and headers should have been set on the client object.
procedure Get (Request : in out Client;
URL : in String;
Reply : out Response'Class);
-- Execute an http POST request on the given URL. The post data is passed in <b>Data</b>.
-- Additional request cookies and headers should have been set on the client object.
procedure Post (Request : in out Client;
URL : in String;
Data : in String;
Reply : out Response'Class);
private
subtype Http_Request is Abstract_Request;
subtype Http_Request_Access is Abstract_Request_Access;
subtype Http_Response is Abstract_Response;
subtype Http_Response_Access is Abstract_Response_Access;
type Http_Manager is interface;
type Http_Manager_Access is access all Http_Manager'Class;
procedure Create (Manager : in Http_Manager;
Http : in out Client'Class) is abstract;
procedure Do_Get (Manager : in Http_Manager;
Http : in Client'Class;
URI : in String;
Reply : out Response'Class) is abstract;
procedure Do_Post (Manager : in Http_Manager;
Http : in Client'Class;
URI : in String;
Data : in String;
Reply : out Response'Class) is abstract;
Default_Http_Manager : Http_Manager_Access;
type Response is limited new Ada.Finalization.Limited_Controlled
and Abstract_Response with record
Delegate : Abstract_Response_Access;
end record;
-- Free the resource used by the response.
overriding
procedure Finalize (Reply : in out Response);
type Client is limited new Ada.Finalization.Limited_Controlled
and Abstract_Request with record
Manager : Http_Manager_Access;
Delegate : Http_Request_Access;
end record;
-- Initialize the client
overriding
procedure Initialize (Http : in out Client);
overriding
procedure Finalize (Http : in out Client);
end Util.Http.Clients;
|
Fix compilation error with GNAT 2015
|
Fix compilation error with GNAT 2015
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
03f82521f8926cea37b4dcf619c074194128ca16
|
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, 2015, 2017, 2018 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with ADO.Queries;
with ADO.Utils;
with ADO.Sessions;
with ADO.Sessions.Entities;
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);
elsif Name = "tag" then
return Util.Beans.Objects.To_Object (From.Tag);
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 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
Object : constant Question_List_Bean_Access := new Question_List_Bean;
begin
Object.Service := Module;
Object.Questions_Bean := Object.Questions'Unchecked_Access;
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;
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 (1);
end if;
Query.Clear;
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.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, 2015, 2017, 2018 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with ADO.Queries;
with ADO.Utils;
with ADO.Sessions;
with AWA.Tags.Modules;
with AWA.Services.Contexts;
package body AWA.Questions.Beans is
use type ADO.Identifier;
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
From.Set_Id (ADO.Utils.To_Identifier (Value));
end if;
exception
when Constraint_Error =>
From.Set_Id (ADO.NO_IDENTIFIER);
end Set_Value;
-- ------------------------------
-- Load question.
-- ------------------------------
overriding
procedure Load (Bean : in out Question_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
Ctx : constant ASC.Service_Context_Access := ASC.Current;
DB : constant ADO.Sessions.Session := ASC.Get_Session (Ctx);
Found : Boolean;
begin
Bean.Service.Load_Question (Bean, Bean.Get_Id, Found);
if not Found then
Outcome := Ada.Strings.Unbounded.To_Unbounded_String ("not-found");
else
Outcome := Ada.Strings.Unbounded.To_Unbounded_String ("loaded");
Bean.Tags.Load_Tags (DB, Bean.Id);
end if;
end Load;
-- ------------------------------
-- Create or save the question.
-- ------------------------------
overriding
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.
-- ------------------------------
overriding
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.Set_Id (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.Question.Set_Id (ADO.Utils.To_Identifier (Value));
end if;
exception
when Constraint_Error =>
null;
end Set_Value;
-- ------------------------------
-- Load the answer.
-- ------------------------------
overriding
procedure Load (Bean : in out Answer_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
Found : Boolean;
begin
if not Bean.is_Null and then Bean.Get_Id /= ADO.NO_IDENTIFIER then
Bean.Service.Load_Answer (Bean, Bean.Question, Bean.Get_Id, Found);
elsif not Bean.Question.Is_Null and then Bean.Question.Get_Id /= ADO.NO_IDENTIFIER then
Bean.Service.Load_Question (Bean.Question, Bean.Question_Id, Found);
else
Found := False;
end if;
if not Found then
Outcome := Ada.Strings.Unbounded.To_Unbounded_String ("not-found");
else
Outcome := Ada.Strings.Unbounded.To_Unbounded_String ("loaded");
end if;
end Load;
-- ------------------------------
-- Create or save the answer.
-- ------------------------------
overriding
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.
-- ------------------------------
overriding
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);
elsif Name = "tag" then
return Util.Beans.Objects.To_Object (From.Tag);
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);
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;
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;
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;
-- ------------------------------
-- Load the list of questions.
-- ------------------------------
overriding
procedure Load (Bean : in out Question_List_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
begin
Bean.Load_List;
end Load;
-- ------------------------------
-- 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
Object : constant Question_List_Bean_Access := new Question_List_Bean;
begin
Object.Service := Module;
Object.Questions_Bean := Object.Questions'Unchecked_Access;
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
From.Id := ADO.Utils.To_Identifier (Value);
From.Answer := Get_Answer_Bean ("answer");
From.Answer.Set_Value ("question_id", Value);
end if;
exception
when Constraint_Error =>
null;
end Set_Value;
-- ------------------------------
-- Load the question and its answers.
-- ------------------------------
overriding
procedure Load (Bean : in out Question_Display_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
package ASC renames AWA.Services.Contexts;
use AWA.Questions.Models;
Session : ADO.Sessions.Session := Bean.Service.Get_Session;
Query : ADO.Queries.Context;
List : AWA.Questions.Models.Question_Display_Info_List_Bean;
Ctx : constant ASC.Service_Context_Access := ASC.Current;
begin
Query.Set_Query (AWA.Questions.Models.Query_Question_Info);
Query.Bind_Param ("question_id", Bean.Id);
Query.Bind_Param ("user_id", Ctx.Get_User_Identifier);
AWA.Questions.Models.List (List, Session, Query);
if List.List.Is_Empty then
Outcome := Ada.Strings.Unbounded.To_Unbounded_String ("not-found");
return;
end if;
Bean.Question := List.List.Element (1);
Query.Clear;
Query.Bind_Param ("question_id", Bean.Id);
Query.Bind_Param ("user_id", Ctx.Get_User_Identifier);
Query.Set_Query (AWA.Questions.Models.Query_Answer_List);
AWA.Questions.Models.List (Bean.Answer_List, Session, Query);
-- Load the tags if any.
Bean.Tags.Load_Tags (Session, Bean.Id);
end Load;
-- ------------------------------
-- 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;
|
Refactor the question beans: - Implement the Load bean operations - Avoid loading a list/question/answer by setting the question/answer id
|
Refactor the question beans:
- Implement the Load bean operations
- Avoid loading a list/question/answer by setting the question/answer id
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
0946715d51ddfa90cd1731b9a6fa58a26a4598f5
|
mat/src/mat-types.ads
|
mat/src/mat-types.ads
|
-----------------------------------------------------------------------
-- 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 MAT.Types is
type String_Ptr is access all String;
subtype Uint8 is Interfaces.Unsigned_8;
subtype Uint16 is Interfaces.Unsigned_16;
subtype Uint32 is Interfaces.Unsigned_32;
subtype Uint64 is Interfaces.Unsigned_64;
subtype Target_Addr is Interfaces.Unsigned_32;
subtype Target_Size is Interfaces.Unsigned_32;
subtype Target_Offset is Interfaces.Unsigned_32;
type Target_Tick_Ref is new Uint64;
type Target_Thread_Ref is new Uint32;
subtype Target_Process_Ref is Uint32;
subtype Target_Time is Target_Tick_Ref;
-- Return an hexadecimal string representation of the value.
function Hex_Image (Value : in Uint32;
Length : in Positive := 8) return String;
-- Format the target time to a printable representation.
function Tick_Image (Value : in Target_Tick_Ref) return String;
function "-" (Left, Right : in Target_Tick_Ref) return Target_Tick_Ref;
end MAT.Types;
|
-----------------------------------------------------------------------
-- mat-types -- Global types
-- 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 Interfaces;
package MAT.Types is
type String_Ptr is access all String;
subtype Uint8 is Interfaces.Unsigned_8;
subtype Uint16 is Interfaces.Unsigned_16;
subtype Uint32 is Interfaces.Unsigned_32;
subtype Uint64 is Interfaces.Unsigned_64;
subtype Target_Addr is Interfaces.Unsigned_64;
subtype Target_Size is Interfaces.Unsigned_64;
subtype Target_Offset is Interfaces.Unsigned_64;
type Target_Tick_Ref is new Uint64;
type Target_Thread_Ref is new Uint32;
subtype Target_Process_Ref is Uint32;
subtype Target_Time is Target_Tick_Ref;
-- Return an hexadecimal string representation of the value.
function Hex_Image (Value : in Uint32;
Length : in Positive := 8) return String;
-- Return an hexadecimal string representation of the value.
function Hex_Image (Value : in Uint64;
Length : in Positive := 16) return String;
-- Format the target time to a printable representation.
function Tick_Image (Value : in Target_Tick_Ref) return String;
function "-" (Left, Right : in Target_Tick_Ref) return Target_Tick_Ref;
end MAT.Types;
|
Change the Target_Addr to a 64-bit value Declare an Hex_Image function for 64-bit values
|
Change the Target_Addr to a 64-bit value
Declare an Hex_Image function for 64-bit values
|
Ada
|
apache-2.0
|
stcarrez/mat,stcarrez/mat,stcarrez/mat
|
60b63a49c8f669e8c1f641ad99f8bfa314f95a01
|
mat/src/mat-commands.ads
|
mat/src/mat-commands.ads
|
-----------------------------------------------------------------------
-- mat-commands -- Command support and execution
-- Copyright (C) 2014 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with GNAT.Sockets;
with MAT.Targets;
package MAT.Commands is
Stop_Interp : exception;
-- Exception raised if some option is invalid.
Usage_Error : exception;
-- The options that can be configured through the command line.
type Options_Type is record
Interactive : Boolean := True;
Graphical : Boolean := False;
Address : GNAT.Sockets.Sock_Addr_Type := (Port => 4096, others => <>);
end record;
-- Procedure that defines a command handler.
type Command_Handler is access procedure (Target : in out MAT.Targets.Target_Type'Class;
Args : in String);
-- Execute the command given in the line.
procedure Execute (Target : in out MAT.Targets.Target_Type'Class;
Line : in String);
-- Enter in the interactive loop reading the commands from the standard input
-- and executing the commands.
procedure Interactive (Target : in out MAT.Targets.Target_Type'Class);
-- Parse the command line arguments and configure the target instance.
procedure Initialize_Options (Target : in out MAT.Targets.Target_Type'Class;
Options : in out Options_Type);
-- Convert the string to a socket address. The string can have two forms:
-- port
-- host:port
function To_Sock_Addr_Type (Param : in String) return GNAT.Sockets.Sock_Addr_Type;
-- Print the application usage.
procedure Usage;
end MAT.Commands;
|
-----------------------------------------------------------------------
-- mat-commands -- Command support and execution
-- Copyright (C) 2014 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with GNAT.Sockets;
with MAT.Targets;
package MAT.Commands is
Stop_Interp : exception;
-- Exception raised if some option is invalid.
Usage_Error : exception;
-- The options that can be configured through the command line.
type Options_Type is record
Interactive : Boolean := True;
Graphical : Boolean := False;
Address : GNAT.Sockets.Sock_Addr_Type := (Port => 4096, others => <>);
end record;
-- Procedure that defines a command handler.
type Command_Handler is access procedure (Target : in out MAT.Targets.Target_Type'Class;
Args : in String);
-- Execute the command given in the line.
procedure Execute (Target : in out MAT.Targets.Target_Type'Class;
Line : in String);
-- Enter in the interactive loop reading the commands from the standard input
-- and executing the commands.
procedure Interactive (Target : in out MAT.Targets.Target_Type'Class);
-- Parse the command line arguments and configure the target instance.
procedure Initialize_Options (Target : in out MAT.Targets.Target_Type'Class;
Options : in out Options_Type);
-- Initialize the process targets by loading the MAT files.
procedure Initialize_Files (Target : in out MAT.Targets.Target_Type'Class);
-- Convert the string to a socket address. The string can have two forms:
-- port
-- host:port
function To_Sock_Addr_Type (Param : in String) return GNAT.Sockets.Sock_Addr_Type;
-- Print the application usage.
procedure Usage;
end MAT.Commands;
|
Declare the Initialize_Files procedure
|
Declare the Initialize_Files procedure
|
Ada
|
apache-2.0
|
stcarrez/mat,stcarrez/mat,stcarrez/mat
|
cfefd02fe0c132480466eb6524a44a8498b04f1e
|
src/asf-rest-definition.adb
|
src/asf-rest-definition.adb
|
-----------------------------------------------------------------------
-- asf-rest -- REST Support
-- Copyright (C) 2016 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
package body ASF.Rest.Definition is
overriding
procedure Dispatch (Handler : in Descriptor;
Req : in out ASF.Rest.Request'Class;
Reply : in out ASF.Rest.Response'Class) is
Object : Object_Type;
begin
Handler.Handler (Object, Req, Reply);
end Dispatch;
package body Definition is
P : aliased String := Pattern;
begin
Instance.Method := Method;
Instance.Permission := Permission;
Instance.Handler := Handler;
Instance.Pattern := P'Access;
ASF.Rest.Register (Entries, Instance'Access);
end Definition;
end ASF.Rest.Definition;
|
-----------------------------------------------------------------------
-- asf-rest -- REST Support
-- Copyright (C) 2016 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
package body ASF.Rest.Definition is
-- ------------------------------
-- Register the list of APIs that have been created by instantiating the <tt>Definition</tt>
-- package. The REST servlet identified by <tt>Name</tt> is searched in the servlet registry
-- and used as the servlet for processing the API requests.
-- ------------------------------
procedure Register (Registry : in out ASF.Servlets.Servlet_Registry;
Name : in String;
ELContext : in EL.Contexts.ELContext'Class) is
begin
ASF.Rest.Register (Registry => Registry,
Name => Name,
URI => URI,
ELContext => ELContext,
List => Entries);
end Register;
overriding
procedure Dispatch (Handler : in Descriptor;
Req : in out ASF.Rest.Request'Class;
Reply : in out ASF.Rest.Response'Class;
Stream : in out ASF.Rest.Output_Stream'Class) is
Object : Object_Type;
begin
Handler.Handler (Object, Req, Reply, Stream);
end Dispatch;
package body Definition is
P : aliased String := Pattern;
begin
Instance.Method := Method;
Instance.Permission := Permission;
Instance.Handler := Handler;
Instance.Pattern := P'Access;
ASF.Rest.Register (Entries, Instance'Access);
end Definition;
end ASF.Rest.Definition;
|
Implement the Register procedure to register all the APIs that have been instantiated to the servlet registry
|
Implement the Register procedure to register all the APIs that have been instantiated
to the servlet registry
|
Ada
|
apache-2.0
|
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
|
877b87b6d6eb1d5ce66b76107f934e4b2c16a354
|
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 Ada.Streams;
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;
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_WRONLY
+ Util.Systems.Constants.O_CREAT
+ Util.Systems.Constants.O_TRUNC,
Mode => Interfaces.C.int (Mode));
Interfaces.C.Strings.Free (Name);
Stream.Buffer := null;
Stream.File.Initialize (File => Fd);
if Fd < 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;
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;
|
Fix the creation of path directories when writing a file
|
Fix the creation of path directories when writing a file
|
Ada
|
apache-2.0
|
stcarrez/babel
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.