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
|
---|---|---|---|---|---|---|---|---|---|
11a5428dcd1929a690a03c8d7dbee1776c29bba0
|
regtests/asf-applications-views-tests.adb
|
regtests/asf-applications-views-tests.adb
|
-----------------------------------------------------------------------
-- Render Tests - Unit tests for ASF.Applications.Views
-- 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.Text_IO;
with ASF.Applications.Main;
with ASF.Requests.Mockup;
with ASF.Responses.Mockup;
with ASF.Requests.Tools;
with ASF.Servlets.Faces;
with Ada.Directories;
with Util.Test_Caller;
with Util.Files;
with Util.Measures;
package body ASF.Applications.Views.Tests is
use Ada.Strings.Unbounded;
overriding
procedure Set_Up (T : in out Test) is
begin
null;
end Set_Up;
-- Set up performed before each test case
-- Test loading of facelet file
procedure Test_Load_Facelet (T : in out Test) is
use ASF;
use ASF.Contexts.Faces;
App : Applications.Main.Application;
-- H : Applications.Views.View_Handler;
View_Name : constant String := To_String (T.File);
Result_File : constant String := To_String (T.Result);
Conf : Applications.Config;
App_Factory : Applications.Main.Application_Factory;
Dir : constant String := "regtests/files";
Path : constant String := Util.Tests.Get_Path (Dir);
Faces : aliased ASF.Servlets.Faces.Faces_Servlet;
begin
Conf.Load_Properties ("regtests/view.properties");
Conf.Set ("view.dir", Path);
App.Initialize (Conf, App_Factory);
App.Register_Application ("/");
App.Add_Servlet ("faces", Faces'Unchecked_Access);
App.Set_Global ("function", "Test_Load_Facelet");
for I in 1 .. 2 loop
declare
S : Util.Measures.Stamp;
Req : ASF.Requests.Mockup.Request;
Rep : aliased ASF.Responses.Mockup.Response;
Content : Unbounded_String;
begin
ASF.Requests.Tools.Set_Context (Req => Req,
Servlet => Faces'Unchecked_Access,
Response => Rep'Unchecked_Access);
Req.Set_Method ("GET");
Req.Set_Path_Info (View_Name);
Req.Set_Parameter ("file-name", To_String (T.Name));
Req.Set_Header ("file", To_String (T.Name));
App.Dispatch (Page => View_Name,
Request => Req,
Response => Rep);
Util.Measures.Report (S, "Pass" & Integer'Image (I) & ": Render view "
& View_Name);
Rep.Read_Content (Content);
Util.Files.Write_File (Result_File, Content);
Util.Tests.Assert_Equal_Files (T => T,
Expect => To_String (T.Expect),
Test => Result_File,
Message => "Restore and render view");
end;
end loop;
end Test_Load_Facelet;
-- Test case name
overriding
function Name (T : Test) return Util.Tests.Message_String is
begin
return Util.Tests.Format ("Test " & To_String (T.Name));
end Name;
-- Perform the test.
overriding
procedure Run_Test (T : in out Test) is
begin
T.Test_Load_Facelet;
end Run_Test;
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
use Ada.Directories;
Result_Dir : constant String := "regtests/result/views";
Dir : constant String := "regtests/files/views";
Expect_Dir : constant String := "regtests/expect/views";
Path : constant String := Util.Tests.Get_Path (Dir);
Expect_Path : constant String := Util.Tests.Get_Path (Expect_Dir);
Result_Path : constant String := Util.Tests.Get_Test_Path (Result_Dir);
Search : Search_Type;
Filter : constant Filter_Type := (others => True);
Ent : Directory_Entry_Type;
begin
if Kind (Path) = Directory then
Ada.Text_IO.Put_Line ("Cannot read test directory: " & Path);
end if;
Start_Search (Search, Directory => Path, Pattern => "*.xhtml", Filter => Filter);
while More_Entries (Search) loop
Get_Next_Entry (Search, Ent);
declare
Simple : constant String := Simple_Name (Ent);
Tst : Test_Case_Access;
begin
if Simple /= "." and then Simple /= ".."
and then Simple /= ".svn" then
Tst := new Test;
Tst.Name := To_Unbounded_String (Dir & "/" & Simple);
Tst.File := To_Unbounded_String ("views/" & Simple);
Tst.Expect := To_Unbounded_String (Expect_Path & "/" & Simple);
Tst.Result := To_Unbounded_String (Result_Path & "/" & Simple);
Suite.Add_Test (Tst.all'Access);
end if;
end;
end loop;
end Add_Tests;
end ASF.Applications.Views.Tests;
|
-----------------------------------------------------------------------
-- Render Tests - Unit tests for ASF.Applications.Views
-- Copyright (C) 2009, 2010, 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.Text_IO;
with ASF.Applications.Main;
with ASF.Requests.Mockup;
with ASF.Responses.Mockup;
with ASF.Requests.Tools;
with ASF.Servlets.Faces;
with Ada.Directories;
with Util.Test_Caller;
with Util.Files;
with Util.Measures;
package body ASF.Applications.Views.Tests is
use Ada.Strings.Unbounded;
overriding
procedure Set_Up (T : in out Test) is
begin
null;
end Set_Up;
-- Set up performed before each test case
-- Test loading of facelet file
procedure Test_Load_Facelet (T : in out Test) is
use ASF;
use ASF.Contexts.Faces;
App : Applications.Main.Application;
-- H : Applications.Views.View_Handler;
View_Name : constant String := To_String (T.File);
Result_File : constant String := To_String (T.Result);
Conf : Applications.Config;
App_Factory : Applications.Main.Application_Factory;
Dir : constant String := "regtests/files";
Path : constant String := Util.Tests.Get_Path (Dir);
Faces : aliased ASF.Servlets.Faces.Faces_Servlet;
begin
Conf.Load_Properties ("regtests/view.properties");
Conf.Set ("view.dir", Path);
App.Initialize (Conf, App_Factory);
App.Register_Application ("/");
App.Add_Servlet ("faces", Faces'Unchecked_Access);
App.Set_Global ("function", "Test_Load_Facelet");
for I in 1 .. 2 loop
declare
S : Util.Measures.Stamp;
Req : ASF.Requests.Mockup.Request;
Rep : aliased ASF.Responses.Mockup.Response;
Content : Unbounded_String;
begin
ASF.Requests.Tools.Set_Context (Req => Req,
Servlet => Faces'Unchecked_Access,
Response => Rep'Unchecked_Access);
Req.Set_Method ("GET");
Req.Set_Path_Info (View_Name);
Req.Set_Parameter ("file-name", To_String (T.Name));
Req.Set_Header ("file", To_String (T.Name));
App.Dispatch (Page => View_Name,
Request => Req,
Response => Rep);
Util.Measures.Report (S, "Pass" & Integer'Image (I) & ": Render view "
& View_Name);
Rep.Read_Content (Content);
Util.Files.Write_File (Result_File, Content);
Util.Tests.Assert_Equal_Files (T => T,
Expect => To_String (T.Expect),
Test => Result_File,
Message => "Restore and render view");
end;
end loop;
end Test_Load_Facelet;
-- Test case name
overriding
function Name (T : Test) return Util.Tests.Message_String is
begin
return Util.Tests.Format ("Test " & To_String (T.Name));
end Name;
-- Perform the test.
overriding
procedure Run_Test (T : in out Test) is
begin
T.Test_Load_Facelet;
end Run_Test;
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
use Ada.Directories;
Result_Dir : constant String := "regtests/result/views";
Dir : constant String := "regtests/files/views";
Expect_Dir : constant String := "regtests/expect/views";
Path : constant String := Util.Tests.Get_Path (Dir);
Expect_Path : constant String := Util.Tests.Get_Path (Expect_Dir);
Result_Path : constant String := Util.Tests.Get_Test_Path (Result_Dir);
Search : Search_Type;
Filter : constant Filter_Type := (others => True);
Ent : Directory_Entry_Type;
begin
if Kind (Path) /= Directory then
Ada.Text_IO.Put_Line ("Cannot read test directory: " & Path);
end if;
Start_Search (Search, Directory => Path, Pattern => "*.xhtml", Filter => Filter);
while More_Entries (Search) loop
Get_Next_Entry (Search, Ent);
declare
Simple : constant String := Simple_Name (Ent);
Tst : Test_Case_Access;
begin
if Simple /= "." and then Simple /= ".."
and then Simple /= ".svn" then
Tst := new Test;
Tst.Name := To_Unbounded_String (Dir & "/" & Simple);
Tst.File := To_Unbounded_String ("views/" & Simple);
Tst.Expect := To_Unbounded_String (Expect_Path & "/" & Simple);
Tst.Result := To_Unbounded_String (Result_Path & "/" & Simple);
Suite.Add_Test (Tst.all'Access);
end if;
end;
end loop;
end Add_Tests;
end ASF.Applications.Views.Tests;
|
Fix an invalid warning reported during execution of unit tests
|
Fix an invalid warning reported during execution of unit tests
|
Ada
|
apache-2.0
|
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
|
a1358d49a65573be77bfbd2e52020786ff36ccc8
|
awa/samples/src/atlas-reviews-beans.adb
|
awa/samples/src/atlas-reviews-beans.adb
|
-----------------------------------------------------------------------
-- atlas-reviews-beans -- Beans for module reviews
-- Copyright (C) 2014 Stephane.Carrez
-- Written by Stephane.Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
package body Atlas.Reviews.Beans is
-- ------------------------------
-- Get the value identified by the name.
-- ------------------------------
overriding
function Get_Value (From : in Review_Bean;
Name : in String) return Util.Beans.Objects.Object is
begin
if From.Is_Null then
return Util.Beans.Objects.Null_Object;
else
return Atlas.Reviews.Models.Review_Bean (From).Get_Value (Name);
end if;
end Get_Value;
-- ------------------------------
-- Set the value identified by the name.
-- ------------------------------
overriding
procedure Set_Value (From : in out Review_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 = "site" then
From.Set_Site (Util.Beans.Objects.To_String (Value));
elsif Name = "text" then
From.Set_Text (Util.Beans.Objects.To_String (Value));
end if;
end Set_Value;
overriding
procedure Save (Bean : in out Review_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
pragma Unreferenced (Outcome);
begin
Bean.Module.Save (Bean);
end Save;
overriding
procedure Delete (Bean : in out Review_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
pragma Unreferenced (Outcome);
begin
Bean.Module.Delete (Bean);
end Delete;
-- ------------------------------
-- Create the Review_Bean bean instance.
-- ------------------------------
function Create_Review_Bean (Module : in Atlas.Reviews.Modules.Review_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access is
Object : constant Review_Bean_Access := new Review_Bean;
begin
Object.Module := Module;
return Object.all'Access;
end Create_Review_Bean;
end Atlas.Reviews.Beans;
|
-----------------------------------------------------------------------
-- atlas-reviews-beans -- Beans for module reviews
-- 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 ADO.Sessions;
with ADO.Queries;
with ADO.Utils;
with ADO.Datasets;
with AWA.Services.Contexts;
package body Atlas.Reviews.Beans is
package ASC renames AWA.Services.Contexts;
-- ------------------------------
-- Get the value identified by the name.
-- ------------------------------
overriding
function Get_Value (From : in Review_Bean;
Name : in String) return Util.Beans.Objects.Object is
begin
if From.Is_Null then
return Util.Beans.Objects.Null_Object;
else
return Atlas.Reviews.Models.Review_Bean (From).Get_Value (Name);
end if;
end Get_Value;
-- ------------------------------
-- Set the value identified by the name.
-- ------------------------------
overriding
procedure Set_Value (From : in out Review_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 = "site" then
From.Set_Site (Util.Beans.Objects.To_String (Value));
elsif Name = "text" then
From.Set_Text (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 : ADO.Sessions.Session := AWA.Services.Contexts.Get_Session (Ctx);
Id : constant ADO.Identifier := ADO.Utils.To_Identifier (Value);
Found : Boolean;
begin
From.Load (DB, Id, Found);
end;
end if;
end Set_Value;
overriding
procedure Save (Bean : in out Review_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
pragma Unreferenced (Outcome);
begin
Bean.Module.Save (Bean);
end Save;
overriding
procedure Delete (Bean : in out Review_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
pragma Unreferenced (Outcome);
begin
Bean.Module.Delete (Bean);
end Delete;
overriding
procedure Load (Bean : in out Review_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
Session : ADO.Sessions.Session := Bean.Module.Get_Session;
begin
null;
end Load;
-- ------------------------------
-- Create the Review_Bean bean instance.
-- ------------------------------
function Create_Review_Bean (Module : in Atlas.Reviews.Modules.Review_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access is
Object : constant Review_Bean_Access := new Review_Bean;
begin
Object.Module := Module;
return Object.all'Access;
end Create_Review_Bean;
-- ------------------------------
-- Get the value identified by the name.
-- ------------------------------
overriding
function Get_Value (From : in Review_List_Bean;
Name : in String) return Util.Beans.Objects.Object is
begin
if Name = "page" then
return Util.Beans.Objects.To_Object (From.Page);
elsif Name = "page_size" then
return Util.Beans.Objects.To_Object (From.Page_Size);
elsif Name = "count" then
return Util.Beans.Objects.To_Object (From.Count);
elsif Name = "reviews" then
return Util.Beans.Objects.To_Object (Value => From.Reviews_Bean,
Storage => Util.Beans.Objects.STATIC);
else
return From.Reviews.Get_Value (Name);
end if;
end Get_Value;
-- ------------------------------
-- Set the value identified by the name.
-- ------------------------------
overriding
procedure Set_Value (From : in out Review_List_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object) is
begin
if Name = "page" then
From.Page := Util.Beans.Objects.To_Integer (Value);
elsif Name = "page_size" then
From.Page_Size := Util.Beans.Objects.To_Integer (Value);
end if;
end Set_Value;
overriding
procedure Load (Into : in out Review_List_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
Session : ADO.Sessions.Session := Into.Module.Get_Session;
Query : ADO.Queries.Context;
Count_Query : ADO.Queries.Context;
First : constant Natural := (Into.Page - 1) * Into.Page_Size;
Last : constant Positive := First + Into.Page_Size;
begin
Query.Set_Query (Atlas.Reviews.Models.Query_List);
Count_Query.Set_Count_Query (Atlas.Reviews.Models.Query_List);
Query.Bind_Param (Name => "first", Value => First);
Query.Bind_Param (Name => "last", Value => Last);
Atlas.Reviews.Models.List (Into.Reviews, Session, Query);
Into.Count := ADO.Datasets.Get_Count (Session, Count_Query);
end Load;
-- ------------------------------
-- Create the Review_List_Bean bean instance.
-- ------------------------------
function Create_Review_List_Bean (Module : in Atlas.Reviews.Modules.Review_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access is
Object : constant Review_List_Bean_Access := new Review_List_Bean;
begin
Object.Module := Module;
Object.Reviews_Bean := Object.Reviews'Access;
Object.Page_Size := 20;
Object.Page := 1;
Object.Count := 0;
return Object.all'Access;
end Create_Review_List_Bean;
end Atlas.Reviews.Beans;
|
Implement the Review_List_Bean
|
Implement the Review_List_Bean
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
e15933626bf862746af57e7f804d093910d4b23b
|
awa/plugins/awa-counters/src/awa-counters-modules.adb
|
awa/plugins/awa-counters/src/awa-counters-modules.adb
|
-----------------------------------------------------------------------
-- awa-counters-modules -- Module counters
-- Copyright (C) 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Unchecked_Deallocation;
with ADO.Queries;
with ADO.Statements;
with ADO.Sessions;
with ADO.Sessions.Entities;
with ADO.SQL;
with Util.Dates;
with Util.Log.Loggers;
with AWA.Services.Contexts;
with AWA.Counters.Models;
with AWA.Modules.Get;
package body AWA.Counters.Modules is
use type ADO.Schemas.Class_Mapping_Access;
package ASC renames AWA.Services.Contexts;
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Awa.Counters.Module");
procedure Load_Definition (DB : in out ADO.Sessions.Master_Session;
Def : in Counter_Def;
Result : out Natural);
procedure Flush (DB : in out ADO.Sessions.Master_Session;
Counter : in Counter_Def;
Def_Id : in Natural;
Counters : in Counter_Maps.Map;
Date : in Ada.Calendar.Time);
-- ------------------------------
-- Initialize the counters module.
-- ------------------------------
overriding
procedure Initialize (Plugin : in out Counter_Module;
App : in AWA.Modules.Application_Access;
Props : in ASF.Applications.Config) is
begin
Log.Info ("Initializing the counters module");
AWA.Modules.Module (Plugin).Initialize (App, Props);
-- Add here the creation of manager instances.
end Initialize;
-- ------------------------------
-- Configures the module after its initialization and after having read its XML configuration.
-- ------------------------------
overriding
procedure Configure (Plugin : in out Counter_Module;
Props : in ASF.Applications.Config) is
pragma Unreferenced (Props);
begin
Plugin.Counter_Limit := Plugin.Get_Config (PARAM_COUNTER_LIMIT, DEFAULT_COUNTER_LIMIT);
Plugin.Age_Limit := Duration (Plugin.Get_Config (PARAM_AGE_LIMIT, 300));
end Configure;
-- ------------------------------
-- Get the counters module.
-- ------------------------------
function Get_Counter_Module return Counter_Module_Access is
function Get is new AWA.Modules.Get (Counter_Module, Counter_Module_Access, NAME);
begin
return Get;
end Get_Counter_Module;
-- ------------------------------
-- Increment the counter identified by <tt>Counter</tt> and associated with the
-- database object <tt>Object</tt>.
-- ------------------------------
procedure Increment (Plugin : in out Counter_Module;
Counter : in Counter_Index_Type;
Object : in ADO.Objects.Object_Ref'Class) is
begin
if Plugin.Counters.Need_Flush (Plugin.Counter_Limit, Plugin.Age_Limit) then
Plugin.Flush;
end if;
Plugin.Counters.Increment (Counter, Object);
end Increment;
protected body Counter_Table is
-- ------------------------------
-- Increment the counter identified by <tt>Counter</tt> and associated with the
-- database object <tt>Object</tt>.
-- ------------------------------
procedure Increment (Counter : in Counter_Index_Type;
Object : in ADO.Objects.Object_Ref'Class) is
procedure Increment (Key : in ADO.Objects.Object_Key;
Element : in out Positive);
procedure Increment (Key : in ADO.Objects.Object_Key;
Element : in out Positive) is
pragma Unreferenced (Key);
begin
Element := Element + 1;
end Increment;
Key : constant ADO.Objects.Object_Key := Object.Get_Key;
Pos : Counter_Maps.Cursor;
begin
if Counters = null then
Counters := new Counter_Map_Array (1 .. Counter_Arrays.Get_Last);
Day := Ada.Calendar.Clock;
Day_End := Util.Dates.Get_Day_End (Day);
end if;
Pos := Counters (Counter).Find (Key);
if Counter_Maps.Has_Element (Pos) then
Counters (Counter).Update_Element (Pos, Increment'Access);
else
Counters (Counter).Insert (Key, 1);
Nb_Counters := Nb_Counters + 1;
end if;
end Increment;
-- ------------------------------
-- Get the counters that have been collected with the date and prepare to collect
-- new counters.
-- ------------------------------
procedure Steal_Counters (Result : out Counter_Map_Array_Access;
Date : out Ada.Calendar.Time) is
begin
Result := Counters;
Date := Day;
Counters := null;
Nb_Counters := 0;
end Steal_Counters;
-- ------------------------------
-- Check if we must flush the counters.
-- ------------------------------
function Need_Flush (Limit : in Natural;
Seconds : in Duration) return Boolean is
use type Ada.Calendar.Time;
begin
if Counters = null then
return False;
elsif Nb_Counters > Limit then
return True;
else
declare
Now : constant Ada.Calendar.Time := Ada.Calendar.Clock;
begin
return Now > Day_End or Now - Day >= Seconds;
end;
end if;
end Need_Flush;
-- ------------------------------
-- Get the definition ID associated with the counter.
-- ------------------------------
procedure Get_Definition (Counter : in Counter_Index_Type;
Result : out Natural) is
begin
if Definitions = null then
Definitions := new Definition_Array_Type (1 .. Counter_Arrays.Get_Last);
Definitions.all := (others => 0);
end if;
if Definitions (Counter) = 0 then
declare
Ctx : constant ASC.Service_Context_Access := ASC.Current;
Session : ADO.Sessions.Master_Session := ASC.Get_Master_Session (Ctx);
begin
Load_Definition (Session, Counter_Arrays.Get_Element (Counter).all,
Definitions (Counter));
end;
end if;
Result := Definitions (Counter);
end Get_Definition;
end Counter_Table;
procedure Load_Definition (DB : in out ADO.Sessions.Master_Session;
Def : in Counter_Def;
Result : out Natural) is
Def_Db : AWA.Counters.Models.Counter_Definition_Ref;
Query : ADO.SQL.Query;
Found : Boolean;
begin
if Def.Table = null then
Query.Set_Filter ("name = :name AND entity_type IS NULL");
else
Query.Set_Filter ("name = :name AND entity_type = :entity_type");
ADO.Sessions.Entities.Bind_Param (Params => Query,
Name => "entity_type",
Table => Def.Table,
Session => DB);
end if;
Query.Bind_Param ("name", Def.Field.all);
Def_Db.Find (DB, Query, Found);
if not Found then
if Def.Table /= null then
Def_Db.Set_Entity_Type (ADO.Sessions.Entities.Find_Entity_Type (DB, Def.Table));
end if;
Def_Db.Set_Name (Def.Field.all);
Def_Db.Save (DB);
end if;
Result := Natural (Def_Db.Get_Id);
end Load_Definition;
procedure Flush (DB : in out ADO.Sessions.Master_Session;
Counter : in Counter_Def;
Def_Id : in Natural;
Counters : in Counter_Maps.Map;
Date : in Ada.Calendar.Time) is
Query : ADO.Queries.Context;
Stmt : ADO.Statements.Query_Statement;
Update : ADO.Statements.Query_Statement;
Iter : Counter_Maps.Cursor := Counters.First;
Id : ADO.Identifier;
begin
Query.Set_Query (AWA.Counters.Models.Query_Counter_Update);
Stmt := DB.Create_Statement (Query);
if Counter.Table /= null then
Query.Set_Query (AWA.Counters.Models.Query_Counter_Update_Field);
Update := DB.Create_Statement (Counter.Table);
Update.Bind_Param ("table", Counter.Table.Table.all);
Update.Bind_Param ("field", Counter.Field.all);
end if;
while Counter_Maps.Has_Element (Iter) loop
Id := ADO.Objects.Get_Value (Counter_Maps.Key (Iter));
Stmt.Bind_Param ("date", Date);
Stmt.Bind_Param ("id", Id);
Stmt.Bind_Param ("counter", Counter_Maps.Element (Iter));
Stmt.Bind_Param ("definition", Integer (Def_Id));
Stmt.Execute;
if Counter.Table /= null then
Update.Bind_Param ("counter", Counter_Maps.Element (Iter));
Update.Bind_Param ("id", Id);
Update.Execute;
end if;
Counter_Maps.Next (Iter);
end loop;
end Flush;
-- ------------------------------
-- Flush the existing counters and update all the database records refered to them.
-- ------------------------------
procedure Flush (Plugin : in out Counter_Module) is
procedure Free is new
Ada.Unchecked_Deallocation (Object => Counter_Map_Array,
Name => Counter_Map_Array_Access);
Day : Ada.Calendar.Time;
Counters : Counter_Map_Array_Access;
begin
Plugin.Counters.Steal_Counters (Counters, Day);
if Counters = null then
return;
end if;
declare
DB : ADO.Sessions.Master_Session := Plugin.Get_Master_Session;
Date : constant Ada.Calendar.Time := Util.Dates.Get_Day_Start (Day);
Def_Id : Natural;
begin
DB.Begin_Transaction;
for I in Counters'Range loop
if not Counters (I).Is_Empty then
declare
Counter : constant Counter_Def := Counter_Arrays.Get_Element (I).all;
begin
Plugin.Counters.Get_Definition (I, Def_Id);
Flush (DB, Counter, Def_Id, Counters (I), Date);
end;
end if;
end loop;
DB.Commit;
end;
Free (Counters);
end Flush;
end AWA.Counters.Modules;
|
-----------------------------------------------------------------------
-- awa-counters-modules -- Module counters
-- Copyright (C) 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Unchecked_Deallocation;
with ADO.Queries;
with ADO.Statements;
with ADO.Sessions;
with ADO.Sessions.Entities;
with ADO.SQL;
with Util.Dates;
with Util.Log.Loggers;
with AWA.Services.Contexts;
with AWA.Counters.Models;
with AWA.Modules.Get;
package body AWA.Counters.Modules is
use type ADO.Schemas.Class_Mapping_Access;
package ASC renames AWA.Services.Contexts;
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Awa.Counters.Module");
procedure Load_Definition (DB : in out ADO.Sessions.Master_Session;
Def : in Counter_Def;
Result : out Natural);
procedure Flush (DB : in out ADO.Sessions.Master_Session;
Counter : in Counter_Def;
Def_Id : in Natural;
Counters : in Counter_Maps.Map;
Date : in Ada.Calendar.Time);
-- ------------------------------
-- Initialize the counters module.
-- ------------------------------
overriding
procedure Initialize (Plugin : in out Counter_Module;
App : in AWA.Modules.Application_Access;
Props : in ASF.Applications.Config) is
begin
Log.Info ("Initializing the counters module");
AWA.Modules.Module (Plugin).Initialize (App, Props);
-- Add here the creation of manager instances.
end Initialize;
-- ------------------------------
-- Configures the module after its initialization and after having read its XML configuration.
-- ------------------------------
overriding
procedure Configure (Plugin : in out Counter_Module;
Props : in ASF.Applications.Config) is
pragma Unreferenced (Props);
begin
Plugin.Counter_Limit := Plugin.Get_Config (PARAM_COUNTER_LIMIT, DEFAULT_COUNTER_LIMIT);
Plugin.Age_Limit := Duration (Plugin.Get_Config (PARAM_AGE_LIMIT, 300));
end Configure;
-- ------------------------------
-- Get the counters module.
-- ------------------------------
function Get_Counter_Module return Counter_Module_Access is
function Get is new AWA.Modules.Get (Counter_Module, Counter_Module_Access, NAME);
begin
return Get;
end Get_Counter_Module;
-- ------------------------------
-- Increment the counter identified by <tt>Counter</tt> and associated with the
-- database object <tt>Object</tt>.
-- ------------------------------
procedure Increment (Plugin : in out Counter_Module;
Counter : in Counter_Index_Type;
Object : in ADO.Objects.Object_Ref'Class) is
begin
if Plugin.Counters.Need_Flush (Plugin.Counter_Limit, Plugin.Age_Limit) then
Plugin.Flush;
end if;
Plugin.Counters.Increment (Counter, Object);
end Increment;
-- ------------------------------
-- Get the current counter value.
-- ------------------------------
procedure Get_Counter (Plugin : in out Counter_Module;
Counter : in AWA.Counters.Counter_Index_Type;
Object : in ADO.Objects.Object_Ref'Class;
Result : out Natural) is
Id : constant ADO.Identifier := ADO.Objects.Get_Value (Object.Get_Key);
DB : ADO.Sessions.Session := Plugin.Get_Session;
Stmt : ADO.Statements.Query_Statement
:= DB.Create_Statement ("SELECT SUM(counter) FROM awa_counter WHERE "
& "object_id = :id AND definition_id = :definition_id");
Def_Id : Natural;
begin
Plugin.Counters.Get_Definition (Counter, Def_Id);
Stmt.Bind_Param ("id", Id);
Stmt.Bind_Param ("definition_id", Def_Id);
Stmt.Execute;
Result := Stmt.Get_Result_Integer;
end Get_Counter;
protected body Counter_Table is
-- ------------------------------
-- Increment the counter identified by <tt>Counter</tt> and associated with the
-- database object <tt>Object</tt>.
-- ------------------------------
procedure Increment (Counter : in Counter_Index_Type;
Object : in ADO.Objects.Object_Ref'Class) is
procedure Increment (Key : in ADO.Objects.Object_Key;
Element : in out Positive);
procedure Increment (Key : in ADO.Objects.Object_Key;
Element : in out Positive) is
pragma Unreferenced (Key);
begin
Element := Element + 1;
end Increment;
Key : constant ADO.Objects.Object_Key := Object.Get_Key;
Pos : Counter_Maps.Cursor;
begin
if Counters = null then
Counters := new Counter_Map_Array (1 .. Counter_Arrays.Get_Last);
Day := Ada.Calendar.Clock;
Day_End := Util.Dates.Get_Day_End (Day);
end if;
Pos := Counters (Counter).Find (Key);
if Counter_Maps.Has_Element (Pos) then
Counters (Counter).Update_Element (Pos, Increment'Access);
else
Counters (Counter).Insert (Key, 1);
Nb_Counters := Nb_Counters + 1;
end if;
end Increment;
-- ------------------------------
-- Get the counters that have been collected with the date and prepare to collect
-- new counters.
-- ------------------------------
procedure Steal_Counters (Result : out Counter_Map_Array_Access;
Date : out Ada.Calendar.Time) is
begin
Result := Counters;
Date := Day;
Counters := null;
Nb_Counters := 0;
end Steal_Counters;
-- ------------------------------
-- Check if we must flush the counters.
-- ------------------------------
function Need_Flush (Limit : in Natural;
Seconds : in Duration) return Boolean is
use type Ada.Calendar.Time;
begin
if Counters = null then
return False;
elsif Nb_Counters > Limit then
return True;
else
declare
Now : constant Ada.Calendar.Time := Ada.Calendar.Clock;
begin
return Now > Day_End or Now - Day >= Seconds;
end;
end if;
end Need_Flush;
-- ------------------------------
-- Get the definition ID associated with the counter.
-- ------------------------------
procedure Get_Definition (Counter : in Counter_Index_Type;
Result : out Natural) is
begin
if Definitions = null then
Definitions := new Definition_Array_Type (1 .. Counter_Arrays.Get_Last);
Definitions.all := (others => 0);
end if;
if Definitions (Counter) = 0 then
declare
Ctx : constant ASC.Service_Context_Access := ASC.Current;
Session : ADO.Sessions.Master_Session := ASC.Get_Master_Session (Ctx);
begin
Load_Definition (Session, Counter_Arrays.Get_Element (Counter).all,
Definitions (Counter));
end;
end if;
Result := Definitions (Counter);
end Get_Definition;
end Counter_Table;
procedure Load_Definition (DB : in out ADO.Sessions.Master_Session;
Def : in Counter_Def;
Result : out Natural) is
Def_Db : AWA.Counters.Models.Counter_Definition_Ref;
Query : ADO.SQL.Query;
Found : Boolean;
begin
if Def.Table = null then
Query.Set_Filter ("name = :name AND entity_type IS NULL");
else
Query.Set_Filter ("name = :name AND entity_type = :entity_type");
ADO.Sessions.Entities.Bind_Param (Params => Query,
Name => "entity_type",
Table => Def.Table,
Session => DB);
end if;
Query.Bind_Param ("name", Def.Field.all);
Def_Db.Find (DB, Query, Found);
if not Found then
if Def.Table /= null then
Def_Db.Set_Entity_Type (ADO.Sessions.Entities.Find_Entity_Type (DB, Def.Table));
end if;
Def_Db.Set_Name (Def.Field.all);
Def_Db.Save (DB);
end if;
Result := Natural (Def_Db.Get_Id);
end Load_Definition;
procedure Flush (DB : in out ADO.Sessions.Master_Session;
Counter : in Counter_Def;
Def_Id : in Natural;
Counters : in Counter_Maps.Map;
Date : in Ada.Calendar.Time) is
Query : ADO.Queries.Context;
Stmt : ADO.Statements.Query_Statement;
Update : ADO.Statements.Query_Statement;
Iter : Counter_Maps.Cursor := Counters.First;
Id : ADO.Identifier;
begin
Query.Set_Query (AWA.Counters.Models.Query_Counter_Update);
Stmt := DB.Create_Statement (Query);
if Counter.Table /= null then
Query.Set_Query (AWA.Counters.Models.Query_Counter_Update_Field);
Update := DB.Create_Statement (Counter.Table);
Update.Bind_Param ("table", Counter.Table.Table.all);
Update.Bind_Param ("field", Counter.Field.all);
end if;
while Counter_Maps.Has_Element (Iter) loop
Id := ADO.Objects.Get_Value (Counter_Maps.Key (Iter));
Stmt.Bind_Param ("date", Date);
Stmt.Bind_Param ("id", Id);
Stmt.Bind_Param ("counter", Counter_Maps.Element (Iter));
Stmt.Bind_Param ("definition", Integer (Def_Id));
Stmt.Execute;
if Counter.Table /= null then
Update.Bind_Param ("counter", Counter_Maps.Element (Iter));
Update.Bind_Param ("id", Id);
Update.Execute;
end if;
Counter_Maps.Next (Iter);
end loop;
end Flush;
-- ------------------------------
-- Flush the existing counters and update all the database records refered to them.
-- ------------------------------
procedure Flush (Plugin : in out Counter_Module) is
procedure Free is new
Ada.Unchecked_Deallocation (Object => Counter_Map_Array,
Name => Counter_Map_Array_Access);
Day : Ada.Calendar.Time;
Counters : Counter_Map_Array_Access;
begin
Plugin.Counters.Steal_Counters (Counters, Day);
if Counters = null then
return;
end if;
declare
DB : ADO.Sessions.Master_Session := Plugin.Get_Master_Session;
Date : constant Ada.Calendar.Time := Util.Dates.Get_Day_Start (Day);
Def_Id : Natural;
begin
DB.Begin_Transaction;
for I in Counters'Range loop
if not Counters (I).Is_Empty then
declare
Counter : constant Counter_Def := Counter_Arrays.Get_Element (I).all;
begin
Plugin.Counters.Get_Definition (I, Def_Id);
Flush (DB, Counter, Def_Id, Counters (I), Date);
end;
end if;
end loop;
DB.Commit;
end;
Free (Counters);
end Flush;
end AWA.Counters.Modules;
|
Implement the Get_Counter procedure
|
Implement the Get_Counter procedure
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
db9a7a072a815c6dd96baf7fd95cd284a6575a6d
|
regtests/ado_harness.adb
|
regtests/ado_harness.adb
|
-----------------------------------------------------------------------
-- ADO Databases -- Database Objects
-- Copyright (C) 2009, 2010, 2013 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with ADO.Testsuite;
with ADO.Drivers.Initializer;
with Regtests;
with Util.Tests;
with Util.Properties;
procedure ADO_Harness is
procedure Initialize (Props : in Util.Properties.Manager);
procedure Harness is new Util.Tests.Harness (ADO.Testsuite.Suite,
Initialize);
procedure Init_Drivers is new ADO.Drivers.Initializer (Util.Properties.Manager'Class,
ADO.Drivers.Initialize);
-- ------------------------------
-- Initialization procedure: setup the database
-- ------------------------------
procedure Initialize (Props : in Util.Properties.Manager) is
DB : constant String := Props.Get ("test.database",
"sqlite:///regtests.db");
begin
Init_Drivers (Props);
Regtests.Initialize (DB);
end Initialize;
begin
Harness ("ado-tests.xml");
end ADO_Harness;
|
-----------------------------------------------------------------------
-- ADO Databases -- Database Objects
-- Copyright (C) 2009, 2010, 2013 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with ADO.Testsuite;
with ADO.Drivers;
with Regtests;
with Util.Tests;
with Util.Properties;
procedure ADO_Harness is
procedure Initialize (Props : in Util.Properties.Manager);
procedure Harness is new Util.Tests.Harness (ADO.Testsuite.Suite,
Initialize);
-- ------------------------------
-- Initialization procedure: setup the database
-- ------------------------------
procedure Initialize (Props : in Util.Properties.Manager) is
DB : constant String := Props.Get ("test.database",
"sqlite:///regtests.db");
begin
ADO.Drivers.Initialize (Props);
Regtests.Initialize (DB);
end Initialize;
begin
Harness ("ado-tests.xml");
end ADO_Harness;
|
Fix the initialization of the database drivers
|
Fix the initialization of the database drivers
|
Ada
|
apache-2.0
|
Letractively/ada-ado
|
7f2b7619bc0c0d508fa55f4e64bb7b2d3a9f1a0c
|
src/security-contexts.ads
|
src/security-contexts.ads
|
-----------------------------------------------------------------------
-- security-contexts -- Context to provide security information and verify permissions
-- Copyright (C) 2011, 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Finalization;
with Util.Strings.Maps;
with Security.Permissions;
-- == Security Context ==
-- The security context provides contextual information for a security controller to
-- verify that a permission is granted.
-- This security context is used as follows:
--
-- * An instance of the security context is declared within a function/procedure as
-- a local variable
-- * This instance will be associated with the current thread through a task attribute
-- * The security context is populated with information to identify the current user,
-- his roles, permissions and other information that could be used by security controllers
-- * To verify a permission, the current security context is retrieved and the
-- <b>Has_Permission</b> operation is called,
-- * The <b>Has_Permission<b> will first look in a small cache stored in the security context.
-- * When not present in the cache, it will use the security manager to find the
-- security controller associated with the permission to verify
-- * The security controller will be called with the security context to check the permission.
-- The whole job of checking the permission is done by the security controller.
-- The security controller retrieves information from the security context to decide
-- whether the permission is granted or not.
-- * The result produced by the security controller is then saved in the local cache.
--
package Security.Contexts is
Invalid_Context : exception;
type Security_Context is new Ada.Finalization.Limited_Controlled with private;
type Security_Context_Access is access all Security_Context'Class;
-- Get the application associated with the current service operation.
function Get_User_Principal (Context : in Security_Context'Class)
return Security.Permissions.Principal_Access;
pragma Inline_Always (Get_User_Principal);
-- Get the permission manager.
function Get_Permission_Manager (Context : in Security_Context'Class)
return Security.Permissions.Permission_Manager_Access;
pragma Inline_Always (Get_Permission_Manager);
-- Check if the permission identified by <b>Permission</b> is allowed according to
-- the current security context. The result is cached in the security context and
-- returned in <b>Result</b>.
procedure Has_Permission (Context : in out Security_Context;
Permission : in Security.Permissions.Permission_Index;
Result : out Boolean);
-- Check if the permission identified by <b>Permission</b> is allowed according to
-- the current security context. The result is cached in the security context and
-- returned in <b>Result</b>.
procedure Has_Permission (Context : in out Security_Context;
Permission : in String;
Result : out Boolean);
-- Initializes the service context. By creating the <b>Security_Context</b> variable,
-- the instance will be associated with the current task attribute. If the current task
-- already has a security context, the new security context is installed, the old one
-- being kept.
overriding
procedure Initialize (Context : in out Security_Context);
-- Finalize the security context releases any object. The previous security context is
-- restored to the current task attribute.
overriding
procedure Finalize (Context : in out Security_Context);
-- Set the current application and user context.
procedure Set_Context (Context : in out Security_Context;
Manager : in Security.Permissions.Permission_Manager_Access;
Principal : in Security.Permissions.Principal_Access);
-- Add a context information represented by <b>Value</b> under the name identified by
-- <b>Name</b> in the security context <b>Context</b>.
procedure Add_Context (Context : in out Security_Context;
Name : in String;
Value : in String);
-- Get the context information registered under the name <b>Name</b> in the security
-- context <b>Context</b>.
-- Raises <b>Invalid_Context</b> if there is no such information.
function Get_Context (Context : in Security_Context;
Name : in String) return String;
-- Returns True if a context information was registered under the name <b>Name</b>.
function Has_Context (Context : in Security_Context;
Name : in String) return Boolean;
-- Get the current security context.
-- Returns null if the current thread is not associated with any security context.
function Current return Security_Context_Access;
pragma Inline_Always (Current);
-- Check if the permission identified by <b>Permission</b> is allowed according to
-- the current security context. The result is cached in the security context and
-- returned in <b>Result</b>.
function Has_Permission (Permission : in Security.Permissions.Permission_Index) return Boolean;
-- Check if the permission identified by <b>Permission</b> is allowed according to
-- the current security context. The result is cached in the security context and
-- returned in <b>Result</b>.
function Has_Permission (Permission : in String) return Boolean;
private
type Permission_Cache is record
Perm : Security.Permissions.Permission_Type;
Result : Boolean;
end record;
type Security_Context is new Ada.Finalization.Limited_Controlled with record
Previous : Security_Context_Access := null;
Manager : Security.Permissions.Permission_Manager_Access := null;
Principal : Security.Permissions.Principal_Access := null;
Context : Util.Strings.Maps.Map;
end record;
end Security.Contexts;
|
-----------------------------------------------------------------------
-- security-contexts -- Context to provide security information and verify permissions
-- Copyright (C) 2011, 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Finalization;
with Util.Strings.Maps;
with Security.Permissions;
-- == Security Context ==
-- The security context provides contextual information for a security controller to
-- verify that a permission is granted.
-- This security context is used as follows:
--
-- * An instance of the security context is declared within a function/procedure as
-- a local variable
--
-- * This instance will be associated with the current thread through a task attribute
--
-- * The security context is populated with information to identify the current user,
-- his roles, permissions and other information that could be used by security controllers
--
-- * To verify a permission, the current security context is retrieved and the
-- <b>Has_Permission</b> operation is called,
--
-- * The <b>Has_Permission<b> will first look in a small cache stored in the security context.
--
-- * When not present in the cache, it will use the security manager to find the
-- security controller associated with the permission to verify
--
-- * The security controller will be called with the security context to check the permission.
-- The whole job of checking the permission is done by the security controller.
-- The security controller retrieves information from the security context to decide
-- whether the permission is granted or not.
--
-- * The result produced by the security controller is then saved in the local cache.
--
package Security.Contexts is
Invalid_Context : exception;
type Security_Context is new Ada.Finalization.Limited_Controlled with private;
type Security_Context_Access is access all Security_Context'Class;
-- Get the application associated with the current service operation.
function Get_User_Principal (Context : in Security_Context'Class)
return Security.Permissions.Principal_Access;
pragma Inline_Always (Get_User_Principal);
-- Get the permission manager.
function Get_Permission_Manager (Context : in Security_Context'Class)
return Security.Permissions.Permission_Manager_Access;
pragma Inline_Always (Get_Permission_Manager);
-- Check if the permission identified by <b>Permission</b> is allowed according to
-- the current security context. The result is cached in the security context and
-- returned in <b>Result</b>.
procedure Has_Permission (Context : in out Security_Context;
Permission : in Security.Permissions.Permission_Index;
Result : out Boolean);
-- Check if the permission identified by <b>Permission</b> is allowed according to
-- the current security context. The result is cached in the security context and
-- returned in <b>Result</b>.
procedure Has_Permission (Context : in out Security_Context;
Permission : in String;
Result : out Boolean);
-- Initializes the service context. By creating the <b>Security_Context</b> variable,
-- the instance will be associated with the current task attribute. If the current task
-- already has a security context, the new security context is installed, the old one
-- being kept.
overriding
procedure Initialize (Context : in out Security_Context);
-- Finalize the security context releases any object. The previous security context is
-- restored to the current task attribute.
overriding
procedure Finalize (Context : in out Security_Context);
-- Set the current application and user context.
procedure Set_Context (Context : in out Security_Context;
Manager : in Security.Permissions.Permission_Manager_Access;
Principal : in Security.Permissions.Principal_Access);
-- Add a context information represented by <b>Value</b> under the name identified by
-- <b>Name</b> in the security context <b>Context</b>.
procedure Add_Context (Context : in out Security_Context;
Name : in String;
Value : in String);
-- Get the context information registered under the name <b>Name</b> in the security
-- context <b>Context</b>.
-- Raises <b>Invalid_Context</b> if there is no such information.
function Get_Context (Context : in Security_Context;
Name : in String) return String;
-- Returns True if a context information was registered under the name <b>Name</b>.
function Has_Context (Context : in Security_Context;
Name : in String) return Boolean;
-- Get the current security context.
-- Returns null if the current thread is not associated with any security context.
function Current return Security_Context_Access;
pragma Inline_Always (Current);
-- Check if the permission identified by <b>Permission</b> is allowed according to
-- the current security context. The result is cached in the security context and
-- returned in <b>Result</b>.
function Has_Permission (Permission : in Security.Permissions.Permission_Index) return Boolean;
-- Check if the permission identified by <b>Permission</b> is allowed according to
-- the current security context. The result is cached in the security context and
-- returned in <b>Result</b>.
function Has_Permission (Permission : in String) return Boolean;
private
type Permission_Cache is record
Perm : Security.Permissions.Permission_Type;
Result : Boolean;
end record;
type Security_Context is new Ada.Finalization.Limited_Controlled with record
Previous : Security_Context_Access := null;
Manager : Security.Permissions.Permission_Manager_Access := null;
Principal : Security.Permissions.Principal_Access := null;
Context : Util.Strings.Maps.Map;
end record;
end Security.Contexts;
|
Fix comment style for dynamo
|
Fix comment style for dynamo
|
Ada
|
apache-2.0
|
stcarrez/ada-security
|
061ec4a1989840e13dc005cff35f51082c4bb249
|
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
-- 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,
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
use type Permissions.Permission_Index;
Index : Permission_Index;
begin
Log.Info ("Adding permission {0}", Name);
Permissions.Add_Permission (Name, Index);
if Index >= Manager.Last_Index then
declare
Count : constant Permission_Index := Index + 32;
Perms : constant Controller_Access_Array_Access
:= new Controller_Access_Array (0 .. Count);
begin
if Manager.Permissions /= null then
Perms (Manager.Permissions'Range) := Manager.Permissions.all;
end if;
Manager.Permissions := Perms;
Manager.Last_Index := Count;
end;
end if;
-- If the permission has a controller, release it.
if Manager.Permissions (Index) /= null then
Log.Warn ("Permission {0} is redefined", Name);
Free (Manager.Permissions (Index));
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
use type Permissions.Permission_Index;
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;
-- ------------------------------
-- 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;
-- Read the policy file
procedure Read_Policy (Manager : in out Policy_Manager;
File : in String) is
use Util;
Reader : Util.Serialize.IO.XML.Parser;
package Policy_Config is
new Reader_Config (Reader, Manager'Unchecked_Access);
pragma Warnings (Off, Policy_Config);
begin
Log.Info ("Reading policy file {0}", File);
-- Prepare the reader to parse the policy configuration.
for I in Manager.Policies'Range loop
exit when Manager.Policies (I) = null;
Manager.Policies (I).Prepare_Config (Reader);
end loop;
-- Read the configuration file.
Reader.Parse (File);
-- Finish the policy configuration.
for I in Manager.Policies'Range loop
exit when Manager.Policies (I) = null;
Manager.Policies (I).Finish_Config (Reader);
end loop;
end Read_Policy;
-- ------------------------------
-- Initialize the 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 : 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 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR 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
-- 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,
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
use type Permissions.Permission_Index;
Index : Permission_Index;
begin
Log.Info ("Adding permission {0}", Name);
Permissions.Add_Permission (Name, Index);
if Index >= Manager.Last_Index then
declare
Count : constant Permission_Index := Index + 32;
Perms : constant Controller_Access_Array_Access
:= new Controller_Access_Array (0 .. Count);
begin
if Manager.Permissions /= null then
Perms (Manager.Permissions'Range) := Manager.Permissions.all;
end if;
Manager.Permissions := Perms;
Manager.Last_Index := Count;
end;
end if;
-- If the permission has a controller, release it.
if Manager.Permissions (Index) /= null then
Log.Warn ("Permission {0} is redefined", Name);
Free (Manager.Permissions (Index));
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
use type Permissions.Permission_Index;
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;
-- ------------------------------
-- 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);
-- Read the configuration file.
Reader.Parse (File);
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 : 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;
|
Implement the new procedure Prepare_Config and Finish_Config Call them in Read_Policy
|
Implement the new procedure Prepare_Config and Finish_Config
Call them in Read_Policy
|
Ada
|
apache-2.0
|
stcarrez/ada-security
|
c297b756271897571c99072172c6f9e59ab0da43
|
examples/filesystem/src/main.adb
|
examples/filesystem/src/main.adb
|
with HAL; use HAL;
with Virtual_File_System; use Virtual_File_System;
with HAL.Filesystem; use HAL.Filesystem;
with Semihosting;
with Semihosting.Filesystem; use Semihosting.Filesystem;
with File_Block_Drivers; use File_Block_Drivers;
with Partitions; use Partitions;
procedure Main is
procedure List_Dir (FS : in out FS_Driver'Class;
Path : Pathname);
procedure List_Partitions (FS : in out FS_Driver'Class;
Path_To_Disk_Image : Pathname);
--------------
-- List_Dir --
--------------
procedure List_Dir (FS : in out FS_Driver'Class; Path : Pathname) is
Status : Status_Kind;
DH : Directory_Handle_Ref;
begin
Status := FS.Open_Directory (Path, DH);
if Status /= Status_Ok then
Semihosting.Log_Line ("Open Directory '" & Path & "' Error: " & Status'Img);
else
declare
Ent : Directory_Entry;
Index : Positive := 1;
begin
Semihosting.Log_Line ("Listing '" & Path & "' content:");
loop
Status := DH.Read_Entry (Index, Ent);
if Status = Status_Ok then
Semihosting.Log_Line (" - '" & DH.Entry_Name (Index) & "'");
Semihosting.Log_Line (" Kind: " & Ent.Entry_Type'Img);
else
exit;
end if;
Index := Index + 1;
end loop;
end;
end if;
end List_Dir;
---------------------
-- List_Partitions --
---------------------
procedure List_Partitions (FS : in out FS_Driver'Class;
Path_To_Disk_Image : Pathname)
is
File : File_Handle_Ref;
begin
if FS.Open (Path_To_Disk_Image, File) /= Status_Ok then
Semihosting.Log_Line ("Cannot open disk image '" &
Path_To_Disk_Image & "'");
return;
end if;
declare
Disk : aliased File_Block_Driver (File);
Nbr : Natural;
P_Entry : Partition_Entry;
begin
Nbr := Number_Of_Partitions (Disk'Unchecked_Access);
Semihosting.Log_Line ("Disk '" & Path_To_Disk_Image & "' has " &
Nbr'Img & " parition(s)");
for Id in 1 .. Nbr loop
if Get_Partition_Entry (Disk'Unchecked_Access,
Id,
P_Entry) /= Status_Ok
then
Semihosting.Log_Line ("Cannot read partition :" & Id'Img);
else
Semihosting.Log_Line (" - partition :" & Id'Img);
Semihosting.Log_Line (" Status:" & P_Entry.Status'Img);
Semihosting.Log_Line (" Kind: " & P_Entry.Kind'Img);
Semihosting.Log_Line (" LBA: " & P_Entry.First_Sector_LBA'Img);
Semihosting.Log_Line (" Number of sectors: " & P_Entry.Number_Of_Sectors'Img);
end if;
end loop;
end;
end List_Partitions;
My_VFS : VFS;
My_VFS2 : aliased VFS;
My_VFS3 : aliased VFS;
My_SHFS : aliased SHFS;
Status : Status_Kind;
FH : File_Handle_Ref;
Data : Byte_Array (1 .. 10);
begin
Status := My_VFS.Mount (Path => "test1",
Filesystem => My_VFS2'Unchecked_Access);
if Status /= Status_Ok then
Semihosting.Log_Line ("Mount Error: " & Status'Img);
end if;
Status := My_VFS2.Mount (Path => "test2",
Filesystem => My_VFS3'Unchecked_Access);
if Status /= Status_Ok then
Semihosting.Log_Line ("Mount Error: " & Status'Img);
end if;
Status := My_VFS.Mount (Path => "host",
Filesystem => My_SHFS'Unchecked_Access);
if Status /= Status_Ok then
Semihosting.Log_Line ("Mount Error: " & Status'Img);
end if;
List_Partitions (My_VFS, "/host/tmp/disk_8_partitions.img");
Status := My_VFS.Unlink ("/test1/no_file");
if Status /= Status_Ok then
Semihosting.Log_Line ("Unlink Error: " & Status'Img);
end if;
Status := My_VFS.Unlink ("//test1/no_file");
if Status /= Status_Ok then
Semihosting.Log_Line ("Unlink Error: " & Status'Img);
end if;
Status := My_VFS.Unlink ("/test1//no_file");
if Status /= Status_Ok then
Semihosting.Log_Line ("Unlink Error: " & Status'Img);
end if;
Status := My_VFS.Unlink ("/test1/test2/no_file");
if Status /= Status_Ok then
Semihosting.Log_Line ("Unlink Error: " & Status'Img);
end if;
Status := My_VFS.Open ("/host/tmp/test.shfs", FH);
if Status /= Status_Ok then
Semihosting.Log_Line ("Open Error: " & Status'Img);
end if;
Status := FH.Read (Data);
if Status /= Status_Ok then
Semihosting.Log_Line ("Read Error: " & Status'Img);
end if;
for C of Data loop
Semihosting.Log (Character'Val (Integer (C)));
end loop;
Semihosting.Log_New_Line;
Status := FH.Seek (10);
if Status /= Status_Ok then
Semihosting.Log_Line ("Seek Error: " & Status'Img);
end if;
Status := FH.Read (Data);
if Status /= Status_Ok then
Semihosting.Log_Line ("Read Error: " & Status'Img);
end if;
for C of Data loop
Semihosting.Log (Character'Val (Integer (C)));
end loop;
Semihosting.Log_New_Line;
Status := FH.Close;
if Status /= Status_Ok then
Semihosting.Log_Line ("Close Error: " & Status'Img);
end if;
List_Dir (My_VFS, "/");
List_Dir (My_VFS, "/test1");
List_Dir (My_VFS, "/test1/");
end Main;
|
with HAL; use HAL;
with Virtual_File_System; use Virtual_File_System;
with HAL.Filesystem; use HAL.Filesystem;
with Semihosting;
with Semihosting.Filesystem; use Semihosting.Filesystem;
with File_Block_Drivers; use File_Block_Drivers;
with Partitions; use Partitions;
procedure Main is
procedure List_Dir (FS : in out FS_Driver'Class;
Path : Pathname);
-- List files in directory
procedure List_Partitions (FS : in out FS_Driver'Class;
Path_To_Disk_Image : Pathname);
-- List partition in a disk file
--------------
-- List_Dir --
--------------
procedure List_Dir (FS : in out FS_Driver'Class; Path : Pathname) is
Status : Status_Kind;
DH : Directory_Handle_Ref;
begin
Status := FS.Open_Directory (Path, DH);
if Status /= Status_Ok then
Semihosting.Log_Line ("Open Directory '" & Path & "' Error: " & Status'Img);
else
declare
Ent : Directory_Entry;
Index : Positive := 1;
begin
Semihosting.Log_Line ("Listing '" & Path & "' content:");
loop
Status := DH.Read_Entry (Index, Ent);
if Status = Status_Ok then
Semihosting.Log_Line (" - '" & DH.Entry_Name (Index) & "'");
Semihosting.Log_Line (" Kind: " & Ent.Entry_Type'Img);
else
exit;
end if;
Index := Index + 1;
end loop;
end;
end if;
end List_Dir;
---------------------
-- List_Partitions --
---------------------
procedure List_Partitions (FS : in out FS_Driver'Class;
Path_To_Disk_Image : Pathname)
is
File : File_Handle_Ref;
begin
if FS.Open (Path_To_Disk_Image, File) /= Status_Ok then
Semihosting.Log_Line ("Cannot open disk image '" &
Path_To_Disk_Image & "'");
return;
end if;
declare
Disk : aliased File_Block_Driver (File);
Nbr : Natural;
P_Entry : Partition_Entry;
begin
Nbr := Number_Of_Partitions (Disk'Unchecked_Access);
Semihosting.Log_Line ("Disk '" & Path_To_Disk_Image & "' has " &
Nbr'Img & " parition(s)");
for Id in 1 .. Nbr loop
if Get_Partition_Entry (Disk'Unchecked_Access,
Id,
P_Entry) /= Status_Ok
then
Semihosting.Log_Line ("Cannot read partition :" & Id'Img);
else
Semihosting.Log_Line (" - partition :" & Id'Img);
Semihosting.Log_Line (" Status:" & P_Entry.Status'Img);
Semihosting.Log_Line (" Kind: " & P_Entry.Kind'Img);
Semihosting.Log_Line (" LBA: " & P_Entry.First_Sector_LBA'Img);
Semihosting.Log_Line (" Number of sectors: " & P_Entry.Number_Of_Sectors'Img);
end if;
end loop;
end;
end List_Partitions;
My_VFS : VFS;
My_VFS2 : aliased VFS;
My_VFS3 : aliased VFS;
My_SHFS : aliased SHFS;
Status : Status_Kind;
FH : File_Handle_Ref;
Data : Byte_Array (1 .. 10);
begin
-- Mount My_VFS2 in My_VFS1
Status := My_VFS.Mount (Path => "vfs2",
Filesystem => My_VFS2'Unchecked_Access);
if Status /= Status_Ok then
Semihosting.Log_Line ("Mount Error: " & Status'Img);
end if;
-- Mount My_VFS3 in My_VFS2
Status := My_VFS2.Mount (Path => "vfs3",
Filesystem => My_VFS3'Unchecked_Access);
if Status /= Status_Ok then
Semihosting.Log_Line ("Mount Error: " & Status'Img);
end if;
-- Mount semi-hosting filesystem in My_VFS1
Status := My_VFS.Mount (Path => "host",
Filesystem => My_SHFS'Unchecked_Access);
if Status /= Status_Ok then
Semihosting.Log_Line ("Mount Error: " & Status'Img);
end if;
-- List all partitions of a disk image on the host
List_Partitions (My_VFS, "/host/tmp/disk_8_partitions.img");
-- Try to unlink a file that doesn't exist in My_VFS2
Status := My_VFS.Unlink ("/vfs2/no_file");
if Status /= Status_Ok then
Semihosting.Log_Line ("Unlink Error: " & Status'Img);
end if;
-- Try to unlink a file that doesn't exist in My_VFS3
Status := My_VFS.Unlink ("/vfs2/vfs3/no_file");
if Status /= Status_Ok then
Semihosting.Log_Line ("Unlink Error: " & Status'Img);
end if;
-- Open a file on the host
Status := My_VFS.Open ("/host/tmp/test.shfs", FH);
if Status /= Status_Ok then
Semihosting.Log_Line ("Open Error: " & Status'Img);
end if;
-- Read the first 10 characters
Status := FH.Read (Data);
if Status /= Status_Ok then
Semihosting.Log_Line ("Read Error: " & Status'Img);
end if;
for C of Data loop
Semihosting.Log (Character'Val (Integer (C)));
end loop;
Semihosting.Log_New_Line;
-- Move file cursor
Status := FH.Seek (10);
if Status /= Status_Ok then
Semihosting.Log_Line ("Seek Error: " & Status'Img);
end if;
-- Read 10 characters again
Status := FH.Read (Data);
if Status /= Status_Ok then
Semihosting.Log_Line ("Read Error: " & Status'Img);
end if;
for C of Data loop
Semihosting.Log (Character'Val (Integer (C)));
end loop;
Semihosting.Log_New_Line;
Status := FH.Close;
if Status /= Status_Ok then
Semihosting.Log_Line ("Close Error: " & Status'Img);
end if;
-- Test directory listing
List_Dir (My_VFS, "/");
List_Dir (My_VFS, "/vfs2");
List_Dir (My_VFS, "/vfs2/");
end Main;
|
Add a few comments
|
examples/filesystem: Add a few comments
|
Ada
|
bsd-3-clause
|
lambourg/Ada_Drivers_Library,AdaCore/Ada_Drivers_Library,simonjwright/Ada_Drivers_Library,Fabien-Chouteau/Ada_Drivers_Library,Fabien-Chouteau/Ada_Drivers_Library,ellamosi/Ada_BMP_Library,simonjwright/Ada_Drivers_Library,AdaCore/Ada_Drivers_Library
|
daf1f0167c92b35c7bfd9ea667ca37fd5849b5e6
|
src/sys/serialize/xml/util-serialize-io-xml.ads
|
src/sys/serialize/xml/util-serialize-io-xml.ads
|
-----------------------------------------------------------------------
-- util-serialize-io-xml -- XML Serialization Driver
-- Copyright (C) 2011, 2012, 2016, 2017, 2020 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Sax.Exceptions;
with Sax.Locators;
with Sax.Readers;
with Sax.Attributes;
with Unicode.CES;
with Input_Sources;
with Ada.Streams;
with Ada.Strings.Unbounded;
with Util.Streams.Buffered;
with Util.Streams.Texts;
package Util.Serialize.IO.XML is
Parse_Error : exception;
type Parser is new Serialize.IO.Parser with private;
-- Parse the stream using the JSON parser.
procedure Parse (Handler : in out Parser;
Stream : in out Util.Streams.Buffered.Input_Buffer_Stream'Class;
Sink : in out Reader'Class);
-- Set the XHTML reader to ignore or not the white spaces.
-- When set to True, the ignorable white spaces will not be kept.
procedure Set_Ignore_White_Spaces (Reader : in out Parser;
Value : in Boolean);
-- Set the XHTML reader to ignore empty lines.
procedure Set_Ignore_Empty_Lines (Reader : in out Parser;
Value : in Boolean);
-- Get the current location (file and line) to report an error message.
function Get_Location (Handler : in Parser) return String;
type Xhtml_Reader is new Sax.Readers.Reader with private;
-- ------------------------------
-- XML Output Stream
-- ------------------------------
-- The <b>Output_Stream</b> provides methods for creating an XML output stream.
-- The stream object takes care of the XML escape rules.
type Output_Stream is limited new Util.Serialize.IO.Output_Stream with private;
-- Set the target output stream.
procedure Initialize (Stream : in out Output_Stream;
Output : in Util.Streams.Texts.Print_Stream_Access);
-- Flush the buffer (if any) to the sink.
overriding
procedure Flush (Stream : in out Output_Stream);
-- Close the sink.
overriding
procedure Close (Stream : in out Output_Stream);
-- Write the buffer array to the output stream.
overriding
procedure Write (Stream : in out Output_Stream;
Buffer : in Ada.Streams.Stream_Element_Array);
-- Write a character on the response stream and escape that character as necessary.
procedure Write_Escape (Stream : in out Output_Stream'Class;
Char : in Wide_Wide_Character);
-- Write the value as a XML string. Special characters are escaped using the XML
-- escape rules.
procedure Write_String (Stream : in out Output_Stream;
Value : in String);
-- Write the value as a XML string. Special characters are escaped using the XML
-- escape rules.
procedure Write_Wide_String (Stream : in out Output_Stream;
Value : in Wide_Wide_String);
-- Write the value as a XML string. Special characters are escaped using the XML
-- escape rules.
procedure Write_String (Stream : in out Output_Stream;
Value : in Util.Beans.Objects.Object);
-- Start a new XML object.
procedure Start_Entity (Stream : in out Output_Stream;
Name : in String);
-- Terminates the current XML object.
procedure End_Entity (Stream : in out Output_Stream;
Name : in String);
-- Write the attribute name/value pair.
overriding
procedure Write_Attribute (Stream : in out Output_Stream;
Name : in String;
Value : in String);
overriding
procedure Write_Wide_Attribute (Stream : in out Output_Stream;
Name : in String;
Value : in Wide_Wide_String);
overriding
procedure Write_Attribute (Stream : in out Output_Stream;
Name : in String;
Value : in Integer);
overriding
procedure Write_Attribute (Stream : in out Output_Stream;
Name : in String;
Value : in Boolean);
-- Write a XML name/value attribute.
procedure Write_Attribute (Stream : in out Output_Stream;
Name : in String;
Value : in Util.Beans.Objects.Object);
-- Write the attribute with a null value.
overriding
procedure Write_Null_Attribute (Stream : in out Output_Stream;
Name : in String);
-- Write the entity value.
overriding
procedure Write_Entity (Stream : in out Output_Stream;
Name : in String;
Value : in String);
overriding
procedure Write_Wide_Entity (Stream : in out Output_Stream;
Name : in String;
Value : in Wide_Wide_String);
overriding
procedure Write_Entity (Stream : in out Output_Stream;
Name : in String;
Value : in Boolean);
overriding
procedure Write_Entity (Stream : in out Output_Stream;
Name : in String;
Value : in Integer);
overriding
procedure Write_Entity (Stream : in out Output_Stream;
Name : in String;
Value : in Ada.Calendar.Time);
overriding
procedure Write_Long_Entity (Stream : in out Output_Stream;
Name : in String;
Value : in Long_Long_Integer);
overriding
procedure Write_Enum_Entity (Stream : in out Output_Stream;
Name : in String;
Value : in String);
-- Write a XML name/value entity (see Write_Attribute).
overriding
procedure Write_Entity (Stream : in out Output_Stream;
Name : in String;
Value : in Util.Beans.Objects.Object);
-- Write an entity with a null value.
overriding
procedure Write_Null_Entity (Stream : in out Output_Stream;
Name : in String);
-- Starts a XML array.
overriding
procedure Start_Array (Stream : in out Output_Stream;
Name : in String);
-- Terminates a XML array.
overriding
procedure End_Array (Stream : in out Output_Stream;
Name : in String);
-- Return the location where the exception was raised.
function Get_Location (Except : Sax.Exceptions.Sax_Parse_Exception'Class)
return String;
private
overriding
procedure Warning (Handler : in out Xhtml_Reader;
Except : in Sax.Exceptions.Sax_Parse_Exception'Class);
overriding
procedure Error (Handler : in out Xhtml_Reader;
Except : in Sax.Exceptions.Sax_Parse_Exception'Class);
overriding
procedure Fatal_Error (Handler : in out Xhtml_Reader;
Except : in Sax.Exceptions.Sax_Parse_Exception'Class);
overriding
procedure Set_Document_Locator (Handler : in out Xhtml_Reader;
Loc : in out Sax.Locators.Locator);
overriding
procedure Start_Document (Handler : in out Xhtml_Reader);
overriding
procedure End_Document (Handler : in out Xhtml_Reader);
overriding
procedure Start_Prefix_Mapping (Handler : in out Xhtml_Reader;
Prefix : in Unicode.CES.Byte_Sequence;
URI : in Unicode.CES.Byte_Sequence);
overriding
procedure End_Prefix_Mapping (Handler : in out Xhtml_Reader;
Prefix : in Unicode.CES.Byte_Sequence);
overriding
procedure Start_Element (Handler : in out Xhtml_Reader;
Namespace_URI : in Unicode.CES.Byte_Sequence := "";
Local_Name : in Unicode.CES.Byte_Sequence := "";
Qname : in Unicode.CES.Byte_Sequence := "";
Atts : in Sax.Attributes.Attributes'Class);
overriding
procedure End_Element (Handler : in out Xhtml_Reader;
Namespace_URI : in Unicode.CES.Byte_Sequence := "";
Local_Name : in Unicode.CES.Byte_Sequence := "";
Qname : in Unicode.CES.Byte_Sequence := "");
overriding
procedure Characters (Handler : in out Xhtml_Reader;
Ch : in Unicode.CES.Byte_Sequence);
overriding
procedure Ignorable_Whitespace (Handler : in out Xhtml_Reader;
Ch : in Unicode.CES.Byte_Sequence);
overriding
procedure Processing_Instruction (Handler : in out Xhtml_Reader;
Target : in Unicode.CES.Byte_Sequence;
Data : in Unicode.CES.Byte_Sequence);
overriding
procedure Skipped_Entity (Handler : in out Xhtml_Reader;
Name : in Unicode.CES.Byte_Sequence);
overriding
procedure Start_Cdata (Handler : in out Xhtml_Reader);
overriding
procedure End_Cdata (Handler : in out Xhtml_Reader);
overriding
function Resolve_Entity (Handler : Xhtml_Reader;
Public_Id : Unicode.CES.Byte_Sequence;
System_Id : Unicode.CES.Byte_Sequence)
return Input_Sources.Input_Source_Access;
overriding
procedure Start_DTD (Handler : in out Xhtml_Reader;
Name : Unicode.CES.Byte_Sequence;
Public_Id : Unicode.CES.Byte_Sequence := "";
System_Id : Unicode.CES.Byte_Sequence := "");
procedure Collect_Text (Handler : in out Xhtml_Reader;
Content : Unicode.CES.Byte_Sequence);
type Xhtml_Reader is new Sax.Readers.Reader with record
Stack_Pos : Natural := 0;
Handler : access Parser'Class;
Text : Ada.Strings.Unbounded.Unbounded_String;
-- Whether white spaces can be ignored.
Ignore_White_Spaces : Boolean := True;
-- Whether empty lines should be ignored (when white spaces are kept).
Ignore_Empty_Lines : Boolean := True;
Sink : access Reader'Class;
end record;
type Parser is new Util.Serialize.IO.Parser with record
-- The SAX locator to find the current file and line number.
Locator : Sax.Locators.Locator;
Has_Pending_Char : Boolean := False;
Pending_Char : Character;
-- Whether white spaces can be ignored.
Ignore_White_Spaces : Boolean := True;
-- Whether empty lines should be ignored (when white spaces are kept).
Ignore_Empty_Lines : Boolean := True;
end record;
type Output_Stream is limited new Util.Serialize.IO.Output_Stream with record
Close_Start : Boolean := False;
Stream : Util.Streams.Texts.Print_Stream_Access;
end record;
end Util.Serialize.IO.XML;
|
-----------------------------------------------------------------------
-- util-serialize-io-xml -- XML Serialization Driver
-- Copyright (C) 2011, 2012, 2016, 2017, 2020, 2021 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Sax.Exceptions;
with Sax.Locators;
with Sax.Readers;
with Sax.Attributes;
with Unicode.CES;
with Input_Sources;
with Ada.Streams;
with Ada.Strings.Unbounded;
with Util.Streams.Buffered;
with Util.Streams.Texts;
package Util.Serialize.IO.XML is
Parse_Error : exception;
type Parser is new Serialize.IO.Parser with private;
-- Parse the stream using the JSON parser.
procedure Parse (Handler : in out Parser;
Stream : in out Util.Streams.Buffered.Input_Buffer_Stream'Class;
Sink : in out Reader'Class);
-- Set the XHTML reader to ignore or not the white spaces.
-- When set to True, the ignorable white spaces will not be kept.
procedure Set_Ignore_White_Spaces (Reader : in out Parser;
Value : in Boolean);
-- Set the XHTML reader to ignore empty lines.
procedure Set_Ignore_Empty_Lines (Reader : in out Parser;
Value : in Boolean);
-- Get the current location (file and line) to report an error message.
function Get_Location (Handler : in Parser) return String;
type Xhtml_Reader is new Sax.Readers.Reader with private;
-- ------------------------------
-- XML Output Stream
-- ------------------------------
-- The <b>Output_Stream</b> provides methods for creating an XML output stream.
-- The stream object takes care of the XML escape rules.
type Output_Stream is limited new Util.Serialize.IO.Output_Stream with private;
-- Set the target output stream.
procedure Initialize (Stream : in out Output_Stream;
Output : in Util.Streams.Texts.Print_Stream_Access);
-- Flush the buffer (if any) to the sink.
overriding
procedure Flush (Stream : in out Output_Stream);
-- Close the sink.
overriding
procedure Close (Stream : in out Output_Stream);
-- Write the buffer array to the output stream.
overriding
procedure Write (Stream : in out Output_Stream;
Buffer : in Ada.Streams.Stream_Element_Array);
-- Write a character on the response stream and escape that character as necessary.
procedure Write_Escape (Stream : in out Output_Stream'Class;
Char : in Wide_Wide_Character);
-- Write the value as a XML string. Special characters are escaped using the XML
-- escape rules.
procedure Write_String (Stream : in out Output_Stream;
Value : in String);
-- Write the value as a XML string. Special characters are escaped using the XML
-- escape rules.
procedure Write_Wide_String (Stream : in out Output_Stream;
Value : in Wide_Wide_String);
-- Write the value as a XML string. Special characters are escaped using the XML
-- escape rules.
procedure Write_String (Stream : in out Output_Stream;
Value : in Util.Beans.Objects.Object);
-- Start a new XML object.
procedure Start_Entity (Stream : in out Output_Stream;
Name : in String);
-- Terminates the current XML object.
procedure End_Entity (Stream : in out Output_Stream;
Name : in String);
-- Write the attribute name/value pair.
overriding
procedure Write_Attribute (Stream : in out Output_Stream;
Name : in String;
Value : in String);
overriding
procedure Write_Wide_Attribute (Stream : in out Output_Stream;
Name : in String;
Value : in Wide_Wide_String);
overriding
procedure Write_Attribute (Stream : in out Output_Stream;
Name : in String;
Value : in Integer);
overriding
procedure Write_Attribute (Stream : in out Output_Stream;
Name : in String;
Value : in Boolean);
-- Write a XML name/value attribute.
procedure Write_Attribute (Stream : in out Output_Stream;
Name : in String;
Value : in Util.Beans.Objects.Object);
-- Write the attribute with a null value.
overriding
procedure Write_Null_Attribute (Stream : in out Output_Stream;
Name : in String);
-- Write the entity value.
overriding
procedure Write_Entity (Stream : in out Output_Stream;
Name : in String;
Value : in String);
overriding
procedure Write_Wide_Entity (Stream : in out Output_Stream;
Name : in String;
Value : in Wide_Wide_String);
overriding
procedure Write_Entity (Stream : in out Output_Stream;
Name : in String;
Value : in Boolean);
overriding
procedure Write_Entity (Stream : in out Output_Stream;
Name : in String;
Value : in Integer);
overriding
procedure Write_Entity (Stream : in out Output_Stream;
Name : in String;
Value : in Ada.Calendar.Time);
overriding
procedure Write_Long_Entity (Stream : in out Output_Stream;
Name : in String;
Value : in Long_Long_Integer);
overriding
procedure Write_Enum_Entity (Stream : in out Output_Stream;
Name : in String;
Value : in String);
-- Write a XML name/value entity (see Write_Attribute).
overriding
procedure Write_Entity (Stream : in out Output_Stream;
Name : in String;
Value : in Util.Beans.Objects.Object);
-- Write an entity with a null value.
overriding
procedure Write_Null_Entity (Stream : in out Output_Stream;
Name : in String);
-- Starts a XML array.
overriding
procedure Start_Array (Stream : in out Output_Stream;
Name : in String);
-- Terminates a XML array.
overriding
procedure End_Array (Stream : in out Output_Stream;
Name : in String);
-- Set the indentation level when writing XML entities.
procedure Set_Indentation (Stream : in out Output_Stream;
Count : in Natural);
-- Return the location where the exception was raised.
function Get_Location (Except : Sax.Exceptions.Sax_Parse_Exception'Class)
return String;
private
overriding
procedure Warning (Handler : in out Xhtml_Reader;
Except : in Sax.Exceptions.Sax_Parse_Exception'Class);
overriding
procedure Error (Handler : in out Xhtml_Reader;
Except : in Sax.Exceptions.Sax_Parse_Exception'Class);
overriding
procedure Fatal_Error (Handler : in out Xhtml_Reader;
Except : in Sax.Exceptions.Sax_Parse_Exception'Class);
overriding
procedure Set_Document_Locator (Handler : in out Xhtml_Reader;
Loc : in out Sax.Locators.Locator);
overriding
procedure Start_Document (Handler : in out Xhtml_Reader);
overriding
procedure End_Document (Handler : in out Xhtml_Reader);
overriding
procedure Start_Prefix_Mapping (Handler : in out Xhtml_Reader;
Prefix : in Unicode.CES.Byte_Sequence;
URI : in Unicode.CES.Byte_Sequence);
overriding
procedure End_Prefix_Mapping (Handler : in out Xhtml_Reader;
Prefix : in Unicode.CES.Byte_Sequence);
overriding
procedure Start_Element (Handler : in out Xhtml_Reader;
Namespace_URI : in Unicode.CES.Byte_Sequence := "";
Local_Name : in Unicode.CES.Byte_Sequence := "";
Qname : in Unicode.CES.Byte_Sequence := "";
Atts : in Sax.Attributes.Attributes'Class);
overriding
procedure End_Element (Handler : in out Xhtml_Reader;
Namespace_URI : in Unicode.CES.Byte_Sequence := "";
Local_Name : in Unicode.CES.Byte_Sequence := "";
Qname : in Unicode.CES.Byte_Sequence := "");
overriding
procedure Characters (Handler : in out Xhtml_Reader;
Ch : in Unicode.CES.Byte_Sequence);
overriding
procedure Ignorable_Whitespace (Handler : in out Xhtml_Reader;
Ch : in Unicode.CES.Byte_Sequence);
overriding
procedure Processing_Instruction (Handler : in out Xhtml_Reader;
Target : in Unicode.CES.Byte_Sequence;
Data : in Unicode.CES.Byte_Sequence);
overriding
procedure Skipped_Entity (Handler : in out Xhtml_Reader;
Name : in Unicode.CES.Byte_Sequence);
overriding
procedure Start_Cdata (Handler : in out Xhtml_Reader);
overriding
procedure End_Cdata (Handler : in out Xhtml_Reader);
overriding
function Resolve_Entity (Handler : Xhtml_Reader;
Public_Id : Unicode.CES.Byte_Sequence;
System_Id : Unicode.CES.Byte_Sequence)
return Input_Sources.Input_Source_Access;
overriding
procedure Start_DTD (Handler : in out Xhtml_Reader;
Name : Unicode.CES.Byte_Sequence;
Public_Id : Unicode.CES.Byte_Sequence := "";
System_Id : Unicode.CES.Byte_Sequence := "");
procedure Collect_Text (Handler : in out Xhtml_Reader;
Content : Unicode.CES.Byte_Sequence);
type Xhtml_Reader is new Sax.Readers.Reader with record
Stack_Pos : Natural := 0;
Handler : access Parser'Class;
Text : Ada.Strings.Unbounded.Unbounded_String;
-- Whether white spaces can be ignored.
Ignore_White_Spaces : Boolean := True;
-- Whether empty lines should be ignored (when white spaces are kept).
Ignore_Empty_Lines : Boolean := True;
Sink : access Reader'Class;
end record;
type Parser is new Util.Serialize.IO.Parser with record
-- The SAX locator to find the current file and line number.
Locator : Sax.Locators.Locator;
Has_Pending_Char : Boolean := False;
Pending_Char : Character;
-- Whether white spaces can be ignored.
Ignore_White_Spaces : Boolean := True;
-- Whether empty lines should be ignored (when white spaces are kept).
Ignore_Empty_Lines : Boolean := True;
end record;
type Output_Stream is limited new Util.Serialize.IO.Output_Stream with record
Close_Start : Boolean := False;
Is_Closed : Boolean := False;
Level : Natural := 0;
Indent : Natural := 0;
Stream : Util.Streams.Texts.Print_Stream_Access;
end record;
end Util.Serialize.IO.XML;
|
Declare the Set_Indentation procedure
|
Declare the Set_Indentation procedure
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
d5c3ad38dfbf0a5745bad22a56fb3ccc68d0376e
|
src/wiki-streams-html.adb
|
src/wiki-streams-html.adb
|
-----------------------------------------------------------------------
-- wiki-streams-html -- Wiki HTML output stream
-- Copyright (C) 2011, 2012, 2013, 2015, 2016 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
package body Wiki.Streams.Html is
type Unicode_Char is mod 2**31;
-- ------------------------------
-- Write a character on the response stream and escape that character as necessary.
-- ------------------------------
procedure Write_Escape (Stream : in out Html_Output_Stream'Class;
Char : in Wiki.Strings.WChar) is
Code : constant Unicode_Char := Wiki.Strings.WChar'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;
-- ------------------------------
-- Write an XML attribute within an XML element.
-- The attribute value is escaped according to the XML escape rules.
-- ------------------------------
procedure Write_Attribute (Writer : in out Html_Output_Stream'Class;
Name : in String;
Content : in String) is
begin
Writer.Write_Wide_Attribute (Name, Wiki.Strings.To_WString (Content));
end Write_Attribute;
end Wiki.Streams.Html;
|
-----------------------------------------------------------------------
-- wiki-streams-html -- Wiki HTML output stream
-- Copyright (C) 2011, 2012, 2013, 2015, 2016 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
package body Wiki.Streams.Html is
type Unicode_Char is mod 2**31;
-- Write the string to the stream.
procedure Write_String (Stream : in out Html_Output_Stream'Class;
Content : in String);
-- ------------------------------
-- Write a character on the response stream and escape that character as necessary.
-- ------------------------------
procedure Write_Escape (Stream : in out Html_Output_Stream'Class;
Char : in Wiki.Strings.WChar) is
Code : constant Unicode_Char := Wiki.Strings.WChar'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;
-- ------------------------------
-- Write a string on the response stream and escape the characters as necessary.
-- ------------------------------
procedure Write_Escape (Stream : in out Html_Output_Stream'Class;
Content : in Wiki.Strings.WString) is
begin
for I in Content'Range loop
Stream.Write_Escape (Content (I));
end loop;
end Write_Escape;
-- ------------------------------
-- Write the string to the stream.
-- ------------------------------
procedure Write_String (Stream : in out Html_Output_Stream'Class;
Content : in String) is
begin
for I in Content'Range loop
Stream.Write (Wiki.Strings.To_WChar (Content (I)));
end loop;
end Write_String;
-- ------------------------------
-- Write an XML attribute within an XML element.
-- The attribute value is escaped according to the XML escape rules.
-- ------------------------------
procedure Write_Escape_Attribute (Stream : in out Html_Output_Stream'Class;
Name : in String;
Content : in Wiki.Strings.WString) is
begin
Stream.Write (' ');
Stream.Write_String (Name);
Stream.Write ('=');
Stream.Write ('"');
for I in Content'Range loop
declare
C : constant Wiki.Strings.WChar := Content (I);
begin
if C = '"' then
Stream.Write (""");
else
Stream.Write_Escape (C);
end if;
end;
end loop;
Stream.Write ('"');
end Write_Escape_Attribute;
-- ------------------------------
-- Write an XML attribute within an XML element.
-- The attribute value is escaped according to the XML escape rules.
-- ------------------------------
procedure Write_Attribute (Writer : in out Html_Output_Stream'Class;
Name : in String;
Content : in String) is
begin
Writer.Write_Wide_Attribute (Name, Wiki.Strings.To_WString (Content));
end Write_Attribute;
end Wiki.Streams.Html;
|
Implement Write_Escape and Write_Escape_Attribute procedures
|
Implement Write_Escape and Write_Escape_Attribute procedures
|
Ada
|
apache-2.0
|
stcarrez/ada-wiki,stcarrez/ada-wiki
|
95c41f8da52264d39de145072d4052c52a83bbeb
|
src/asf-applications.ads
|
src/asf-applications.ads
|
-----------------------------------------------------------------------
-- applications -- Ada Web Application
-- Copyright (C) 2009, 2010, 2013 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Strings;
with Util.Properties;
package ASF.Applications is
use Util.Properties;
type Config is new Util.Properties.Manager with private;
type Config_Param is private;
-- Directory where the facelet files are stored.
VIEW_DIR_PARAM : constant Config_Param;
VIEW_DIR : aliased constant String := "view.dir";
DEF_VIEW_DIR : aliased constant String := "web";
-- Extension used by requests
VIEW_EXT_PARAM : constant Config_Param;
VIEW_EXT : aliased constant String := "view.ext";
DEF_VIEW_EXT : aliased constant String := "";
-- Extension used by facelet files
VIEW_FILE_EXT_PARAM : constant Config_Param;
VIEW_FILE_EXT : aliased constant String := "view.file_ext";
DEF_VIEW_FILE_EXT : aliased constant String := ".xhtml";
-- Whether white spaces in XHTML files are ignored.
VIEW_IGNORE_WHITE_SPACES_PARAM : constant Config_Param;
VIEW_IGNORE_WHITE_SPACES : aliased constant String := "view.ignore_white_spaces";
DEF_IGNORE_WHITE_SPACES : aliased constant String := "false";
-- Whether empty lines in XHTML files are ignored.
VIEW_IGNORE_EMPTY_LINES_PARAM : constant Config_Param;
VIEW_IGNORE_EMPTY_LINES : aliased constant String := "view.ignore_empty_lines";
DEF_IGNORE_EMPTY_LINES : aliased constant String := "false";
-- Whether the unknown tags are escaped in the output
VIEW_ESCAPE_UNKNOWN_TAGS_PARAM : constant Config_Param;
VIEW_ESCAPE_UNKNOWN_TAGS : aliased constant String := "view.escape_unknown_tags";
DEF_ESCAPE_UNKNOWN_TAGS : aliased constant String := "false";
-- Extensions used by static pages
VIEW_STATIC_EXT_PARAM : constant Config_Param;
VIEW_STATIC_EXT : aliased constant String := "view.static.ext";
DEF_STATIC_EXT : aliased constant String := "";
-- Directories which contain static pages
VIEW_STATIC_DIR_PARAM : constant Config_Param;
VIEW_STATIC_DIR : aliased constant String := "view.static.dir";
DEF_STATIC_DIR : aliased constant String := "css,js,scripts,themes";
-- The 404 error page to render
ERROR_404_PARAM : constant Config_Param;
ERROR_404_PAGE : aliased constant String := "view.error.404";
DEF_ERROR_404 : aliased constant String := "errors/404";
-- The 500 error page to render
ERROR_500_PARAM : constant Config_Param;
ERROR_500_PAGE : aliased constant String := "view.error.500";
DEF_ERROR_500 : aliased constant String := "errors/500";
-- Get the configuration parameter;
function Get (Self : Config;
Param : Config_Param) return String;
-- Get the configuration parameter;
function Get (Self : Config;
Param : Config_Param) return Boolean;
-- Create the configuration parameter definition instance.
generic
-- The parameter name.
Name : in String;
-- The default value.
Default : in String;
package Parameter is
-- Returns the configuration parameter.
function P return Config_Param;
pragma Inline_Always (P);
PARAM_NAME : aliased constant String := Name;
PARAM_VALUE : aliased constant String := Default;
end Parameter;
private
type Config_Param is record
Name : Util.Strings.Name_Access;
Default : Util.Strings.Name_Access;
end record;
subtype P is Config_Param;
VIEW_DIR_PARAM : constant Config_Param := P '(Name => VIEW_DIR'Access,
Default => DEF_VIEW_DIR'Access);
VIEW_EXT_PARAM : constant Config_Param := P '(Name => VIEW_EXT'Access,
Default => DEF_VIEW_EXT'Access);
VIEW_FILE_EXT_PARAM : constant Config_Param := P '(Name => VIEW_FILE_EXT'Access,
Default => DEF_VIEW_FILE_EXT'Access);
VIEW_IGNORE_WHITE_SPACES_PARAM : constant Config_Param
:= P '(Name => VIEW_IGNORE_WHITE_SPACES'Access,
Default => DEF_IGNORE_WHITE_SPACES'Access);
VIEW_IGNORE_EMPTY_LINES_PARAM : constant Config_Param
:= P '(Name => VIEW_IGNORE_EMPTY_LINES'Access,
Default => DEF_IGNORE_EMPTY_LINES'Access);
VIEW_ESCAPE_UNKNOWN_TAGS_PARAM : constant Config_Param
:= P '(Name => VIEW_ESCAPE_UNKNOWN_TAGS'Access,
Default => DEF_ESCAPE_UNKNOWN_TAGS'Access);
VIEW_STATIC_EXT_PARAM : constant Config_Param := P '(Name => VIEW_STATIC_EXT'Access,
Default => DEF_STATIC_EXT'Access);
VIEW_STATIC_DIR_PARAM : constant Config_Param := P '(Name => VIEW_STATIC_DIR'Access,
Default => DEF_STATIC_DIR'Access);
ERROR_404_PARAM : constant Config_Param := P '(Name => ERROR_404_PAGE'Access,
Default => DEF_ERROR_404'Access);
ERROR_500_PARAM : constant Config_Param := P '(Name => ERROR_500_PAGE'Access,
Default => DEF_ERROR_500'Access);
type Config is new Util.Properties.Manager with null record;
end ASF.Applications;
|
-----------------------------------------------------------------------
-- applications -- Ada Web Application
-- Copyright (C) 2009, 2010, 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.Strings.Unbounded;
with Util.Strings;
with Util.Properties;
package ASF.Applications is
use Util.Properties;
type Config is new Util.Properties.Manager with private;
type Config_Param is private;
-- Directory where the facelet files are stored.
VIEW_DIR_PARAM : constant Config_Param;
VIEW_DIR : aliased constant String := "view.dir";
DEF_VIEW_DIR : aliased constant String := "web";
-- Extension used by requests
VIEW_EXT_PARAM : constant Config_Param;
VIEW_EXT : aliased constant String := "view.ext";
DEF_VIEW_EXT : aliased constant String := "";
-- Extension used by facelet files
VIEW_FILE_EXT_PARAM : constant Config_Param;
VIEW_FILE_EXT : aliased constant String := "view.file_ext";
DEF_VIEW_FILE_EXT : aliased constant String := ".xhtml";
-- Whether white spaces in XHTML files are ignored.
VIEW_IGNORE_WHITE_SPACES_PARAM : constant Config_Param;
VIEW_IGNORE_WHITE_SPACES : aliased constant String := "view.ignore_white_spaces";
DEF_IGNORE_WHITE_SPACES : aliased constant String := "false";
-- Whether empty lines in XHTML files are ignored.
VIEW_IGNORE_EMPTY_LINES_PARAM : constant Config_Param;
VIEW_IGNORE_EMPTY_LINES : aliased constant String := "view.ignore_empty_lines";
DEF_IGNORE_EMPTY_LINES : aliased constant String := "false";
-- Whether the unknown tags are escaped in the output
VIEW_ESCAPE_UNKNOWN_TAGS_PARAM : constant Config_Param;
VIEW_ESCAPE_UNKNOWN_TAGS : aliased constant String := "view.escape_unknown_tags";
DEF_ESCAPE_UNKNOWN_TAGS : aliased constant String := "false";
-- Extensions used by static pages
VIEW_STATIC_EXT_PARAM : constant Config_Param;
VIEW_STATIC_EXT : aliased constant String := "view.static.ext";
DEF_STATIC_EXT : aliased constant String := "";
-- Directories which contain static pages
VIEW_STATIC_DIR_PARAM : constant Config_Param;
VIEW_STATIC_DIR : aliased constant String := "view.static.dir";
DEF_STATIC_DIR : aliased constant String := "css,js,scripts,themes";
-- The 404 error page to render
ERROR_404_PARAM : constant Config_Param;
ERROR_404_PAGE : aliased constant String := "view.error.404";
DEF_ERROR_404 : aliased constant String := "errors/404";
-- The 500 error page to render
ERROR_500_PARAM : constant Config_Param;
ERROR_500_PAGE : aliased constant String := "view.error.500";
DEF_ERROR_500 : aliased constant String := "errors/500";
-- Get the configuration parameter;
function Get (Self : Config;
Param : Config_Param) return String;
-- Get the configuration parameter;
function Get (Self : Config;
Param : Config_Param) return Ada.Strings.Unbounded.Unbounded_String;
-- Get the configuration parameter;
function Get (Self : Config;
Param : Config_Param) return Boolean;
-- Create the configuration parameter definition instance.
generic
-- The parameter name.
Name : in String;
-- The default value.
Default : in String;
package Parameter is
-- Returns the configuration parameter.
function P return Config_Param;
pragma Inline_Always (P);
PARAM_NAME : aliased constant String := Name;
PARAM_VALUE : aliased constant String := Default;
end Parameter;
private
type Config_Param is record
Name : Util.Strings.Name_Access;
Default : Util.Strings.Name_Access;
end record;
subtype P is Config_Param;
VIEW_DIR_PARAM : constant Config_Param := P '(Name => VIEW_DIR'Access,
Default => DEF_VIEW_DIR'Access);
VIEW_EXT_PARAM : constant Config_Param := P '(Name => VIEW_EXT'Access,
Default => DEF_VIEW_EXT'Access);
VIEW_FILE_EXT_PARAM : constant Config_Param := P '(Name => VIEW_FILE_EXT'Access,
Default => DEF_VIEW_FILE_EXT'Access);
VIEW_IGNORE_WHITE_SPACES_PARAM : constant Config_Param
:= P '(Name => VIEW_IGNORE_WHITE_SPACES'Access,
Default => DEF_IGNORE_WHITE_SPACES'Access);
VIEW_IGNORE_EMPTY_LINES_PARAM : constant Config_Param
:= P '(Name => VIEW_IGNORE_EMPTY_LINES'Access,
Default => DEF_IGNORE_EMPTY_LINES'Access);
VIEW_ESCAPE_UNKNOWN_TAGS_PARAM : constant Config_Param
:= P '(Name => VIEW_ESCAPE_UNKNOWN_TAGS'Access,
Default => DEF_ESCAPE_UNKNOWN_TAGS'Access);
VIEW_STATIC_EXT_PARAM : constant Config_Param := P '(Name => VIEW_STATIC_EXT'Access,
Default => DEF_STATIC_EXT'Access);
VIEW_STATIC_DIR_PARAM : constant Config_Param := P '(Name => VIEW_STATIC_DIR'Access,
Default => DEF_STATIC_DIR'Access);
ERROR_404_PARAM : constant Config_Param := P '(Name => ERROR_404_PAGE'Access,
Default => DEF_ERROR_404'Access);
ERROR_500_PARAM : constant Config_Param := P '(Name => ERROR_500_PAGE'Access,
Default => DEF_ERROR_500'Access);
type Config is new Util.Properties.Manager with null record;
end ASF.Applications;
|
Declare a new Get function that returns an Unbounded_String
|
Declare a new Get function that returns an Unbounded_String
|
Ada
|
apache-2.0
|
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
|
10f08f7a91cddc1bca00e105b61a8e72d6cdff6c
|
src/gen-model-tables.adb
|
src/gen-model-tables.adb
|
-----------------------------------------------------------------------
-- gen-model-tables -- Database table model representation
-- Copyright (C) 2009, 2010, 2011, 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings;
with Util.Strings;
package body Gen.Model.Tables is
-- ------------------------------
-- 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 : Column_Definition;
Name : String) return Util.Beans.Objects.Object is
use type Gen.Model.Mappings.Mapping_Definition_Access;
begin
if Name = "type" and From.Type_Mapping /= null then
declare
Bean : constant Util.Beans.Basic.Readonly_Bean_Access := From.Type_Mapping.all'Access;
begin
return Util.Beans.Objects.To_Object (Bean, Util.Beans.Objects.STATIC);
end;
elsif Name = "type" then
return Util.Beans.Objects.To_Object (From.Type_Name);
elsif Name = "index" then
return Util.Beans.Objects.To_Object (From.Number);
elsif Name = "isUnique" then
return Util.Beans.Objects.To_Object (From.Unique);
elsif Name = "isNull" then
return Util.Beans.Objects.To_Object (not From.Not_Null);
elsif Name = "isInserted" then
return Util.Beans.Objects.To_Object (From.Is_Inserted);
elsif Name = "isUpdated" then
return Util.Beans.Objects.To_Object (From.Is_Updated);
elsif Name = "sqlType" then
return Util.Beans.Objects.To_Object (From.Sql_Type);
elsif Name = "sqlName" then
return Util.Beans.Objects.To_Object (From.Sql_Name);
elsif Name = "isVersion" then
return Util.Beans.Objects.To_Object (From.Is_Version);
elsif Name = "isReadable" then
return Util.Beans.Objects.To_Object (From.Is_Readable);
elsif Name = "isPrimaryKey" then
return Util.Beans.Objects.To_Object (From.Is_Key);
elsif Name = "isPrimitiveType" then
return Util.Beans.Objects.To_Object (From.Is_Basic_Type);
elsif Name = "generator" then
return From.Generator;
else
return Definition (From).Get_Value (Name);
end if;
end Get_Value;
-- ------------------------------
-- Returns true if the column type is a basic type.
-- ------------------------------
function Is_Basic_Type (From : Column_Definition) return Boolean is
use type Gen.Model.Mappings.Mapping_Definition_Access;
use type Gen.Model.Mappings.Basic_Type;
Name : constant String := To_String (From.Type_Name);
begin
if From.Type_Mapping /= null then
return From.Type_Mapping.Kind /= Gen.Model.Mappings.T_BLOB;
end if;
return Name = "int" or Name = "String"
or Name = "ADO.Identifier" or Name = "Timestamp"
or Name = "Integer"
or Name = "long" or Name = "Long" or Name = "Date" or Name = "Time";
end Is_Basic_Type;
-- ------------------------------
-- Returns the column type.
-- ------------------------------
function Get_Type (From : Column_Definition) return String is
use type Gen.Model.Mappings.Mapping_Definition_Access;
begin
if From.Type_Mapping /= null then
return To_String (From.Type_Mapping.Target);
else
return To_String (From.Type_Name);
end if;
end Get_Type;
-- ------------------------------
-- Prepare the generation of the model.
-- ------------------------------
overriding
procedure Prepare (O : in out Column_Definition) is
begin
O.Type_Mapping := Gen.Model.Mappings.Find_Type (O.Type_Name);
if Length (O.Sql_Type) = 0 then
end if;
end Prepare;
-- ------------------------------
-- 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 : Association_Definition;
Name : String) return Util.Beans.Objects.Object is
begin
return Column_Definition (From).Get_Value (Name);
end Get_Value;
-- ------------------------------
-- Initialize the table definition instance.
-- ------------------------------
overriding
procedure Initialize (O : in out Table_Definition) is
begin
O.Members_Bean := Util.Beans.Objects.To_Object (O.Members'Unchecked_Access,
Util.Beans.Objects.STATIC);
end Initialize;
-- ------------------------------
-- Create a table with the given name.
-- ------------------------------
function Create_Table (Name : in Unbounded_String) return Table_Definition_Access is
Table : constant Table_Definition_Access := new Table_Definition;
begin
Table.Name := Name;
declare
Pos : constant Natural := Index (Table.Name, ".", Ada.Strings.Backward);
begin
if Pos > 0 then
Table.Pkg_Name := Unbounded_Slice (Table.Name, 1, Pos - 1);
Table.Type_Name := Unbounded_Slice (Table.Name, Pos + 1, Length (Table.Name));
else
Table.Pkg_Name := To_Unbounded_String ("ADO");
Table.Type_Name := Table.Name;
end if;
end;
return Table;
end Create_Table;
-- ------------------------------
-- Create a table column with the given name and add it to the table.
-- ------------------------------
procedure Add_Column (Table : in out Table_Definition;
Name : in Unbounded_String;
Column : out Column_Definition_Access) is
begin
Column := new Column_Definition;
Column.Name := Name;
Column.Sql_Name := Name;
Column.Number := Table.Members.Get_Count;
Table.Members.Append (Column);
if Name = "version" then
Table.Version_Column := Column;
Column.Is_Version := True;
Column.Is_Updated := False;
Column.Is_Inserted := False;
elsif Name = "id" then
Table.Id_Column := Column;
Column.Is_Key := True;
end if;
end Add_Column;
-- ------------------------------
-- 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 Table_Definition;
Name : in String) return Util.Beans.Objects.Object is
begin
if Name = "members" or Name = "columns" then
return From.Members_Bean;
elsif Name = "id" and From.Id_Column /= null then
declare
Bean : constant Util.Beans.Basic.Readonly_Bean_Access := From.Id_Column.all'Access;
begin
return Util.Beans.Objects.To_Object (Bean, Util.Beans.Objects.STATIC);
end;
elsif Name = "version" and From.Version_Column /= null then
declare
Bean : constant Util.Beans.Basic.Readonly_Bean_Access
:= From.Version_Column.all'Unchecked_Access;
begin
return Util.Beans.Objects.To_Object (Bean, Util.Beans.Objects.STATIC);
end;
elsif Name = "hasAssociations" then
return Util.Beans.Objects.To_Object (From.Has_Associations);
elsif Name = "type" then
return Util.Beans.Objects.To_Object (From.Type_Name);
elsif Name = "table" then
return Util.Beans.Objects.To_Object (From.Name);
else
return Definition (From).Get_Value (Name);
end if;
end Get_Value;
-- ------------------------------
-- Prepare the generation of the model.
-- ------------------------------
overriding
procedure Prepare (O : in out Table_Definition) is
Iter : Column_List.Cursor := O.Members.First;
begin
while Column_List.Has_Element (Iter) loop
Column_List.Element (Iter).Prepare;
Column_List.Next (Iter);
end loop;
end Prepare;
-- ------------------------------
-- Set the table name and determines the package name.
-- ------------------------------
procedure Set_Table_Name (Table : in out Table_Definition;
Name : in String) is
Pos : constant Natural := Util.Strings.Rindex (Name, '.');
begin
Table.Name := To_Unbounded_String (Name);
if Pos > 0 then
Table.Pkg_Name := To_Unbounded_String (Name (Name'First .. Pos - 1));
Table.Type_Name := To_Unbounded_String (Name (Pos + 1 .. Name'Last));
else
Table.Pkg_Name := To_Unbounded_String ("ADO");
Table.Type_Name := Table.Name;
end if;
end Set_Table_Name;
end Gen.Model.Tables;
|
-----------------------------------------------------------------------
-- gen-model-tables -- Database table model representation
-- Copyright (C) 2009, 2010, 2011, 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings;
with Util.Strings;
package body Gen.Model.Tables is
-- ------------------------------
-- 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 : Column_Definition;
Name : String) return Util.Beans.Objects.Object is
use type Gen.Model.Mappings.Mapping_Definition_Access;
begin
if Name = "type" and From.Type_Mapping /= null then
declare
Bean : constant Util.Beans.Basic.Readonly_Bean_Access := From.Type_Mapping.all'Access;
begin
return Util.Beans.Objects.To_Object (Bean, Util.Beans.Objects.STATIC);
end;
elsif Name = "type" then
return Util.Beans.Objects.To_Object (From.Type_Name);
elsif Name = "index" then
return Util.Beans.Objects.To_Object (From.Number);
elsif Name = "isUnique" then
return Util.Beans.Objects.To_Object (From.Unique);
elsif Name = "isNull" then
return Util.Beans.Objects.To_Object (not From.Not_Null);
elsif Name = "isInserted" then
return Util.Beans.Objects.To_Object (From.Is_Inserted);
elsif Name = "isUpdated" then
return Util.Beans.Objects.To_Object (From.Is_Updated);
elsif Name = "sqlType" then
return Util.Beans.Objects.To_Object (From.Sql_Type);
elsif Name = "sqlName" then
return Util.Beans.Objects.To_Object (From.Sql_Name);
elsif Name = "isVersion" then
return Util.Beans.Objects.To_Object (From.Is_Version);
elsif Name = "isReadable" then
return Util.Beans.Objects.To_Object (From.Is_Readable);
elsif Name = "isPrimaryKey" then
return Util.Beans.Objects.To_Object (From.Is_Key);
elsif Name = "isPrimitiveType" then
return Util.Beans.Objects.To_Object (From.Is_Basic_Type);
elsif Name = "generator" then
return From.Generator;
else
return Definition (From).Get_Value (Name);
end if;
end Get_Value;
-- ------------------------------
-- Returns true if the column type is a basic type.
-- ------------------------------
function Is_Basic_Type (From : Column_Definition) return Boolean is
use type Gen.Model.Mappings.Mapping_Definition_Access;
use type Gen.Model.Mappings.Basic_Type;
Name : constant String := To_String (From.Type_Name);
begin
if From.Type_Mapping /= null then
return From.Type_Mapping.Kind /= Gen.Model.Mappings.T_BLOB;
end if;
return Name = "int" or Name = "String"
or Name = "ADO.Identifier" or Name = "Timestamp"
or Name = "Integer"
or Name = "long" or Name = "Long" or Name = "Date" or Name = "Time";
end Is_Basic_Type;
-- ------------------------------
-- Returns the column type.
-- ------------------------------
function Get_Type (From : Column_Definition) return String is
use type Gen.Model.Mappings.Mapping_Definition_Access;
begin
if From.Type_Mapping /= null then
return To_String (From.Type_Mapping.Target);
else
return To_String (From.Type_Name);
end if;
end Get_Type;
-- ------------------------------
-- Prepare the generation of the model.
-- ------------------------------
overriding
procedure Prepare (O : in out Column_Definition) is
begin
O.Type_Mapping := Gen.Model.Mappings.Find_Type (O.Type_Name);
end Prepare;
-- ------------------------------
-- 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 : Association_Definition;
Name : String) return Util.Beans.Objects.Object is
begin
return Column_Definition (From).Get_Value (Name);
end Get_Value;
-- ------------------------------
-- Initialize the table definition instance.
-- ------------------------------
overriding
procedure Initialize (O : in out Table_Definition) is
begin
O.Members_Bean := Util.Beans.Objects.To_Object (O.Members'Unchecked_Access,
Util.Beans.Objects.STATIC);
end Initialize;
-- ------------------------------
-- Create a table with the given name.
-- ------------------------------
function Create_Table (Name : in Unbounded_String) return Table_Definition_Access is
Table : constant Table_Definition_Access := new Table_Definition;
begin
Table.Name := Name;
declare
Pos : constant Natural := Index (Table.Name, ".", Ada.Strings.Backward);
begin
if Pos > 0 then
Table.Pkg_Name := Unbounded_Slice (Table.Name, 1, Pos - 1);
Table.Type_Name := Unbounded_Slice (Table.Name, Pos + 1, Length (Table.Name));
else
Table.Pkg_Name := To_Unbounded_String ("ADO");
Table.Type_Name := Table.Name;
end if;
end;
return Table;
end Create_Table;
-- ------------------------------
-- Create a table column with the given name and add it to the table.
-- ------------------------------
procedure Add_Column (Table : in out Table_Definition;
Name : in Unbounded_String;
Column : out Column_Definition_Access) is
begin
Column := new Column_Definition;
Column.Name := Name;
Column.Sql_Name := Name;
Column.Number := Table.Members.Get_Count;
Table.Members.Append (Column);
if Name = "version" then
Table.Version_Column := Column;
Column.Is_Version := True;
Column.Is_Updated := False;
Column.Is_Inserted := False;
elsif Name = "id" then
Table.Id_Column := Column;
Column.Is_Key := True;
end if;
end Add_Column;
-- ------------------------------
-- 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 Table_Definition;
Name : in String) return Util.Beans.Objects.Object is
begin
if Name = "members" or Name = "columns" then
return From.Members_Bean;
elsif Name = "id" and From.Id_Column /= null then
declare
Bean : constant Util.Beans.Basic.Readonly_Bean_Access := From.Id_Column.all'Access;
begin
return Util.Beans.Objects.To_Object (Bean, Util.Beans.Objects.STATIC);
end;
elsif Name = "version" and From.Version_Column /= null then
declare
Bean : constant Util.Beans.Basic.Readonly_Bean_Access
:= From.Version_Column.all'Unchecked_Access;
begin
return Util.Beans.Objects.To_Object (Bean, Util.Beans.Objects.STATIC);
end;
elsif Name = "hasAssociations" then
return Util.Beans.Objects.To_Object (From.Has_Associations);
elsif Name = "type" then
return Util.Beans.Objects.To_Object (From.Type_Name);
elsif Name = "table" then
return Util.Beans.Objects.To_Object (From.Name);
else
return Definition (From).Get_Value (Name);
end if;
end Get_Value;
-- ------------------------------
-- Prepare the generation of the model.
-- ------------------------------
overriding
procedure Prepare (O : in out Table_Definition) is
Iter : Column_List.Cursor := O.Members.First;
begin
while Column_List.Has_Element (Iter) loop
Column_List.Element (Iter).Prepare;
Column_List.Next (Iter);
end loop;
end Prepare;
-- ------------------------------
-- Set the table name and determines the package name.
-- ------------------------------
procedure Set_Table_Name (Table : in out Table_Definition;
Name : in String) is
Pos : constant Natural := Util.Strings.Rindex (Name, '.');
begin
Table.Name := To_Unbounded_String (Name);
if Pos > 0 then
Table.Pkg_Name := To_Unbounded_String (Name (Name'First .. Pos - 1));
Table.Type_Name := To_Unbounded_String (Name (Pos + 1 .. Name'Last));
else
Table.Pkg_Name := To_Unbounded_String ("ADO");
Table.Type_Name := Table.Name;
end if;
end Set_Table_Name;
end Gen.Model.Tables;
|
Fix compilation
|
Fix compilation
|
Ada
|
apache-2.0
|
Letractively/ada-gen,Letractively/ada-gen,Letractively/ada-gen,Letractively/ada-gen
|
1ca6973fec957533765a65ac59a0ab742efb065e
|
awa/plugins/awa-comments/src/awa-comments-beans.ads
|
awa/plugins/awa-comments/src/awa-comments-beans.ads
|
-----------------------------------------------------------------------
-- awa-comments-beans -- Beans for the comments module
-- Copyright (C) 2014 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Util.Beans.Basic;
with Util.Beans.Objects.Lists;
with ADO;
with ADO.Schemas;
with ADO.Sessions;
with AWA.Comments.Models;
with AWA.Comments.Modules;
-- == Comment Beans ==
-- Several bean types are provided to represent and manage a list of tags.
-- The tag module registers the bean constructors when it is initialized.
-- To use them, one must declare a bean definition in the application XML configuration.
--
-- === Comment_List_Bean ===
-- The <tt>Comment_List_Bean</tt> holds a list of comments 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>postCommentList</managed-bean-name>
-- <managed-bean-class>AWA.Comments.Beans.Comment_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_post</value>
-- </managed-property>
-- <managed-property>
-- <property-name>permission</property-name>
-- <property-class>String</property-class>
-- <value>blog-comment-post</value>
-- </managed-property>
-- </managed-bean>
--
-- The <tt>entity_type</tt> property defines the name of the database table to which the comments
-- 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 comment.
--
package AWA.Comments.Beans is
type Comment_List_Bean is
new Util.Beans.Objects.Lists.List_Bean and Util.Beans.Basic.Bean with private;
type Comment_List_Bean_Access is access all Comment_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 Comment_List_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object);
-- Set the entity type (database table) with which the comments are associated.
procedure Set_Entity_Type (Into : in out Comment_List_Bean;
Table : in ADO.Schemas.Class_Mapping_Access);
-- Set the permission to check before removing or adding a comment on the entity.
procedure Set_Permission (Into : in out Comment_List_Bean;
Permission : in String);
-- Load the comments associated with the given database identifier.
procedure Load_Comments (Into : in out Comment_List_Bean;
Session : in ADO.Sessions.Session;
For_Entity_Id : in ADO.Identifier);
-- Create the comment list bean instance.
function Create_Comment_List_Bean (Module : in AWA.Comments.Modules.Comment_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access;
private
type Comment_List_Bean is
new Util.Beans.Objects.Lists.List_Bean and Util.Beans.Basic.Bean with record
Module : AWA.Comments.Modules.Comment_Module_Access;
Entity_Type : Ada.Strings.Unbounded.Unbounded_String;
Permission : Ada.Strings.Unbounded.Unbounded_String;
Current : Natural := 0;
end record;
end AWA.Comments.Beans;
|
-----------------------------------------------------------------------
-- awa-comments-beans -- Beans for the comments module
-- Copyright (C) 2014 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Util.Beans.Basic;
with Util.Beans.Objects.Lists;
with ADO;
with ADO.Schemas;
with ADO.Sessions;
with AWA.Comments.Models;
with AWA.Comments.Modules;
-- == Comment Beans ==
-- Several bean types are provided to represent and manage a list of tags.
-- The tag module registers the bean constructors when it is initialized.
-- To use them, one must declare a bean definition in the application XML configuration.
--
-- === Comment_List_Bean ===
-- The <tt>Comment_List_Bean</tt> holds a list of comments 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>postCommentList</managed-bean-name>
-- <managed-bean-class>AWA.Comments.Beans.Comment_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_post</value>
-- </managed-property>
-- <managed-property>
-- <property-name>permission</property-name>
-- <property-class>String</property-class>
-- <value>blog-comment-post</value>
-- </managed-property>
-- </managed-bean>
--
-- The <tt>entity_type</tt> property defines the name of the database table to which the comments
-- 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 comment.
--
package AWA.Comments.Beans is
type Comment_Bean is new AWA.Comments.Models.Comment_Bean with record
Module : Modules.Comment_Module_Access := null;
Entity_Type : Ada.Strings.Unbounded.Unbounded_String;
Permission : Ada.Strings.Unbounded.Unbounded_String;
end record;
type Comment_Bean_Access is access all Comment_Bean'Class;
-- Get the value identified by the name.
overriding
function Get_Value (From : in Comment_Bean;
Name : in String) return Util.Beans.Objects.Object;
-- Set the value identified by the name.
overriding
procedure Set_Value (From : in out Comment_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object);
-- Create the comment.
overriding
procedure Create (Bean : in out Comment_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String);
-- Save the comment.
overriding
procedure Save (Bean : in out Comment_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String);
-- Delete the comment.
overriding
procedure Delete (Bean : in out Comment_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String);
-- Create a new comment bean instance.
function Create_Comment_Bean (Module : in AWA.Comments.Modules.Comment_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access;
type Comment_List_Bean is
new Util.Beans.Objects.Lists.List_Bean and Util.Beans.Basic.Bean with private;
type Comment_List_Bean_Access is access all Comment_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 Comment_List_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object);
-- Set the entity type (database table) with which the comments are associated.
procedure Set_Entity_Type (Into : in out Comment_List_Bean;
Table : in ADO.Schemas.Class_Mapping_Access);
-- Set the permission to check before removing or adding a comment on the entity.
procedure Set_Permission (Into : in out Comment_List_Bean;
Permission : in String);
-- Load the comments associated with the given database identifier.
procedure Load_Comments (Into : in out Comment_List_Bean;
Session : in ADO.Sessions.Session;
For_Entity_Id : in ADO.Identifier);
-- Create the comment list bean instance.
function Create_Comment_List_Bean (Module : in AWA.Comments.Modules.Comment_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access;
private
type Comment_List_Bean is
new Util.Beans.Objects.Lists.List_Bean and Util.Beans.Basic.Bean with record
Module : AWA.Comments.Modules.Comment_Module_Access;
Entity_Type : Ada.Strings.Unbounded.Unbounded_String;
Permission : Ada.Strings.Unbounded.Unbounded_String;
Current : Natural := 0;
end record;
end AWA.Comments.Beans;
|
Define the Comment_Bean to expose the comment and allow its creation and removal from the ASF view
|
Define the Comment_Bean to expose the comment and allow its creation
and removal from the ASF view
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
91b72c5f9fb63e41ca5b3c8f4764256a165c62bc
|
src/wiki-render-text.adb
|
src/wiki-render-text.adb
|
-----------------------------------------------------------------------
-- wiki-render-text -- Wiki Text renderer
-- Copyright (C) 2011, 2012, 2013, 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Characters.Conversions;
with Wiki.Filters.Html;
package body Wiki.Render.Text is
LF : constant Wide_Wide_Character := Wide_Wide_Character'Val (16#0A#);
-- ------------------------------
-- Set the output writer.
-- ------------------------------
procedure Set_Writer (Document : in out Text_Renderer;
Writer : in Wiki.Writers.Writer_Type_Access) is
begin
Document.Writer := Writer;
end Set_Writer;
-- ------------------------------
-- Emit a new line.
-- ------------------------------
procedure New_Line (Document : in out Text_Renderer) is
begin
Document.Writer.Write (LF);
Document.Empty_Line := True;
end New_Line;
-- ------------------------------
-- Add a section header in the document.
-- ------------------------------
overriding
procedure Add_Header (Document : in out Text_Renderer;
Header : in Unbounded_Wide_Wide_String;
Level : in Positive) is
pragma Unreferenced (Level);
begin
Document.Close_Paragraph;
if not Document.Empty_Line then
Document.Add_Line_Break;
end if;
Document.Writer.Write (Header);
Document.Add_Line_Break;
end Add_Header;
-- ------------------------------
-- Add a line break (<br>).
-- ------------------------------
overriding
procedure Add_Line_Break (Document : in out Text_Renderer) is
begin
Document.Writer.Write (Ada.Characters.Conversions.To_Wide_Wide_Character (ASCII.LF));
Document.Empty_Line := True;
end Add_Line_Break;
-- ------------------------------
-- Add a paragraph (<p>). Close the previous paragraph if any.
-- The paragraph must be closed at the next paragraph or next header.
-- ------------------------------
overriding
procedure Add_Paragraph (Document : in out Text_Renderer) is
begin
Document.Close_Paragraph;
Document.Need_Paragraph := True;
Document.Add_Line_Break;
end Add_Paragraph;
-- ------------------------------
-- Add a blockquote (<blockquote>). The level indicates the blockquote nested level.
-- The blockquote must be closed at the next header.
-- ------------------------------
overriding
procedure Add_Blockquote (Document : in out Text_Renderer;
Level : in Natural) is
begin
Document.Close_Paragraph;
for I in 1 .. Level loop
Document.Writer.Write (" ");
end loop;
end Add_Blockquote;
-- ------------------------------
-- Add a list item (<li>). Close the previous paragraph and list item if any.
-- The list item will be closed at the next list item, next paragraph or next header.
-- ------------------------------
overriding
procedure Add_List_Item (Document : in out Text_Renderer;
Level : in Positive;
Ordered : in Boolean) is
pragma Unreferenced (Level, Ordered);
begin
if not Document.Empty_Line then
Document.Add_Line_Break;
end if;
Document.Need_Paragraph := False;
Document.Open_Paragraph;
end Add_List_Item;
procedure Close_Paragraph (Document : in out Text_Renderer) is
begin
if Document.Has_Paragraph then
Document.Add_Line_Break;
end if;
Document.Has_Paragraph := False;
end Close_Paragraph;
procedure Open_Paragraph (Document : in out Text_Renderer) is
begin
if Document.Need_Paragraph then
Document.Has_Paragraph := True;
Document.Need_Paragraph := False;
end if;
end Open_Paragraph;
-- ------------------------------
-- Add an horizontal rule (<hr>).
-- ------------------------------
overriding
procedure Add_Horizontal_Rule (Document : in out Text_Renderer) is
begin
Document.Close_Paragraph;
Document.Writer.Write ("---------------------------------------------------------");
Document.Add_Line_Break;
end Add_Horizontal_Rule;
-- ------------------------------
-- Add a link.
-- ------------------------------
overriding
procedure Add_Link (Document : in out Text_Renderer;
Name : in Unbounded_Wide_Wide_String;
Link : in Unbounded_Wide_Wide_String;
Language : in Unbounded_Wide_Wide_String;
Title : in Unbounded_Wide_Wide_String) is
pragma Unreferenced (Language);
begin
Document.Open_Paragraph;
if Length (Title) > 0 then
Document.Writer.Write (Title);
end if;
Document.Writer.Write (Link);
if Link /= Name then
Document.Writer.Write (Name);
end if;
Document.Empty_Line := False;
end Add_Link;
-- ------------------------------
-- Add an image.
-- ------------------------------
overriding
procedure Add_Image (Document : in out Text_Renderer;
Link : in Unbounded_Wide_Wide_String;
Alt : in Unbounded_Wide_Wide_String;
Position : in Unbounded_Wide_Wide_String;
Description : in Unbounded_Wide_Wide_String) is
pragma Unreferenced (Position);
begin
Document.Open_Paragraph;
if Length (Alt) > 0 then
Document.Writer.Write (Alt);
end if;
if Length (Description) > 0 then
Document.Writer.Write (Description);
end if;
Document.Writer.Write (Link);
Document.Empty_Line := False;
end Add_Image;
-- ------------------------------
-- Add a quote.
-- ------------------------------
overriding
procedure Add_Quote (Document : in out Text_Renderer;
Quote : in Unbounded_Wide_Wide_String;
Link : in Unbounded_Wide_Wide_String;
Language : in Unbounded_Wide_Wide_String) is
pragma Unreferenced (Link, Language);
begin
Document.Open_Paragraph;
Document.Writer.Write (Quote);
Document.Empty_Line := False;
end Add_Quote;
-- ------------------------------
-- Add a text block with the given format.
-- ------------------------------
overriding
procedure Add_Text (Document : in out Text_Renderer;
Text : in Unbounded_Wide_Wide_String;
Format : in Wiki.Documents.Format_Map) is
pragma Unreferenced (Format);
begin
if Document.Empty_Line and Document.Indent_Level /= 0 then
for I in 1 .. Document.Indent_Level loop
Document.Writer.Write (' ');
end loop;
end if;
Document.Writer.Write (Text);
Document.Empty_Line := False;
end Add_Text;
-- ------------------------------
-- Add a text block that is pre-formatted.
-- ------------------------------
procedure Add_Preformatted (Document : in out Text_Renderer;
Text : in Unbounded_Wide_Wide_String;
Format : in Unbounded_Wide_Wide_String) is
pragma Unreferenced (Format);
begin
Document.Close_Paragraph;
Document.Writer.Write (Text);
Document.Empty_Line := False;
end Add_Preformatted;
overriding
procedure Start_Element (Document : in out Text_Renderer;
Name : in Unbounded_Wide_Wide_String;
Attributes : in Wiki.Attributes.Attribute_List_Type) is
pragma Unreferenced (Attributes);
use type Wiki.Filters.Html.Html_Tag_Type;
Tag : constant Wiki.Filters.Html.Html_Tag_Type := Wiki.Filters.Html.Find_Tag (Name);
begin
if Tag = Wiki.Filters.Html.DT_TAG then
Document.Close_Paragraph;
Document.Indent_Level := 0;
elsif Tag = Wiki.Filters.Html.DD_TAG then
Document.Close_Paragraph;
Document.Empty_Line := True;
Document.Indent_Level := 4;
end if;
end Start_Element;
overriding
procedure End_Element (Document : in out Text_Renderer;
Name : in Unbounded_Wide_Wide_String) is
use type Wiki.Filters.Html.Html_Tag_Type;
Tag : constant Wiki.Filters.Html.Html_Tag_Type := Wiki.Filters.Html.Find_Tag (Name);
begin
if Tag = Wiki.Filters.Html.DT_TAG then
Document.Close_Paragraph;
Document.Indent_Level := 0;
elsif Tag = Wiki.Filters.Html.DD_TAG then
Document.Close_Paragraph;
Document.Indent_Level := 0;
elsif Tag = Wiki.Filters.Html.DL_TAG then
Document.Close_Paragraph;
Document.New_Line;
end if;
end End_Element;
-- ------------------------------
-- Finish the document after complete wiki text has been parsed.
-- ------------------------------
overriding
procedure Finish (Document : in out Text_Renderer) is
begin
Document.Close_Paragraph;
end Finish;
end Wiki.Render.Text;
|
-----------------------------------------------------------------------
-- wiki-render-text -- Wiki Text renderer
-- Copyright (C) 2011, 2012, 2013, 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Characters.Conversions;
with Wiki.Filters.Html;
with Wiki.Helpers;
package body Wiki.Render.Text is
-- ------------------------------
-- Set the output writer.
-- ------------------------------
procedure Set_Output_Stream (Engine : in out Text_Renderer;
Stream : in Streams.Output_Stream_Access) is
begin
Engine.Output := Stream;
end Set_Output_Stream;
-- ------------------------------
-- Emit a new line.
-- ------------------------------
procedure New_Line (Document : in out Text_Renderer) is
begin
Document.Output.Write (Wiki.Helpers.LF);
Document.Empty_Line := True;
end New_Line;
-- ------------------------------
-- Add a section header in the document.
-- ------------------------------
procedure Add_Header (Document : in out Text_Renderer;
Header : in Unbounded_Wide_Wide_String;
Level : in Positive) is
pragma Unreferenced (Level);
begin
Document.Close_Paragraph;
if not Document.Empty_Line then
Document.Add_Line_Break;
end if;
Document.Writer.Write (Header);
Document.Add_Line_Break;
end Add_Header;
-- ------------------------------
-- Add a line break (<br>).
-- ------------------------------
procedure Add_Line_Break (Document : in out Text_Renderer) is
begin
Document.Writer.Write (Ada.Characters.Conversions.To_Wide_Wide_Character (ASCII.LF));
Document.Empty_Line := True;
end Add_Line_Break;
-- ------------------------------
-- Add a paragraph (<p>). Close the previous paragraph if any.
-- The paragraph must be closed at the next paragraph or next header.
-- ------------------------------
procedure Add_Paragraph (Document : in out Text_Renderer) is
begin
Document.Close_Paragraph;
Document.Need_Paragraph := True;
Document.Add_Line_Break;
end Add_Paragraph;
-- ------------------------------
-- Add a blockquote (<blockquote>). The level indicates the blockquote nested level.
-- The blockquote must be closed at the next header.
-- ------------------------------
procedure Add_Blockquote (Document : in out Text_Renderer;
Level : in Natural) is
begin
Document.Close_Paragraph;
for I in 1 .. Level loop
Document.Writer.Write (" ");
end loop;
end Add_Blockquote;
-- ------------------------------
-- Add a list item (<li>). Close the previous paragraph and list item if any.
-- The list item will be closed at the next list item, next paragraph or next header.
-- ------------------------------
procedure Add_List_Item (Document : in out Text_Renderer;
Level : in Positive;
Ordered : in Boolean) is
pragma Unreferenced (Level, Ordered);
begin
if not Document.Empty_Line then
Document.Add_Line_Break;
end if;
Document.Need_Paragraph := False;
Document.Open_Paragraph;
end Add_List_Item;
procedure Close_Paragraph (Document : in out Text_Renderer) is
begin
if Document.Has_Paragraph then
Document.Add_Line_Break;
end if;
Document.Has_Paragraph := False;
end Close_Paragraph;
procedure Open_Paragraph (Document : in out Text_Renderer) is
begin
if Document.Need_Paragraph then
Document.Has_Paragraph := True;
Document.Need_Paragraph := False;
end if;
end Open_Paragraph;
-- ------------------------------
-- Add a link.
-- ------------------------------
procedure Add_Link (Document : in out Text_Renderer;
Name : in Unbounded_Wide_Wide_String;
Link : in Unbounded_Wide_Wide_String;
Language : in Unbounded_Wide_Wide_String;
Title : in Unbounded_Wide_Wide_String) is
pragma Unreferenced (Language);
begin
Document.Open_Paragraph;
if Length (Title) > 0 then
Document.Writer.Write (Title);
end if;
Document.Writer.Write (Link);
if Link /= Name then
Document.Writer.Write (Name);
end if;
Document.Empty_Line := False;
end Add_Link;
-- ------------------------------
-- Add an image.
-- ------------------------------
procedure Add_Image (Document : in out Text_Renderer;
Link : in Unbounded_Wide_Wide_String;
Alt : in Unbounded_Wide_Wide_String;
Position : in Unbounded_Wide_Wide_String;
Description : in Unbounded_Wide_Wide_String) is
pragma Unreferenced (Position);
begin
Document.Open_Paragraph;
if Length (Alt) > 0 then
Document.Writer.Write (Alt);
end if;
if Length (Description) > 0 then
Document.Writer.Write (Description);
end if;
Document.Writer.Write (Link);
Document.Empty_Line := False;
end Add_Image;
-- ------------------------------
-- Add a quote.
-- ------------------------------
procedure Add_Quote (Document : in out Text_Renderer;
Quote : in Unbounded_Wide_Wide_String;
Link : in Unbounded_Wide_Wide_String;
Language : in Unbounded_Wide_Wide_String) is
pragma Unreferenced (Link, Language);
begin
Document.Open_Paragraph;
Document.Writer.Write (Quote);
Document.Empty_Line := False;
end Add_Quote;
-- ------------------------------
-- Add a text block with the given format.
-- ------------------------------
procedure Add_Text (Document : in out Text_Renderer;
Text : in Unbounded_Wide_Wide_String;
Format : in Wiki.Documents.Format_Map) is
pragma Unreferenced (Format);
begin
if Document.Empty_Line and Document.Indent_Level /= 0 then
for I in 1 .. Document.Indent_Level loop
Document.Writer.Write (' ');
end loop;
end if;
Document.Writer.Write (Text);
Document.Empty_Line := False;
end Add_Text;
-- ------------------------------
-- Add a text block that is pre-formatted.
-- ------------------------------
procedure Add_Preformatted (Document : in out Text_Renderer;
Text : in Unbounded_Wide_Wide_String;
Format : in Unbounded_Wide_Wide_String) is
pragma Unreferenced (Format);
begin
Document.Close_Paragraph;
Document.Writer.Write (Text);
Document.Empty_Line := False;
end Add_Preformatted;
procedure Start_Element (Document : in out Text_Renderer;
Name : in Unbounded_Wide_Wide_String;
Attributes : in Wiki.Attributes.Attribute_List_Type) is
pragma Unreferenced (Attributes);
use type Wiki.Filters.Html.Html_Tag_Type;
Tag : constant Wiki.Filters.Html.Html_Tag_Type := Wiki.Filters.Html.Find_Tag (Name);
begin
if Tag = Wiki.Filters.Html.DT_TAG then
Document.Close_Paragraph;
Document.Indent_Level := 0;
elsif Tag = Wiki.Filters.Html.DD_TAG then
Document.Close_Paragraph;
Document.Empty_Line := True;
Document.Indent_Level := 4;
end if;
end Start_Element;
procedure End_Element (Document : in out Text_Renderer;
Name : in Unbounded_Wide_Wide_String) is
use type Wiki.Filters.Html.Html_Tag_Type;
Tag : constant Wiki.Filters.Html.Html_Tag_Type := Wiki.Filters.Html.Find_Tag (Name);
begin
if Tag = Wiki.Filters.Html.DT_TAG then
Document.Close_Paragraph;
Document.Indent_Level := 0;
elsif Tag = Wiki.Filters.Html.DD_TAG then
Document.Close_Paragraph;
Document.Indent_Level := 0;
elsif Tag = Wiki.Filters.Html.DL_TAG then
Document.Close_Paragraph;
Document.New_Line;
end if;
end End_Element;
-- Render the node instance from the document.
overriding
procedure Render (Engine : in out Text_Renderer;
Doc : in Wiki.Nodes.Document;
Node : in Wiki.Nodes.Node_Type) is
begin
case Node.Kind is
when Wiki.Nodes.N_HEADER =>
Engine.Close_Paragraph;
if not Engine.Empty_Line then
Engine.Add_Line_Break;
end if;
Engine.Writer.Write (Node.Content);
Engine.Add_Line_Break;
when Wiki.Nodes.N_LINE_BREAK =>
Engine.Add_Line_Break;
when Wiki.Nodes.N_HORIZONTAL_RULE =>
Engine.Close_Paragraph;
Engine.Output.Write ("---------------------------------------------------------");
Engine.Add_Line_Break;
when Wiki.Nodes.N_PARAGRAPH =>
Engine.Close_Paragraph;
Engine.Need_Paragraph := True;
Engine.Add_Line_Break;
end case;
end Render;
--
-- ------------------------------
-- Finish the document after complete wiki text has been parsed.
-- ------------------------------
overriding
procedure Finish (Document : in out Text_Renderer) is
begin
Document.Close_Paragraph;
end Finish;
end Wiki.Render.Text;
|
Implement the Render operation
|
Implement the Render operation
|
Ada
|
apache-2.0
|
stcarrez/ada-wiki,stcarrez/ada-wiki
|
1202b74875b056cb443b09143298dbb07a9ec6b3
|
src/base/properties/util-properties.ads
|
src/base/properties/util-properties.ads
|
-----------------------------------------------------------------------
-- util-properties -- Generic name/value property management
-- Copyright (C) 2001 - 2019 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Ada.Finalization;
with Ada.Text_IO;
with Util.Beans.Objects;
with Util.Beans.Basic;
with Util.Strings.Vectors;
private with Util.Concurrent.Counters;
-- = Property Files =
-- The `Util.Properties` package and children implements support to read, write and use
-- property files either in the Java property file format or the Windows INI configuration file.
-- Each property is assigned a key and a value. The list of properties are stored in the
-- `Util.Properties.Manager` tagged record and they are indexed by the key name. A property
-- is therefore unique in the list. Properties can be grouped together in sub-properties so
-- that a key can represent another list of properties. To use the packages described here,
-- use the following GNAT project:
--
-- with "utilada_base";
--
-- == File formats ==
-- The property file consists of a simple name and value pair separated by the `=` sign.
-- Thanks to the Windows INI file format, list of properties can be grouped together
-- in sections by using the `[section-name]` notation.
--
-- test.count=20
-- test.repeat=5
-- [FileTest]
-- test.count=5
-- test.repeat=2
--
-- == Using property files ==
-- An instance of the `Util.Properties.Manager` tagged record must be declared and it provides
-- various operations that can be used. When created, the property manager is empty. One way
-- to fill it is by using the `Load_Properties` procedure to read the property file. Another
-- way is by using the `Set` procedure to insert or change a property by giving its name
-- and its value.
--
-- In this example, the property file `test.properties` is loaded and assuming that it contains
-- the above configuration example, the `Get ("test.count")` will return the string `"20"`.
-- The property `test.repeat` is then modified to have the value `"23"` and the properties are
-- then saved in the file.
--
-- with Util.Properties;
-- ...
-- Props : Util.Properties.Manager;
-- ...
-- Props.Load_Properties (Path => "test.properties");
-- Ada.Text_IO.Put_Line ("Count: " & Props.Get ("test.count");
-- Props.Set ("test.repeat", "23");
-- Props.Save_Properties (Path => "test.properties");
--
-- To be able to access a section from the property manager, it is necessary to retrieve it
-- by using the `Get` function and giving the section name. For example, to retrieve the
-- `test.count` property of the `FileTest` section, the following code is used:
--
-- FileTest : Util.Properties.Manager := Props.Get ("FileTest");
-- ...
-- Ada.Text_IO.Put_Line ("[FileTest] Count: "
-- & FileTest.Get ("test.count");
--
-- When getting or removing a property, the `NO_PROPERTY` exception is raised if the property
-- name was not found in the map. To avoid that exception, it is possible to check whether
-- the name is known by using the `Exists` function.
--
-- if Props.Exists ("test.old_count") then
-- ... -- Property exist
-- end if;
--
-- @include util-properties-json.ads
-- @include util-properties-bundles.ads
--
-- == Advance usage of properties ==
-- The property manager holds the name and value pairs by using an Ada Bean object.
--
-- It is possible to iterate over the properties by using the `Iterate` procedure that
-- accepts as parameter a `Process` procedure that gets the property name as well as the
-- property value. The value itself is passed as an `Util.Beans.Objects.Object` type.
--
package Util.Properties is
NO_PROPERTY : exception;
use Ada.Strings.Unbounded;
subtype Value is Util.Beans.Objects.Object;
function "+" (S : String) return Unbounded_String renames To_Unbounded_String;
function "-" (S : Unbounded_String) return String renames To_String;
function To_String (V : in Value) return String
renames Util.Beans.Objects.To_String;
-- The manager holding the name/value pairs and providing the operations
-- to get and set the properties.
type Manager is new Ada.Finalization.Controlled and Util.Beans.Basic.Bean with private;
type Manager_Access is access all Manager'Class;
-- Get the value identified by the name.
-- If the name cannot be found, the method should return the Null object.
overriding
function Get_Value (From : in Manager;
Name : in String) return Util.Beans.Objects.Object;
-- Set the value identified by the name.
-- If the map contains the given name, the value changed.
-- Otherwise name is added to the map and the value associated with it.
overriding
procedure Set_Value (From : in out Manager;
Name : in String;
Value : in Util.Beans.Objects.Object);
-- Returns TRUE if the property manager is empty.
function Is_Empty (Self : in Manager'Class) return Boolean;
-- Returns TRUE if the property exists.
function Exists (Self : in Manager'Class;
Name : in Unbounded_String) return Boolean;
-- Returns TRUE if the property exists.
function Exists (Self : in Manager'Class;
Name : in String) return Boolean;
-- Returns the property value. Raises an exception if not found.
function Get (Self : in Manager'Class;
Name : in String) return String;
-- Returns the property value. Raises an exception if not found.
function Get (Self : in Manager'Class;
Name : in String) return Unbounded_String;
-- Returns the property value. Raises an exception if not found.
function Get (Self : in Manager'Class;
Name : in Unbounded_String) return Unbounded_String;
-- Returns the property value. Raises an exception if not found.
function Get (Self : in Manager'Class;
Name : in Unbounded_String) return String;
-- Returns the property value or Default if it does not exist.
function Get (Self : in Manager'Class;
Name : in String;
Default : in String) return String;
-- Returns a property manager that is associated with the given name.
-- Raises NO_PROPERTY if there is no such property manager or if a property exists
-- but is not a property manager.
function Get (Self : in Manager'Class;
Name : in String) return Manager;
-- Create a property manager and associated it with the given name.
function Create (Self : in out Manager'Class;
Name : in String) return Manager;
-- Set the value of the property. The property is created if it
-- does not exists.
procedure Set (Self : in out Manager'Class;
Name : in String;
Item : in String);
-- Set the value of the property. The property is created if it
-- does not exists.
procedure Set (Self : in out Manager'Class;
Name : in String;
Item : in Unbounded_String);
-- Set the value of the property. The property is created if it
-- does not exists.
procedure Set (Self : in out Manager'Class;
Name : in Unbounded_String;
Item : in Unbounded_String);
-- Remove the property given its name. If the property does not
-- exist, raises NO_PROPERTY exception.
procedure Remove (Self : in out Manager'Class;
Name : in String);
-- Remove the property given its name. If the property does not
-- exist, raises NO_PROPERTY exception.
procedure Remove (Self : in out Manager'Class;
Name : in Unbounded_String);
-- Iterate over the properties and execute the given procedure passing the
-- property name and its value.
procedure Iterate (Self : in Manager'Class;
Process : access procedure (Name : in String;
Item : in Value));
-- Collect the name of the properties defined in the manager.
-- When a prefix is specified, only the properties starting with the prefix are
-- returned.
procedure Get_Names (Self : in Manager;
Into : in out Util.Strings.Vectors.Vector;
Prefix : in String := "");
-- Load the properties from the file input stream. The file must follow
-- the definition of Java property files. When a prefix is specified, keep
-- only the properties that starts with the prefix. When <b>Strip</b> is True,
-- the prefix part is removed from the property name.
procedure Load_Properties (Self : in out Manager'Class;
File : in Ada.Text_IO.File_Type;
Prefix : in String := "";
Strip : in Boolean := False);
-- Load the properties from the file. The file must follow the
-- definition of Java property files. When a prefix is specified, keep
-- only the properties that starts with the prefix. When <b>Strip</b> is True,
-- the prefix part is removed from the property name.
-- Raises NAME_ERROR if the file does not exist.
procedure Load_Properties (Self : in out Manager'Class;
Path : in String;
Prefix : in String := "";
Strip : in Boolean := False);
-- Save the properties in the given file path.
procedure Save_Properties (Self : in out Manager'Class;
Path : in String;
Prefix : in String := "");
-- Copy the properties from FROM which start with a given prefix.
-- If the prefix is empty, all properties are copied. When <b>Strip</b> is True,
-- the prefix part is removed from the property name.
procedure Copy (Self : in out Manager'Class;
From : in Manager'Class;
Prefix : in String := "";
Strip : in Boolean := False);
-- Get the property manager represented by the item value.
-- Raise the Conversion_Error exception if the value is not a property manager.
function To_Manager (Item : in Value) return Manager;
-- Returns True if the item value represents a property manager.
function Is_Manager (Item : in Value) return Boolean;
private
-- Abstract interface for the implementation of Properties
-- (this allows to decouples the implementation from the API)
package Interface_P is
type Manager is abstract limited new Util.Beans.Basic.Bean with record
Count : Util.Concurrent.Counters.Counter;
Shared : Boolean := False;
end record;
type Manager_Access is access all Manager'Class;
-- Returns TRUE if the property exists.
function Exists (Self : in Manager;
Name : in String)
return Boolean is abstract;
-- Remove the property given its name.
procedure Remove (Self : in out Manager;
Name : in String) is abstract;
-- Iterate over the properties and execute the given procedure passing the
-- property name and its value.
procedure Iterate (Self : in Manager;
Process : access procedure (Name : in String;
Item : in Value))
is abstract;
-- Deep copy of properties stored in 'From' to 'To'.
function Create_Copy (Self : in Manager)
return Manager_Access is abstract;
end Interface_P;
-- Create a property implementation if there is none yet.
procedure Check_And_Create_Impl (Self : in out Manager);
type Manager is new Ada.Finalization.Controlled and Util.Beans.Basic.Bean with record
Impl : Interface_P.Manager_Access := null;
end record;
overriding
procedure Adjust (Object : in out Manager);
overriding
procedure Finalize (Object : in out Manager);
end Util.Properties;
|
-----------------------------------------------------------------------
-- util-properties -- Generic name/value property management
-- Copyright (C) 2001 - 2020 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Ada.Finalization;
with Ada.Text_IO;
with Util.Beans.Objects;
with Util.Beans.Basic;
with Util.Strings.Vectors;
private with Util.Concurrent.Counters;
-- = Property Files =
-- The `Util.Properties` package and children implements support to read, write and use
-- property files either in the Java property file format or the Windows INI configuration file.
-- Each property is assigned a key and a value. The list of properties are stored in the
-- `Util.Properties.Manager` tagged record and they are indexed by the key name. A property
-- is therefore unique in the list. Properties can be grouped together in sub-properties so
-- that a key can represent another list of properties. To use the packages described here,
-- use the following GNAT project:
--
-- with "utilada_base";
--
-- == File formats ==
-- The property file consists of a simple name and value pair separated by the `=` sign.
-- Thanks to the Windows INI file format, list of properties can be grouped together
-- in sections by using the `[section-name]` notation.
--
-- test.count=20
-- test.repeat=5
-- [FileTest]
-- test.count=5
-- test.repeat=2
--
-- == Using property files ==
-- An instance of the `Util.Properties.Manager` tagged record must be declared and it provides
-- various operations that can be used. When created, the property manager is empty. One way
-- to fill it is by using the `Load_Properties` procedure to read the property file. Another
-- way is by using the `Set` procedure to insert or change a property by giving its name
-- and its value.
--
-- In this example, the property file `test.properties` is loaded and assuming that it contains
-- the above configuration example, the `Get ("test.count")` will return the string `"20"`.
-- The property `test.repeat` is then modified to have the value `"23"` and the properties are
-- then saved in the file.
--
-- with Util.Properties;
-- ...
-- Props : Util.Properties.Manager;
-- ...
-- Props.Load_Properties (Path => "test.properties");
-- Ada.Text_IO.Put_Line ("Count: " & Props.Get ("test.count");
-- Props.Set ("test.repeat", "23");
-- Props.Save_Properties (Path => "test.properties");
--
-- To be able to access a section from the property manager, it is necessary to retrieve it
-- by using the `Get` function and giving the section name. For example, to retrieve the
-- `test.count` property of the `FileTest` section, the following code is used:
--
-- FileTest : Util.Properties.Manager := Props.Get ("FileTest");
-- ...
-- Ada.Text_IO.Put_Line ("[FileTest] Count: "
-- & FileTest.Get ("test.count");
--
-- When getting or removing a property, the `NO_PROPERTY` exception is raised if the property
-- name was not found in the map. To avoid that exception, it is possible to check whether
-- the name is known by using the `Exists` function.
--
-- if Props.Exists ("test.old_count") then
-- ... -- Property exist
-- end if;
--
-- @include util-properties-json.ads
-- @include util-properties-bundles.ads
--
-- == Advance usage of properties ==
-- The property manager holds the name and value pairs by using an Ada Bean object.
--
-- It is possible to iterate over the properties by using the `Iterate` procedure that
-- accepts as parameter a `Process` procedure that gets the property name as well as the
-- property value. The value itself is passed as an `Util.Beans.Objects.Object` type.
--
package Util.Properties is
NO_PROPERTY : exception;
use Ada.Strings.Unbounded;
subtype Value is Util.Beans.Objects.Object;
function "+" (S : String) return Unbounded_String renames To_Unbounded_String;
function "-" (S : Unbounded_String) return String renames To_String;
function To_String (V : in Value) return String
renames Util.Beans.Objects.To_String;
-- The manager holding the name/value pairs and providing the operations
-- to get and set the properties.
type Manager is new Ada.Finalization.Controlled and Util.Beans.Basic.Bean with private;
type Manager_Access is access all Manager'Class;
-- Get the value identified by the name.
-- If the name cannot be found, the method should return the Null object.
overriding
function Get_Value (From : in Manager;
Name : in String) return Util.Beans.Objects.Object;
-- Set the value identified by the name.
-- If the map contains the given name, the value changed.
-- Otherwise name is added to the map and the value associated with it.
overriding
procedure Set_Value (From : in out Manager;
Name : in String;
Value : in Util.Beans.Objects.Object);
-- Returns TRUE if the property manager is empty.
function Is_Empty (Self : in Manager'Class) return Boolean;
-- Returns TRUE if the property exists.
function Exists (Self : in Manager'Class;
Name : in Unbounded_String) return Boolean;
-- Returns TRUE if the property exists.
function Exists (Self : in Manager'Class;
Name : in String) return Boolean;
-- Returns the property value. Raises an exception if not found.
function Get (Self : in Manager'Class;
Name : in String) return String;
-- Returns the property value. Raises an exception if not found.
function Get (Self : in Manager'Class;
Name : in String) return Unbounded_String;
-- Returns the property value. Raises an exception if not found.
function Get (Self : in Manager'Class;
Name : in Unbounded_String) return Unbounded_String;
-- Returns the property value. Raises an exception if not found.
function Get (Self : in Manager'Class;
Name : in Unbounded_String) return String;
-- Returns the property value or Default if it does not exist.
function Get (Self : in Manager'Class;
Name : in String;
Default : in String) return String;
-- Returns a property manager that is associated with the given name.
-- Raises NO_PROPERTY if there is no such property manager or if a property exists
-- but is not a property manager.
function Get (Self : in Manager'Class;
Name : in String) return Manager;
-- Create a property manager and associated it with the given name.
function Create (Self : in out Manager'Class;
Name : in String) return Manager;
-- Set the value of the property. The property is created if it
-- does not exists.
procedure Set (Self : in out Manager'Class;
Name : in String;
Item : in String);
-- Set the value of the property. The property is created if it
-- does not exists.
procedure Set (Self : in out Manager'Class;
Name : in String;
Item : in Unbounded_String);
-- Set the value of the property. The property is created if it
-- does not exists.
procedure Set (Self : in out Manager'Class;
Name : in Unbounded_String;
Item : in Unbounded_String);
-- Remove the property given its name. If the property does not
-- exist, raises NO_PROPERTY exception.
procedure Remove (Self : in out Manager'Class;
Name : in String);
-- Remove the property given its name. If the property does not
-- exist, raises NO_PROPERTY exception.
procedure Remove (Self : in out Manager'Class;
Name : in Unbounded_String);
-- Iterate over the properties and execute the given procedure passing the
-- property name and its value.
procedure Iterate (Self : in Manager'Class;
Process : access procedure (Name : in String;
Item : in Value));
-- Collect the name of the properties defined in the manager.
-- When a prefix is specified, only the properties starting with the prefix are
-- returned.
procedure Get_Names (Self : in Manager;
Into : in out Util.Strings.Vectors.Vector;
Prefix : in String := "");
-- Load the properties from the file input stream. The file must follow
-- the definition of Java property files. When a prefix is specified, keep
-- only the properties that starts with the prefix. When <b>Strip</b> is True,
-- the prefix part is removed from the property name.
procedure Load_Properties (Self : in out Manager'Class;
File : in Ada.Text_IO.File_Type;
Prefix : in String := "";
Strip : in Boolean := False);
-- Load the properties from the file. The file must follow the
-- definition of Java property files. When a prefix is specified, keep
-- only the properties that starts with the prefix. When <b>Strip</b> is True,
-- the prefix part is removed from the property name.
-- Raises NAME_ERROR if the file does not exist.
procedure Load_Properties (Self : in out Manager'Class;
Path : in String;
Prefix : in String := "";
Strip : in Boolean := False);
-- Save the properties in the given file path.
procedure Save_Properties (Self : in out Manager'Class;
Path : in String;
Prefix : in String := "");
-- Copy the properties from FROM which start with a given prefix.
-- If the prefix is empty, all properties are copied. When <b>Strip</b> is True,
-- the prefix part is removed from the property name.
procedure Copy (Self : in out Manager'Class;
From : in Manager'Class;
Prefix : in String := "";
Strip : in Boolean := False);
-- Get the property manager represented by the item value.
-- Raise the Conversion_Error exception if the value is not a property manager.
function To_Manager (Item : in Value) return Manager;
-- Returns True if the item value represents a property manager.
function Is_Manager (Item : in Value) return Boolean;
-- Abstract interface for the implementation of Properties
-- (this allows to decouples the implementation from the API)
package Implementation is
type Manager is limited interface and Util.Beans.Basic.Bean;
type Manager_Access is access all Manager'Class;
-- Returns TRUE if the property exists.
function Exists (Self : in Manager;
Name : in String)
return Boolean is abstract;
-- Remove the property given its name.
procedure Remove (Self : in out Manager;
Name : in String) is abstract;
-- Iterate over the properties and execute the given procedure passing the
-- property name and its value.
procedure Iterate
(Self : in Manager;
Process : access procedure (Name : in String;
Item : in Value)) is abstract;
-- Deep copy of properties stored in 'From' to 'To'.
function Create_Copy (Self : in Manager)
return Manager_Access is abstract;
type Shared_Manager is limited interface and Manager;
type Shared_Manager_Access is access all Shared_Manager'Class;
function Is_Shared (Self : in Shared_Manager) return Boolean is abstract;
procedure Set_Shared (Self : in out Shared_Manager;
Shared : in Boolean) is abstract;
procedure Adjust (Self : in out Shared_Manager) is abstract;
procedure Finalize (Self : in out Shared_Manager;
Release : out Boolean) is abstract;
generic
with function Allocator return Shared_Manager_Access;
procedure Create (Self : in out Util.Properties.Manager'Class);
generic
with function Allocator return Shared_Manager_Access;
procedure Initialize (Self : in out Util.Properties.Manager'Class);
generic
type Manager_Type is limited new Manager with private;
package Shared_Implementation is
type Manager is limited new Manager_Type and Shared_Manager with private;
overriding
function Is_Shared (Self : in Manager) return Boolean;
overriding
procedure Set_Shared (Self : in out Manager;
Shared : in Boolean);
overriding
procedure Adjust (Self : in out Manager);
overriding
procedure Finalize (Self : in out Manager;
Release : out Boolean);
private
type Manager is limited new Manager_Type and Shared_Manager with record
Count : Util.Concurrent.Counters.Counter := Util.Concurrent.Counters.ONE;
Shared : Boolean := False;
end record;
end Shared_Implementation;
end Implementation;
private
type Manager is new Ada.Finalization.Controlled and Util.Beans.Basic.Bean with record
Impl : Implementation.Shared_Manager_Access := null;
end record;
overriding
procedure Adjust (Object : in out Manager);
overriding
procedure Finalize (Object : in out Manager);
end Util.Properties;
|
Refactor the implementation to allow an external implementation of the Manager class
|
Refactor the implementation to allow an external implementation of the Manager class
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
d4c3ed3680a88f0505f4d66a21cd0ac4674f84c1
|
src/ado-queries.adb
|
src/ado-queries.adb
|
-----------------------------------------------------------------------
-- ado-queries -- Database Queries
-- Copyright (C) 2011, 2012, 2013, 2014, 2015, 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Unchecked_Deallocation;
with ADO.Queries.Loaders;
package body ADO.Queries is
-- ------------------------------
-- Set the query definition which identifies the SQL query to execute.
-- The query is represented by the <tt>sql</tt> XML entry.
-- ------------------------------
procedure Set_Query (Into : in out Context;
Query : in Query_Definition_Access) is
begin
Into.Query_Def := Query;
Into.Is_Count := False;
end Set_Query;
-- ------------------------------
-- Set the query definition which identifies the SQL query to execute.
-- The query count is represented by the <tt>sql-count</tt> XML entry.
-- ------------------------------
procedure Set_Count_Query (Into : in out Context;
Query : in Query_Definition_Access) is
begin
Into.Query_Def := Query;
Into.Is_Count := True;
end Set_Count_Query;
procedure Set_Query (Into : in out Context;
Name : in String) is
begin
Into.Query_Def := ADO.Queries.Loaders.Find_Query (Name);
end Set_Query;
-- ------------------------------
-- Set the query to execute as SQL statement.
-- ------------------------------
procedure Set_SQL (Into : in out Context;
SQL : in String) is
begin
ADO.SQL.Clear (Into.SQL);
ADO.SQL.Append (Into.SQL, SQL);
end Set_SQL;
-- ------------------------------
-- Set the limit for the SQL query.
-- ------------------------------
procedure Set_Limit (Into : in out Context;
First : in Natural;
Last : in Natural) is
begin
Into.First := First;
Into.Last := Last;
end Set_Limit;
-- ------------------------------
-- Get the first row index.
-- ------------------------------
function Get_First_Row_Index (From : in Context) return Natural is
begin
return From.First;
end Get_First_Row_Index;
-- ------------------------------
-- Get the last row index.
-- ------------------------------
function Get_Last_Row_Index (From : in Context) return Natural is
begin
return From.Last;
end Get_Last_Row_Index;
-- ------------------------------
-- Get the maximum number of rows that the SQL query can return.
-- This operation uses the <b>sql-count</b> query.
-- ------------------------------
function Get_Max_Row_Count (From : in Context) return Natural is
begin
return From.Max_Row_Count;
end Get_Max_Row_Count;
-- ------------------------------
-- Get the SQL query that correspond to the query context.
-- ------------------------------
function Get_SQL (From : in Context;
Manager : in Query_Manager'Class) return String is
begin
if From.Query_Def = null then
return ADO.SQL.To_String (From.SQL);
else
return Get_SQL (From.Query_Def, Manager, From.Is_Count);
end if;
end Get_SQL;
-- ------------------------------
-- Find the query with the given name.
-- Returns the query definition that matches the name or null if there is none
-- ------------------------------
function Find_Query (File : in Query_File_Info;
Name : in String) return Query_Definition_Access is
Query : Query_Definition_Access := File.File.Queries;
begin
while Query /= null loop
if Query.Name.all = Name then
return Query;
end if;
Query := Query.Next;
end loop;
return null;
end Find_Query;
function Get_SQL (From : in Query_Definition_Access;
Manager : in Query_Manager;
Use_Count : in Boolean) return String is
Query : Query_Info_Ref.Ref;
begin
ADO.Queries.Loaders.Read_Query (Manager, From);
Query := Manager.Queries (From.Query);
if Query.Is_Null then
return "";
end if;
if Use_Count then
if Length (Query.Value.Count_Query (Manager.Driver).SQL) > 0 then
return To_String (Query.Value.Count_Query (Manager.Driver).SQL);
else
return To_String (Query.Value.Count_Query (ADO.Drivers.Driver_Index'First).SQL);
end if;
elsif Length (Query.Value.Main_Query (Manager.Driver).SQL) > 0 then
return To_String (Query.Value.Main_Query (Manager.Driver).SQL);
else
return To_String (Query.Value.Main_Query (ADO.Drivers.Driver_Index'First).SQL);
end if;
end Get_SQL;
overriding
procedure Finalize (Manager : in out Query_Manager) is
procedure Free is
new Ada.Unchecked_Deallocation (Object => File_Table,
Name => File_Table_Access);
procedure Free is
new Ada.Unchecked_Deallocation (Object => Query_Table,
Name => Query_Table_Access);
begin
Free (Manager.Queries);
Free (Manager.Files);
end Finalize;
end ADO.Queries;
|
-----------------------------------------------------------------------
-- ado-queries -- Database Queries
-- Copyright (C) 2011, 2012, 2013, 2014, 2015, 2017, 2018 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Unchecked_Deallocation;
with ADO.Queries.Loaders;
package body ADO.Queries is
-- ------------------------------
-- Set the query definition which identifies the SQL query to execute.
-- The query is represented by the <tt>sql</tt> XML entry.
-- ------------------------------
procedure Set_Query (Into : in out Context;
Query : in Query_Definition_Access) is
begin
Into.Query_Def := Query;
Into.Is_Count := False;
end Set_Query;
-- ------------------------------
-- Set the query definition which identifies the SQL query to execute.
-- The query count is represented by the <tt>sql-count</tt> XML entry.
-- ------------------------------
procedure Set_Count_Query (Into : in out Context;
Query : in Query_Definition_Access) is
begin
Into.Query_Def := Query;
Into.Is_Count := True;
end Set_Count_Query;
procedure Set_Query (Into : in out Context;
Name : in String) is
begin
Into.Query_Def := ADO.Queries.Loaders.Find_Query (Name);
end Set_Query;
-- ------------------------------
-- Set the query to execute as SQL statement.
-- ------------------------------
procedure Set_SQL (Into : in out Context;
SQL : in String) is
begin
ADO.SQL.Clear (Into.SQL);
ADO.SQL.Append (Into.SQL, SQL);
end Set_SQL;
-- ------------------------------
-- Set the limit for the SQL query.
-- ------------------------------
procedure Set_Limit (Into : in out Context;
First : in Natural;
Last : in Natural) is
begin
Into.First := First;
Into.Last := Last;
end Set_Limit;
-- ------------------------------
-- Get the first row index.
-- ------------------------------
function Get_First_Row_Index (From : in Context) return Natural is
begin
return From.First;
end Get_First_Row_Index;
-- ------------------------------
-- Get the last row index.
-- ------------------------------
function Get_Last_Row_Index (From : in Context) return Natural is
begin
return From.Last;
end Get_Last_Row_Index;
-- ------------------------------
-- Get the maximum number of rows that the SQL query can return.
-- This operation uses the <b>sql-count</b> query.
-- ------------------------------
function Get_Max_Row_Count (From : in Context) return Natural is
begin
return From.Max_Row_Count;
end Get_Max_Row_Count;
-- ------------------------------
-- Get the SQL query that correspond to the query context.
-- ------------------------------
function Get_SQL (From : in Context;
Manager : in Query_Manager'Class) return String is
begin
if From.Query_Def = null then
return ADO.SQL.To_String (From.SQL);
else
return Get_SQL (From.Query_Def, Manager, From.Is_Count);
end if;
end Get_SQL;
-- ------------------------------
-- Find the query with the given name.
-- Returns the query definition that matches the name or null if there is none
-- ------------------------------
function Find_Query (File : in Query_File_Info;
Name : in String) return Query_Definition_Access is
Query : Query_Definition_Access := File.File.Queries;
begin
while Query /= null loop
if Query.Name.all = Name then
return Query;
end if;
Query := Query.Next;
end loop;
return null;
end Find_Query;
function Get_SQL (From : in Query_Definition_Access;
Manager : in Query_Manager;
Use_Count : in Boolean) return String is
Query : Query_Info_Ref.Ref;
begin
ADO.Queries.Loaders.Read_Query (Manager, From);
Query := Manager.Queries (From.Query);
if Query.Is_Null then
raise Query_Error with "Query does not exist";
end if;
if Use_Count then
if Length (Query.Value.Count_Query (Manager.Driver).SQL) > 0 then
return To_String (Query.Value.Count_Query (Manager.Driver).SQL);
elsif Length (Query.Value.Count_Query (ADO.Drivers.Driver_Index'First).SQL) > 0 then
return To_String (Query.Value.Count_Query (ADO.Drivers.Driver_Index'First).SQL);
else
raise Query_Error with "Default count-query is empty";
end if;
elsif Length (Query.Value.Main_Query (Manager.Driver).SQL) > 0 then
return To_String (Query.Value.Main_Query (Manager.Driver).SQL);
elsif Length (Query.Value.Main_Query (ADO.Drivers.Driver_Index'First).SQL) > 0 then
return To_String (Query.Value.Main_Query (ADO.Drivers.Driver_Index'First).SQL);
else
raise Query_Error with "Default query is empty";
end if;
end Get_SQL;
overriding
procedure Finalize (Manager : in out Query_Manager) is
procedure Free is
new Ada.Unchecked_Deallocation (Object => File_Table,
Name => File_Table_Access);
procedure Free is
new Ada.Unchecked_Deallocation (Object => Query_Table,
Name => Query_Table_Access);
begin
Free (Manager.Queries);
Free (Manager.Files);
end Finalize;
end ADO.Queries;
|
Raise the Query_Error exception if we try to get an SQL from a query that does not define the SQL
|
Raise the Query_Error exception if we try to get an SQL from a query that does not define the SQL
|
Ada
|
apache-2.0
|
stcarrez/ada-ado
|
bfa55004f73507b09af059a13438eb7ba709a230
|
src/asf-factory.adb
|
src/asf-factory.adb
|
-----------------------------------------------------------------------
-- asf-factory -- Component and tag factory
-- Copyright (C) 2009, 2010, 2011, 2012, 2013 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Log.Loggers;
with Ada.Strings.Hash;
package body ASF.Factory is
-- The logger
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("ASF.Factory");
-- ------------------------------
-- Compute a hash for the tag name.
-- ------------------------------
function Hash (Key : in Tag_Name) return Ada.Containers.Hash_Type is
use type Ada.Containers.Hash_Type;
H1 : constant Ada.Containers.Hash_Type := Ada.Strings.Hash (Key.URI.all);
H2 : constant Ada.Containers.Hash_Type := Ada.Strings.Hash (Key.Name.all);
begin
return H1 xor H2;
end Hash;
-- ------------------------------
-- Returns true if both tag names are identical.
-- ------------------------------
function "=" (Left, Right : in Tag_Name) return Boolean is
begin
return Left.URI.all = Right.URI.all and Left.Name.all = Right.Name.all;
end "=";
-- ------------------------------
-- Find the create function in bound to the name in the given URI namespace.
-- Returns null if no such binding exist.
-- ------------------------------
function Find (Factory : in Component_Factory;
URI : in String;
Name : in String) return Binding_Access is
Key : constant Tag_Name := Tag_Name '(URI => URI'Unrestricted_Access,
Name => Name'Unrestricted_Access);
Pos : constant Factory_Maps.Cursor := Factory.Map.Find (Key);
begin
if Factory_Maps.Has_Element (Pos) then
return Factory_Maps.Element (Pos);
else
return null;
end if;
end Find;
-- ------------------------------
-- Register a binding library in the factory
-- ------------------------------
procedure Register (Factory : in out Component_Factory;
Bindings : in Factory_Bindings_Access) is
begin
Log.Info ("Register bindings: {0}", Bindings.URI.all);
for I in Bindings.Bindings'Range loop
declare
Key : constant Tag_Name := Tag_Name '(URI => Bindings.URI,
Name => Bindings.Bindings (I).Name);
begin
Factory.Map.Include (Key, Bindings.Bindings (I)'Access);
end;
end loop;
end Register;
-- ------------------------------
-- Register the converter instance under the given name.
-- ------------------------------
procedure Register (Factory : in out Component_Factory;
Name : in String;
Converter : in ASF.Converters.Converter_Access) is
begin
Log.Info ("Register converter: {0}", Name);
Factory.Converters.Include (EL.Objects.To_Object (Name), Converter);
end Register;
-- ------------------------------
-- Find the converter instance that was registered under the given name.
-- Returns null if no such converter exist.
-- ------------------------------
function Find (Factory : in Component_Factory;
Name : in EL.Objects.Object) return ASF.Converters.Converter_Access is
Pos : constant Converter_Maps.Cursor := Factory.Converters.Find (Name);
begin
if Converter_Maps.Has_Element (Pos) then
return Converter_Maps.Element (Pos);
else
return null;
end if;
end Find;
-- ------------------------------
-- Register the validator instance under the given name.
-- ------------------------------
procedure Register (Factory : in out Component_Factory;
Name : in String;
Validator : in ASF.Validators.Validator_Access) is
begin
Log.Info ("Register validator: {0}", Name);
Factory.Validators.Include (EL.Objects.To_Object (Name), Validator);
end Register;
-- ------------------------------
-- Find the validator instance that was registered under the given name.
-- Returns null if no such validator exist.
-- ------------------------------
function Find (Factory : in Component_Factory;
Name : in EL.Objects.Object) return ASF.Validators.Validator_Access is
Pos : constant Validator_Maps.Cursor := Factory.Validators.Find (Name);
begin
if Validator_Maps.Has_Element (Pos) then
return Validator_Maps.Element (Pos);
else
return null;
end if;
end Find;
end ASF.Factory;
|
-----------------------------------------------------------------------
-- asf-factory -- Component and tag factory
-- Copyright (C) 2009, 2010, 2011, 2012, 2013 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Log.Loggers;
with Ada.Strings.Hash;
package body ASF.Factory is
-- The logger
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("ASF.Factory");
-- ------------------------------
-- Compute a hash for the tag name.
-- ------------------------------
function Hash (Key : in Tag_Name) return Ada.Containers.Hash_Type is
use type Ada.Containers.Hash_Type;
H1 : constant Ada.Containers.Hash_Type := Ada.Strings.Hash (Key.URI.all);
H2 : constant Ada.Containers.Hash_Type := Ada.Strings.Hash (Key.Name.all);
begin
return H1 xor H2;
end Hash;
-- ------------------------------
-- Returns true if both tag names are identical.
-- ------------------------------
function "=" (Left, Right : in Tag_Name) return Boolean is
begin
return Left.URI.all = Right.URI.all and Left.Name.all = Right.Name.all;
end "=";
-- ------------------------------
-- Find the create function in bound to the name in the given URI namespace.
-- Returns null if no such binding exist.
-- ------------------------------
function Find (Factory : in Component_Factory;
URI : in String;
Name : in String) return Binding_Type is
Key : constant Tag_Name := Tag_Name '(URI => URI'Unrestricted_Access,
Name => Name'Unrestricted_Access);
Pos : constant Factory_Maps.Cursor := Factory.Map.Find (Key);
begin
if Factory_Maps.Has_Element (Pos) then
return Factory_Maps.Element (Pos);
else
return Null_Binding;
end if;
end Find;
-- ------------------------------
-- Register a binding library in the factory
-- ------------------------------
procedure Register (Factory : in out Component_Factory;
Bindings : in Factory_Bindings_Access) is
begin
Log.Info ("Register bindings: {0}", Bindings.URI.all);
for I in Bindings.Bindings'Range loop
declare
Key : constant Tag_Name := Tag_Name '(URI => Bindings.URI,
Name => Bindings.Bindings (I).Name);
begin
Factory.Map.Include (Key, Bindings.Bindings (I));
end;
end loop;
end Register;
procedure Register (Factory : in out Component_Factory;
URI : in ASF.Views.Nodes.Name_Access;
Name : in ASF.Views.Nodes.Name_Access;
Tag : in ASF.Views.Nodes.Tag_Node_Create_Access;
Create : in ASF.Views.Nodes.Create_Access) is
Key : constant Tag_Name := Tag_Name '(URI => URI, Name => Name);
Bind : constant Binding_Type := Binding_Type '(Name => Name,
Tag => Tag,
Component => Create);
begin
Factory.Map.Include (Key, Bind);
end Register;
-- ------------------------------
-- Register the converter instance under the given name.
-- ------------------------------
procedure Register (Factory : in out Component_Factory;
Name : in String;
Converter : in ASF.Converters.Converter_Access) is
begin
Log.Info ("Register converter: {0}", Name);
Factory.Converters.Include (EL.Objects.To_Object (Name), Converter);
end Register;
-- ------------------------------
-- Find the converter instance that was registered under the given name.
-- Returns null if no such converter exist.
-- ------------------------------
function Find (Factory : in Component_Factory;
Name : in EL.Objects.Object) return ASF.Converters.Converter_Access is
Pos : constant Converter_Maps.Cursor := Factory.Converters.Find (Name);
begin
if Converter_Maps.Has_Element (Pos) then
return Converter_Maps.Element (Pos);
else
return null;
end if;
end Find;
-- ------------------------------
-- Register the validator instance under the given name.
-- ------------------------------
procedure Register (Factory : in out Component_Factory;
Name : in String;
Validator : in ASF.Validators.Validator_Access) is
begin
Log.Info ("Register validator: {0}", Name);
Factory.Validators.Include (EL.Objects.To_Object (Name), Validator);
end Register;
-- ------------------------------
-- Find the validator instance that was registered under the given name.
-- Returns null if no such validator exist.
-- ------------------------------
function Find (Factory : in Component_Factory;
Name : in EL.Objects.Object) return ASF.Validators.Validator_Access is
Pos : constant Validator_Maps.Cursor := Factory.Validators.Find (Name);
begin
if Validator_Maps.Has_Element (Pos) then
return Validator_Maps.Element (Pos);
else
return null;
end if;
end Find;
end ASF.Factory;
|
Update the Find procedure to return a Binding_Type Implement the Register procedure to register a single binding
|
Update the Find procedure to return a Binding_Type
Implement the Register procedure to register a single binding
|
Ada
|
apache-2.0
|
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
|
590e3fa526387bb2b984d4da386e89989790bc5f
|
src/definitions.ads
|
src/definitions.ads
|
-- This file is covered by the Internet Software Consortium (ISC) License
-- Reference: ../License.txt
package Definitions is
pragma Pure;
raven_version_major : constant String := "1";
raven_version_minor : constant String := "34";
copyright_years : constant String := "2015-2019";
raven_tool : constant String := "ravenadm";
variant_standard : constant String := "standard";
contact_nobody : constant String := "nobody";
contact_automaton : constant String := "automaton";
dlgroup_main : constant String := "main";
dlgroup_none : constant String := "none";
options_none : constant String := "none";
options_all : constant String := "all";
broken_all : constant String := "all";
boolean_yes : constant String := "yes";
homepage_none : constant String := "none";
spkg_complete : constant String := "complete";
spkg_docs : constant String := "docs";
spkg_examples : constant String := "examples";
ports_default : constant String := "floating";
default_ssl : constant String := "libressl";
default_mysql : constant String := "oracle-5.7";
default_lua : constant String := "5.3";
default_perl : constant String := "5.30";
default_pgsql : constant String := "11";
default_php : constant String := "7.3";
default_python3 : constant String := "3.7";
default_ruby : constant String := "2.5";
default_tcltk : constant String := "8.6";
default_firebird : constant String := "2.5";
default_compiler : constant String := "gcc8";
compiler_version : constant String := "8.3.0";
previous_compiler : constant String := "8.2.0";
binutils_version : constant String := "2.33.1";
previous_binutils : constant String := "2.32";
arc_ext : constant String := ".tzst";
jobs_per_cpu : constant := 2;
type supported_opsys is (dragonfly, freebsd, netbsd, openbsd, sunos, linux, macos);
type supported_arch is (x86_64, i386, aarch64);
type cpu_range is range 1 .. 64;
type scanners is range cpu_range'First .. cpu_range'Last;
type builders is range cpu_range'First .. cpu_range'Last * jobs_per_cpu;
type count_type is (total, success, failure, ignored, skipped);
-- Modify following with post-patch sed accordingly
platform_type : constant supported_opsys := dragonfly;
host_localbase : constant String := "/raven";
raven_var : constant String := "/var/ravenports";
host_pkg8 : constant String := host_localbase & "/sbin/ravensw";
ravenexec : constant String := host_localbase & "/libexec/ravenexec";
end Definitions;
|
-- This file is covered by the Internet Software Consortium (ISC) License
-- Reference: ../License.txt
package Definitions is
pragma Pure;
raven_version_major : constant String := "1";
raven_version_minor : constant String := "34";
copyright_years : constant String := "2015-2019";
raven_tool : constant String := "ravenadm";
variant_standard : constant String := "standard";
contact_nobody : constant String := "nobody";
contact_automaton : constant String := "automaton";
dlgroup_main : constant String := "main";
dlgroup_none : constant String := "none";
options_none : constant String := "none";
options_all : constant String := "all";
broken_all : constant String := "all";
boolean_yes : constant String := "yes";
homepage_none : constant String := "none";
spkg_complete : constant String := "complete";
spkg_docs : constant String := "docs";
spkg_examples : constant String := "examples";
ports_default : constant String := "floating";
default_ssl : constant String := "libressl";
default_mysql : constant String := "oracle-5.7";
default_lua : constant String := "5.3";
default_perl : constant String := "5.30";
default_pgsql : constant String := "11";
default_php : constant String := "7.3";
default_python3 : constant String := "3.7";
default_ruby : constant String := "2.5";
default_tcltk : constant String := "8.6";
default_firebird : constant String := "2.5";
default_compiler : constant String := "gcc9";
compiler_version : constant String := "9.2.0";
previous_compiler : constant String := "8.3.0";
binutils_version : constant String := "2.33.1";
previous_binutils : constant String := "2.32";
arc_ext : constant String := ".tzst";
jobs_per_cpu : constant := 2;
type supported_opsys is (dragonfly, freebsd, netbsd, openbsd, sunos, linux, macos);
type supported_arch is (x86_64, i386, aarch64);
type cpu_range is range 1 .. 64;
type scanners is range cpu_range'First .. cpu_range'Last;
type builders is range cpu_range'First .. cpu_range'Last * jobs_per_cpu;
type count_type is (total, success, failure, ignored, skipped);
-- Modify following with post-patch sed accordingly
platform_type : constant supported_opsys := dragonfly;
host_localbase : constant String := "/raven";
raven_var : constant String := "/var/ravenports";
host_pkg8 : constant String := host_localbase & "/sbin/ravensw";
ravenexec : constant String := host_localbase & "/libexec/ravenexec";
end Definitions;
|
Move ports compiler to gcc9
|
Move ports compiler to gcc9
|
Ada
|
isc
|
jrmarino/ravenadm,jrmarino/ravenadm,jrmarino/ravenadm
|
3340583023bb28a0ffdb5d3096c9e65f883603bb
|
src/asf-converters-dates.adb
|
src/asf-converters-dates.adb
|
-----------------------------------------------------------------------
-- asf-converters-dates -- Date Converters
-- 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 Ada.Calendar;
with Ada.Exceptions;
with Util.Properties.Bundles;
with Util.Beans.Objects.Time;
with Util.Dates.Formats;
with Util.Log.Loggers;
with ASF.Applications.Main;
with ASF.Locales;
package body ASF.Converters.Dates is
use Ada.Strings.Unbounded;
use Util.Log;
-- The logger
Log : constant Loggers.Logger := Loggers.Create ("ASF.Converters.Dates");
-- ------------------------------
-- Get the date format pattern that must be used for formatting a date on the given component.
-- ------------------------------
function Get_Pattern (Convert : in Date_Converter;
Context : in ASF.Contexts.Faces.Faces_Context'Class;
Component : in ASF.Components.Base.UIComponent'Class) return String is
pragma Unreferenced (Convert);
Pattern : constant String := Component.Get_Attribute (Context => Context,
Name => "format",
Default => "%x");
begin
return Pattern;
end Get_Pattern;
-- ------------------------------
-- Convert the object value into a string. The object value is associated
-- with the specified component.
-- If the string cannot be converted, the Invalid_Conversion exception should be raised.
-- ------------------------------
function To_String (Convert : in Date_Converter;
Context : in ASF.Contexts.Faces.Faces_Context'Class;
Component : in ASF.Components.Base.UIComponent'Class;
Value : in Util.Beans.Objects.Object) return String is
Bundle : ASF.Locales.Bundle;
Pattern : constant String := Date_Converter'Class (Convert).Get_Pattern (Context, Component);
begin
begin
Context.Get_Application.Load_Bundle (Name => "dates",
Locale => "en",
Bundle => Bundle);
exception
when E : Util.Properties.Bundles.NO_BUNDLE =>
Log.Error ("Cannot localize dates: {0}", Ada.Exceptions.Exception_Message (E));
end;
-- Convert the value as a date here so that we can raise an Invalid_Conversion exception.
declare
Date : constant Ada.Calendar.Time := Util.Beans.Objects.Time.To_Time (Value);
Result : constant String := Util.Dates.Formats.Format (Pattern, Date, Bundle);
begin
return Result;
end;
exception
when E : others =>
raise Invalid_Conversion with Ada.Exceptions.Exception_Message (E);
end To_String;
-- ------------------------------
-- Convert the date string into an object for the specified component.
-- If the string cannot be converted, the Invalid_Conversion exception should be raised.
-- ------------------------------
function To_Object (Convert : in Date_Converter;
Context : in ASF.Contexts.Faces.Faces_Context'Class;
Component : in ASF.Components.Base.UIComponent'Class;
Value : in String) return Util.Beans.Objects.Object is
pragma Unreferenced (Convert, Context, Component, Value);
begin
Log.Error ("String to date conversion is not yet implemented");
return Util.Beans.Objects.Null_Object;
end To_Object;
end ASF.Converters.Dates;
|
-----------------------------------------------------------------------
-- asf-converters-dates -- Date Converters
-- 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.Calendar;
with Ada.Exceptions;
with Util.Properties.Bundles;
with Util.Beans.Objects.Time;
with Util.Dates.Formats;
with Util.Log.Loggers;
with ASF.Applications.Main;
with ASF.Locales;
package body ASF.Converters.Dates is
use Util.Log;
-- The logger
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("ASF.Converters.Dates");
-- ------------------------------
-- Get the date format pattern that must be used for formatting a date on the given component.
-- ------------------------------
function Get_Pattern (Convert : in Date_Converter;
Context : in ASF.Contexts.Faces.Faces_Context'Class;
Component : in ASF.Components.Base.UIComponent'Class) return String is
pragma Unreferenced (Convert);
Pattern : constant String := Component.Get_Attribute (Context => Context,
Name => "format",
Default => "%x");
begin
return Pattern;
end Get_Pattern;
-- ------------------------------
-- Convert the object value into a string. The object value is associated
-- with the specified component.
-- If the string cannot be converted, the Invalid_Conversion exception should be raised.
-- ------------------------------
function To_String (Convert : in Date_Converter;
Context : in ASF.Contexts.Faces.Faces_Context'Class;
Component : in ASF.Components.Base.UIComponent'Class;
Value : in Util.Beans.Objects.Object) return String is
Bundle : ASF.Locales.Bundle;
Pattern : constant String := Date_Converter'Class (Convert).Get_Pattern (Context, Component);
begin
begin
ASF.Applications.Main.Load_Bundle (Context.Get_Application.all,
Name => "dates",
Locale => "en",
Bundle => Bundle);
exception
when E : Util.Properties.Bundles.NO_BUNDLE =>
Log.Error ("Cannot localize dates: {0}", Ada.Exceptions.Exception_Message (E));
end;
-- Convert the value as a date here so that we can raise an Invalid_Conversion exception.
declare
Date : constant Ada.Calendar.Time := Util.Beans.Objects.Time.To_Time (Value);
Result : constant String := Util.Dates.Formats.Format (Pattern, Date, Bundle);
begin
return Result;
end;
exception
when E : others =>
raise Invalid_Conversion with Ada.Exceptions.Exception_Message (E);
end To_String;
-- ------------------------------
-- Convert the date string into an object for the specified component.
-- If the string cannot be converted, the Invalid_Conversion exception should be raised.
-- ------------------------------
function To_Object (Convert : in Date_Converter;
Context : in ASF.Contexts.Faces.Faces_Context'Class;
Component : in ASF.Components.Base.UIComponent'Class;
Value : in String) return Util.Beans.Objects.Object is
pragma Unreferenced (Convert, Context, Component, Value);
begin
Log.Error ("String to date conversion is not yet implemented");
return Util.Beans.Objects.Null_Object;
end To_Object;
end ASF.Converters.Dates;
|
Fix compilation warning
|
Fix compilation warning
|
Ada
|
apache-2.0
|
Letractively/ada-asf,Letractively/ada-asf,Letractively/ada-asf
|
49e74885ae84f18d8eeda6e3df64b01a21aa5dad
|
src/asf-converters-dates.ads
|
src/asf-converters-dates.ads
|
-----------------------------------------------------------------------
-- asf-converters-dates -- Date Converters
-- 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.Beans.Objects;
with ASF.Components.Base;
with ASF.Contexts.Faces;
-- The <b>ASF.Converters.Dates</b> defines the date converter to format a date object
-- into a localized representation.
--
-- See JSR 314 - JavaServer Faces Specification 9.4.3 <f:convertDateTime>
-- (To_String is the JSF getAsString method and To_Object is the JSF getAsObject method)
package ASF.Converters.Dates is
-- ------------------------------
-- Converter
-- ------------------------------
-- The <b>Date_Converter</b> translates the object value which holds an Ada.Calendar
-- into a printable date representation. It translates a string into an Ada Calendar time.
-- Unlike the Java implementation, the instance will be shared by multiple
-- views and requests.
type Date_Converter is new Converter with null record;
type Date_Converter_Access is access all Date_Converter'Class;
-- Convert the object value into a string. The object value is associated
-- with the specified component.
-- If the string cannot be converted, the Invalid_Conversion exception should be raised.
function To_String (Convert : in Date_Converter;
Context : in ASF.Contexts.Faces.Faces_Context'Class;
Component : in ASF.Components.Base.UIComponent'Class;
Value : in Util.Beans.Objects.Object) return String;
-- Convert the date string into an object for the specified component.
-- If the string cannot be converted, the Invalid_Conversion exception should be raised.
function To_Object (Convert : in Date_Converter;
Context : in ASF.Contexts.Faces.Faces_Context'Class;
Component : in ASF.Components.Base.UIComponent'Class;
Value : in String) return Util.Beans.Objects.Object;
-- Get the date format pattern that must be used for formatting a date on the given component.
function Get_Pattern (Convert : in Date_Converter;
Context : in ASF.Contexts.Faces.Faces_Context'Class;
Component : in ASF.Components.Base.UIComponent'Class) return String;
end ASF.Converters.Dates;
|
-----------------------------------------------------------------------
-- asf-converters-dates -- Date Converters
-- Copyright (C) 2011, 2014 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Util.Beans.Objects;
with Util.Locales;
with ASF.Components.Base;
with ASF.Contexts.Faces;
with ASF.Locales;
-- The <b>ASF.Converters.Dates</b> defines the date converter to format a date object
-- into a localized representation.
--
-- See JSR 314 - JavaServer Faces Specification 9.4.3 <f:convertDateTime>
-- (To_String is the JSF getAsString method and To_Object is the JSF getAsObject method)
package ASF.Converters.Dates is
type Style_Type is (DEFAULT, SHORT, MEDIUM, LONG, FULL);
type Format_Type is (DATE, TIME, BOTH, CONVERTER_PATTERN, COMPONENT_FORMAT);
-- ------------------------------
-- Converter
-- ------------------------------
-- The <b>Date_Converter</b> translates the object value which holds an Ada.Calendar
-- into a printable date representation. It translates a string into an Ada Calendar time.
-- Unlike the Java implementation, the instance will be shared by multiple
-- views and requests.
type Date_Converter is new Converter with private;
type Date_Converter_Access is access all Date_Converter'Class;
-- Convert the object value into a string. The object value is associated
-- with the specified component.
-- If the string cannot be converted, the Invalid_Conversion exception should be raised.
function To_String (Convert : in Date_Converter;
Context : in ASF.Contexts.Faces.Faces_Context'Class;
Component : in ASF.Components.Base.UIComponent'Class;
Value : in Util.Beans.Objects.Object) return String;
-- Convert the date string into an object for the specified component.
-- If the string cannot be converted, the Invalid_Conversion exception should be raised.
function To_Object (Convert : in Date_Converter;
Context : in ASF.Contexts.Faces.Faces_Context'Class;
Component : in ASF.Components.Base.UIComponent'Class;
Value : in String) return Util.Beans.Objects.Object;
-- Get the date format pattern that must be used for formatting a date on the given component.
function Get_Pattern (Convert : in Date_Converter;
Context : in ASF.Contexts.Faces.Faces_Context'Class;
Bundle : in ASF.Locales.Bundle;
Component : in ASF.Components.Base.UIComponent'Class) return String;
-- Get the locale that must be used to format the date.
function Get_Locale (Convert : in Date_Converter;
Context : in ASF.Contexts.Faces.Faces_Context'Class)
return Util.Locales.Locale;
-- Create a date converter.
function Create_Date_Converter (Date : in Style_Type;
Time : in Style_Type;
Format : in Format_Type;
Locale : in String;
Pattern : in String) return Date_Converter_Access;
private
type Date_Converter is new Converter with record
Date_Style : Style_Type := DEFAULT;
Time_Style : Style_Type := DEFAULT;
Format : Format_Type;
Locale : Util.Locales.Locale;
Pattern : Ada.Strings.Unbounded.Unbounded_String;
end record;
end ASF.Converters.Dates;
|
Add support for various date conversion formats defined in JSR-314 - new type Style_Type to define the pre-defined date and time formats - new type Format_Type to define the global date+time or pattern format - new operation Get_Locale to return the date conversion target locale - new function Create_Date_Converter to build the date converter instance - define in the Date_Converter instance the date, time, locale and pattern
|
Add support for various date conversion formats defined in JSR-314
- new type Style_Type to define the pre-defined date and time formats
- new type Format_Type to define the global date+time or pattern format
- new operation Get_Locale to return the date conversion target locale
- new function Create_Date_Converter to build the date converter instance
- define in the Date_Converter instance the date, time, locale and pattern
|
Ada
|
apache-2.0
|
Letractively/ada-asf,Letractively/ada-asf,Letractively/ada-asf
|
68816c0e796afc938493f726fc3ec1ca4acebc45
|
src/lzma/util-streams-buffered-lzma.adb
|
src/lzma/util-streams-buffered-lzma.adb
|
-----------------------------------------------------------------------
-- util-streams-buffered-lzma -- LZMA 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.Encoders.Base64;
package body Util.Streams.Buffered.Lzma is
-- -----------------------
-- Initialize the stream to write on the given stream.
-- An internal buffer is allocated for writing the stream.
-- -----------------------
procedure Initialize (Stream : in out Compress_Stream;
Output : in Output_Stream_Access;
Size : in Natural;
Format : in String) is
begin
Stream.Initialize (Output, Size);
Stream.Transform := new Util.Encoders.Lzma.Compress;
end Initialize;
-- -----------------------
-- Close the sink.
-- -----------------------
overriding
procedure Close (Stream : in out Compress_Stream) is
begin
Stream.Flush;
Stream.Output.Close;
end Close;
-- -----------------------
-- Write the buffer array to the output stream.
-- -----------------------
overriding
procedure Write (Stream : in out Compress_Stream;
Buffer : in Ada.Streams.Stream_Element_Array) is
First_Encoded : Ada.Streams.Stream_Element_Offset := Buffer'First;
Last_Encoded : Ada.Streams.Stream_Element_Offset;
Last_Pos : Ada.Streams.Stream_Element_Offset;
begin
while First_Encoded <= Buffer'Last loop
Stream.Transform.Transform
(Data => Buffer (First_Encoded .. Buffer'Last),
Into => Stream.Buffer (Stream.Write_Pos .. Stream.Buffer'Last),
Last => Last_Pos,
Encoded => Last_Encoded);
if Last_Encoded < Buffer'Last then
Stream.Output.Write (Stream.Buffer (Stream.Buffer'First .. Last_Pos));
Stream.Write_Pos := Stream.Buffer'First;
else
Stream.Write_Pos := Last_Pos + 1;
end if;
First_Encoded := Last_Encoded + 1;
end loop;
end Write;
-- -----------------------
-- Flush the buffer by writing on the output stream.
-- Raises Data_Error if there is no output stream.
-- -----------------------
overriding
procedure Flush (Stream : in out Compress_Stream) is
Last_Pos : Ada.Streams.Stream_Element_Offset;
begin
loop
Stream.Transform.Finish (Stream.Buffer (Stream.Write_Pos .. Stream.Buffer'Last),
Last_Pos);
Stream.Write_Pos := Last_Pos + 1;
Output_Buffer_Stream (Stream).Flush;
exit when Stream.Write_Pos < Stream.Buffer'Last;
Stream.Write_Pos := 1;
end loop;
end Flush;
-- -----------------------
-- Flush the stream and release the buffer.
-- -----------------------
overriding
procedure Finalize (Object : in out Compress_Stream) is
begin
null;
end Finalize;
end Util.Streams.Buffered.Lzma;
|
-----------------------------------------------------------------------
-- util-streams-buffered-lzma -- LZMA 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.Encoders.Lzma;
package body Util.Streams.Buffered.Lzma is
-- -----------------------
-- Initialize the stream to write on the given stream.
-- An internal buffer is allocated for writing the stream.
-- -----------------------
procedure Initialize (Stream : in out Compress_Stream;
Output : in Output_Stream_Access;
Size : in Natural;
Format : in String) is
begin
Stream.Initialize (Output, Size);
Stream.Transform := new Util.Encoders.Lzma.Compress;
end Initialize;
-- -----------------------
-- Close the sink.
-- -----------------------
overriding
procedure Close (Stream : in out Compress_Stream) is
begin
Stream.Flush;
Stream.Output.Close;
end Close;
-- -----------------------
-- Write the buffer array to the output stream.
-- -----------------------
overriding
procedure Write (Stream : in out Compress_Stream;
Buffer : in Ada.Streams.Stream_Element_Array) is
First_Encoded : Ada.Streams.Stream_Element_Offset := Buffer'First;
Last_Encoded : Ada.Streams.Stream_Element_Offset;
Last_Pos : Ada.Streams.Stream_Element_Offset;
begin
while First_Encoded <= Buffer'Last loop
Stream.Transform.Transform
(Data => Buffer (First_Encoded .. Buffer'Last),
Into => Stream.Buffer (Stream.Write_Pos .. Stream.Buffer'Last),
Last => Last_Pos,
Encoded => Last_Encoded);
if Last_Encoded < Buffer'Last then
Stream.Output.Write (Stream.Buffer (Stream.Buffer'First .. Last_Pos));
Stream.Write_Pos := Stream.Buffer'First;
else
Stream.Write_Pos := Last_Pos + 1;
end if;
First_Encoded := Last_Encoded + 1;
end loop;
end Write;
-- -----------------------
-- Flush the buffer by writing on the output stream.
-- Raises Data_Error if there is no output stream.
-- -----------------------
overriding
procedure Flush (Stream : in out Compress_Stream) is
Last_Pos : Ada.Streams.Stream_Element_Offset := Stream.Write_Pos - 1;
begin
loop
Stream.Transform.Finish (Stream.Buffer (Stream.Write_Pos .. Stream.Buffer'Last),
Last_Pos);
Stream.Write_Pos := Last_Pos + 1;
Output_Buffer_Stream (Stream).Flush;
exit when Stream.Write_Pos < Stream.Buffer'Last;
Stream.Write_Pos := 1;
end loop;
end Flush;
-- -----------------------
-- Flush the stream and release the buffer.
-- -----------------------
overriding
procedure Finalize (Object : in out Compress_Stream) is
begin
null;
end Finalize;
end Util.Streams.Buffered.Lzma;
|
Fix compilation warning
|
Fix compilation warning
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
199f8ccaf0b5d3fb6d4d7da152a0ab34a84c12ff
|
samples/volume_server.adb
|
samples/volume_server.adb
|
-----------------------------------------------------------------------
-- volume_server -- Example of server with a servlet
-- Copyright (C) 2010 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with ASF.Server.Web;
with ASF.Servlets;
with Volume_Servlet;
procedure Volume_Server is
Compute : aliased Volume_Servlet.Servlet;
App : aliased ASF.Servlets.Servlet_Registry;
WS : ASF.Server.Web.AWS_Container;
begin
-- Register the servlets and filters
App.Add_Servlet (Name => "compute", Server => Compute'Unchecked_Access);
-- Define servlet mappings
App.Add_Mapping (Name => "compute", Pattern => "*.html");
WS.Register_Application ("/volume", App'Unchecked_Access);
WS.Start;
delay 60.0;
end Volume_Server;
|
-----------------------------------------------------------------------
-- volume_server -- Example of server with a servlet
-- Copyright (C) 2010 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with ASF.Server.Web;
with ASF.Servlets;
with Volume_Servlet;
with Util.Log.Loggers;
procedure Volume_Server is
Compute : aliased Volume_Servlet.Servlet;
App : aliased ASF.Servlets.Servlet_Registry;
WS : ASF.Server.Web.AWS_Container;
Log : Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Volume_Server");
begin
-- Register the servlets and filters
App.Add_Servlet (Name => "compute", Server => Compute'Unchecked_Access);
-- Define servlet mappings
App.Add_Mapping (Name => "compute", Pattern => "*.html");
WS.Register_Application ("/volume", App'Unchecked_Access);
Log.Info ("Connect you browser to: http://localhost:8080/volume/compute.html");
WS.Start;
delay 60.0;
end Volume_Server;
|
Add a log message to indicate the URL to connect to
|
Add a log message to indicate the URL to connect to
|
Ada
|
apache-2.0
|
Letractively/ada-asf,Letractively/ada-asf,Letractively/ada-asf
|
94ef3845ca7dfe2ac50402614a10ca10665ab0af
|
awa/plugins/awa-questions/src/awa-questions-beans.adb
|
awa/plugins/awa-questions/src/awa-questions-beans.adb
|
-----------------------------------------------------------------------
-- awa-questions-beans -- Beans for module questions
-- Copyright (C) 2012, 2013 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with ADO.Queries;
with ADO.Sessions;
with AWA.Services.Contexts;
with AWA.Questions.Services;
package body AWA.Questions.Beans is
-- ------------------------------
-- 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 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.Service.Load_Question (From,
ADO.Identifier (Util.Beans.Objects.To_Integer (Value)));
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
begin
Bean.Service.Save_Question (Bean);
end Save;
-- ------------------------------
-- Delete the question.
-- ------------------------------
procedure Delete (Bean : in out Question_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
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.Get_Question_Manager;
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_Null (Value) then
From.Service.Load_Answer (From,
ADO.Identifier (Util.Beans.Objects.To_Integer (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.Identifier (Util.Beans.Objects.To_Integer (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
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
begin
null;
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.Get_Question_Manager;
return Object.all'Access;
end Create_Answer_Bean;
-- ------------------------------
-- Create the Question_Info_List_Bean bean instance.
-- ------------------------------
function Create_Question_List_Bean (Module : in AWA.Questions.Modules.Question_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access is
use AWA.Questions.Models;
use AWA.Services;
Object : constant Question_Info_List_Bean_Access := new Question_Info_List_Bean;
Session : ADO.Sessions.Session := Module.Get_Session;
Query : ADO.Queries.Context;
begin
Query.Set_Query (AWA.Questions.Models.Query_Question_List);
AWA.Questions.Models.List (Object.all, Session, Query);
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);
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
use AWA.Questions.Models;
use AWA.Services;
Session : ADO.Sessions.Session := From.Service.Get_Session;
Query : ADO.Queries.Context;
List : AWA.Questions.Models.Question_Display_Info_List_Bean;
begin
Query.Set_Query (AWA.Questions.Models.Query_Question_Info);
Query.Bind_Param ("question_id", Util.Beans.Objects.To_Integer (Value));
AWA.Questions.Models.List (List, Session, Query);
if not List.List.Is_Empty then
From.Question := List.List.Element (0);
end if;
Query.Clear;
Query.Set_Query (AWA.Questions.Models.Query_Answer_List);
Query.Bind_Param ("question_id", Util.Beans.Objects.To_Integer (Value));
AWA.Questions.Models.List (From.Answer_List, Session, Query);
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.Get_Question_Manager;
Object.Question_Bean := Object.Question'Access;
Object.Answer_List_Bean := Object.Answer_List'Access;
return Object.all'Access;
end Create_Question_Display_Bean;
end AWA.Questions.Beans;
|
-----------------------------------------------------------------------
-- awa-questions-beans -- Beans for module questions
-- Copyright (C) 2012, 2013 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with ADO.Queries;
with ADO.Sessions;
with ADO.Sessions.Entities;
with AWA.Services.Contexts;
with AWA.Questions.Services;
package body AWA.Questions.Beans is
-- ------------------------------
-- 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 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.Service.Load_Question (From,
ADO.Identifier (Util.Beans.Objects.To_Integer (Value)));
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
begin
Bean.Service.Save_Question (Bean);
end Save;
-- ------------------------------
-- Delete the question.
-- ------------------------------
procedure Delete (Bean : in out Question_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
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.Get_Question_Manager;
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_Null (Value) then
From.Service.Load_Answer (From,
ADO.Identifier (Util.Beans.Objects.To_Integer (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.Identifier (Util.Beans.Objects.To_Integer (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
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
begin
null;
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.Get_Question_Manager;
return Object.all'Access;
end Create_Answer_Bean;
-- ------------------------------
-- Create the Question_Info_List_Bean bean instance.
-- ------------------------------
function Create_Question_List_Bean (Module : in AWA.Questions.Modules.Question_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access is
use AWA.Questions.Models;
use AWA.Services;
Object : constant Question_Info_List_Bean_Access := new Question_Info_List_Bean;
Session : ADO.Sessions.Session := Module.Get_Session;
Query : ADO.Queries.Context;
begin
Query.Set_Query (AWA.Questions.Models.Query_Question_List);
ADO.Sessions.Entities.Bind_Param (Params => Query,
Name => "entity_type",
Table => AWA.Questions.Models.QUESTION_TABLE,
Session => Session);
AWA.Questions.Models.List (Object.all, Session, Query);
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);
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
use AWA.Questions.Models;
use AWA.Services;
Session : ADO.Sessions.Session := From.Service.Get_Session;
Query : ADO.Queries.Context;
List : AWA.Questions.Models.Question_Display_Info_List_Bean;
begin
Query.Set_Query (AWA.Questions.Models.Query_Question_Info);
Query.Bind_Param ("question_id", Util.Beans.Objects.To_Integer (Value));
ADO.Sessions.Entities.Bind_Param (Params => Query,
Name => "entity_type",
Table => AWA.Questions.Models.QUESTION_TABLE,
Session => Session);
AWA.Questions.Models.List (List, Session, Query);
if not List.List.Is_Empty then
From.Question := List.List.Element (0);
end if;
Query.Clear;
Query.Set_Query (AWA.Questions.Models.Query_Answer_List);
Query.Bind_Param ("question_id", Util.Beans.Objects.To_Integer (Value));
AWA.Questions.Models.List (From.Answer_List, Session, Query);
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.Get_Question_Manager;
Object.Question_Bean := Object.Question'Access;
Object.Answer_List_Bean := Object.Answer_List'Access;
return Object.all'Access;
end Create_Question_Display_Bean;
end AWA.Questions.Beans;
|
Add the question table entity type to queries
|
Add the question table entity type to queries
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
d2927ea93bad7412fb66b9261f3dd5323076bc46
|
awa/plugins/awa-questions/src/awa-questions-beans.ads
|
awa/plugins/awa-questions/src/awa-questions-beans.ads
|
-----------------------------------------------------------------------
-- awa-questions-beans -- Beans for module questions
-- Copyright (C) 2012, 2013 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Util.Beans.Basic;
with Util.Beans.Objects;
with AWA.Questions.Modules;
with AWA.Questions.Models;
with AWA.Questions.Services;
package AWA.Questions.Beans is
type Question_Bean is new AWA.Questions.Models.Question_Bean with record
Service : Services.Question_Service_Access := null;
end record;
type Question_Bean_Access is access all Question_Bean'Class;
-- Get the value identified by the name.
overriding
function Get_Value (From : in Question_Bean;
Name : in String) return Util.Beans.Objects.Object;
-- Set the value identified by the name.
overriding
procedure Set_Value (From : in out Question_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object);
-- Create or save the question.
procedure Save (Bean : in out Question_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String);
-- Delete the question.
procedure Delete (Bean : in out Question_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String);
-- Create the Questions_Bean bean instance.
function Create_Question_Bean (Module : in AWA.Questions.Modules.Question_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access;
type Answer_Bean is new AWA.Questions.Models.Answer_Bean with record
Service : Services.Question_Service_Access := null;
Question : AWA.Questions.Models.Question_Ref;
end record;
type Answer_Bean_Access is access all Answer_Bean'Class;
-- Get the value identified by the name.
overriding
function Get_Value (From : in Answer_Bean;
Name : in String) return Util.Beans.Objects.Object;
-- Set the value identified by the name.
overriding
procedure Set_Value (From : in out Answer_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object);
-- Create or save the answer.
procedure Save (Bean : in out Answer_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String);
-- Delete the question.
procedure Delete (Bean : in out Answer_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String);
-- Create the answer bean instance.
function Create_Answer_Bean (Module : in AWA.Questions.Modules.Question_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access;
-- Create the Question_Info_List_Bean bean instance.
function Create_Question_List_Bean (Module : in AWA.Questions.Modules.Question_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access;
type Question_Display_Bean is new Util.Beans.Basic.Bean with record
Service : Services.Question_Service_Access := null;
Answer_List : aliased AWA.Questions.Models.Answer_Info_List_Bean;
Answer_List_Bean : AWA.Questions.Models.Answer_Info_List_Bean_Access;
Question : aliased AWA.Questions.Models.Question_Display_Info;
Question_Bean : Util.Beans.Basic.Readonly_Bean_Access;
end record;
type Question_Display_Bean_Access is access all Question_Display_Bean'Class;
-- Get the value identified by the name.
overriding
function Get_Value (From : in Question_Display_Bean;
Name : in String) return Util.Beans.Objects.Object;
-- Set the value identified by the name.
overriding
procedure Set_Value (From : in out Question_Display_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object);
-- Create the Question_Display_Bean bean instance.
function Create_Question_Display_Bean (Module : in AWA.Questions.Modules.Question_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access;
end AWA.Questions.Beans;
|
-----------------------------------------------------------------------
-- awa-questions-beans -- Beans for module questions
-- Copyright (C) 2012, 2013 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Util.Beans.Basic;
with Util.Beans.Objects;
with AWA.Questions.Modules;
with AWA.Questions.Models;
package AWA.Questions.Beans is
type Question_Bean is new AWA.Questions.Models.Question_Bean with record
Service : Modules.Question_Module_Access := null;
end record;
type Question_Bean_Access is access all Question_Bean'Class;
-- Get the value identified by the name.
overriding
function Get_Value (From : in Question_Bean;
Name : in String) return Util.Beans.Objects.Object;
-- Set the value identified by the name.
overriding
procedure Set_Value (From : in out Question_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object);
-- Create or save the question.
procedure Save (Bean : in out Question_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String);
-- Delete the question.
procedure Delete (Bean : in out Question_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String);
-- Create the Questions_Bean bean instance.
function Create_Question_Bean (Module : in AWA.Questions.Modules.Question_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access;
type Answer_Bean is new AWA.Questions.Models.Answer_Bean with record
Service : Modules.Question_Module_Access := null;
Question : AWA.Questions.Models.Question_Ref;
end record;
type Answer_Bean_Access is access all Answer_Bean'Class;
-- Get the value identified by the name.
overriding
function Get_Value (From : in Answer_Bean;
Name : in String) return Util.Beans.Objects.Object;
-- Set the value identified by the name.
overriding
procedure Set_Value (From : in out Answer_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object);
-- Create or save the answer.
procedure Save (Bean : in out Answer_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String);
-- Delete the question.
procedure Delete (Bean : in out Answer_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String);
-- Create the answer bean instance.
function Create_Answer_Bean (Module : in AWA.Questions.Modules.Question_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access;
-- Create the Question_Info_List_Bean bean instance.
function Create_Question_List_Bean (Module : in AWA.Questions.Modules.Question_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access;
type Question_Display_Bean is new Util.Beans.Basic.Bean with record
Service : Modules.Question_Module_Access := null;
Answer_List : aliased AWA.Questions.Models.Answer_Info_List_Bean;
Answer_List_Bean : AWA.Questions.Models.Answer_Info_List_Bean_Access;
Question : aliased AWA.Questions.Models.Question_Display_Info;
Question_Bean : Util.Beans.Basic.Readonly_Bean_Access;
end record;
type Question_Display_Bean_Access is access all Question_Display_Bean'Class;
-- Get the value identified by the name.
overriding
function Get_Value (From : in Question_Display_Bean;
Name : in String) return Util.Beans.Objects.Object;
-- Set the value identified by the name.
overriding
procedure Set_Value (From : in out Question_Display_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object);
-- Create the Question_Display_Bean bean instance.
function Create_Question_Display_Bean (Module : in AWA.Questions.Modules.Question_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access;
end AWA.Questions.Beans;
|
Move the question services in the question module (simplify the implementation)
|
Move the question services in the question module (simplify the implementation)
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
6d6ff583d910b2404e6599c4390f0dc80f7f7247
|
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
-- 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,
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
use type Permissions.Permission_Index;
Index : Permission_Index;
begin
Log.Info ("Adding permission {0}", Name);
Permissions.Add_Permission (Name, Index);
if Index >= Manager.Last_Index then
declare
Count : constant Permission_Index := Index + 32;
Perms : constant Controller_Access_Array_Access
:= new Controller_Access_Array (0 .. Count);
begin
if Manager.Permissions /= null then
Perms (Manager.Permissions'Range) := Manager.Permissions.all;
end if;
Manager.Permissions := Perms;
Manager.Last_Index := Count;
end;
end if;
-- If the permission has a controller, release it.
if Manager.Permissions (Index) /= null then
Log.Warn ("Permission {0} is redefined", Name);
Free (Manager.Permissions (Index));
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
use type Permissions.Permission_Index;
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;
-- ------------------------------
-- 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 : 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 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR 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
-- 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
use type Permissions.Permission_Index;
Index : Permission_Index;
begin
Log.Info ("Adding permission {0}", Name);
Permissions.Add_Permission (Name, Index);
if Index >= Manager.Last_Index then
declare
Count : constant Permission_Index := Index + 32;
Perms : constant Controller_Access_Array_Access
:= new Controller_Access_Array (0 .. Count);
begin
if Manager.Permissions /= null then
Perms (Manager.Permissions'Range) := Manager.Permissions.all;
end if;
Manager.Permissions := Perms;
Manager.Last_Index := Count;
end;
end if;
-- 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
use type Permissions.Permission_Index;
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;
-- ------------------------------
-- 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;
|
Fix compilation on Windows with GNAT 2011
|
Fix compilation on Windows with GNAT 2011
|
Ada
|
apache-2.0
|
Letractively/ada-security
|
e4e2fd3c6668028c34006ab59a60c26ca7a2e54c
|
awa/plugins/awa-comments/src/awa-comments-modules.ads
|
awa/plugins/awa-comments/src/awa-comments-modules.ads
|
-----------------------------------------------------------------------
-- awa-comments-module -- Comments module
-- Copyright (C) 2011, 2012, 2013, 2014 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with ASF.Applications;
with ADO;
with AWA.Modules;
with AWA.Modules.Get;
with AWA.Modules.Lifecycles;
with AWA.Comments.Models;
-- == Integration ==
-- The <tt>Comment_Module</tt> manages the comments associated with entities. It provides
-- operations that are used by the comment beans to manage the comments.
-- An instance of the <tt>Comment_Module</tt> must be declared and registered in the
-- AWA application. The module instance can be defined as follows:
--
-- type Application is new AWA.Applications.Application with record
-- Comment_Module : aliased AWA.Comments.Modules.Comment_Module;
-- end record;
--
-- And registered in the `Initialize_Modules` procedure by using:
--
-- Register (App => App.Self.all'Access,
-- Name => AWA.Comments.Modules.NAME,
-- URI => "comments",
-- Module => App.Comment_Module'Access);
--
package AWA.Comments.Modules is
NAME : constant String := "comments";
Not_Found : exception;
-- The <tt>Comment_Lifecycle</tt> package allows to receive life cycle events related
-- to the <tt>Comment</tt> object.
package Comment_Lifecycle is
new AWA.Modules.Lifecycles (Element_Type => AWA.Comments.Models.Comment_Ref'Class);
type Comment_Module is new AWA.Modules.Module with null record;
type Comment_Module_Access is access all Comment_Module'Class;
overriding
procedure Initialize (Plugin : in out Comment_Module;
App : in AWA.Modules.Application_Access;
Props : in ASF.Applications.Config);
-- Load the comment identified by the given identifier.
procedure Load_Comment (Model : in Comment_Module;
Comment : in out AWA.Comments.Models.Comment_Ref'Class;
Id : in ADO.Identifier);
-- Create a new comment for the associated database entity.
procedure Create_Comment (Model : in Comment_Module;
Permission : in String;
Entity_Type : in String;
Comment : in out AWA.Comments.Models.Comment_Ref'Class);
-- Update the comment represented by <tt>Comment</tt> if the current user has the
-- permission identified by <tt>Permission</tt>.
procedure Update_Comment (Model : in Comment_Module;
Permission : in String;
Comment : in out AWA.Comments.Models.Comment_Ref'Class);
-- Delete the comment represented by <tt>Comment</tt> if the current user has the
-- permission identified by <tt>Permission</tt>.
procedure Delete_Comment (Model : in Comment_Module;
Permission : in String;
Comment : in out AWA.Comments.Models.Comment_Ref'Class);
-- Set the publication status of the comment represented by <tt>Comment</tt>
-- if the current user has the permission identified by <tt>Permission</tt>.
procedure Publish_Comment (Model : in Comment_Module;
Permission : in String;
Id : in ADO.Identifier;
Status : in AWA.Comments.Models.Status_Type;
Comment : in out AWA.Comments.Models.Comment_Ref'Class);
function Get_Comment_Module is
new AWA.Modules.Get (Comment_Module, Comment_Module_Access, NAME);
end AWA.Comments.Modules;
|
-----------------------------------------------------------------------
-- awa-comments-module -- Comments module
-- Copyright (C) 2011, 2012, 2013, 2014 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with ASF.Applications;
with ADO;
with AWA.Modules;
with AWA.Modules.Get;
with AWA.Modules.Lifecycles;
with AWA.Comments.Models;
-- == Integration ==
-- The <tt>Comment_Module</tt> manages the comments associated with entities. It provides
-- operations that are used by the comment beans to manage the comments.
-- An instance of the <tt>Comment_Module</tt> must be declared and registered in the
-- AWA application. The module instance can be defined as follows:
--
-- type Application is new AWA.Applications.Application with record
-- Comment_Module : aliased AWA.Comments.Modules.Comment_Module;
-- end record;
--
-- And registered in the `Initialize_Modules` procedure by using:
--
-- Register (App => App.Self.all'Access,
-- Name => AWA.Comments.Modules.NAME,
-- URI => "comments",
-- Module => App.Comment_Module'Access);
--
package AWA.Comments.Modules is
NAME : constant String := "comments";
Not_Found : exception;
-- The <tt>Comment_Lifecycle</tt> package allows to receive life cycle events related
-- to the <tt>Comment</tt> object.
package Comment_Lifecycle is
new AWA.Modules.Lifecycles (Element_Type => AWA.Comments.Models.Comment_Ref'Class);
subtype Listener is Comment_Lifecycle.Listener;
type Comment_Module is new AWA.Modules.Module with null record;
type Comment_Module_Access is access all Comment_Module'Class;
overriding
procedure Initialize (Plugin : in out Comment_Module;
App : in AWA.Modules.Application_Access;
Props : in ASF.Applications.Config);
-- Load the comment identified by the given identifier.
procedure Load_Comment (Model : in Comment_Module;
Comment : in out AWA.Comments.Models.Comment_Ref'Class;
Id : in ADO.Identifier);
-- Create a new comment for the associated database entity.
procedure Create_Comment (Model : in Comment_Module;
Permission : in String;
Entity_Type : in String;
Comment : in out AWA.Comments.Models.Comment_Ref'Class);
-- Update the comment represented by <tt>Comment</tt> if the current user has the
-- permission identified by <tt>Permission</tt>.
procedure Update_Comment (Model : in Comment_Module;
Permission : in String;
Comment : in out AWA.Comments.Models.Comment_Ref'Class);
-- Delete the comment represented by <tt>Comment</tt> if the current user has the
-- permission identified by <tt>Permission</tt>.
procedure Delete_Comment (Model : in Comment_Module;
Permission : in String;
Comment : in out AWA.Comments.Models.Comment_Ref'Class);
-- Set the publication status of the comment represented by <tt>Comment</tt>
-- if the current user has the permission identified by <tt>Permission</tt>.
procedure Publish_Comment (Model : in Comment_Module;
Permission : in String;
Id : in ADO.Identifier;
Status : in AWA.Comments.Models.Status_Type;
Comment : in out AWA.Comments.Models.Comment_Ref'Class);
function Get_Comment_Module is
new AWA.Modules.Get (Comment_Module, Comment_Module_Access, NAME);
end AWA.Comments.Modules;
|
Define the subtype Listener
|
Define the subtype Listener
|
Ada
|
apache-2.0
|
Letractively/ada-awa,tectronics/ada-awa,Letractively/ada-awa,tectronics/ada-awa,Letractively/ada-awa,tectronics/ada-awa
|
b04099c1321ad15c2e2918245fbf27046ea36a5d
|
examples/MicroBit/src/beacon.adb
|
examples/MicroBit/src/beacon.adb
|
------------------------------------------------------------------------------
-- --
-- Copyright (C) 2016, AdaCore --
-- --
-- Redistribution and use in source and binary forms, with or without --
-- modification, are permitted provided that the following conditions are --
-- met: --
-- 1. Redistributions of source code must retain the above copyright --
-- notice, this list of conditions and the following disclaimer. --
-- 2. Redistributions in binary form must reproduce the above copyright --
-- notice, this list of conditions and the following disclaimer in --
-- the documentation and/or other materials provided with the --
-- distribution. --
-- 3. Neither the name of the copyright holder nor the names of its --
-- contributors may be used to endorse or promote products derived --
-- from this software without specific prior written permission. --
-- --
-- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS --
-- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT --
-- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR --
-- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT --
-- HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, --
-- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT --
-- LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, --
-- DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY --
-- THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT --
-- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE --
-- OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. --
-- --
------------------------------------------------------------------------------
with nRF51.Tasks;
with nRF51.Events;
with nRF51.Radio; use nRF51.Radio;
with NRF51_SVD.RADIO; use NRF51_SVD.RADIO;
with nRF51.Clock; use nRF51.Clock;
with Bluetooth_Low_Energy.Packets; use Bluetooth_Low_Energy.Packets;
with Bluetooth_Low_Energy; use Bluetooth_Low_Energy;
with Bluetooth_Low_Energy.Beacon; use Bluetooth_Low_Energy.Beacon;
with HAL; use HAL;
package body Beacon is
Current_Adv_Channel : BLE_Advertising_Channel_Number := 37;
Beacon_Packet : BLE_Packet;
----------------------
-- Initialize_Radio --
----------------------
procedure Initialize_Radio is
Beacon_UUID : constant BLE_UUID :=
Make_UUID ((1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16));
begin
Beacon_Packet := Make_Beacon_Packet (UUID => Beacon_UUID,
Major => 0,
Minor => 0,
Power => 0);
-- Setup high frequency clock for BLE transmission
Set_High_Freq_Source (HFCLK_RC);
Start_High_Freq;
while not High_Freq_Running loop
null;
end loop;
-- Setup radio module for BLE
Setup_For_Bluetooth_Low_Energy;
-- Set BLE advertising address
Set_Logic_Addresses (Base0 => 16#89_BE_D6_00#,
Base1 => 16#00_00_00_00#,
Base_Length_In_Byte => 3,
AP0 => 16#8E#,
AP1 => 16#00#,
AP2 => 16#00#,
AP3 => 16#00#,
AP4 => 16#00#,
AP5 => 16#00#,
AP6 => 16#00#,
AP7 => 16#00#);
-- Select logic address
Set_TX_Address (0);
-- Transmission power
Set_Power (Zero_Dbm);
-- Enable shortcuts for easier radio operation
Enable_Shortcut (Ready_To_Start);
Enable_Shortcut (End_To_Disable);
end Initialize_Radio;
------------------------
-- Send_Beacon_Packet --
------------------------
procedure Send_Beacon_Packet is
begin
Configure_Whitening (True, UInt6 (Current_Adv_Channel));
Set_Frequency
(Radio_Frequency_MHz (Channel_Frequency (Current_Adv_Channel)));
if Current_Adv_Channel /= BLE_Advertising_Channel_Number'Last then
Current_Adv_Channel := Current_Adv_Channel + 1;
else
Current_Adv_Channel := BLE_Advertising_Channel_Number'First;
end if;
-- Set TX packet address
Set_Packet (Get_Address (Beacon_Packet));
-- Clear all events
nRF51.Events.Clear (nRF51.Events.Radio_DISABLED);
nRF51.Events.Clear (nRF51.Events.Radio_ADDRESS);
nRF51.Events.Clear (nRF51.Events.Radio_PAYLOAD);
nRF51.Events.Clear (nRF51.Events.Radio_END);
-- Start transmission
nRF51.Tasks.Trigger (nRF51.Tasks.Radio_TXEN);
-- Wait for end of transmission
while not nRF51.Events.Triggered (nRF51.Events.Radio_DISABLED) loop
null;
end loop;
end Send_Beacon_Packet;
end Beacon;
|
------------------------------------------------------------------------------
-- --
-- Copyright (C) 2016, AdaCore --
-- --
-- Redistribution and use in source and binary forms, with or without --
-- modification, are permitted provided that the following conditions are --
-- met: --
-- 1. Redistributions of source code must retain the above copyright --
-- notice, this list of conditions and the following disclaimer. --
-- 2. Redistributions in binary form must reproduce the above copyright --
-- notice, this list of conditions and the following disclaimer in --
-- the documentation and/or other materials provided with the --
-- distribution. --
-- 3. Neither the name of the copyright holder nor the names of its --
-- contributors may be used to endorse or promote products derived --
-- from this software without specific prior written permission. --
-- --
-- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS --
-- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT --
-- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR --
-- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT --
-- HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, --
-- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT --
-- LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, --
-- DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY --
-- THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT --
-- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE --
-- OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. --
-- --
------------------------------------------------------------------------------
with nRF51.Tasks;
with nRF51.Events;
with nRF51.Radio; use nRF51.Radio;
with NRF51_SVD.RADIO; use NRF51_SVD.RADIO;
with nRF51.Clock; use nRF51.Clock;
with Bluetooth_Low_Energy.Packets; use Bluetooth_Low_Energy.Packets;
with Bluetooth_Low_Energy; use Bluetooth_Low_Energy;
with Bluetooth_Low_Energy.Beacon; use Bluetooth_Low_Energy.Beacon;
with HAL; use HAL;
package body Beacon is
Current_Adv_Channel : BLE_Advertising_Channel_Number := 37;
Beacon_Packet : BLE_Packet;
----------------------
-- Initialize_Radio --
----------------------
procedure Initialize_Radio is
Beacon_UUID : constant BLE_UUID :=
Make_UUID ((1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16));
begin
Beacon_Packet := Make_Beacon_Packet (UUID => Beacon_UUID,
Major => 0,
Minor => 0,
Power => 0);
-- Setup high frequency clock for BLE transmission
Set_High_Freq_Source (HFCLK_RC);
Start_High_Freq;
while not High_Freq_Running loop
null;
end loop;
-- Setup radio module for BLE
Setup_For_Bluetooth_Low_Energy;
-- Set BLE advertising address
Set_Logic_Addresses (Base0 => 16#89_BE_D6_00#,
Base1 => 16#00_00_00_00#,
Base_Length_In_Byte => 3,
AP0 => 16#8E#,
AP1 => 16#00#,
AP2 => 16#00#,
AP3 => 16#00#,
AP4 => 16#00#,
AP5 => 16#00#,
AP6 => 16#00#,
AP7 => 16#00#);
-- Select logic address
Set_TX_Address (0);
-- Transmission power
Set_Power (Zero_Dbm);
-- Enable shortcuts for easier radio operation
Enable_Shortcut (Ready_To_Start);
Enable_Shortcut (End_To_Disable);
end Initialize_Radio;
------------------------
-- Send_Beacon_Packet --
------------------------
procedure Send_Beacon_Packet is
begin
Configure_Whitening (True, UInt6 (Current_Adv_Channel));
Set_Frequency
(Radio_Frequency_MHz (Channel_Frequency (Current_Adv_Channel)));
if Current_Adv_Channel /= BLE_Advertising_Channel_Number'Last then
Current_Adv_Channel := Current_Adv_Channel + 1;
else
Current_Adv_Channel := BLE_Advertising_Channel_Number'First;
end if;
-- Set TX packet address
Set_Packet (Memory_Address (Beacon_Packet));
-- Clear all events
nRF51.Events.Clear (nRF51.Events.Radio_DISABLED);
nRF51.Events.Clear (nRF51.Events.Radio_ADDRESS);
nRF51.Events.Clear (nRF51.Events.Radio_PAYLOAD);
nRF51.Events.Clear (nRF51.Events.Radio_END);
-- Start transmission
nRF51.Tasks.Trigger (nRF51.Tasks.Radio_TXEN);
-- Wait for end of transmission
while not nRF51.Events.Triggered (nRF51.Events.Radio_DISABLED) loop
null;
end loop;
end Send_Beacon_Packet;
end Beacon;
|
Fix compilation error
|
MicroBit: Fix compilation error
|
Ada
|
bsd-3-clause
|
Fabien-Chouteau/Ada_Drivers_Library,AdaCore/Ada_Drivers_Library,AdaCore/Ada_Drivers_Library,simonjwright/Ada_Drivers_Library,ellamosi/Ada_BMP_Library,simonjwright/Ada_Drivers_Library,lambourg/Ada_Drivers_Library,Fabien-Chouteau/Ada_Drivers_Library
|
227c401f6634acfe4f0eca2a5179232ebf44668a
|
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 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;
|
-----------------------------------------------------------------------
-- 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);
D := ASF.Servlets.Rest.Create_Route (Servlet);
Route := ASF.Routes.Route_Type_Refs.Create (D.all'Access);
else
D := ASF.Routes.Servlets.Rest.API_Route_Type (R.all)'Access;
end if;
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;
|
Allow to override the route mapping
|
Allow to override the route mapping
|
Ada
|
apache-2.0
|
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
|
409d4fb44609509565f4376f18a7a2cd4dbf8dd0
|
src/el-beans.ads
|
src/el-beans.ads
|
-----------------------------------------------------------------------
-- EL.Beans -- Interface Definition with Getter and Setters
-- Copyright (C) 2009, 2010 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with EL.Objects;
package EL.Beans is
-- Exception raised when the value identified by a name is not
-- recognized.
No_Value : exception;
-- ------------------------------
-- Read-only Bean interface.
-- ------------------------------
-- The ''Readonly_Bean'' interface allows to plug a complex
-- runtime object to the expression resolver. This interface
-- must be implemented by any tagged record that should be
-- accessed as a variable for an expression.
--
-- For example, if 'foo' is bound to an object implementing that
-- interface, expressions like 'foo.name' will resolve to 'foo'
-- and the 'Get_Value' method will be called with 'name'.
--
type Readonly_Bean is limited interface;
type Readonly_Bean_Access is access all Readonly_Bean'Class;
-- Get the value identified by the name.
-- If the name cannot be found, the method should return the Null object.
function Get_Value (From : Readonly_Bean;
Name : String) return EL.Objects.Object is abstract;
-- ------------------------------
-- Bean interface.
-- ------------------------------
-- The ''Bean'' interface allows to modify a property value.
type Bean is limited interface and Readonly_Bean;
-- Set the value identified by the name.
-- If the name cannot be found, the method should raise the No_Value
-- exception.
procedure Set_Value (From : in out Bean;
Name : in String;
Value : in EL.Objects.Object) is abstract;
-- ------------------------------
-- List of objects
-- ------------------------------
-- The <b>List_Bean</b> interface gives access to a list of objects.
type List_Bean is limited interface and Readonly_Bean;
type List_Bean_Access is access all List_Bean'Class;
-- Get the number of elements in the list.
function Get_Count (From : List_Bean) return Natural is abstract;
-- Set the current row index. Valid row indexes start at 1.
procedure Set_Row_Index (From : in out List_Bean;
Index : in Natural) is abstract;
-- Get the element at the current row index.
function Get_Row (From : List_Bean) return EL.Objects.Object is abstract;
end EL.Beans;
|
-----------------------------------------------------------------------
-- EL.Beans -- Interface Definition with Getter and Setters
-- Copyright (C) 2009, 2010 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with EL.Objects;
package EL.Beans is
pragma Preelaborate;
-- Exception raised when the value identified by a name is not
-- recognized.
No_Value : exception;
-- ------------------------------
-- Read-only Bean interface.
-- ------------------------------
-- The ''Readonly_Bean'' interface allows to plug a complex
-- runtime object to the expression resolver. This interface
-- must be implemented by any tagged record that should be
-- accessed as a variable for an expression.
--
-- For example, if 'foo' is bound to an object implementing that
-- interface, expressions like 'foo.name' will resolve to 'foo'
-- and the 'Get_Value' method will be called with 'name'.
--
type Readonly_Bean is limited interface;
type Readonly_Bean_Access is access all Readonly_Bean'Class;
-- Get the value identified by the name.
-- If the name cannot be found, the method should return the Null object.
function Get_Value (From : Readonly_Bean;
Name : String) return EL.Objects.Object is abstract;
-- ------------------------------
-- Bean interface.
-- ------------------------------
-- The ''Bean'' interface allows to modify a property value.
type Bean is limited interface and Readonly_Bean;
-- Set the value identified by the name.
-- If the name cannot be found, the method should raise the No_Value
-- exception.
procedure Set_Value (From : in out Bean;
Name : in String;
Value : in EL.Objects.Object) is abstract;
-- ------------------------------
-- List of objects
-- ------------------------------
-- The <b>List_Bean</b> interface gives access to a list of objects.
type List_Bean is limited interface and Readonly_Bean;
type List_Bean_Access is access all List_Bean'Class;
-- Get the number of elements in the list.
function Get_Count (From : List_Bean) return Natural is abstract;
-- Set the current row index. Valid row indexes start at 1.
procedure Set_Row_Index (From : in out List_Bean;
Index : in Natural) is abstract;
-- Get the element at the current row index.
function Get_Row (From : List_Bean) return EL.Objects.Object is abstract;
end EL.Beans;
|
Add preelaborate pragma
|
Add preelaborate pragma
|
Ada
|
apache-2.0
|
Letractively/ada-el
|
fdea95a039054a07bf18a0b638815f74fd2993fe
|
awa/regtests/awa-blogs-modules-tests.adb
|
awa/regtests/awa-blogs-modules-tests.adb
|
-----------------------------------------------------------------------
-- awa-blogs-tests -- Unit tests for blogs module
-- Copyright (C) 2011, 2012, 2013, 2014 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Test_Caller;
with ADO;
with Security.Contexts;
with AWA.Services.Contexts;
with AWA.Blogs.Modules;
with AWA.Tests.Helpers.Users;
package body AWA.Blogs.Modules.Tests is
use Util.Tests;
use ADO;
package Caller is new Util.Test_Caller (Test, "Blogs.Services");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test AWA.Blogs.Services.Create_Blog",
Test_Create_Blog'Access);
Caller.Add_Test (Suite, "Test AWA.Blogs.Services.Create_Post",
Test_Create_Post'Access);
end Add_Tests;
-- ------------------------------
-- Test creation of a blog
-- ------------------------------
procedure Test_Create_Blog (T : in out Test) is
Manager : AWA.Blogs.Modules.Blog_Module_Access;
Blog_Id : ADO.Identifier;
Sec_Ctx : Security.Contexts.Security_Context;
Context : AWA.Services.Contexts.Service_Context;
begin
AWA.Tests.Helpers.Users.Login (Context, Sec_Ctx, "[email protected]");
Manager := AWA.Blogs.Modules.Get_Blog_Module;
Manager.Create_Blog (Workspace_Id => 0,
Title => "My blog",
Result => Blog_Id);
T.Assert (Blog_Id > 0, "Invalid blog identifier");
end Test_Create_Blog;
-- ------------------------------
-- Test creating and updating of a blog post
-- ------------------------------
procedure Test_Create_Post (T : in out Test) is
Manager : AWA.Blogs.Modules.Blog_Module_Access;
Blog_Id : ADO.Identifier;
Post_Id : ADO.Identifier;
Sec_Ctx : Security.Contexts.Security_Context;
Context : AWA.Services.Contexts.Service_Context;
begin
AWA.Tests.Helpers.Users.Login (Context, Sec_Ctx, "[email protected]");
Manager := AWA.Blogs.Modules.Get_Blog_Module;
Manager.Create_Blog (Workspace_Id => 0,
Title => "My blog post",
Result => Blog_Id);
T.Assert (Blog_Id > 0, "Invalid blog identifier");
for I in 1 .. 5 loop
Manager.Create_Post (Blog_Id => Blog_Id,
Title => "Testing blog title",
URI => "testing-blog-title",
Text => "The blog content",
Status => AWA.Blogs.Models.POST_DRAFT,
Result => Post_Id);
T.Assert (Post_Id > 0, "Invalid post identifier");
Manager.Update_Post (Post_Id => Post_Id,
Title => "New blog post title",
URI => "testing-blog-title",
Text => "The new post content",
Status => AWA.Blogs.Models.POST_DRAFT);
-- Keep the last post in the database.
exit when I = 5;
Manager.Delete_Post (Post_Id => Post_Id);
-- Verify that a Not_Found exception is raised if the post was deleted.
begin
Manager.Update_Post (Post_Id => Post_Id,
Title => "Something",
Text => "Content",
URI => "testing-blog-title",
Status => AWA.Blogs.Models.POST_DRAFT);
T.Assert (False, "Exception Not_Found was not raised");
exception
when Not_Found =>
null;
end;
-- Verify that a Not_Found exception is raised if the post was deleted.
begin
Manager.Delete_Post (Post_Id => Post_Id);
T.Assert (False, "Exception Not_Found was not raised");
exception
when Not_Found =>
null;
end;
end loop;
end Test_Create_Post;
end AWA.Blogs.Modules.Tests;
|
-----------------------------------------------------------------------
-- awa-blogs-tests -- Unit tests for blogs module
-- Copyright (C) 2011, 2012, 2013, 2014 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Test_Caller;
with ADO;
with Security.Contexts;
with AWA.Services.Contexts;
with AWA.Blogs.Modules;
with AWA.Tests.Helpers.Users;
package body AWA.Blogs.Modules.Tests is
use Util.Tests;
use ADO;
package Caller is new Util.Test_Caller (Test, "Blogs.Services");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test AWA.Blogs.Services.Create_Blog",
Test_Create_Blog'Access);
Caller.Add_Test (Suite, "Test AWA.Blogs.Services.Create_Post",
Test_Create_Post'Access);
end Add_Tests;
-- ------------------------------
-- Test creation of a blog
-- ------------------------------
procedure Test_Create_Blog (T : in out Test) is
Manager : AWA.Blogs.Modules.Blog_Module_Access;
Blog_Id : ADO.Identifier;
Sec_Ctx : Security.Contexts.Security_Context;
Context : AWA.Services.Contexts.Service_Context;
begin
AWA.Tests.Helpers.Users.Login (Context, Sec_Ctx, "[email protected]");
Manager := AWA.Blogs.Modules.Get_Blog_Module;
Manager.Create_Blog (Workspace_Id => 0,
Title => "My blog",
Result => Blog_Id);
T.Assert (Blog_Id > 0, "Invalid blog identifier");
end Test_Create_Blog;
-- ------------------------------
-- Test creating and updating of a blog post
-- ------------------------------
procedure Test_Create_Post (T : in out Test) is
Manager : AWA.Blogs.Modules.Blog_Module_Access;
Blog_Id : ADO.Identifier;
Post_Id : ADO.Identifier;
Sec_Ctx : Security.Contexts.Security_Context;
Context : AWA.Services.Contexts.Service_Context;
begin
AWA.Tests.Helpers.Users.Login (Context, Sec_Ctx, "[email protected]");
Manager := AWA.Blogs.Modules.Get_Blog_Module;
Manager.Create_Blog (Workspace_Id => 0,
Title => "My blog post",
Result => Blog_Id);
T.Assert (Blog_Id > 0, "Invalid blog identifier");
for I in 1 .. 5 loop
Manager.Create_Post (Blog_Id => Blog_Id,
Title => "Testing blog title",
URI => "testing-blog-title",
Text => "The blog content",
Comment => False,
Status => AWA.Blogs.Models.POST_DRAFT,
Result => Post_Id);
T.Assert (Post_Id > 0, "Invalid post identifier");
Manager.Update_Post (Post_Id => Post_Id,
Title => "New blog post title",
URI => "testing-blog-title",
Text => "The new post content",
Comment => True,
Status => AWA.Blogs.Models.POST_DRAFT);
-- Keep the last post in the database.
exit when I = 5;
Manager.Delete_Post (Post_Id => Post_Id);
-- Verify that a Not_Found exception is raised if the post was deleted.
begin
Manager.Update_Post (Post_Id => Post_Id,
Title => "Something",
Text => "Content",
URI => "testing-blog-title",
Comment => True,
Status => AWA.Blogs.Models.POST_DRAFT);
T.Assert (False, "Exception Not_Found was not raised");
exception
when Not_Found =>
null;
end;
-- Verify that a Not_Found exception is raised if the post was deleted.
begin
Manager.Delete_Post (Post_Id => Post_Id);
T.Assert (False, "Exception Not_Found was not raised");
exception
when Not_Found =>
null;
end;
end loop;
end Test_Create_Post;
end AWA.Blogs.Modules.Tests;
|
Update the unit tests
|
Update the unit tests
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
8b30b26546a78f36f938bc643b85bdd1daa774d1
|
src/wiki-strings.ads
|
src/wiki-strings.ads
|
-----------------------------------------------------------------------
-- wiki-strings -- Wiki string types and operations
-- Copyright (C) 2016, 2017, 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.Containers;
with Ada.Strings.Wide_Wide_Unbounded;
with Ada.Strings.Wide_Wide_Maps;
with Ada.Strings.Wide_Wide_Hash;
with Ada.Characters.Conversions;
with Ada.Wide_Wide_Characters.Handling;
with Ada.Strings.Wide_Wide_Fixed;
with Ada.Strings.UTF_Encoding.Wide_Wide_Strings;
with Util.Texts.Builders;
package Wiki.Strings is
pragma Preelaborate;
subtype WChar is Wide_Wide_Character;
subtype WString is Wide_Wide_String;
subtype UString is Ada.Strings.Wide_Wide_Unbounded.Unbounded_Wide_Wide_String;
subtype WChar_Mapping is Ada.Strings.Wide_Wide_Maps.Wide_Wide_Character_Mapping;
function To_WChar (C : in Character) return WChar
renames Ada.Characters.Conversions.To_Wide_Wide_Character;
function To_Char (C : in WChar; Substitute : in Character := ' ') return Character
renames Ada.Characters.Conversions.To_Character;
function To_String (S : in WString; Output_BOM : in Boolean := False) return String
renames Ada.Strings.UTF_Encoding.Wide_Wide_Strings.Encode;
function To_UString (S : in WString) return UString
renames Ada.Strings.Wide_Wide_Unbounded.To_Unbounded_Wide_Wide_String;
function To_WString (S : in UString) return WString
renames Ada.Strings.Wide_Wide_Unbounded.To_Wide_Wide_String;
function To_WString (S : in String) return WString
renames Ada.Strings.UTF_Encoding.Wide_Wide_Strings.Decode;
function Hash (S : in WString) return Ada.Containers.Hash_Type
renames Ada.Strings.Wide_Wide_Hash;
procedure Append (Into : in out UString; S : in WString)
renames Ada.Strings.Wide_Wide_Unbounded.Append;
procedure Append (Into : in out UString; S : in WChar)
renames Ada.Strings.Wide_Wide_Unbounded.Append;
function Length (S : in UString) return Natural
renames Ada.Strings.Wide_Wide_Unbounded.Length;
function Element (S : in UString; Pos : in Positive) return WChar
renames Ada.Strings.Wide_Wide_Unbounded.Element;
function Is_Alphanumeric (C : in WChar) return Boolean
renames Ada.Wide_Wide_Characters.Handling.Is_Alphanumeric;
function Index (S : in WString;
P : in WString;
Going : in Ada.Strings.Direction := Ada.Strings.Forward;
Mapping : in WChar_Mapping := Ada.Strings.Wide_Wide_Maps.Identity)
return Natural renames Ada.Strings.Wide_Wide_Fixed.Index;
Null_UString : UString
renames Ada.Strings.Wide_Wide_Unbounded.Null_Unbounded_Wide_Wide_String;
package Wide_Wide_Builders is new Util.Texts.Builders (Element_Type => WChar,
Input => WString,
Chunk_Size => 512);
subtype BString is Wide_Wide_Builders.Builder;
function Length (Source : in Bstring) return Natural renames Wide_Wide_Builders.Length;
function Element (Source : in BString;
Position : in Positive) return WChar renames Wide_Wide_Builders.Element;
procedure Append_String (Source : in out BString;
Content : in WString) renames Wide_Wide_Builders.Append;
procedure Append (Source : in out BString;
Content : in BString;
From : in Positive;
To : in Positive) renames Wide_Wide_Builders.Append;
-- Search for the first occurrence of the character in the builder and
-- starting after the from index. Returns the index of the first occurence or 0.
function Index (Source : in BString;
Char : in WChar;
From : in Positive := 1) return Natural;
-- Find the last position of the character in the string and starting
-- at the given position. Stop at the first character different than `Char`.
function Last_Position (Source : in Bstring;
Char : in WChar;
From : in Positive := 1) return Natural;
-- Count the the number of consecutive occurence of the given character
-- and starting at the given position.
function Count_Occurence (Source : in Bstring;
Char : in Wchar;
From : in Positive := 1) return Natural;
function Skip_Spaces (Source : in Bstring;
From : in Positive;
Last : in Positive) return Positive;
end Wiki.Strings;
|
-----------------------------------------------------------------------
-- wiki-strings -- Wiki string types and operations
-- Copyright (C) 2016, 2017, 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.Containers;
with Ada.Strings.Wide_Wide_Unbounded;
with Ada.Strings.Wide_Wide_Maps;
with Ada.Strings.Wide_Wide_Hash;
with Ada.Characters.Conversions;
with Ada.Wide_Wide_Characters.Handling;
with Ada.Strings.Wide_Wide_Fixed;
with Ada.Strings.UTF_Encoding.Wide_Wide_Strings;
with Util.Texts.Builders;
package Wiki.Strings is
pragma Preelaborate;
subtype WChar is Wide_Wide_Character;
subtype WString is Wide_Wide_String;
subtype UString is Ada.Strings.Wide_Wide_Unbounded.Unbounded_Wide_Wide_String;
subtype WChar_Mapping is Ada.Strings.Wide_Wide_Maps.Wide_Wide_Character_Mapping;
function To_WChar (C : in Character) return WChar
renames Ada.Characters.Conversions.To_Wide_Wide_Character;
function To_Char (C : in WChar; Substitute : in Character := ' ') return Character
renames Ada.Characters.Conversions.To_Character;
function To_String (S : in WString; Output_BOM : in Boolean := False) return String
renames Ada.Strings.UTF_Encoding.Wide_Wide_Strings.Encode;
function To_UString (S : in WString) return UString
renames Ada.Strings.Wide_Wide_Unbounded.To_Unbounded_Wide_Wide_String;
function To_WString (S : in UString) return WString
renames Ada.Strings.Wide_Wide_Unbounded.To_Wide_Wide_String;
function To_WString (S : in String) return WString
renames Ada.Strings.UTF_Encoding.Wide_Wide_Strings.Decode;
function Hash (S : in WString) return Ada.Containers.Hash_Type
renames Ada.Strings.Wide_Wide_Hash;
procedure Append (Into : in out UString; S : in WString)
renames Ada.Strings.Wide_Wide_Unbounded.Append;
procedure Append (Into : in out UString; S : in WChar)
renames Ada.Strings.Wide_Wide_Unbounded.Append;
function Length (S : in UString) return Natural
renames Ada.Strings.Wide_Wide_Unbounded.Length;
function Element (S : in UString; Pos : in Positive) return WChar
renames Ada.Strings.Wide_Wide_Unbounded.Element;
function Is_Alphanumeric (C : in WChar) return Boolean
renames Ada.Wide_Wide_Characters.Handling.Is_Alphanumeric;
function Index (S : in WString;
P : in WString;
Going : in Ada.Strings.Direction := Ada.Strings.Forward;
Mapping : in WChar_Mapping := Ada.Strings.Wide_Wide_Maps.Identity)
return Natural renames Ada.Strings.Wide_Wide_Fixed.Index;
Null_UString : UString
renames Ada.Strings.Wide_Wide_Unbounded.Null_Unbounded_Wide_Wide_String;
package Wide_Wide_Builders is new Util.Texts.Builders (Element_Type => WChar,
Input => WString,
Chunk_Size => 512);
subtype BString is Wide_Wide_Builders.Builder;
function Length (Source : in BString) return Natural renames Wide_Wide_Builders.Length;
function Element (Source : in BString;
Position : in Positive) return WChar renames Wide_Wide_Builders.Element;
function To_WString (Source : in BString) return WString renames Wide_Wide_Builders.To_Array;
procedure Clear (Source : in out BString) renames Wide_Wide_Builders.Clear;
procedure Append_String (Source : in out BString;
Content : in WString) renames Wide_Wide_Builders.Append;
procedure Append (Source : in out BString;
Content : in BString;
From : in Positive;
To : in Positive) renames Wide_Wide_Builders.Append;
procedure Append_Char (Source : in out BString;
Item : in WChar) renames Wide_Wide_Builders.Append;
-- Search for the first occurrence of the character in the builder and
-- starting after the from index. Returns the index of the first occurence or 0.
function Index (Source : in BString;
Char : in WChar;
From : in Positive := 1) return Natural;
-- Find the last position of the character in the string and starting
-- at the given position. Stop at the first character different than `Char`.
function Last_Position (Source : in BString;
Char : in WChar;
From : in Positive := 1) return Natural;
-- Count the the number of consecutive occurence of the given character
-- and starting at the given position.
function Count_Occurence (Source : in BString;
Char : in WChar;
From : in Positive := 1) return Natural;
function Count_Occurence (Source : in WString;
Char : in WChar;
From : in Positive := 1) return Natural;
function Skip_Spaces (Source : in BString;
From : in Positive;
Last : in Positive) return Positive;
procedure Scan_Line_Fragment (Source : in BString;
Process : not null
access procedure (Text : in WString;
Offset : in Natural));
end Wiki.Strings;
|
Add new operations for strings
|
Add new operations for strings
|
Ada
|
apache-2.0
|
stcarrez/ada-wiki,stcarrez/ada-wiki
|
d75ecbc991be32fd77e4f9d755c542cb65abf1d6
|
src/wiki-helpers.adb
|
src/wiki-helpers.adb
|
-----------------------------------------------------------------------
-- wiki-helpers -- Helper operations for wiki parsers and renderer
-- 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.Wide_Wide_Characters.Handling;
package body Wiki.Helpers is
-- ------------------------------
-- Returns True if the character is a space or tab.
-- ------------------------------
function Is_Space (C : in Wide_Wide_Character) return Boolean is
begin
return Ada.Wide_Wide_Characters.Handling.Is_Space (C) or C = HT;
end Is_Space;
-- ------------------------------
-- Returns True if the character is a space, tab or a newline.
-- ------------------------------
function Is_Space_Or_Newline (C : in Wide_Wide_Character) return Boolean is
begin
return Is_Space (C) or Ada.Wide_Wide_Characters.Handling.Is_Line_Terminator (C);
end Is_Space_Or_Newline;
-- ------------------------------
-- Returns True if the text is a valid URL
-- ------------------------------
function Is_Url (Text : in Wide_Wide_String) return Boolean is
begin
if Text'Length <= 9 then
return False;
else
return Text (Text'First .. Text'First + 6) = "http://"
or Text (Text'First .. Text'First + 7) = "https://";
end if;
end Is_Url;
-- ------------------------------
-- Returns True if the extension part correspond to an image.
-- Recognized extension are: .png, .gif, .jpg, .jpeg.
-- The extension case is ignored.
-- ------------------------------
function Is_Image_Extension (Ext : in Wide_Wide_String) return Boolean is
S : constant Wide_Wide_String := Ada.Wide_Wide_Characters.Handling.To_Lower (Ext);
begin
return S = ".png" or S = ".jpg" or S = ".gif" or S = ".jpeg";
end Is_Image_Extension;
end Wiki.Helpers;
|
-----------------------------------------------------------------------
-- wiki-helpers -- Helper operations for wiki parsers and renderer
-- 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.Wide_Wide_Characters.Handling;
package body Wiki.Helpers is
-- ------------------------------
-- Returns True if the character is a space or tab.
-- ------------------------------
function Is_Space (C : in Wide_Wide_Character) return Boolean is
begin
return Ada.Wide_Wide_Characters.Handling.Is_Space (C) or C = HT;
end Is_Space;
-- ------------------------------
-- Returns True if the character is a space, tab or a newline.
-- ------------------------------
function Is_Space_Or_Newline (C : in Wide_Wide_Character) return Boolean is
begin
return Is_Space (C) or Ada.Wide_Wide_Characters.Handling.Is_Line_Terminator (C);
end Is_Space_Or_Newline;
-- ------------------------------
-- Returns True if the text is a valid URL
-- ------------------------------
function Is_Url (Text : in Wide_Wide_String) return Boolean is
begin
if Text'Length <= 9 then
return False;
else
return Text (Text'First .. Text'First + 6) = "http://"
or Text (Text'First .. Text'First + 7) = "https://";
end if;
end Is_Url;
-- ------------------------------
-- Returns True if the extension part correspond to an image.
-- Recognized extension are: .png, .gif, .jpg, .jpeg.
-- The extension case is ignored.
-- ------------------------------
function Is_Image_Extension (Ext : in Wide_Wide_String) return Boolean is
S : constant Wide_Wide_String := Ada.Wide_Wide_Characters.Handling.To_Lower (Ext);
begin
return S = ".png" or S = ".jpg" or S = ".gif" or S = ".jpeg";
end Is_Image_Extension;
-- ------------------------------
-- Given the current tag on the top of the stack and the new tag that will be pushed,
-- decide whether the current tag must be closed or not.
-- Returns True if the current tag must be closed.
-- ------------------------------
function Need_Close (Tag : in Html_Tag;
Current_Tag : in Html_Tag) return Boolean is
begin
if No_End_Tag (Current_Tag) then
return True;
elsif Current_Tag = Tag and Tag_Omission (Current_Tag) then
return True;
else
case Current_Tag is
when DT_TAG | DD_TAG =>
return Tag = DD_TAG or Tag = DL_TAG or Tag = DT_TAG;
when TD_TAG =>
return Tag = TD_TAG or Tag = TR_TAG or Tag = TH_TAG;
when TR_TAG =>
return False;
when others =>
return False;
end case;
end if;
end Need_Close;
end Wiki.Helpers;
|
Move the Need_Close internal function to the Wiki.Helpers package
|
Move the Need_Close internal function to the Wiki.Helpers package
|
Ada
|
apache-2.0
|
stcarrez/ada-wiki,stcarrez/ada-wiki
|
a62bed55a0d5299be6a3e024d5e8e79ccd92e207
|
awa/regtests/awa-events-tests.adb
|
awa/regtests/awa-events-tests.adb
|
-----------------------------------------------------------------------
-- events-tests -- Unit tests for AWA events
-- Copyright (C) 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Tests;
with Util.Test_Caller;
with EL.Beans;
with EL.Expressions;
with EL.Contexts.Default;
with ASF.Applications;
with AWA.Applications;
with AWA.Applications.Configs;
with AWA.Applications.Factory;
with AWA.Tests;
with ADO.Sessions;
with AWA.Events.Queues;
with AWA.Events.Queues.Fifos;
with AWA.Events.Services;
package body AWA.Events.Tests is
use AWA.Events.Services;
package Event_Test_4 is new AWA.Events.Definition (Name => "event-test-4");
package Event_Test_1 is new AWA.Events.Definition (Name => "event-test-1");
package Event_Test_3 is new AWA.Events.Definition (Name => "event-test-3");
package Event_Test_2 is new AWA.Events.Definition (Name => "event-test-2");
package Event_Test_5 is new AWA.Events.Definition (Name => "event-test-5");
package Caller is new Util.Test_Caller (Test, "Events.Tests");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test AWA.Events.Find_Event_Index",
Test_Find_Event'Access);
Caller.Add_Test (Suite, "Test AWA.Events.Initialize",
Test_Initialize'Access);
Caller.Add_Test (Suite, "Test AWA.Events.Add_Action",
Test_Add_Action'Access);
Caller.Add_Test (Suite, "Test AWA.Events.Dispatch",
Test_Dispatch'Access);
end Add_Tests;
-- ------------------------------
-- Test searching an event name in the definition list.
-- ------------------------------
procedure Test_Find_Event (T : in out Test) is
begin
Util.Tests.Assert_Equals (T, Integer (Event_Test_4.Kind),
Integer (Find_Event_Index ("event-test-4")), "Find_Event");
Util.Tests.Assert_Equals (T, Integer (Event_Test_5.Kind),
Integer (Find_Event_Index ("event-test-5")), "Find_Event");
Util.Tests.Assert_Equals (T, Integer (Event_Test_1.Kind),
Integer (Find_Event_Index ("event-test-1")), "Find_Event");
end Test_Find_Event;
-- ------------------------------
-- Test creation and initialization of event manager.
-- ------------------------------
procedure Test_Initialize (T : in out Test) is
App : AWA.Applications.Application_Access := AWA.Tests.Get_Application;
Manager : Event_Manager;
Session : ADO.Sessions.Master_Session := App.Get_Master_Session;
begin
Manager.Initialize (Session);
-- T.Assert (Manager.Actions /= null, "Initialization failed");
end Test_Initialize;
-- ------------------------------
-- Test adding an action.
-- ------------------------------
procedure Test_Add_Action (T : in out Test) is
use AWA.Events.Queues;
App : AWA.Applications.Application_Access := AWA.Tests.Get_Application;
Manager : Event_Manager;
Ctx : EL.Contexts.Default.Default_Context;
Session : ADO.Sessions.Master_Session := App.Get_Master_Session;
Action : EL.Expressions.Method_Expression := EL.Expressions.Create_Expression ("#{a.send}", Ctx);
Props : EL.Beans.Param_Vectors.Vector;
Pos : Event_Index := Find_Event_Index ("event-test-4");
Queue : Queue_Access;
begin
Manager.Initialize (Session);
Queue := AWA.Events.Queues.Fifos.Create_Queue ("fifo", Props, Ctx);
Manager.Add_Queue (Queue);
for I in 1 .. 10 loop
Manager.Add_Action (Event => "event-test-4",
Queue => Queue,
Action => Action,
Params => Props);
-- Util.Tests.Assert_Equals (T, 1, Integer (Manager.Actions (Pos).Queues.Length),
-- "Add_Action failed");
end loop;
end Test_Add_Action;
-- Test dispatching events
procedure Test_Dispatch (T : in out Test) is
Factory : AWA.Applications.Factory.Application_Factory;
Conf : ASF.Applications.Config;
App : aliased AWA.Applications.Application;
Ctx : aliased EL.Contexts.Default.Default_Context;
Path : constant String := Util.Tests.Get_Test_Path ("regtests/config/event-test.xml");
begin
Conf.Set ("database", Util.Tests.Get_Parameter ("database"));
App.Initialize (Conf => Conf,
Factory => Factory);
AWA.Applications.Configs.Read_Configuration (App => App,
File => Path,
Context => Ctx'Unchecked_Access);
for I in 1 .. 100 loop
declare
Event : Module_Event;
begin
Event.Set_Event_Kind (Event_Test_4.Kind);
Event.Set_Parameter ("prio", "3");
Event.Set_Parameter ("template", "def");
App.Send_Event (Event);
end;
end loop;
end Test_Dispatch;
end AWA.Events.Tests;
|
-----------------------------------------------------------------------
-- events-tests -- Unit tests for AWA events
-- Copyright (C) 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Tests;
with Util.Test_Caller;
with EL.Beans;
with EL.Expressions;
with EL.Contexts.Default;
with ASF.Applications;
with AWA.Applications;
with AWA.Applications.Configs;
with AWA.Applications.Factory;
with AWA.Tests;
with ADO.Sessions;
with AWA.Events.Queues;
with AWA.Events.Services;
package body AWA.Events.Tests is
use AWA.Events.Services;
package Event_Test_4 is new AWA.Events.Definition (Name => "event-test-4");
package Event_Test_1 is new AWA.Events.Definition (Name => "event-test-1");
package Event_Test_3 is new AWA.Events.Definition (Name => "event-test-3");
package Event_Test_2 is new AWA.Events.Definition (Name => "event-test-2");
package Event_Test_5 is new AWA.Events.Definition (Name => "event-test-5");
package Caller is new Util.Test_Caller (Test, "Events.Tests");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test AWA.Events.Find_Event_Index",
Test_Find_Event'Access);
Caller.Add_Test (Suite, "Test AWA.Events.Initialize",
Test_Initialize'Access);
Caller.Add_Test (Suite, "Test AWA.Events.Add_Action",
Test_Add_Action'Access);
Caller.Add_Test (Suite, "Test AWA.Events.Dispatch",
Test_Dispatch'Access);
end Add_Tests;
-- ------------------------------
-- Test searching an event name in the definition list.
-- ------------------------------
procedure Test_Find_Event (T : in out Test) is
begin
Util.Tests.Assert_Equals (T, Integer (Event_Test_4.Kind),
Integer (Find_Event_Index ("event-test-4")), "Find_Event");
Util.Tests.Assert_Equals (T, Integer (Event_Test_5.Kind),
Integer (Find_Event_Index ("event-test-5")), "Find_Event");
Util.Tests.Assert_Equals (T, Integer (Event_Test_1.Kind),
Integer (Find_Event_Index ("event-test-1")), "Find_Event");
end Test_Find_Event;
-- ------------------------------
-- Test creation and initialization of event manager.
-- ------------------------------
procedure Test_Initialize (T : in out Test) is
App : AWA.Applications.Application_Access := AWA.Tests.Get_Application;
Manager : Event_Manager;
Session : ADO.Sessions.Master_Session := App.Get_Master_Session;
begin
Manager.Initialize (Session);
-- T.Assert (Manager.Actions /= null, "Initialization failed");
end Test_Initialize;
-- ------------------------------
-- Test adding an action.
-- ------------------------------
procedure Test_Add_Action (T : in out Test) is
use AWA.Events.Queues;
App : AWA.Applications.Application_Access := AWA.Tests.Get_Application;
Manager : Event_Manager;
Ctx : EL.Contexts.Default.Default_Context;
Session : ADO.Sessions.Master_Session := App.Get_Master_Session;
Action : EL.Expressions.Method_Expression := EL.Expressions.Create_Expression ("#{a.send}", Ctx);
Props : EL.Beans.Param_Vectors.Vector;
Pos : Event_Index := Find_Event_Index ("event-test-4");
Queue : Queue_Ref;
begin
Manager.Initialize (Session);
Queue := AWA.Events.Queues.Create_Queue ("test", "fifo", Props, Ctx);
Manager.Add_Queue (Queue);
for I in 1 .. 10 loop
Manager.Add_Action (Event => "event-test-4",
Queue => Queue,
Action => Action,
Params => Props);
-- Util.Tests.Assert_Equals (T, 1, Integer (Manager.Actions (Pos).Queues.Length),
-- "Add_Action failed");
end loop;
end Test_Add_Action;
-- Test dispatching events
procedure Test_Dispatch (T : in out Test) is
Factory : AWA.Applications.Factory.Application_Factory;
Conf : ASF.Applications.Config;
App : aliased AWA.Applications.Application;
Ctx : aliased EL.Contexts.Default.Default_Context;
Path : constant String := Util.Tests.Get_Test_Path ("regtests/config/event-test.xml");
begin
Conf.Set ("database", Util.Tests.Get_Parameter ("database"));
App.Initialize (Conf => Conf,
Factory => Factory);
AWA.Applications.Configs.Read_Configuration (App => App,
File => Path,
Context => Ctx'Unchecked_Access);
for I in 1 .. 100 loop
declare
Event : Module_Event;
begin
Event.Set_Event_Kind (Event_Test_4.Kind);
Event.Set_Parameter ("prio", "3");
Event.Set_Parameter ("template", "def");
App.Send_Event (Event);
end;
end loop;
end Test_Dispatch;
end AWA.Events.Tests;
|
Update the AWA event unit test
|
Update the AWA event unit test
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
8ce55164e21692345bf00e73b66bcca0b62e197a
|
regtests/util-commands-tests.adb
|
regtests/util-commands-tests.adb
|
-----------------------------------------------------------------------
-- util-commands-tests - Test for commands
-- Copyright (C) 2018, 2019, 2020 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with 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;
Context : in out Test_Context_Type);
-- Write the help associated with the command.
procedure Help (Command : in out Test_Command_Type;
Name : in String;
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
pragma Unreferenced (Name);
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;
Context : in out Test_Context_Type) is
pragma Unreferenced (Context);
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 out Test_Command_Type;
Name : in String;
Context : in out Test_Context_Type) is
pragma Unreferenced (Name);
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;
declare
Ctx : Test_Context_Type;
begin
C1.Expect_Help := False;
C2.Expect_Help := False;
Initialize (Args, "help");
D.Execute ("help", Args, Ctx);
T.Assert (not Ctx.Success, "Some arguments not parsed correctly");
end;
declare
Ctx : Test_Context_Type;
begin
Initialize (Args, "help missing");
D.Execute ("help", Args, Ctx);
T.Fail ("No exception raised for missing command");
exception
when Not_Found =>
null;
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);
Args.Initialize (Line => "cmd list");
declare
Ctx : Test_Context_Type;
begin
D.Usage (Args, Ctx);
C1.Expect_Help := True;
Initialize (Args, "help list");
D.Execute ("help", Args, Ctx);
T.Assert (Ctx.Success, "Some arguments not parsed correctly");
D.Usage (Args, Ctx, "list");
end;
end Test_Usage;
end Util.Commands.Tests;
|
-----------------------------------------------------------------------
-- util-commands-tests - Test for commands
-- Copyright (C) 2018, 2019, 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 GNAT.Command_Line;
with Util.Test_Caller;
with Util.Log;
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 := 0;
Success : Boolean := False;
end record;
procedure Simple (Name : in String;
Args : in Argument_List'Class;
Ctx : in out Test_Context_Type);
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");
package Simple_Command is new
Util.Commands.Drivers (Context_Type => Test_Context_Type,
Config_Parser => Util.Commands.Parsers.No_Parser,
Driver_Name => "simple");
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;
Context : in out Test_Context_Type);
-- Write the help associated with the command.
procedure Help (Command : in out Test_Command_Type;
Name : in String;
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);
Caller.Add_Test (Suite, "Test Util.Commands.Driver.Add_Command",
Test_Simple_Command'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
pragma Unreferenced (Name);
begin
Command.Log (Util.Log.ERROR_LEVEL, "command", "execute command message");
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;
Context : in out Test_Context_Type) is
pragma Unreferenced (Context);
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 out Test_Command_Type;
Name : in String;
Context : in out Test_Context_Type) is
pragma Unreferenced (Name);
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;
declare
Ctx : Test_Context_Type;
begin
C1.Expect_V := False;
C1.Expect_N := True;
C1.Expect_C := 8;
C1.Expect_A := 3;
Initialize (Args, "bad -c 8 -n test titi last");
D.Execute ("bad", Args, Ctx);
T.Fail ("No exception raised for missing command");
exception
when Not_Found =>
null;
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;
declare
Ctx : Test_Context_Type;
begin
C1.Expect_Help := False;
C2.Expect_Help := False;
Initialize (Args, "help");
D.Execute ("help", Args, Ctx);
T.Assert (not Ctx.Success, "Some arguments not parsed correctly");
end;
declare
Ctx : Test_Context_Type;
begin
Initialize (Args, "help missing");
D.Execute ("help", Args, Ctx);
T.Fail ("No exception raised for missing command");
exception
when Not_Found =>
null;
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);
Args.Initialize (Line => "cmd list");
declare
Ctx : Test_Context_Type;
begin
D.Usage (Args, Ctx);
C1.Expect_Help := True;
Initialize (Args, "help list");
D.Execute ("help", Args, Ctx);
T.Assert (Ctx.Success, "Some arguments not parsed correctly");
D.Usage (Args, Ctx, "list");
end;
end Test_Usage;
procedure Simple (Name : in String;
Args : in Argument_List'Class;
Ctx : in out Test_Context_Type) is
pragma Unreferenced (Name, Args);
begin
Ctx.Number := 1;
Ctx.Success := True;
end Simple;
-- Test command based on the No_Parser.
procedure Test_Simple_Command (T : in out Test) is
D : Simple_Command.Driver_Type;
Args : String_Argument_List (500, 30);
begin
D.Add_Command ("list", "list command", Simple'Access);
declare
Ctx : Test_Context_Type;
begin
Initialize (Args, "list --count=4 -v -n test titi");
D.Execute ("list", Args, Ctx);
T.Assert (Ctx.Success, "Some arguments not parsed correctly");
Util.Tests.Assert_Equals (T, 1, Ctx.Number, "Invalid context number");
D.Usage (Args, Ctx, "list");
end;
end Test_Simple_Command;
end Util.Commands.Tests;
|
Add Test_Simple_Command and register the new test for execution
|
Add Test_Simple_Command and register the new test for execution
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
c8294d7123d4789c5d71822ffe7107e37f3a66b0
|
matp/src/events/mat-events-timelines.ads
|
matp/src/events/mat-events-timelines.ads
|
-----------------------------------------------------------------------
-- mat-events-timelines - Timelines
-- 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.Containers.Vectors;
with MAT.Expressions;
with MAT.Events.Targets;
package MAT.Events.Timelines is
-- Describe a section of the timeline. The section has a starting and ending
-- event that marks the boundary of the section within the collected events.
-- The timeline section gives the duration and some statistics about memory
-- allocation made in the section.
type Timeline_Info is record
First_Event : MAT.Events.Targets.Probe_Event_Type;
Last_Event : MAT.Events.Targets.Probe_Event_Type;
Duration : MAT.Types.Target_Time := 0;
Malloc_Count : Natural := 0;
Realloc_Count : Natural := 0;
Free_Count : Natural := 0;
end record;
package Timeline_Info_Vectors is
new Ada.Containers.Vectors (Positive, Timeline_Info);
subtype Timeline_Info_Vector is Timeline_Info_Vectors.Vector;
subtype Timeline_Info_Cursor is Timeline_Info_Vectors.Cursor;
procedure Extract (Target : in out MAT.Events.Targets.Target_Events'Class;
Into : in out Timeline_Info_Vector);
-- Find in the events stream the events which are associated with a given event.
-- When the <tt>Event</tt> is a memory allocation, find the associated reallocation
-- and free events. When the event is a free, find the associated allocations.
-- Collect at most <tt>Max</tt> events.
procedure Find_Related (Target : in out MAT.Events.Targets.Target_Events'Class;
Event : in MAT.Events.Targets.Probe_Event_Type;
Max : in Positive;
List : in out MAT.Events.Targets.Target_Event_Vector);
-- Find the sizes of malloc and realloc events which is selected by the given filter.
-- Update the <tt>Sizes</tt> map to keep track of the first event and last event and
-- the number of events found for the corresponding size.
procedure Find_Sizes (Target : in out MAT.Events.Targets.Target_Events'Class;
Filter : in MAT.Expressions.Expression_Type;
Sizes : in out MAT.Events.Targets.Size_Event_Info_Map);
-- Find the function address from the call event frames for the events which is selected
-- by the given filter. The function addresses are collected up to the given frame depth.
-- Update the <tt>Frames</tt> map to keep track of the first event and last event and
-- the number of events found for the corresponding frame address.
procedure Find_Frames (Target : in out MAT.Events.Targets.Target_Events'Class;
Filter : in MAT.Expressions.Expression_Type;
Depth : in Natural;
Frames : in out MAT.Events.Targets.Frame_Event_Info_Map);
end MAT.Events.Timelines;
|
-----------------------------------------------------------------------
-- mat-events-timelines - Timelines
-- 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.Containers.Vectors;
with MAT.Expressions;
with MAT.Events.Targets;
package MAT.Events.Timelines is
-- Describe a section of the timeline. The section has a starting and ending
-- event that marks the boundary of the section within the collected events.
-- The timeline section gives the duration and some statistics about memory
-- allocation made in the section.
type Timeline_Info is record
First_Event : MAT.Events.Targets.Probe_Event_Type;
Last_Event : MAT.Events.Targets.Probe_Event_Type;
Duration : MAT.Types.Target_Time := 0;
Malloc_Count : Natural := 0;
Realloc_Count : Natural := 0;
Free_Count : Natural := 0;
Alloc_Size : MAT.Types.Target_Size := 0;
Free_Size : MAT.Types.Target_Size := 0;
end record;
package Timeline_Info_Vectors is
new Ada.Containers.Vectors (Positive, Timeline_Info);
subtype Timeline_Info_Vector is Timeline_Info_Vectors.Vector;
subtype Timeline_Info_Cursor is Timeline_Info_Vectors.Cursor;
procedure Extract (Target : in out MAT.Events.Targets.Target_Events'Class;
Into : in out Timeline_Info_Vector);
-- Find in the events stream the events which are associated with a given event.
-- When the <tt>Event</tt> is a memory allocation, find the associated reallocation
-- and free events. When the event is a free, find the associated allocations.
-- Collect at most <tt>Max</tt> events.
procedure Find_Related (Target : in out MAT.Events.Targets.Target_Events'Class;
Event : in MAT.Events.Targets.Probe_Event_Type;
Max : in Positive;
List : in out MAT.Events.Targets.Target_Event_Vector);
-- Find the sizes of malloc and realloc events which is selected by the given filter.
-- Update the <tt>Sizes</tt> map to keep track of the first event and last event and
-- the number of events found for the corresponding size.
procedure Find_Sizes (Target : in out MAT.Events.Targets.Target_Events'Class;
Filter : in MAT.Expressions.Expression_Type;
Sizes : in out MAT.Events.Targets.Size_Event_Info_Map);
-- Find the function address from the call event frames for the events which is selected
-- by the given filter. The function addresses are collected up to the given frame depth.
-- Update the <tt>Frames</tt> map to keep track of the first event and last event and
-- the number of events found for the corresponding frame address.
procedure Find_Frames (Target : in out MAT.Events.Targets.Target_Events'Class;
Filter : in MAT.Expressions.Expression_Type;
Depth : in Natural;
Frames : in out MAT.Events.Targets.Frame_Event_Info_Map);
end MAT.Events.Timelines;
|
Add Alloc_Size and Free_Size in the Timeline_Info record
|
Add Alloc_Size and Free_Size in the Timeline_Info record
|
Ada
|
apache-2.0
|
stcarrez/mat,stcarrez/mat,stcarrez/mat
|
5dc588c633c316fea092d3ad66405fc9c7d4f4ea
|
matp/src/symbols/mat-symbols-targets.ads
|
matp/src/symbols/mat-symbols-targets.ads
|
-----------------------------------------------------------------------
-- mat-symbols-targets - Symbol files management
-- Copyright (C) 2014, 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Ada.Containers.Ordered_Maps;
with Bfd.Symbols;
with Bfd.Files;
with Bfd.Constants;
with Util.Refs;
with MAT.Types;
with MAT.Consoles;
with MAT.Memory;
package MAT.Symbols.Targets is
type Symbol_Info is record
File : Ada.Strings.Unbounded.Unbounded_String;
Name : Ada.Strings.Unbounded.Unbounded_String;
Line : Natural;
end record;
-- The <tt>Region_Symbols</tt> holds the symbol table associated with the program or
-- a shared library loaded by the program. The <tt>Region</tt> indicates
-- the text segment address of the program or the loaded library.
type Region_Symbols is new Util.Refs.Ref_Entity with record
Region : MAT.Memory.Region_Info;
Offset : MAT.Types.Target_Addr;
File : Bfd.Files.File_Type;
Symbols : Bfd.Symbols.Symbol_Table;
end record;
type Region_Symbols_Access is access all Region_Symbols;
-- Load the symbol table for the associated region.
procedure Open (Symbols : in out Region_Symbols;
Path : in String);
package Region_Symbols_Refs is
new Util.Refs.References (Region_Symbols, Region_Symbols_Access);
subtype Region_Symbols_Ref is Region_Symbols_Refs.Ref;
-- The <tt>Symbols_Maps</tt> keeps a sorted list of symbol tables indexed
-- by their mapping address.
use type Region_Symbols_Refs.Ref;
use type MAT.Types.Target_Addr;
package Symbols_Maps is
new Ada.Containers.Ordered_Maps (Key_Type => MAT.Types.Target_Addr,
Element_Type => Region_Symbols_Ref);
subtype Symbols_Map is Symbols_Maps.Map;
subtype Symbols_Cursor is Symbols_Maps.Cursor;
type Target_Symbols is new Util.Refs.Ref_Entity with record
Path : Ada.Strings.Unbounded.Unbounded_String;
File : Bfd.Files.File_Type;
Symbols : Bfd.Symbols.Symbol_Table;
Libraries : Symbols_Maps.Map;
Demangle : Bfd.Demangle_Flags := Bfd.Constants.DMGL_AUTO;
Console : MAT.Consoles.Console_Access;
end record;
type Target_Symbols_Access is access all Target_Symbols;
-- Open the binary and load the symbols from that file.
procedure Open (Symbols : in out Target_Symbols;
Path : in String);
-- Load the symbols associated with a shared library described by the memory region.
procedure Load_Symbols (Symbols : in out Target_Symbols;
Region : in MAT.Memory.Region_Info;
Offset_Addr : in MAT.Types.Target_Addr);
-- Load the symbols associated with all the shared libraries described by
-- the memory region map.
procedure Load_Symbols (Symbols : in out Target_Symbols;
Regions : in MAT.Memory.Region_Info_Map);
-- Demangle the symbol.
procedure Demangle (Symbols : in Target_Symbols;
Symbol : in out Symbol_Info);
-- Find the nearest source file and line for the given address.
procedure Find_Nearest_Line (Symbols : in Target_Symbols;
Addr : in MAT.Types.Target_Addr;
Symbol : out Symbol_Info);
package Target_Symbols_Refs is
new Util.Refs.References (Target_Symbols, Target_Symbols_Access);
subtype Target_Symbols_Ref is Target_Symbols_Refs.Ref;
end MAT.Symbols.Targets;
|
-----------------------------------------------------------------------
-- mat-symbols-targets - Symbol files management
-- Copyright (C) 2014, 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Ada.Containers.Ordered_Maps;
with Bfd.Symbols;
with Bfd.Files;
with Bfd.Constants;
with Util.Refs;
with MAT.Types;
with MAT.Consoles;
with MAT.Memory;
package MAT.Symbols.Targets is
-- The <tt>Region_Symbols</tt> holds the symbol table associated with the program or
-- a shared library loaded by the program. The <tt>Region</tt> indicates
-- the text segment address of the program or the loaded library.
type Region_Symbols is new Util.Refs.Ref_Entity with record
Region : MAT.Memory.Region_Info;
Offset : MAT.Types.Target_Addr;
File : Bfd.Files.File_Type;
Symbols : Bfd.Symbols.Symbol_Table;
end record;
type Region_Symbols_Access is access all Region_Symbols;
-- Load the symbol table for the associated region.
procedure Open (Symbols : in out Region_Symbols;
Path : in String);
package Region_Symbols_Refs is
new Util.Refs.References (Region_Symbols, Region_Symbols_Access);
subtype Region_Symbols_Ref is Region_Symbols_Refs.Ref;
type Symbol_Info is limited record
File : Ada.Strings.Unbounded.Unbounded_String;
Name : Ada.Strings.Unbounded.Unbounded_String;
Line : Natural;
Symbols : Region_Symbols_Ref;
end record;
-- The <tt>Symbols_Maps</tt> keeps a sorted list of symbol tables indexed
-- by their mapping address.
use type Region_Symbols_Refs.Ref;
use type MAT.Types.Target_Addr;
package Symbols_Maps is
new Ada.Containers.Ordered_Maps (Key_Type => MAT.Types.Target_Addr,
Element_Type => Region_Symbols_Ref);
subtype Symbols_Map is Symbols_Maps.Map;
subtype Symbols_Cursor is Symbols_Maps.Cursor;
type Target_Symbols is new Util.Refs.Ref_Entity with record
Path : Ada.Strings.Unbounded.Unbounded_String;
File : Bfd.Files.File_Type;
Symbols : Bfd.Symbols.Symbol_Table;
Libraries : Symbols_Maps.Map;
Demangle : Bfd.Demangle_Flags := Bfd.Constants.DMGL_AUTO;
Console : MAT.Consoles.Console_Access;
end record;
type Target_Symbols_Access is access all Target_Symbols;
-- Open the binary and load the symbols from that file.
procedure Open (Symbols : in out Target_Symbols;
Path : in String);
-- Load the symbols associated with a shared library described by the memory region.
procedure Load_Symbols (Symbols : in out Target_Symbols;
Region : in MAT.Memory.Region_Info;
Offset_Addr : in MAT.Types.Target_Addr);
-- Load the symbols associated with all the shared libraries described by
-- the memory region map.
procedure Load_Symbols (Symbols : in out Target_Symbols;
Regions : in MAT.Memory.Region_Info_Map);
-- Demangle the symbol.
procedure Demangle (Symbols : in Target_Symbols;
Symbol : in out Symbol_Info);
-- Find the nearest source file and line for the given address.
procedure Find_Nearest_Line (Symbols : in Target_Symbols;
Addr : in MAT.Types.Target_Addr;
Symbol : out Symbol_Info);
package Target_Symbols_Refs is
new Util.Refs.References (Target_Symbols, Target_Symbols_Access);
subtype Target_Symbols_Ref is Target_Symbols_Refs.Ref;
end MAT.Symbols.Targets;
|
Change Symbol_Info to a limited type (because we don't need the copy) and add a reference to the Region_Symbols object
|
Change Symbol_Info to a limited type (because we don't need the copy)
and add a reference to the Region_Symbols object
|
Ada
|
apache-2.0
|
stcarrez/mat,stcarrez/mat,stcarrez/mat
|
4e2d7fcdd25d995793870afb1da82c9119f38c48
|
awa/plugins/awa-comments/src/awa-comments-modules.adb
|
awa/plugins/awa-comments/src/awa-comments-modules.adb
|
-----------------------------------------------------------------------
-- awa-comments-module -- Comments module
-- Copyright (C) 2011, 2012, 2013, 2014 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Calendar;
with Util.Log.Loggers;
with ADO.Sessions;
with ADO.Sessions.Entities;
with Security.Permissions;
with AWA.Users.Models;
with AWA.Permissions;
with AWA.Modules.Beans;
with AWA.Services.Contexts;
with AWA.Comments.Beans;
package body AWA.Comments.Modules is
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("AWA.Comments.Module");
package Register is new AWA.Modules.Beans (Module => Comment_Module,
Module_Access => Comment_Module_Access);
-- ------------------------------
-- Initialize the comments module.
-- ------------------------------
overriding
procedure Initialize (Plugin : in out Comment_Module;
App : in AWA.Modules.Application_Access;
Props : in ASF.Applications.Config) is
begin
Log.Info ("Initializing the comments module");
-- Setup the resource bundles.
App.Register ("commentMsg", "comments");
-- Register the comment list bean.
Register.Register (Plugin => Plugin,
Name => "AWA.Comments.Beans.Comment_List_Bean",
Handler => AWA.Comments.Beans.Create_Comment_List_Bean'Access);
-- Register the comment bean.
Register.Register (Plugin => Plugin,
Name => "AWA.Comments.Beans.Comment_Bean",
Handler => AWA.Comments.Beans.Create_Comment_Bean'Access);
AWA.Modules.Module (Plugin).Initialize (App, Props);
end Initialize;
-- ------------------------------
-- Load the comment identified by the given identifier.
-- ------------------------------
procedure Load_Comment (Model : in Comment_Module;
Comment : in out AWA.Comments.Models.Comment_Ref'Class;
Id : in ADO.Identifier) is
pragma Unreferenced (Model);
Ctx : constant Services.Contexts.Service_Context_Access := AWA.Services.Contexts.Current;
DB : ADO.Sessions.Session := AWA.Services.Contexts.Get_Session (Ctx);
Found : Boolean;
begin
Comment.Load (DB, Id, Found);
end Load_Comment;
-- ------------------------------
-- Create a new comment for the associated database entity.
-- ------------------------------
procedure Create_Comment (Model : in Comment_Module;
Permission : in String;
Entity_Type : in String;
Comment : in out AWA.Comments.Models.Comment_Ref'Class) is
pragma Unreferenced (Model);
Ctx : constant Services.Contexts.Service_Context_Access := AWA.Services.Contexts.Current;
User : constant AWA.Users.Models.User_Ref := Ctx.Get_User;
DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx);
begin
Ctx.Start;
Log.Info ("Creating new comment for {0}", ADO.Identifier'Image (Comment.Get_Entity_Id));
-- Check that the user has the create permission on the given workspace.
AWA.Permissions.Check (Permission => Security.Permissions.Get_Permission_Index (Permission),
Entity => Comment.Get_Entity_Id);
Comment.Set_Entity_Type (ADO.Sessions.Entities.Find_Entity_Type (DB, Entity_Type));
Comment.Set_Author (User);
Comment.Set_Create_Date (Ada.Calendar.Clock);
Comment.Save (DB);
Ctx.Commit;
end Create_Comment;
-- ------------------------------
-- Update the comment represented by <tt>Comment</tt> if the current user has the
-- permission identified by <tt>Permission</tt>.
-- ------------------------------
procedure Update_Comment (Model : in Comment_Module;
Permission : in String;
Comment : in out AWA.Comments.Models.Comment_Ref'Class) is
pragma Unreferenced (Model);
Ctx : constant Services.Contexts.Service_Context_Access := AWA.Services.Contexts.Current;
DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx);
begin
if not Comment.Is_Inserted then
Log.Error ("The comment was not created");
raise Not_Found with "The comment was not inserted";
end if;
Ctx.Start;
Log.Info ("Updating the comment {0}", ADO.Identifier'Image (Comment.Get_Id));
-- Check that the user has the update permission on the given comment.
AWA.Permissions.Check (Permission => Security.Permissions.Get_Permission_Index (Permission),
Entity => Comment);
Comment.Save (DB);
Ctx.Commit;
end Update_Comment;
-- ------------------------------
-- Delete the comment represented by <tt>Comment</tt> if the current user has the
-- permission identified by <tt>Permission</tt>.
-- ------------------------------
procedure Delete_Comment (Model : in Comment_Module;
Permission : in String;
Comment : in out AWA.Comments.Models.Comment_Ref'Class) is
pragma Unreferenced (Model);
Ctx : constant Services.Contexts.Service_Context_Access := AWA.Services.Contexts.Current;
DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx);
begin
Ctx.Start;
-- Check that the user has the delete permission on the given answer.
AWA.Permissions.Check (Permission => Security.Permissions.Get_Permission_Index (Permission),
Entity => Comment);
Comment.Delete (DB);
Ctx.Commit;
end Delete_Comment;
end AWA.Comments.Modules;
|
-----------------------------------------------------------------------
-- awa-comments-module -- Comments module
-- Copyright (C) 2011, 2012, 2013, 2014 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Calendar;
with Util.Log.Loggers;
with ADO.Sessions;
with ADO.Sessions.Entities;
with Security.Permissions;
with AWA.Users.Models;
with AWA.Permissions;
with AWA.Modules.Beans;
with AWA.Services.Contexts;
with AWA.Comments.Beans;
package body AWA.Comments.Modules is
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("AWA.Comments.Module");
package Register is new AWA.Modules.Beans (Module => Comment_Module,
Module_Access => Comment_Module_Access);
-- ------------------------------
-- Initialize the comments module.
-- ------------------------------
overriding
procedure Initialize (Plugin : in out Comment_Module;
App : in AWA.Modules.Application_Access;
Props : in ASF.Applications.Config) is
begin
Log.Info ("Initializing the comments module");
-- Setup the resource bundles.
App.Register ("commentMsg", "comments");
-- Register the comment list bean.
Register.Register (Plugin => Plugin,
Name => "AWA.Comments.Beans.Comment_List_Bean",
Handler => AWA.Comments.Beans.Create_Comment_List_Bean'Access);
-- Register the comment bean.
Register.Register (Plugin => Plugin,
Name => "AWA.Comments.Beans.Comment_Bean",
Handler => AWA.Comments.Beans.Create_Comment_Bean'Access);
AWA.Modules.Module (Plugin).Initialize (App, Props);
end Initialize;
-- ------------------------------
-- Load the comment identified by the given identifier.
-- ------------------------------
procedure Load_Comment (Model : in Comment_Module;
Comment : in out AWA.Comments.Models.Comment_Ref'Class;
Id : in ADO.Identifier) is
pragma Unreferenced (Model);
Ctx : constant Services.Contexts.Service_Context_Access := AWA.Services.Contexts.Current;
DB : ADO.Sessions.Session := AWA.Services.Contexts.Get_Session (Ctx);
Found : Boolean;
begin
Comment.Load (DB, Id, Found);
end Load_Comment;
-- ------------------------------
-- Create a new comment for the associated database entity.
-- ------------------------------
procedure Create_Comment (Model : in Comment_Module;
Permission : in String;
Entity_Type : in String;
Comment : in out AWA.Comments.Models.Comment_Ref'Class) is
pragma Unreferenced (Model);
Ctx : constant Services.Contexts.Service_Context_Access := AWA.Services.Contexts.Current;
User : constant AWA.Users.Models.User_Ref := Ctx.Get_User;
DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx);
begin
Ctx.Start;
Log.Info ("Creating new comment for {0}", ADO.Identifier'Image (Comment.Get_Entity_Id));
-- Check that the user has the create permission on the given workspace.
AWA.Permissions.Check (Permission => Security.Permissions.Get_Permission_Index (Permission),
Entity => Comment.Get_Entity_Id);
Comment.Set_Entity_Type (ADO.Sessions.Entities.Find_Entity_Type (DB, Entity_Type));
Comment.Set_Author (User);
Comment.Set_Create_Date (Ada.Calendar.Clock);
Comment.Save (DB);
Ctx.Commit;
end Create_Comment;
-- ------------------------------
-- Update the comment represented by <tt>Comment</tt> if the current user has the
-- permission identified by <tt>Permission</tt>.
-- ------------------------------
procedure Update_Comment (Model : in Comment_Module;
Permission : in String;
Comment : in out AWA.Comments.Models.Comment_Ref'Class) is
pragma Unreferenced (Model);
Ctx : constant Services.Contexts.Service_Context_Access := AWA.Services.Contexts.Current;
DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx);
begin
if not Comment.Is_Inserted then
Log.Error ("The comment was not created");
raise Not_Found with "The comment was not inserted";
end if;
Ctx.Start;
Log.Info ("Updating the comment {0}", ADO.Identifier'Image (Comment.Get_Id));
-- Check that the user has the update permission on the given comment.
AWA.Permissions.Check (Permission => Security.Permissions.Get_Permission_Index (Permission),
Entity => Comment);
Comment.Save (DB);
Ctx.Commit;
end Update_Comment;
-- ------------------------------
-- Delete the comment represented by <tt>Comment</tt> if the current user has the
-- permission identified by <tt>Permission</tt>.
-- ------------------------------
procedure Delete_Comment (Model : in Comment_Module;
Permission : in String;
Comment : in out AWA.Comments.Models.Comment_Ref'Class) is
pragma Unreferenced (Model);
Ctx : constant Services.Contexts.Service_Context_Access := AWA.Services.Contexts.Current;
DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx);
begin
Ctx.Start;
-- Check that the user has the delete permission on the given answer.
AWA.Permissions.Check (Permission => Security.Permissions.Get_Permission_Index (Permission),
Entity => Comment);
Comment.Delete (DB);
Ctx.Commit;
end Delete_Comment;
-- ------------------------------
-- Set the publication status of the comment represented by <tt>Comment</tt>
-- if the current user has the permission identified by <tt>Permission</tt>.
-- ------------------------------
procedure Publish_Comment (Model : in Comment_Module;
Permission : in String;
Id : in ADO.Identifier;
Status : in AWA.Comments.Models.Status_Type;
Comment : in out AWA.Comments.Models.Comment_Ref'Class) is
pragma Unreferenced (Model);
Ctx : constant Services.Contexts.Service_Context_Access := AWA.Services.Contexts.Current;
DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx);
begin
Ctx.Start;
-- Check that the user has the permission to publish for the given comment.
AWA.Permissions.Check (Permission => Security.Permissions.Get_Permission_Index (Permission),
Entity => Id);
Comment.Load (DB, Id);
Comment.Set_Status (Status);
Comment.Save (DB);
Ctx.Commit;
end Publish_Comment;
end AWA.Comments.Modules;
|
Implement the Publish_Comment operation, check the permission, load the comment, change the status and return the comment instance
|
Implement the Publish_Comment operation, check the permission, load
the comment, change the status and return the comment instance
|
Ada
|
apache-2.0
|
Letractively/ada-awa,tectronics/ada-awa,tectronics/ada-awa,tectronics/ada-awa,Letractively/ada-awa,Letractively/ada-awa
|
a0ed598eb3b82d28c870b279508429210c08ce40
|
src/portscan-tests.adb
|
src/portscan-tests.adb
|
-- This file is covered by the Internet Software Consortium (ISC) License
-- Reference: ../License.txt
with File_Operations;
with PortScan.Log;
with Parameters;
with Unix;
with Ada.Characters.Latin_1;
with Ada.Directories;
with Ada.Exceptions;
package body PortScan.Tests is
package FOP renames File_Operations;
package LOG renames PortScan.Log;
package PM renames Parameters;
package LAT renames Ada.Characters.Latin_1;
package DIR renames Ada.Directories;
package EX renames Ada.Exceptions;
--------------------------------------------------------------------------------------------
-- exec_phase_check_plist
--------------------------------------------------------------------------------------------
function exec_check_plist
(specification : PSP.Portspecs;
log_handle : TIO.File_Type;
phase_name : String;
seq_id : port_id;
rootdir : String) return Boolean
is
passed_check : Boolean := True;
namebase : constant String := specification.get_namebase;
directory_list : entry_crate.Map;
dossier_list : entry_crate.Map;
begin
LOG.log_phase_begin (log_handle, phase_name);
TIO.Put_Line (log_handle, "====> Checking for package manifest issues");
if not ingest_manifests (specification => specification,
log_handle => log_handle,
directory_list => directory_list,
dossier_list => dossier_list,
seq_id => seq_id,
namebase => namebase,
rootdir => rootdir)
then
passed_check := False;
end if;
if orphaned_directories_detected (log_handle => log_handle,
directory_list => directory_list,
namebase => namebase,
rootdir => rootdir)
then
passed_check := False;
end if;
if missing_directories_detected (log_handle, directory_list) then
passed_check := False;
end if;
if orphaned_files_detected (log_handle, dossier_list, namebase, rootdir) then
passed_check := False;
end if;
if missing_files_detected (log_handle, dossier_list) then
passed_check := False;
end if;
if passed_check then
TIO.Put_Line (log_handle, "====> No manifest issues found");
end if;
LOG.log_phase_end (log_handle);
return passed_check;
end exec_check_plist;
--------------------------------------------------------------------------------------------
-- ingest_manifests
--------------------------------------------------------------------------------------------
function ingest_manifests
(specification : PSP.Portspecs;
log_handle : TIO.File_Type;
directory_list : in out entry_crate.Map;
dossier_list : in out entry_crate.Map;
seq_id : port_id;
namebase : String;
rootdir : String) return Boolean
is
procedure eat_plist (position : subpackage_crate.Cursor);
procedure insert_directory (directory : String; subpackage : HT.Text);
result : Boolean := True;
procedure insert_directory (directory : String; subpackage : HT.Text)
is
numsep : Natural := HT.count_char (directory, LAT.Solidus);
canvas : HT.Text := HT.SUS (directory);
begin
for x in 1 .. numsep + 1 loop
declare
paint : String := HT.USS (canvas);
my_new_rec : entry_record := (subpackage, False);
begin
if paint /= "" then
if not directory_list.Contains (canvas) then
directory_list.Insert (canvas, my_new_rec);
end if;
canvas := HT.SUS (HT.head (paint, "/"));
end if;
end;
end loop;
end insert_directory;
procedure eat_plist (position : subpackage_crate.Cursor)
is
subpackage : HT.Text := subpackage_crate.Element (position).subpackage;
manifest_file : String := "/construction/" & namebase & "/.manifest." &
HT.USS (subpackage) & ".mktmp";
contents : String := FOP.get_file_contents (rootdir & manifest_file);
identifier : constant String := HT.USS (subpackage) & " manifest: ";
markers : HT.Line_Markers;
begin
HT.initialize_markers (contents, markers);
loop
exit when not HT.next_line_present (contents, markers);
declare
line : constant String := HT.extract_line (contents, markers);
line_text : HT.Text := HT.SUS (line);
new_rec : entry_record := (subpackage, False);
begin
if HT.leads (line, "@comment ") then
null;
elsif HT.leads (line, "@terminfo") then
null;
elsif HT.leads (line, "@dir ") then
declare
dir : String := line (line'First + 5 .. line'Last);
dir_text : HT.Text := HT.SUS (dir);
begin
if directory_list.Contains (dir_text) then
result := False;
declare
spkg : String := HT.USS (directory_list.Element (dir_text).subpackage);
begin
if spkg /= "" then
TIO.Put_Line
(log_handle,
"Redundant @dir symbol, " & identifier & dir &
" will already be created by the " & spkg & " manifest");
else
TIO.Put_Line
(log_handle,
"Redundant @dir symbol, " & identifier & dir &
" will already be created by another manifest");
end if;
end;
else
insert_directory (dir, subpackage);
end if;
end;
else
declare
modline : String := modify_file_if_necessary (line);
ml_text : HT.Text := HT.SUS (modline);
begin
if dossier_list.Contains (ml_text) then
result := False;
declare
spkg : String := HT.USS (dossier_list.Element (ml_text).subpackage);
begin
TIO.Put_Line
(log_handle,
"Duplicate file entry, " & identifier & modline &
" already present in " & spkg & " manifest");
end;
else
dossier_list.Insert (ml_text, new_rec);
declare
plistdir : String := DIR.Containing_Directory (modline);
begin
insert_directory (plistdir, subpackage);
end;
end if;
end;
end if;
end;
end loop;
exception
when issue : others =>
TIO.Put_Line (log_handle, "check-plist error: " & EX.Exception_Message (issue));
end eat_plist;
begin
all_ports (seq_id).subpackages.Iterate (eat_plist'Access);
return result;
end ingest_manifests;
--------------------------------------------------------------------------------------------
-- directory_excluded
--------------------------------------------------------------------------------------------
function directory_excluded (candidate : String) return Boolean
is
-- mandatory candidate has ${STAGEDIR}/ stripped (no leading slash)
rawlbase : constant String := HT.USS (PM.configuration.dir_localbase);
localbase : constant String := rawlbase (rawlbase'First + 1 .. rawlbase'Last);
lblen : constant Natural := localbase'Length;
begin
if candidate = localbase then
return True;
end if;
if not HT.leads (candidate, localbase & "/") then
-- This should never happen
return False;
end if;
declare
shortcan : String := candidate (candidate'First + lblen + 1 .. candidate'Last);
begin
if shortcan = "bin" or else
shortcan = "etc" or else
shortcan = "etc/rc.d" or else
shortcan = "include" or else
shortcan = "lib" or else
shortcan = "lib/pkgconfig" or else
shortcan = "libdata" or else
shortcan = "libexec" or else
shortcan = "sbin" or else
shortcan = "share" or else
shortcan = "www"
then
return True;
end if;
if not HT.leads (shortcan, "share/") then
return False;
end if;
end;
declare
shortcan : String := candidate (candidate'First + lblen + 7 .. candidate'Last);
begin
if shortcan = "doc" or else
shortcan = "examples" or else
shortcan = "info" or else
shortcan = "locale" or else
shortcan = "man" or else
shortcan = "nls"
then
return True;
end if;
if shortcan'Length /= 8 or else
not HT.leads (shortcan, "man/man")
then
return False;
end if;
case shortcan (shortcan'Last) is
when '1' .. '9' | 'l' | 'n' => return True;
when others => return False;
end case;
end;
end directory_excluded;
--------------------------------------------------------------------------------------------
-- orphaned_directories_detected
--------------------------------------------------------------------------------------------
function orphaned_directories_detected
(log_handle : TIO.File_Type;
directory_list : in out entry_crate.Map;
namebase : String;
rootdir : String) return Boolean
is
rawlbase : constant String := HT.USS (PM.configuration.dir_localbase);
localbase : constant String := rawlbase (rawlbase'First + 1 .. rawlbase'Last);
stagedir : String := rootdir & "/construction/" & namebase & "/stage";
command : String := rootdir & "/usr/bin/find " & stagedir & " -type d -printf " &
LAT.Quotation & "%P\n" & LAT.Quotation;
status : Integer;
comres : String := HT.USS (Unix.piped_command (command, status));
markers : HT.Line_Markers;
lblen : constant Natural := localbase'Length;
result : Boolean := False;
errprefix : constant String := "Orphaned directory detected: ";
begin
if status /= 0 then
TIO.Put_Line ("orphaned_directories_detected: command error: " & comres);
return True;
end if;
HT.initialize_markers (comres, markers);
loop
exit when not HT.next_line_present (comres, markers);
declare
line : constant String := HT.extract_line (comres, markers);
line_text : HT.Text := HT.SUS (line);
begin
if line /= "" then
if HT.leads (line, localbase) then
declare
plist_dir : HT.Text := HT.SUS (line (line'First + lblen + 1 .. line'Last));
begin
if directory_list.Contains (plist_dir) then
directory_list.Update_Element (Position => directory_list.Find (plist_dir),
Process => mark_verified'Access);
else
if not directory_excluded (line) then
TIO.Put_Line (log_handle, errprefix & line);
result := True;
end if;
end if;
end;
else
if directory_list.Contains (line_text) then
directory_list.Update_Element (Position => directory_list.Find (line_text),
Process => mark_verified'Access);
else
TIO.Put_Line (log_handle, errprefix & line);
result := True;
end if;
end if;
end if;
end;
end loop;
return result;
end orphaned_directories_detected;
--------------------------------------------------------------------------------------------
-- mark_verified
--------------------------------------------------------------------------------------------
procedure mark_verified (key : HT.Text; Element : in out entry_record) is
begin
Element.verified := True;
end mark_verified;
--------------------------------------------------------------------------------------------
-- missing_directories_detected
--------------------------------------------------------------------------------------------
function missing_directories_detected
(log_handle : TIO.File_Type;
directory_list : in out entry_crate.Map) return Boolean
is
procedure check (position : entry_crate.Cursor);
result : Boolean := False;
procedure check (position : entry_crate.Cursor)
is
rec : entry_record renames entry_crate.Element (position);
plist_dir : String := HT.USS (entry_crate.Key (position));
begin
if not rec.verified then
TIO.Put_Line
(log_handle,
"Directory " & plist_dir & " listed on " & HT.USS (rec.subpackage) &
" manifest is not present in the stage directory.");
result := True;
end if;
end check;
begin
directory_list.Iterate (check'Access);
return result;
end missing_directories_detected;
--------------------------------------------------------------------------------------------
-- missing_files_detected
--------------------------------------------------------------------------------------------
function missing_files_detected
(log_handle : TIO.File_Type;
dossier_list : in out entry_crate.Map) return Boolean
is
procedure check (position : entry_crate.Cursor);
result : Boolean := False;
procedure check (position : entry_crate.Cursor)
is
rec : entry_record renames entry_crate.Element (position);
plist_file : String := HT.USS (entry_crate.Key (position));
begin
if not rec.verified then
TIO.Put_Line
(log_handle,
"File " & plist_file & " listed on " & HT.USS (rec.subpackage) &
" manifest is not present in the stage directory.");
result := True;
end if;
end check;
begin
dossier_list.Iterate (check'Access);
return result;
end missing_files_detected;
--------------------------------------------------------------------------------------------
-- orphaned_files_detected
--------------------------------------------------------------------------------------------
function orphaned_files_detected
(log_handle : TIO.File_Type;
dossier_list : in out entry_crate.Map;
namebase : String;
rootdir : String) return Boolean
is
rawlbase : constant String := HT.USS (PM.configuration.dir_localbase);
localbase : constant String := rawlbase (rawlbase'First + 1 .. rawlbase'Last);
stagedir : String := rootdir & "/construction/" & namebase & "/stage";
command : String := rootdir & "/usr/bin/find " & stagedir &
" \( -type f -o -type l \) -printf " &
LAT.Quotation & "%P\n" & LAT.Quotation;
status : Integer;
comres : String := HT.USS (Unix.piped_command (command, status));
markers : HT.Line_Markers;
lblen : constant Natural := localbase'Length;
result : Boolean := False;
errprefix : constant String := "Orphaned file detected: ";
begin
if status /= 0 then
TIO.Put_Line ("orphaned_files_detected: command error: " & comres);
return True;
end if;
HT.initialize_markers (comres, markers);
loop
exit when not HT.next_line_present (comres, markers);
declare
line : constant String := HT.extract_line (comres, markers);
line_text : HT.Text := HT.SUS (line);
begin
if line /= "" then
if HT.leads (line, localbase) then
declare
plist_file : HT.Text := HT.SUS (line (line'First + lblen + 1 .. line'Last));
begin
if dossier_list.Contains (plist_file) then
dossier_list.Update_Element (Position => dossier_list.Find (plist_file),
Process => mark_verified'Access);
else
TIO.Put_Line (log_handle, errprefix & line);
result := True;
end if;
end;
else
if dossier_list.Contains (line_text) then
dossier_list.Update_Element (Position => dossier_list.Find (line_text),
Process => mark_verified'Access);
else
TIO.Put_Line (log_handle, errprefix & line);
result := True;
end if;
end if;
end if;
end;
end loop;
return result;
end orphaned_files_detected;
--------------------------------------------------------------------------------------------
-- modify_file_if_necessary
--------------------------------------------------------------------------------------------
function modify_file_if_necessary (original : String) return String
is
function strip_raw_localbase (wrkstr : String) return String;
function strip_raw_localbase (wrkstr : String) return String
is
rawlbase : constant String := HT.USS (PM.configuration.dir_localbase) & "/";
begin
if HT.leads (wrkstr, rawlbase) then
return wrkstr (wrkstr'First + rawlbase'Length .. wrkstr'Last);
else
return wrkstr;
end if;
end strip_raw_localbase;
begin
if HT.leads (original, "@info ") then
return strip_raw_localbase (original (original'First + 6 .. original 'Last));
else
return original;
end if;
end modify_file_if_necessary;
end PortScan.Tests;
|
-- This file is covered by the Internet Software Consortium (ISC) License
-- Reference: ../License.txt
with File_Operations;
with PortScan.Log;
with Parameters;
with Unix;
with Ada.Characters.Latin_1;
with Ada.Directories;
with Ada.Exceptions;
package body PortScan.Tests is
package FOP renames File_Operations;
package LOG renames PortScan.Log;
package PM renames Parameters;
package LAT renames Ada.Characters.Latin_1;
package DIR renames Ada.Directories;
package EX renames Ada.Exceptions;
--------------------------------------------------------------------------------------------
-- exec_phase_check_plist
--------------------------------------------------------------------------------------------
function exec_check_plist
(specification : PSP.Portspecs;
log_handle : TIO.File_Type;
phase_name : String;
seq_id : port_id;
rootdir : String) return Boolean
is
passed_check : Boolean := True;
namebase : constant String := specification.get_namebase;
directory_list : entry_crate.Map;
dossier_list : entry_crate.Map;
begin
LOG.log_phase_begin (log_handle, phase_name);
TIO.Put_Line (log_handle, "====> Checking for package manifest issues");
if not ingest_manifests (specification => specification,
log_handle => log_handle,
directory_list => directory_list,
dossier_list => dossier_list,
seq_id => seq_id,
namebase => namebase,
rootdir => rootdir)
then
passed_check := False;
end if;
if orphaned_directories_detected (log_handle => log_handle,
directory_list => directory_list,
namebase => namebase,
rootdir => rootdir)
then
passed_check := False;
end if;
if missing_directories_detected (log_handle, directory_list) then
passed_check := False;
end if;
if orphaned_files_detected (log_handle, dossier_list, namebase, rootdir) then
passed_check := False;
end if;
if missing_files_detected (log_handle, dossier_list) then
passed_check := False;
end if;
if passed_check then
TIO.Put_Line (log_handle, "====> No manifest issues found");
end if;
LOG.log_phase_end (log_handle);
return passed_check;
end exec_check_plist;
--------------------------------------------------------------------------------------------
-- ingest_manifests
--------------------------------------------------------------------------------------------
function ingest_manifests
(specification : PSP.Portspecs;
log_handle : TIO.File_Type;
directory_list : in out entry_crate.Map;
dossier_list : in out entry_crate.Map;
seq_id : port_id;
namebase : String;
rootdir : String) return Boolean
is
procedure eat_plist (position : subpackage_crate.Cursor);
procedure insert_directory (directory : String; subpackage : HT.Text);
result : Boolean := True;
procedure insert_directory (directory : String; subpackage : HT.Text)
is
numsep : Natural := HT.count_char (directory, LAT.Solidus);
canvas : HT.Text := HT.SUS (directory);
begin
for x in 1 .. numsep + 1 loop
declare
paint : String := HT.USS (canvas);
my_new_rec : entry_record := (subpackage, False);
begin
if paint /= "" then
if not directory_list.Contains (canvas) then
directory_list.Insert (canvas, my_new_rec);
end if;
canvas := HT.SUS (HT.head (paint, "/"));
end if;
end;
end loop;
end insert_directory;
procedure eat_plist (position : subpackage_crate.Cursor)
is
subpackage : HT.Text := subpackage_crate.Element (position).subpackage;
manifest_file : String := "/construction/" & namebase & "/.manifest." &
HT.USS (subpackage) & ".mktmp";
contents : String := FOP.get_file_contents (rootdir & manifest_file);
identifier : constant String := HT.USS (subpackage) & " manifest: ";
markers : HT.Line_Markers;
begin
HT.initialize_markers (contents, markers);
loop
exit when not HT.next_line_present (contents, markers);
declare
line : constant String := HT.extract_line (contents, markers);
line_text : HT.Text := HT.SUS (line);
new_rec : entry_record := (subpackage, False);
begin
if HT.leads (line, "@comment ") then
null;
elsif HT.leads (line, "@terminfo") then
null;
elsif HT.leads (line, "@dir ") then
declare
dir : String := line (line'First + 5 .. line'Last);
dir_text : HT.Text := HT.SUS (dir);
begin
if directory_list.Contains (dir_text) then
result := False;
declare
spkg : String := HT.USS (directory_list.Element (dir_text).subpackage);
begin
if spkg /= "" then
TIO.Put_Line
(log_handle,
"Redundant @dir symbol, " & identifier & dir &
" will already be created by the " & spkg & " manifest");
else
TIO.Put_Line
(log_handle,
"Redundant @dir symbol, " & identifier & dir &
" will already be created by another manifest");
end if;
end;
else
insert_directory (dir, subpackage);
end if;
end;
else
declare
modline : String := modify_file_if_necessary (line);
ml_text : HT.Text := HT.SUS (modline);
begin
if dossier_list.Contains (ml_text) then
result := False;
declare
spkg : String := HT.USS (dossier_list.Element (ml_text).subpackage);
begin
TIO.Put_Line
(log_handle,
"Duplicate file entry, " & identifier & modline &
" already present in " & spkg & " manifest");
end;
else
dossier_list.Insert (ml_text, new_rec);
declare
plistdir : String := DIR.Containing_Directory (modline);
begin
insert_directory (plistdir, subpackage);
end;
end if;
end;
end if;
end;
end loop;
exception
when issue : others =>
TIO.Put_Line (log_handle, "check-plist error: " & EX.Exception_Message (issue));
end eat_plist;
begin
all_ports (seq_id).subpackages.Iterate (eat_plist'Access);
return result;
end ingest_manifests;
--------------------------------------------------------------------------------------------
-- directory_excluded
--------------------------------------------------------------------------------------------
function directory_excluded (candidate : String) return Boolean
is
-- mandatory candidate has ${STAGEDIR}/ stripped (no leading slash)
rawlbase : constant String := HT.USS (PM.configuration.dir_localbase);
localbase : constant String := rawlbase (rawlbase'First + 1 .. rawlbase'Last);
lblen : constant Natural := localbase'Length;
begin
if candidate = localbase then
return True;
end if;
if not HT.leads (candidate, localbase & "/") then
-- This should never happen
return False;
end if;
declare
shortcan : String := candidate (candidate'First + lblen + 1 .. candidate'Last);
begin
if shortcan = "bin" or else
shortcan = "etc" or else
shortcan = "etc/rc.d" or else
shortcan = "include" or else
shortcan = "lib" or else
shortcan = "lib/pkgconfig" or else
shortcan = "libdata" or else
shortcan = "libexec" or else
shortcan = "sbin" or else
shortcan = "share" or else
shortcan = "www"
then
return True;
end if;
if not HT.leads (shortcan, "share/") then
return False;
end if;
end;
declare
shortcan : String := candidate (candidate'First + lblen + 7 .. candidate'Last);
begin
if shortcan = "doc" or else
shortcan = "examples" or else
shortcan = "info" or else
shortcan = "locale" or else
shortcan = "man" or else
shortcan = "nls"
then
return True;
end if;
if shortcan'Length /= 8 or else
not HT.leads (shortcan, "man/man")
then
return False;
end if;
case shortcan (shortcan'Last) is
when '1' .. '9' | 'l' | 'n' => return True;
when others => return False;
end case;
end;
end directory_excluded;
--------------------------------------------------------------------------------------------
-- orphaned_directories_detected
--------------------------------------------------------------------------------------------
function orphaned_directories_detected
(log_handle : TIO.File_Type;
directory_list : in out entry_crate.Map;
namebase : String;
rootdir : String) return Boolean
is
rawlbase : constant String := HT.USS (PM.configuration.dir_localbase);
localbase : constant String := rawlbase (rawlbase'First + 1 .. rawlbase'Last);
stagedir : String := rootdir & "/construction/" & namebase & "/stage";
command : String := rootdir & "/usr/bin/find " & stagedir & " -type d -printf " &
LAT.Quotation & "%P\n" & LAT.Quotation;
status : Integer;
comres : String := HT.USS (Unix.piped_command (command, status));
markers : HT.Line_Markers;
lblen : constant Natural := localbase'Length;
result : Boolean := False;
errprefix : constant String := "Orphaned directory detected: ";
begin
if status /= 0 then
TIO.Put_Line ("orphaned_directories_detected: command error: " & comres);
return True;
end if;
HT.initialize_markers (comres, markers);
loop
exit when not HT.next_line_present (comres, markers);
declare
line : constant String := HT.extract_line (comres, markers);
line_text : HT.Text := HT.SUS (line);
begin
if line /= "" then
if HT.leads (line, localbase) then
declare
plist_dir : HT.Text := HT.SUS (line (line'First + lblen + 1 .. line'Last));
begin
if directory_list.Contains (plist_dir) then
directory_list.Update_Element (Position => directory_list.Find (plist_dir),
Process => mark_verified'Access);
else
if not directory_excluded (line) then
TIO.Put_Line (log_handle, errprefix & line);
result := True;
end if;
end if;
end;
else
if directory_list.Contains (line_text) then
directory_list.Update_Element (Position => directory_list.Find (line_text),
Process => mark_verified'Access);
else
TIO.Put_Line (log_handle, errprefix & line);
result := True;
end if;
end if;
end if;
end;
end loop;
return result;
end orphaned_directories_detected;
--------------------------------------------------------------------------------------------
-- mark_verified
--------------------------------------------------------------------------------------------
procedure mark_verified (key : HT.Text; Element : in out entry_record) is
begin
Element.verified := True;
end mark_verified;
--------------------------------------------------------------------------------------------
-- missing_directories_detected
--------------------------------------------------------------------------------------------
function missing_directories_detected
(log_handle : TIO.File_Type;
directory_list : in out entry_crate.Map) return Boolean
is
procedure check (position : entry_crate.Cursor);
result : Boolean := False;
procedure check (position : entry_crate.Cursor)
is
rec : entry_record renames entry_crate.Element (position);
plist_dir : String := HT.USS (entry_crate.Key (position));
begin
if not rec.verified then
TIO.Put_Line
(log_handle,
"Directory " & plist_dir & " listed on " & HT.USS (rec.subpackage) &
" manifest is not present in the stage directory.");
result := True;
end if;
end check;
begin
directory_list.Iterate (check'Access);
return result;
end missing_directories_detected;
--------------------------------------------------------------------------------------------
-- missing_files_detected
--------------------------------------------------------------------------------------------
function missing_files_detected
(log_handle : TIO.File_Type;
dossier_list : in out entry_crate.Map) return Boolean
is
procedure check (position : entry_crate.Cursor);
result : Boolean := False;
procedure check (position : entry_crate.Cursor)
is
rec : entry_record renames entry_crate.Element (position);
plist_file : String := HT.USS (entry_crate.Key (position));
begin
if not rec.verified then
TIO.Put_Line
(log_handle,
"File " & plist_file & " listed on " & HT.USS (rec.subpackage) &
" manifest is not present in the stage directory.");
result := True;
end if;
end check;
begin
dossier_list.Iterate (check'Access);
return result;
end missing_files_detected;
--------------------------------------------------------------------------------------------
-- orphaned_files_detected
--------------------------------------------------------------------------------------------
function orphaned_files_detected
(log_handle : TIO.File_Type;
dossier_list : in out entry_crate.Map;
namebase : String;
rootdir : String) return Boolean
is
rawlbase : constant String := HT.USS (PM.configuration.dir_localbase);
localbase : constant String := rawlbase (rawlbase'First + 1 .. rawlbase'Last);
stagedir : String := rootdir & "/construction/" & namebase & "/stage";
command : String := rootdir & "/usr/bin/find " & stagedir &
" \( -type f -o -type l \) -printf " &
LAT.Quotation & "%P\n" & LAT.Quotation;
status : Integer;
comres : String := HT.USS (Unix.piped_command (command, status));
markers : HT.Line_Markers;
lblen : constant Natural := localbase'Length;
result : Boolean := False;
errprefix : constant String := "Orphaned file detected: ";
begin
if status /= 0 then
TIO.Put_Line ("orphaned_files_detected: command error: " & comres);
return True;
end if;
HT.initialize_markers (comres, markers);
loop
exit when not HT.next_line_present (comres, markers);
declare
line : constant String := HT.extract_line (comres, markers);
line_text : HT.Text := HT.SUS (line);
begin
if line /= "" then
if HT.leads (line, localbase) then
declare
plist_file : HT.Text := HT.SUS (line (line'First + lblen + 1 .. line'Last));
begin
if dossier_list.Contains (plist_file) then
dossier_list.Update_Element (Position => dossier_list.Find (plist_file),
Process => mark_verified'Access);
else
TIO.Put_Line (log_handle, errprefix & line);
result := True;
end if;
end;
else
if dossier_list.Contains (line_text) then
dossier_list.Update_Element (Position => dossier_list.Find (line_text),
Process => mark_verified'Access);
else
TIO.Put_Line (log_handle, errprefix & line);
result := True;
end if;
end if;
end if;
end;
end loop;
return result;
end orphaned_files_detected;
--------------------------------------------------------------------------------------------
-- modify_file_if_necessary
--------------------------------------------------------------------------------------------
function modify_file_if_necessary (original : String) return String
is
function strip_raw_localbase (wrkstr : String) return String;
function strip_raw_localbase (wrkstr : String) return String
is
rawlbase : constant String := HT.USS (PM.configuration.dir_localbase) & "/";
begin
if HT.leads (wrkstr, rawlbase) then
return wrkstr (wrkstr'First + rawlbase'Length .. wrkstr'Last);
else
return wrkstr;
end if;
end strip_raw_localbase;
begin
if HT.leads (original, "@info ") then
return strip_raw_localbase (original (original'First + 6 .. original 'Last));
elsif HT.leads (original, "@sample ") then
return strip_raw_localbase (original (original'First + 8 .. original 'Last));
else
return original;
end if;
end modify_file_if_necessary;
end PortScan.Tests;
|
Support @sample keyword
|
Support @sample keyword
|
Ada
|
isc
|
jrmarino/ravenadm,jrmarino/ravenadm,jrmarino/ravenadm
|
7ea393008b9409786eabed8d42786b587f39a7be
|
src/base/commands/util-commands-drivers.ads
|
src/base/commands/util-commands-drivers.ads
|
-----------------------------------------------------------------------
-- util-commands-drivers -- Support to make command line tools
-- Copyright (C) 2017, 2018, 2019 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Log;
with Util.Commands.Parsers;
private with Ada.Strings.Unbounded;
private with Ada.Containers.Indefinite_Ordered_Maps;
-- == Command line driver ==
-- The `Util.Commands.Drivers` generic package provides a support to build command line
-- tools that have different commands identified by a name. It defines the `Driver_Type`
-- tagged record that provides a registry of application commands. It gives entry points
-- to register commands and execute them.
--
-- The `Context_Type` package parameter defines the type for the `Context` parameter
-- that is passed to the command when it is executed. It can be used to provide
-- application specific context to the command.
--
-- The `Config_Parser` describes the parser package that will handle the analysis of
-- command line options. To use the GNAT options parser, it is possible to use the
-- `Util.Commands.Parsers.GNAT_Parser` package.
generic
-- The command execution context.
type Context_Type (<>) is limited private;
with package Config_Parser is new Util.Commands.Parsers.Config_Parser (<>);
Driver_Name : String := "Drivers";
package Util.Commands.Drivers is
subtype Config_Type is Config_Parser.Config_Type;
-- 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;
-- Get the description associated with the command.
function Get_Description (Command : in Command_Type) return String;
-- Get the name used to register the command.
function Get_Name (Command : in Command_Type) return String;
-- Execute the command with the arguments. The command name is passed with the command
-- arguments.
procedure Execute (Command : in out Command_Type;
Name : in String;
Args : in Argument_List'Class;
Context : in out Context_Type) is abstract;
-- Setup the command before parsing the arguments and executing it.
procedure Setup (Command : in out Command_Type;
Config : in out Config_Type;
Context : in out Context_Type) is null;
-- Write the help associated with the command.
procedure Help (Command : in out Command_Type;
Name : in String;
Context : in out Context_Type) is abstract;
-- Write the command usage.
procedure Usage (Command : in out Command_Type;
Name : in String;
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.
-- 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 out Help_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 Help_Command_Type;
Name : in String;
Context : in out Context_Type);
type Driver_Type is tagged limited private;
-- Report the command usage.
procedure Usage (Driver : in Driver_Type;
Args : in Argument_List'Class;
Context : in out Context_Type;
Name : in String := "");
-- Set the driver description printed in the usage.
procedure Set_Description (Driver : in out Driver_Type;
Description : in String);
-- Set the driver usage printed in the usage.
procedure Set_Usage (Driver : in out Driver_Type;
Usage : in String);
-- Register the command under the given name.
procedure Add_Command (Driver : in out Driver_Type;
Name : in String;
Command : in Command_Access);
procedure Add_Command (Driver : in out Driver_Type;
Name : in String;
Description : in String;
Command : in Command_Access);
-- Register the command under the given name.
procedure Add_Command (Driver : in out Driver_Type;
Name : in String;
Description : 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;
Name : Ada.Strings.Unbounded.Unbounded_String;
Description : Ada.Strings.Unbounded.Unbounded_String;
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 out 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 out Handler_Command_Type;
Name : in String;
Context : in out Context_Type);
type Driver_Type is tagged limited record
List : Command_Maps.Map;
Desc : Ada.Strings.Unbounded.Unbounded_String;
Usage : Ada.Strings.Unbounded.Unbounded_String;
end record;
end Util.Commands.Drivers;
|
-----------------------------------------------------------------------
-- util-commands-drivers -- Support to make command line tools
-- Copyright (C) 2017, 2018, 2019 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Log;
with Util.Commands.Parsers;
private with Ada.Strings.Unbounded;
private with Ada.Containers.Ordered_Sets;
-- == Command line driver ==
-- The `Util.Commands.Drivers` generic package provides a support to build command line
-- tools that have different commands identified by a name. It defines the `Driver_Type`
-- tagged record that provides a registry of application commands. It gives entry points
-- to register commands and execute them.
--
-- The `Context_Type` package parameter defines the type for the `Context` parameter
-- that is passed to the command when it is executed. It can be used to provide
-- application specific context to the command.
--
-- The `Config_Parser` describes the parser package that will handle the analysis of
-- command line options. To use the GNAT options parser, it is possible to use the
-- `Util.Commands.Parsers.GNAT_Parser` package.
generic
-- The command execution context.
type Context_Type (<>) is limited private;
with package Config_Parser is new Util.Commands.Parsers.Config_Parser (<>);
Driver_Name : String := "Drivers";
package Util.Commands.Drivers is
subtype Config_Type is Config_Parser.Config_Type;
-- 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;
-- Get the description associated with the command.
function Get_Description (Command : in Command_Type) return String;
-- Get the name used to register the command.
function Get_Name (Command : in Command_Type) return String;
-- Execute the command with the arguments. The command name is passed with the command
-- arguments.
procedure Execute (Command : in out Command_Type;
Name : in String;
Args : in Argument_List'Class;
Context : in out Context_Type) is abstract;
-- Setup the command before parsing the arguments and executing it.
procedure Setup (Command : in out Command_Type;
Config : in out Config_Type;
Context : in out Context_Type) is null;
-- Write the help associated with the command.
procedure Help (Command : in out Command_Type;
Name : in String;
Context : in out Context_Type) is abstract;
-- Write the command usage.
procedure Usage (Command : in out Command_Type;
Name : in String;
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.
-- 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 out Help_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 Help_Command_Type;
Name : in String;
Context : in out Context_Type);
type Driver_Type is tagged limited private;
-- Report the command usage.
procedure Usage (Driver : in Driver_Type;
Args : in Argument_List'Class;
Context : in out Context_Type;
Name : in String := "");
-- Set the driver description printed in the usage.
procedure Set_Description (Driver : in out Driver_Type;
Description : in String);
-- Set the driver usage printed in the usage.
procedure Set_Usage (Driver : in out Driver_Type;
Usage : in String);
-- Register the command under the given name.
procedure Add_Command (Driver : in out Driver_Type;
Name : in String;
Command : in Command_Access);
procedure Add_Command (Driver : in out Driver_Type;
Name : in String;
Description : in String;
Command : in Command_Access);
-- Register the command under the given name.
procedure Add_Command (Driver : in out Driver_Type;
Name : in String;
Description : 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
type Command_Type is abstract tagged limited record
Driver : access Driver_Type'Class;
Name : Ada.Strings.Unbounded.Unbounded_String;
Description : Ada.Strings.Unbounded.Unbounded_String;
end record;
function "<" (Left, Right : in Command_Access) return Boolean is
(Ada.Strings.Unbounded."<" (Left.Name, Right.Name));
package Command_Sets is
new Ada.Containers.Ordered_Sets (Element_Type => Command_Access,
"<" => "<",
"=" => "=");
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 out 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 out Handler_Command_Type;
Name : in String;
Context : in out Context_Type);
type Driver_Type is tagged limited record
List : Command_Sets.Set;
Desc : Ada.Strings.Unbounded.Unbounded_String;
Usage : Ada.Strings.Unbounded.Unbounded_String;
end record;
end Util.Commands.Drivers;
|
Change the implementation to use an Ordered_Set instead of an Indefinite_Hashed_Map
|
Change the implementation to use an Ordered_Set instead of an Indefinite_Hashed_Map
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
5cdd09f63554fed20b7eb1e76a2d328eaa4677e9
|
awa/plugins/awa-workspaces/src/awa-workspaces-modules.adb
|
awa/plugins/awa-workspaces/src/awa-workspaces-modules.adb
|
-----------------------------------------------------------------------
-- awa-workspaces-module -- Module workspaces
-- 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.Calendar;
with AWA.Users.Models;
with AWA.Modules.Beans;
with AWA.Permissions.Services;
with ADO.SQL;
with Util.Log.Loggers;
with AWA.Users.Modules;
with AWA.Workspaces.Beans;
package body AWA.Workspaces.Modules is
package ASC renames AWA.Services.Contexts;
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Awa.Workspaces.Module");
package Register is new AWA.Modules.Beans (Module => Workspace_Module,
Module_Access => Workspace_Module_Access);
-- ------------------------------
-- Initialize the workspaces module.
-- ------------------------------
overriding
procedure Initialize (Plugin : in out Workspace_Module;
App : in AWA.Modules.Application_Access;
Props : in ASF.Applications.Config) is
begin
Log.Info ("Initializing the workspaces module");
-- Register here any bean class, servlet, filter.
Register.Register (Plugin => Plugin,
Name => "AWA.Workspaces.Beans.Workspaces_Bean",
Handler => AWA.Workspaces.Beans.Create_Workspaces_Bean'Access);
Register.Register (Plugin => Plugin,
Name => "AWA.Workspaces.Beans.Member_List_Bean",
Handler => AWA.Workspaces.Beans.Create_Member_List_Bean'Access);
Register.Register (Plugin => Plugin,
Name => "AWA.Workspaces.Beans.Invitation_Bean",
Handler => AWA.Workspaces.Beans.Create_Invitation_Bean'Access);
AWA.Modules.Module (Plugin).Initialize (App, Props);
Plugin.User_Manager := AWA.Users.Modules.Get_User_Manager;
-- Add here the creation of manager instances.
end Initialize;
-- ------------------------------
-- Get the current workspace associated with the current user.
-- If the user has not workspace, create one.
-- ------------------------------
procedure Get_Workspace (Session : in out ADO.Sessions.Master_Session;
Context : in AWA.Services.Contexts.Service_Context_Access;
Workspace : out AWA.Workspaces.Models.Workspace_Ref) is
User : constant AWA.Users.Models.User_Ref := Context.Get_User;
WS : AWA.Workspaces.Models.Workspace_Ref;
Member : AWA.Workspaces.Models.Workspace_Member_Ref;
Query : ADO.SQL.Query;
Found : Boolean;
begin
if User.Is_Null then
Log.Error ("There is no current user. The workspace cannot be identified");
Workspace := AWA.Workspaces.Models.Null_Workspace;
return;
end if;
-- Find the workspace associated with the current user.
Query.Add_Param (User.Get_Id);
Query.Set_Filter ("o.owner_id = ?");
WS.Find (Session, Query, Found);
if Found then
Workspace := WS;
return;
end if;
-- Create a workspace for this user.
WS.Set_Owner (User);
WS.Set_Create_Date (Ada.Calendar.Clock);
WS.Save (Session);
-- Create the member instance for this user.
Member.Set_Workspace (WS);
Member.Set_Member (User);
Member.Set_Role ("Owner");
Member.Set_Join_Date (ADO.Nullable_Time '(Is_Null => False, Value => WS.Get_Create_Date));
Member.Save (Session);
-- And give full control of the workspace for this user
AWA.Permissions.Services.Add_Permission (Session => Session,
User => User.Get_Id,
Entity => WS);
Workspace := WS;
end Get_Workspace;
-- ------------------------------
-- Load the invitation from the access key and verify that the key is still valid.
-- ------------------------------
procedure Load_Invitation (Module : in Workspace_Module;
Key : in String;
Invitation : in out AWA.Workspaces.Models.Invitation_Ref'Class;
Inviter : in out AWA.Users.Models.User_Ref) is
use type Ada.Calendar.Time;
Ctx : constant ASC.Service_Context_Access := AWA.Services.Contexts.Current;
DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx);
Query : ADO.SQL.Query;
DB_Key : AWA.Users.Models.Access_Key_Ref;
Found : Boolean;
begin
Log.Debug ("Loading invitation from key {0}", Key);
Query.Set_Filter ("o.access_key = :key");
Query.Bind_Param ("key", Key);
DB_Key.Find (DB, Query, Found);
if not Found then
Log.Info ("Invitation key {0} does not exist");
raise Not_Found;
end if;
if DB_Key.Get_Expire_Date < Ada.Calendar.Clock then
Log.Info ("Invitation key {0} has expired");
raise Not_Found;
end if;
Query.Set_Filter ("o.invitee_id = :user");
Query.Bind_Param ("user", DB_Key.Get_User.Get_Id);
Invitation.Find (DB, Query, Found);
if not Found then
Log.Warn ("Invitation key {0} has been withdawn");
raise Not_Found;
end if;
Inviter := AWA.Users.Models.User_Ref (Invitation.Get_Inviter);
end Load_Invitation;
-- ------------------------------
-- Accept the invitation identified by the access key.
-- ------------------------------
procedure Accept_Invitation (Module : in Workspace_Module;
Key : in String) is
use type Ada.Calendar.Time;
use type ADO.Identifier;
Ctx : constant ASC.Service_Context_Access := AWA.Services.Contexts.Current;
User : constant AWA.Users.Models.User_Ref := Ctx.Get_User;
DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx);
Query : ADO.SQL.Query;
DB_Key : AWA.Users.Models.Access_Key_Ref;
Found : Boolean;
Invitation : AWA.Workspaces.Models.Invitation_Ref;
Invitee_Id : ADO.Identifier;
Workspace_Id : ADO.Identifier;
Member : AWA.Workspaces.Models.Workspace_Member_Ref;
User_Member : AWA.Workspaces.Models.Workspace_Member_Ref;
Now : constant Ada.Calendar.Time := Ada.Calendar.Clock;
begin
Log.Debug ("Accept invitation with key {0}", Key);
Ctx.Start;
-- Get the access key and verify its validity.
Query.Set_Filter ("o.access_key = :key");
Query.Bind_Param ("key", Key);
DB_Key.Find (DB, Query, Found);
if not Found then
Log.Info ("Invitation key {0} does not exist", Key);
raise Not_Found;
end if;
if DB_Key.Get_Expire_Date < Now then
Log.Info ("Invitation key {0} has expired", Key);
raise Not_Found;
end if;
-- Find the invitation associated with the access key.
Invitee_Id := DB_Key.Get_User.Get_Id;
Query.Set_Filter ("o.invitee_id = :user");
Query.Bind_Param ("user", Invitee_Id);
Invitation.Find (DB, Query, Found);
if not Found then
Log.Warn ("Invitation key {0} has been withdawn", Key);
raise Not_Found;
end if;
Workspace_Id := Invitation.Get_Workspace.Get_Id;
-- Update the workspace member relation.
Query.Clear;
Query.Set_Filter ("o.member_id = ? AND o.workspace_id = ?");
Query.Add_Param (Invitee_Id);
Query.Add_Param (Workspace_Id);
Member.Find (DB, Query, Found);
if not Found then
Log.Warn ("Invitation key {0} has been withdawn", Key);
raise Not_Found;
end if;
Member.Set_Join_Date (ADO.Nullable_Time '(Is_Null => False,
Value => Now));
Invitation.Set_Acceptance_Date (ADO.Nullable_Time '(Is_Null => False,
Value => Now));
-- The user who received the invitation is different from the user who is
-- logged and accepted the validation. Since the key is verified, this is
-- the same user but the user who accepted the invitation registered using
-- another email address.
if Invitee_Id /= User.Get_Id then
-- Check whether the user is not already part of the workspace.
Query.Clear;
Query.Set_Filter ("o.member_id = ? AND o.workspace_id = ?");
Query.Add_Param (User.Get_Id);
Query.Add_Param (Workspace_Id);
User_Member.Find (DB, Query, Found);
if Found then
Member.Delete (DB);
Invitation.Delete (DB);
Log.Info ("Invitation accepted by user who is already a member");
else
Member.Set_Member (User);
Log.Info ("Invitation accepted by user with another email address");
end if;
Invitation.Set_Invitee (User);
end if;
if not Member.Is_Null then
Member.Save (DB);
end if;
DB_Key.Delete (DB);
if not Invitation.Is_Null then
Invitation.Save (DB);
end if;
Ctx.Commit;
end Accept_Invitation;
-- ------------------------------
-- Send the invitation to the user.
-- ------------------------------
procedure Send_Invitation (Module : in Workspace_Module;
Invitation : in out AWA.Workspaces.Models.Invitation_Ref'Class) is
use type ADO.Identifier;
Ctx : constant ASC.Service_Context_Access := AWA.Services.Contexts.Current;
DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx);
User : constant AWA.Users.Models.User_Ref := Ctx.Get_User;
WS : AWA.Workspaces.Models.Workspace_Ref;
Query : ADO.SQL.Query;
Found : Boolean;
Key : AWA.Users.Models.Access_Key_Ref;
Email : AWA.Users.Models.Email_Ref;
Invitee : AWA.Users.Models.User_Ref;
Invit : AWA.Workspaces.Models.Invitation_Ref;
Member : AWA.Workspaces.Models.Workspace_Member_Ref;
Email_Address : constant String := Invitation.Get_Email;
begin
Log.Info ("Sending invitation to {0}", Email_Address);
Ctx.Start;
if User.Is_Null then
Log.Error ("There is no current user. The workspace cannot be identified");
return;
end if;
-- Find the workspace associated with the current user.
Query.Add_Param (User.Get_Id);
Query.Set_Filter ("o.owner_id = ?");
WS.Find (DB, Query, Found);
if not Found then
return;
end if;
Query.Clear;
Query.Set_Filter ("o.email = ?");
Query.Add_Param (Email_Address);
Email.Find (DB, Query, Found);
if not Found then
Email.Set_User_Id (0);
Email.Set_Email (Email_Address);
Email.Save (DB);
Invitee.Set_Email (Email);
Invitee.Set_Name (Email_Address);
Invitee.Save (DB);
Email.Set_User_Id (Invitee.Get_Id);
Email.Save (DB);
else
Invitee.Load (DB, Email.Get_User_Id);
end if;
-- Create the workspace member relation.
Query.Clear;
Query.Set_Filter ("o.member_id = ? AND o.workspace_id = ?");
Query.Add_Param (Invitee.Get_Id);
Query.Add_Param (WS.Get_Id);
Member.Find (DB, Query, Found);
if not Found then
Member.Set_Member (Invitee);
Member.Set_Workspace (WS);
Member.Set_Role ("Invited");
Member.Save (DB);
end if;
-- Check for a previous invitation for the user and delete it.
Query.Set_Filter ("o.invitee_id = ? AND o.workspace_id = ?");
Invit.Find (DB, Query, Found);
if Found then
Key := AWA.Users.Models.Access_Key_Ref (Invit.Get_Access_Key);
Key.Delete (DB);
if not Invitation.Is_Inserted or else Invit.Get_Id /= Invitation.Get_Id then
Invit.Delete (DB);
end if;
end if;
Key := AWA.Users.Models.Access_Key_Ref (Invitation.Get_Access_Key);
Module.User_Manager.Create_Access_Key (Invitee, Key, 365 * 86400.0, DB);
Key.Save (DB);
Invitation.Set_Access_Key (Key);
Invitation.Set_Inviter (User);
Invitation.Set_Invitee (Invitee);
Invitation.Set_Workspace (WS);
Invitation.Set_Create_Date (Ada.Calendar.Clock);
Invitation.Save (DB);
-- Send the email with the reset password key
declare
Event : AWA.Events.Module_Event;
begin
Event.Set_Parameter ("key", Key.Get_Access_Key);
Event.Set_Parameter ("email", Email_Address);
Event.Set_Parameter ("name", Invitee.Get_Name);
Event.Set_Parameter ("message", Invitation.Get_Message);
Event.Set_Parameter ("inviter", User.Get_Name);
Event.Set_Event_Kind (Invite_User_Event.Kind);
Module.Send_Event (Event);
end;
Ctx.Commit;
end Send_Invitation;
end AWA.Workspaces.Modules;
|
-----------------------------------------------------------------------
-- awa-workspaces-module -- Module workspaces
-- Copyright (C) 2011, 2012, 2013, 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Calendar;
with AWA.Users.Models;
with AWA.Modules.Beans;
with AWA.Permissions.Services;
with ADO.SQL;
with Util.Log.Loggers;
with AWA.Users.Modules;
with AWA.Workspaces.Beans;
package body AWA.Workspaces.Modules is
use type ADO.Identifier;
package ASC renames AWA.Services.Contexts;
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Awa.Workspaces.Module");
package Register is new AWA.Modules.Beans (Module => Workspace_Module,
Module_Access => Workspace_Module_Access);
-- ------------------------------
-- Initialize the workspaces module.
-- ------------------------------
overriding
procedure Initialize (Plugin : in out Workspace_Module;
App : in AWA.Modules.Application_Access;
Props : in ASF.Applications.Config) is
begin
Log.Info ("Initializing the workspaces module");
-- Register here any bean class, servlet, filter.
Register.Register (Plugin => Plugin,
Name => "AWA.Workspaces.Beans.Workspaces_Bean",
Handler => AWA.Workspaces.Beans.Create_Workspaces_Bean'Access);
Register.Register (Plugin => Plugin,
Name => "AWA.Workspaces.Beans.Member_List_Bean",
Handler => AWA.Workspaces.Beans.Create_Member_List_Bean'Access);
Register.Register (Plugin => Plugin,
Name => "AWA.Workspaces.Beans.Invitation_Bean",
Handler => AWA.Workspaces.Beans.Create_Invitation_Bean'Access);
AWA.Modules.Module (Plugin).Initialize (App, Props);
Plugin.User_Manager := AWA.Users.Modules.Get_User_Manager;
-- Add here the creation of manager instances.
end Initialize;
-- ------------------------------
-- Get the current workspace associated with the current user.
-- If the user has not workspace, create one.
-- ------------------------------
procedure Get_Workspace (Session : in out ADO.Sessions.Master_Session;
Context : in AWA.Services.Contexts.Service_Context_Access;
Workspace : out AWA.Workspaces.Models.Workspace_Ref) is
User : constant AWA.Users.Models.User_Ref := Context.Get_User;
WS : AWA.Workspaces.Models.Workspace_Ref;
Member : AWA.Workspaces.Models.Workspace_Member_Ref;
Query : ADO.SQL.Query;
Found : Boolean;
begin
if User.Is_Null then
Log.Error ("There is no current user. The workspace cannot be identified");
Workspace := AWA.Workspaces.Models.Null_Workspace;
return;
end if;
-- Find the workspace associated with the current user.
Query.Add_Param (User.Get_Id);
Query.Set_Filter ("o.owner_id = ?");
WS.Find (Session, Query, Found);
if Found then
Workspace := WS;
return;
end if;
-- Create a workspace for this user.
WS.Set_Owner (User);
WS.Set_Create_Date (Ada.Calendar.Clock);
WS.Save (Session);
-- Create the member instance for this user.
Member.Set_Workspace (WS);
Member.Set_Member (User);
Member.Set_Role ("Owner");
Member.Set_Join_Date (ADO.Nullable_Time '(Is_Null => False, Value => WS.Get_Create_Date));
Member.Save (Session);
-- And give full control of the workspace for this user
AWA.Permissions.Services.Add_Permission (Session => Session,
User => User.Get_Id,
Entity => WS,
Workspace => WS.Get_Id);
Workspace := WS;
end Get_Workspace;
-- ------------------------------
-- Load the invitation from the access key and verify that the key is still valid.
-- ------------------------------
procedure Load_Invitation (Module : in Workspace_Module;
Key : in String;
Invitation : in out AWA.Workspaces.Models.Invitation_Ref'Class;
Inviter : in out AWA.Users.Models.User_Ref) is
use type Ada.Calendar.Time;
Ctx : constant ASC.Service_Context_Access := AWA.Services.Contexts.Current;
DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx);
Query : ADO.SQL.Query;
DB_Key : AWA.Users.Models.Access_Key_Ref;
Found : Boolean;
begin
Log.Debug ("Loading invitation from key {0}", Key);
Query.Set_Filter ("o.access_key = :key");
Query.Bind_Param ("key", Key);
DB_Key.Find (DB, Query, Found);
if not Found then
Log.Info ("Invitation key {0} does not exist");
raise Not_Found;
end if;
if DB_Key.Get_Expire_Date < Ada.Calendar.Clock then
Log.Info ("Invitation key {0} has expired");
raise Not_Found;
end if;
Query.Set_Filter ("o.invitee_id = :user");
Query.Bind_Param ("user", DB_Key.Get_User.Get_Id);
Invitation.Find (DB, Query, Found);
if not Found then
Log.Warn ("Invitation key {0} has been withdawn");
raise Not_Found;
end if;
Inviter := AWA.Users.Models.User_Ref (Invitation.Get_Inviter);
end Load_Invitation;
-- ------------------------------
-- Accept the invitation identified by the access key.
-- ------------------------------
procedure Accept_Invitation (Module : in Workspace_Module;
Key : in String) is
use type Ada.Calendar.Time;
Ctx : constant ASC.Service_Context_Access := AWA.Services.Contexts.Current;
User : constant AWA.Users.Models.User_Ref := Ctx.Get_User;
DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx);
Query : ADO.SQL.Query;
DB_Key : AWA.Users.Models.Access_Key_Ref;
Found : Boolean;
Invitation : AWA.Workspaces.Models.Invitation_Ref;
Invitee_Id : ADO.Identifier;
Workspace_Id : ADO.Identifier;
Member : AWA.Workspaces.Models.Workspace_Member_Ref;
User_Member : AWA.Workspaces.Models.Workspace_Member_Ref;
Now : constant Ada.Calendar.Time := Ada.Calendar.Clock;
begin
Log.Debug ("Accept invitation with key {0}", Key);
Ctx.Start;
-- Get the access key and verify its validity.
Query.Set_Filter ("o.access_key = :key");
Query.Bind_Param ("key", Key);
DB_Key.Find (DB, Query, Found);
if not Found then
Log.Info ("Invitation key {0} does not exist", Key);
raise Not_Found;
end if;
if DB_Key.Get_Expire_Date < Now then
Log.Info ("Invitation key {0} has expired", Key);
raise Not_Found;
end if;
-- Find the invitation associated with the access key.
Invitee_Id := DB_Key.Get_User.Get_Id;
Query.Set_Filter ("o.invitee_id = :user");
Query.Bind_Param ("user", Invitee_Id);
Invitation.Find (DB, Query, Found);
if not Found then
Log.Warn ("Invitation key {0} has been withdawn", Key);
raise Not_Found;
end if;
Workspace_Id := Invitation.Get_Workspace.Get_Id;
-- Update the workspace member relation.
Query.Clear;
Query.Set_Filter ("o.member_id = ? AND o.workspace_id = ?");
Query.Add_Param (Invitee_Id);
Query.Add_Param (Workspace_Id);
Member.Find (DB, Query, Found);
if not Found then
Log.Warn ("Invitation key {0} has been withdawn", Key);
raise Not_Found;
end if;
Member.Set_Join_Date (ADO.Nullable_Time '(Is_Null => False,
Value => Now));
Invitation.Set_Acceptance_Date (ADO.Nullable_Time '(Is_Null => False,
Value => Now));
-- The user who received the invitation is different from the user who is
-- logged and accepted the validation. Since the key is verified, this is
-- the same user but the user who accepted the invitation registered using
-- another email address.
if Invitee_Id /= User.Get_Id then
-- Check whether the user is not already part of the workspace.
Query.Clear;
Query.Set_Filter ("o.member_id = ? AND o.workspace_id = ?");
Query.Add_Param (User.Get_Id);
Query.Add_Param (Workspace_Id);
User_Member.Find (DB, Query, Found);
if Found then
Member.Delete (DB);
Invitation.Delete (DB);
Log.Info ("Invitation accepted by user who is already a member");
else
Member.Set_Member (User);
Log.Info ("Invitation accepted by user with another email address");
end if;
Invitation.Set_Invitee (User);
end if;
if not Member.Is_Null then
Member.Save (DB);
end if;
DB_Key.Delete (DB);
if not Invitation.Is_Null then
Invitation.Save (DB);
end if;
Ctx.Commit;
end Accept_Invitation;
-- ------------------------------
-- Send the invitation to the user.
-- ------------------------------
procedure Send_Invitation (Module : in Workspace_Module;
Invitation : in out AWA.Workspaces.Models.Invitation_Ref'Class) is
Ctx : constant ASC.Service_Context_Access := AWA.Services.Contexts.Current;
DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx);
User : constant AWA.Users.Models.User_Ref := Ctx.Get_User;
WS : AWA.Workspaces.Models.Workspace_Ref;
Query : ADO.SQL.Query;
Found : Boolean;
Key : AWA.Users.Models.Access_Key_Ref;
Email : AWA.Users.Models.Email_Ref;
Invitee : AWA.Users.Models.User_Ref;
Invit : AWA.Workspaces.Models.Invitation_Ref;
Member : AWA.Workspaces.Models.Workspace_Member_Ref;
Email_Address : constant String := Invitation.Get_Email;
begin
Log.Info ("Sending invitation to {0}", Email_Address);
Ctx.Start;
if User.Is_Null then
Log.Error ("There is no current user. The workspace cannot be identified");
return;
end if;
-- Find the workspace associated with the current user.
Query.Add_Param (User.Get_Id);
Query.Set_Filter ("o.owner_id = ?");
WS.Find (DB, Query, Found);
if not Found then
return;
end if;
Query.Clear;
Query.Set_Filter ("o.email = ?");
Query.Add_Param (Email_Address);
Email.Find (DB, Query, Found);
if not Found then
Email.Set_User_Id (0);
Email.Set_Email (Email_Address);
Email.Save (DB);
Invitee.Set_Email (Email);
Invitee.Set_Name (Email_Address);
Invitee.Save (DB);
Email.Set_User_Id (Invitee.Get_Id);
Email.Save (DB);
else
Invitee.Load (DB, Email.Get_User_Id);
end if;
-- Create the workspace member relation.
Query.Clear;
Query.Set_Filter ("o.member_id = ? AND o.workspace_id = ?");
Query.Add_Param (Invitee.Get_Id);
Query.Add_Param (WS.Get_Id);
Member.Find (DB, Query, Found);
if not Found then
Member.Set_Member (Invitee);
Member.Set_Workspace (WS);
Member.Set_Role ("Invited");
Member.Save (DB);
end if;
-- Check for a previous invitation for the user and delete it.
Query.Set_Filter ("o.invitee_id = ? AND o.workspace_id = ?");
Invit.Find (DB, Query, Found);
if Found then
Key := AWA.Users.Models.Access_Key_Ref (Invit.Get_Access_Key);
Key.Delete (DB);
if not Invitation.Is_Inserted or else Invit.Get_Id /= Invitation.Get_Id then
Invit.Delete (DB);
end if;
end if;
Key := AWA.Users.Models.Access_Key_Ref (Invitation.Get_Access_Key);
Module.User_Manager.Create_Access_Key (Invitee, Key, 365 * 86400.0, DB);
Key.Save (DB);
Invitation.Set_Access_Key (Key);
Invitation.Set_Inviter (User);
Invitation.Set_Invitee (Invitee);
Invitation.Set_Workspace (WS);
Invitation.Set_Create_Date (Ada.Calendar.Clock);
Invitation.Save (DB);
-- Send the email with the reset password key
declare
Event : AWA.Events.Module_Event;
begin
Event.Set_Parameter ("key", Key.Get_Access_Key);
Event.Set_Parameter ("email", Email_Address);
Event.Set_Parameter ("name", Invitee.Get_Name);
Event.Set_Parameter ("message", Invitation.Get_Message);
Event.Set_Parameter ("inviter", User.Get_Name);
Event.Set_Event_Kind (Invite_User_Event.Kind);
Module.Send_Event (Event);
end;
Ctx.Commit;
end Send_Invitation;
-- ------------------------------
-- Delete the member from the workspace. Remove the invitation if there is one.
-- ------------------------------
procedure Delete_Member (Module : in Workspace_Module;
User_Id : in ADO.Identifier;
Workspace_Id : in ADO.Identifier) is
Ctx : constant ASC.Service_Context_Access := AWA.Services.Contexts.Current;
DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx);
User : constant AWA.Users.Models.User_Ref := Ctx.Get_User;
Query : ADO.SQL.Query;
Found : Boolean;
Key : AWA.Users.Models.Access_Key_Ref;
Member : AWA.Workspaces.Models.Workspace_Member_Ref;
Invitation : AWA.Workspaces.Models.Invitation_Ref;
begin
Log.Info ("Delete user member {0}", ADO.Identifier'Image (User_Id));
if User.Get_Id = User_Id then
Log.Warn ("Refusing to delete the current user");
return;
end if;
Ctx.Start;
-- Get the workspace member instance for the user and remove it.
Query.Set_Filter ("o.member_id = ? AND o.workspace_id = ?");
Query.Add_Param (User_Id);
Query.Add_Param (Workspace_Id);
Member.Find (DB, Query, Found);
if Found then
Member.Delete (DB);
end if;
-- Get the invitation and remove it.
Query.Set_Filter ("o.invitee_id = ? AND o.workspace_id = ?");
Invitation.Find (DB, Query, Found);
if Found then
Key := AWA.Users.Models.Access_Key_Ref (Invitation.Get_Access_Key);
Key.Delete (DB);
Invitation.Delete (DB);
end if;
-- Remove all permissions assigned to the user in the workspace.
AWA.Permissions.Services.Delete_Permissions (DB, User_Id, Workspace_Id);
Ctx.Commit;
end Delete_Member;
end AWA.Workspaces.Modules;
|
Implement the Delete_Member procedure to withraw an invitation, remove the user from the workspace and delete all the permissions for that user/workspace pair
|
Implement the Delete_Member procedure to withraw an invitation, remove the user from
the workspace and delete all the permissions for that user/workspace pair
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
5f8f258b2bb6e6d73f1ac312ba376421f4f97cfc
|
src/security.ads
|
src/security.ads
|
-----------------------------------------------------------------------
-- security -- Security
-- Copyright (C) 2010, 2011, 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
-- == Introduction ==
-- The <tt>Security</tt> package provides a security framework that allows
-- an application to use OpenID or OAuth security frameworks. This security
-- framework was first developed within the Ada Server Faces project.
-- This package defines abstractions that are close or similar to Java
-- security package.
--
-- The security framework uses the following abstractions:
--
-- === Policy and policy manager ===
-- The <tt>Policy</tt> defines and implements the set of security rules that specify how to
-- protect the system or resources. The <tt>Policy_Manager</tt> maintains the security policies.
--
-- === Principal ===
-- The <tt>Principal</tt> is the entity that can be authenticated. A principal is obtained
-- after successful authentication of a user or of a system through an authorization process.
-- The OpenID or OAuth authentication processes generate such security principal.
--
-- === Permission ===
-- The <tt>Permission</tt> represents an access to a system or application resource.
-- A permission is checked by using the security policy manager. The policy manager uses a
-- security controller to enforce the permission.
--
-- === Security Context ===
-- The <tt>Security_Context</tt> holds the contextual information that the security controller
-- can use to verify the permission. The security context is associated with a principal and
-- a set of policy context.
--
-- == Overview ==
-- An application will create a security policy manager and register one or several security
-- policies (yellow). The framework defines a simple role based security policy and an URL
-- security policy intended to provide security in web applications. The security policy manager
-- reads some security policy configuration file which allows the security policies to configure
-- and create the security controllers. These controllers will enforce the security according
-- to the application security rules. All these components are built only once when
-- an application starts.
--
-- A user is authenticated through an authentication system which creates a <tt>Principal</tt>
-- instance that identifies the user (green). The security framework provides two authentication
-- systems: OpenID and OAuth.
--
-- [http://ada-security.googlecode.com/svn/wiki/ModelOverview.png]
--
-- When a permission must be enforced, a security context is created and linked to the
-- <tt>Principal</tt> instance (blue). Additional security policy context can be added depending
-- on the application context. To check the permission, the security policy manager is called
-- and it will ask a security controller to verify the permission.
--
-- The framework allows an application to plug its own security policy, its own policy context,
-- its own principal and authentication mechanism.
--
-- @include security-permissions.ads
--
-- == Principal ==
-- A principal is created by using either the [Security_Auth OpenID],
-- the [Security_OAuth OAuth] or another authentication mechanism. The authentication produces
-- an object that must implement the <tt>Principal</tt> interface. For example:
--
-- P : Security.Auth.Principal_Access := Security.Auth.Create_Principal (Auth);
--
-- or
--
-- P : Security.OAuth.Clients.Access_Token_Access := Security.OAuth.Clients.Create_Access_Token
--
-- The principal is then stored in a security context.
--
-- @include security-contexts.ads
--
-- [Security_Policies Security Policies]
-- [Security_Auth OpenID]
-- [Security_OAuth OAuth]
--
package Security is
pragma Preelaborate;
-- ------------------------------
-- Principal
-- ------------------------------
type Principal is limited interface;
type Principal_Access is access all Principal'Class;
-- Get the principal name.
function Get_Name (From : in Principal) return String is abstract;
end Security;
|
-----------------------------------------------------------------------
-- security -- Security
-- Copyright (C) 2010, 2011, 2012, 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
-- == Introduction ==
-- The <tt>Security</tt> package provides a security framework that allows
-- an application to use OpenID or OAuth security frameworks. This security
-- framework was first developed within the Ada Server Faces project.
-- This package defines abstractions that are close or similar to Java
-- security package.
--
-- The security framework uses the following abstractions:
--
-- === Policy and policy manager ===
-- The <tt>Policy</tt> defines and implements the set of security rules that specify how to
-- protect the system or resources. The <tt>Policy_Manager</tt> maintains the security policies.
--
-- === Principal ===
-- The <tt>Principal</tt> is the entity that can be authenticated. A principal is obtained
-- after successful authentication of a user or of a system through an authorization process.
-- The OpenID or OAuth authentication processes generate such security principal.
--
-- === Permission ===
-- The <tt>Permission</tt> represents an access to a system or application resource.
-- A permission is checked by using the security policy manager. The policy manager uses a
-- security controller to enforce the permission.
--
-- === Security Context ===
-- The <tt>Security_Context</tt> holds the contextual information that the security controller
-- can use to verify the permission. The security context is associated with a principal and
-- a set of policy context.
--
-- == Overview ==
-- An application will create a security policy manager and register one or several security
-- policies (yellow). The framework defines a simple role based security policy and an URL
-- security policy intended to provide security in web applications. The security policy manager
-- reads some security policy configuration file which allows the security policies to configure
-- and create the security controllers. These controllers will enforce the security according
-- to the application security rules. All these components are built only once when
-- an application starts.
--
-- A user is authenticated through an authentication system which creates a <tt>Principal</tt>
-- instance that identifies the user (green). The security framework provides two authentication
-- systems: OpenID and OAuth.
--
-- [images/ModelOverview.png]
--
-- When a permission must be enforced, a security context is created and linked to the
-- <tt>Principal</tt> instance (blue). Additional security policy context can be added depending
-- on the application context. To check the permission, the security policy manager is called
-- and it will ask a security controller to verify the permission.
--
-- The framework allows an application to plug its own security policy, its own policy context,
-- its own principal and authentication mechanism.
--
-- @include security-permissions.ads
--
-- == Principal ==
-- A principal is created by using either the [Security_Auth OpenID],
-- the [Security_OAuth OAuth] or another authentication mechanism. The authentication produces
-- an object that must implement the <tt>Principal</tt> interface. For example:
--
-- P : Security.Auth.Principal_Access := Security.Auth.Create_Principal (Auth);
--
-- or
--
-- P : Security.OAuth.Clients.Access_Token_Access := Security.OAuth.Clients.Create_Access_Token
--
-- The principal is then stored in a security context.
--
-- @include security-contexts.ads
--
-- [Security_Policies Security Policies]
-- [Security_Auth OpenID]
-- [Security_OAuth OAuth]
--
package Security is
pragma Preelaborate;
-- ------------------------------
-- Principal
-- ------------------------------
type Principal is limited interface;
type Principal_Access is access all Principal'Class;
-- Get the principal name.
function Get_Name (From : in Principal) return String is abstract;
end Security;
|
Update the documentation
|
Update the documentation
|
Ada
|
apache-2.0
|
stcarrez/ada-security
|
184b97a77de2717e419cbc2253f5ee34e0f4232d
|
src/security.ads
|
src/security.ads
|
-----------------------------------------------------------------------
-- security -- Security
-- Copyright (C) 2010, 2011, 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
-- == Introduction ==
-- The <tt>Security</tt> package provides a security framework that allows
-- an application to use OpenID or OAuth security frameworks. This security
-- framework was first developed within the Ada Server Faces project.
-- This package defines abstractions that are close or similar to Java
-- security package.
--
-- The security framework uses the following abstractions:
--
-- === Policy and policy manager ===
-- The <tt>Policy</tt> defines and implements the set of security rules that specify how to
-- protect the system or resources. The <tt>Policy_Manager</tt> maintains the security policies.
--
-- === Principal ===
-- The <tt>Principal</tt> is the entity that can be authenticated. A principal is obtained
-- after successful authentication of a user or of a system through an authorization process.
-- The OpenID or OAuth authentication processes generate such security principal.
--
-- === Permission ===
-- The <tt>Permission</tt> represents an access to a system or application resource.
-- A permission is checked by using the security policy manager. The policy manager uses a
-- security controller to enforce the permission.
--
-- === Security Context ===
-- The <tt>Security_Context</tt> holds the contextual information that the security controller
-- can use to verify the permission. The security context is associated with a principal and
-- a set of policy context.
--
-- == Overview ==
-- An application will create a security policy manager and register one or several security
-- policies. The framework defines a simple role based security policy and an URL security
-- policy intended to provide security in web applications. The security policy manager reads
-- some security policy configuration file which allows the security policies to configure
-- and create the security controllers. These controllers will enforce the security according
-- to the application security rules. All these components (yellow) are built only once when
-- an application starts.
--
-- A user is authenticated through an authentication system which creates a <tt>Principal</tt>
-- instance that identifies the user (green). The security framework provides two authentication
-- systems: OpenID and OAuth.
--
-- [http://ada-security.googlecode.com/svn/wiki/ModelOverview.png]
--
-- When a permission must be enforced, a security context is created and linked to the
-- <tt>Principal</tt> instance. Additional security policy context can be added depending on
-- the application context. To check the permission, the security policy manager is called
-- and it will ask a security controller to verify the permission.
--
-- The framework allows an application to plug its own security policy, its own policy context,
-- its own principal and authentication mechanism.
--
-- @include security-permissions.ads
-- @include security-contexts.ads
-- @include security-controllers.ads
package Security is
-- ------------------------------
-- Principal
-- ------------------------------
type Principal is limited interface;
type Principal_Access is access all Principal'Class;
-- Get the principal name.
function Get_Name (From : in Principal) return String is abstract;
end Security;
|
-----------------------------------------------------------------------
-- security -- Security
-- Copyright (C) 2010, 2011, 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
-- == Introduction ==
-- The <tt>Security</tt> package provides a security framework that allows
-- an application to use OpenID or OAuth security frameworks. This security
-- framework was first developed within the Ada Server Faces project.
-- This package defines abstractions that are close or similar to Java
-- security package.
--
-- The security framework uses the following abstractions:
--
-- === Policy and policy manager ===
-- The <tt>Policy</tt> defines and implements the set of security rules that specify how to
-- protect the system or resources. The <tt>Policy_Manager</tt> maintains the security policies.
--
-- === Principal ===
-- The <tt>Principal</tt> is the entity that can be authenticated. A principal is obtained
-- after successful authentication of a user or of a system through an authorization process.
-- The OpenID or OAuth authentication processes generate such security principal.
--
-- === Permission ===
-- The <tt>Permission</tt> represents an access to a system or application resource.
-- A permission is checked by using the security policy manager. The policy manager uses a
-- security controller to enforce the permission.
--
-- === Security Context ===
-- The <tt>Security_Context</tt> holds the contextual information that the security controller
-- can use to verify the permission. The security context is associated with a principal and
-- a set of policy context.
--
-- == Overview ==
-- An application will create a security policy manager and register one or several security
-- policies. The framework defines a simple role based security policy and an URL security
-- policy intended to provide security in web applications. The security policy manager reads
-- some security policy configuration file which allows the security policies to configure
-- and create the security controllers. These controllers will enforce the security according
-- to the application security rules. All these components (yellow) are built only once when
-- an application starts.
--
-- A user is authenticated through an authentication system which creates a <tt>Principal</tt>
-- instance that identifies the user (green). The security framework provides two authentication
-- systems: OpenID and OAuth.
--
-- [http://ada-security.googlecode.com/svn/wiki/ModelOverview.png]
--
-- When a permission must be enforced, a security context is created and linked to the
-- <tt>Principal</tt> instance. Additional security policy context can be added depending on
-- the application context. To check the permission, the security policy manager is called
-- and it will ask a security controller to verify the permission.
--
-- The framework allows an application to plug its own security policy, its own policy context,
-- its own principal and authentication mechanism.
--
-- @include security-permissions.ads
-- @include security-contexts.ads
--
-- [Security_Policies Security Policies]
--
package Security is
-- ------------------------------
-- Principal
-- ------------------------------
type Principal is limited interface;
type Principal_Access is access all Principal'Class;
-- Get the principal name.
function Get_Name (From : in Principal) return String is abstract;
end Security;
|
Add some links in the documentation
|
Add some links in the documentation
|
Ada
|
apache-2.0
|
stcarrez/ada-security
|
ac43d3ce2c63032f710c85b33e7a3fec6486506c
|
awa/plugins/awa-storages/src/awa-storages-services.adb
|
awa/plugins/awa-storages/src/awa-storages-services.adb
|
-----------------------------------------------------------------------
-- awa-storages-services -- Storage service
-- Copyright (C) 2012, 2013 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Log.Loggers;
with ADO.Objects;
with ADO.Queries;
with ADO.Statements;
with ADO.Sessions.Entities;
with AWA.Services.Contexts;
with AWA.Workspaces.Models;
with AWA.Workspaces.Modules;
with AWA.Permissions;
with AWA.Storages.Stores.Files;
package body AWA.Storages.Services is
use AWA.Services;
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("AWA.Storages.Services");
-- ------------------------------
-- Get the persistent store that manages the data store identified by <tt>Kind</tt>.
-- ------------------------------
function Get_Store (Service : in Storage_Service;
Kind : in AWA.Storages.Models.Storage_Type)
return AWA.Storages.Stores.Store_Access is
begin
return Service.Stores (Kind);
end Get_Store;
-- ------------------------------
-- Initializes the storage service.
-- ------------------------------
overriding
procedure Initialize (Service : in out Storage_Service;
Module : in AWA.Modules.Module'Class) is
Root : constant String := Module.Get_Config (Stores.Files.Root_Directory_Parameter.P);
Tmp : constant String := Module.Get_Config (Stores.Files.Tmp_Directory_Parameter.P);
begin
AWA.Modules.Module_Manager (Service).Initialize (Module);
Service.Stores (Storages.Models.DATABASE) := Service.Database_Store'Unchecked_Access;
Service.Stores (Storages.Models.FILE) := AWA.Storages.Stores.Files.Create_File_Store (Root);
Service.Stores (Storages.Models.TMP) := AWA.Storages.Stores.Files.Create_File_Store (Tmp);
Service.Database_Store.Tmp := Service.Stores (Storages.Models.TMP);
end Initialize;
-- ------------------------------
-- Create or save the folder.
-- ------------------------------
procedure Save_Folder (Service : in Storage_Service;
Folder : in out AWA.Storages.Models.Storage_Folder_Ref'Class) is
pragma Unreferenced (Service);
Ctx : constant Contexts.Service_Context_Access := AWA.Services.Contexts.Current;
DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx);
Workspace : AWA.Workspaces.Models.Workspace_Ref;
begin
if not Folder.Is_Null then
Workspace := AWA.Workspaces.Models.Workspace_Ref (Folder.Get_Workspace);
end if;
if Workspace.Is_Null then
AWA.Workspaces.Modules.Get_Workspace (DB, Ctx, Workspace);
Folder.Set_Workspace (Workspace);
end if;
-- Check that the user has the create folder permission on the given workspace.
AWA.Permissions.Check (Permission => ACL_Create_Folder.Permission,
Entity => Workspace);
Ctx.Start;
if not Folder.Is_Inserted then
Folder.Set_Create_Date (Ada.Calendar.Clock);
Folder.Set_Owner (Ctx.Get_User);
end if;
Folder.Save (DB);
Ctx.Commit;
end Save_Folder;
-- ------------------------------
-- Load the folder instance identified by the given identifier.
-- ------------------------------
procedure Load_Folder (Service : in Storage_Service;
Folder : in out AWA.Storages.Models.Storage_Folder_Ref'Class;
Id : in ADO.Identifier) is
pragma Unreferenced (Service);
Ctx : constant Contexts.Service_Context_Access := AWA.Services.Contexts.Current;
DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx);
begin
Folder.Load (Session => DB, Id => Id);
end Load_Folder;
-- ------------------------------
-- Load the storage instance identified by the given identifier.
-- ------------------------------
procedure Load_Storage (Service : in Storage_Service;
Storage : in out AWA.Storages.Models.Storage_Ref'Class;
Id : in ADO.Identifier) is
pragma Unreferenced (Service);
Ctx : constant Contexts.Service_Context_Access := AWA.Services.Contexts.Current;
DB : ADO.Sessions.Session := AWA.Services.Contexts.Get_Session (Ctx);
begin
Storage.Load (Session => DB, Id => Id);
end Load_Storage;
-- ------------------------------
-- Save the data object contained in the <b>Data</b> part element into the
-- target storage represented by <b>Into</b>.
-- ------------------------------
procedure Save (Service : in Storage_Service;
Into : in out AWA.Storages.Models.Storage_Ref'Class;
Data : in ASF.Parts.Part'Class;
Storage : in AWA.Storages.Models.Storage_Type) is
begin
Storage_Service'Class (Service).Save (Into, Data.Get_Local_Filename, Storage);
end Save;
-- ------------------------------
-- Save the file pointed to by the <b>Path</b> string in the storage
-- object represented by <b>Into</b> and managed by the storage service.
-- ------------------------------
procedure Save (Service : in Storage_Service;
Into : in out AWA.Storages.Models.Storage_Ref'Class;
Path : in String;
Storage : in AWA.Storages.Models.Storage_Type) is
use type AWA.Storages.Models.Storage_Type;
use type Stores.Store_Access;
Ctx : constant Contexts.Service_Context_Access := AWA.Services.Contexts.Current;
DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx);
Workspace : AWA.Workspaces.Models.Workspace_Ref;
Store : Stores.Store_Access;
Created : Boolean;
begin
Log.Info ("Save {0} in storage space", Path);
Into.Set_Storage (Storage);
Store := Storage_Service'Class (Service).Get_Store (Into.Get_Storage);
if Store = null then
Log.Error ("There is no store for storage {0}", Models.Storage_Type'Image (Storage));
end if;
if not Into.Is_Null then
Workspace := AWA.Workspaces.Models.Workspace_Ref (Into.Get_Workspace);
end if;
if Workspace.Is_Null then
AWA.Workspaces.Modules.Get_Workspace (DB, Ctx, Workspace);
Into.Set_Workspace (Workspace);
end if;
-- Check that the user has the create storage permission on the given workspace.
AWA.Permissions.Check (Permission => ACL_Create_Storage.Permission,
Entity => Workspace);
Ctx.Start;
Created := not Into.Is_Inserted;
if Created then
Into.Set_Create_Date (Ada.Calendar.Clock);
Into.Set_Owner (Ctx.Get_User);
end if;
Into.Save (DB);
Store.Save (DB, Into, Path);
Into.Save (DB);
-- Notify the listeners.
if Created then
Storage_Lifecycle.Notify_Create (Service, Into);
else
Storage_Lifecycle.Notify_Update (Service, Into);
end if;
Ctx.Commit;
end Save;
-- ------------------------------
-- Load the storage content identified by <b>From</b> into the blob descriptor <b>Into</b>.
-- Raises the <b>NOT_FOUND</b> exception if there is no such storage.
-- ------------------------------
procedure Load (Service : in Storage_Service;
From : in ADO.Identifier;
Name : out Ada.Strings.Unbounded.Unbounded_String;
Mime : out Ada.Strings.Unbounded.Unbounded_String;
Date : out Ada.Calendar.Time;
Into : out ADO.Blob_Ref) is
use type AWA.Storages.Models.Storage_Type;
use type AWA.Storages.Stores.Store_Access;
Ctx : constant Contexts.Service_Context_Access := AWA.Services.Contexts.Current;
User : constant ADO.Identifier := Ctx.Get_User_Identifier;
DB : ADO.Sessions.Session := AWA.Services.Contexts.Get_Session (Ctx);
Query : ADO.Statements.Query_Statement
:= DB.Create_Statement (Models.Query_Storage_Get_Data);
Kind : AWA.Storages.Models.Storage_Type;
begin
Query.Bind_Param ("store_id", From);
Query.Bind_Param ("user_id", User);
ADO.Sessions.Entities.Bind_Param (Query, "table",
AWA.Workspaces.Models.WORKSPACE_TABLE, DB);
Query.Execute;
if not Query.Has_Elements then
Log.Warn ("Storage entity {0} not found", ADO.Identifier'Image (From));
raise ADO.Objects.NOT_FOUND;
end if;
Mime := Query.Get_Unbounded_String (0);
Date := Query.Get_Time (1);
Name := Query.Get_Unbounded_String (2);
Kind := AWA.Storages.Models.Storage_Type'Val (Query.Get_Integer (4));
if Kind = AWA.Storages.Models.DATABASE then
Into := Query.Get_Blob (5);
else
declare
Store : Stores.Store_Access;
Storage : AWA.Storages.Models.Storage_Ref;
File : AWA.Storages.Storage_File;
Found : Boolean;
begin
Store := Storage_Service'Class (Service).Get_Store (Kind);
if Store = null then
Log.Error ("There is no store for storage {0}", Models.Storage_Type'Image (Kind));
end if;
Storage.Load (DB, From, Found);
if not Found then
Log.Warn ("Storage entity {0} not found", ADO.Identifier'Image (From));
raise ADO.Objects.NOT_FOUND;
end if;
Store.Load (DB, Storage, File);
Into := ADO.Create_Blob (AWA.Storages.Get_Path (File));
end;
end if;
end Load;
-- Load the storage content into a file. If the data is not stored in a file, a temporary
-- file is created with the data content fetched from the store (ex: the database).
-- The `Mode` parameter indicates whether the file will be read or written.
-- The `Expire` parameter allows to control the expiration of the temporary file.
procedure Get_Local_File (Service : in Storage_Service;
From : in ADO.Identifier;
Mode : in Read_Mode := READ;
Into : out Storage_File) is
use type Stores.Store_Access;
use type Models.Storage_Type;
Ctx : constant Contexts.Service_Context_Access := AWA.Services.Contexts.Current;
User : constant ADO.Identifier := Ctx.Get_User_Identifier;
DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx);
Query : ADO.Queries.Context;
Found : Boolean;
Storage : AWA.Storages.Models.Storage_Ref;
Local : AWA.Storages.Models.Store_Local_Ref;
Store : Stores.Store_Access;
begin
if Mode = READ then
Query.Set_Query (AWA.Storages.Models.Query_Storage_Get_Local);
Query.Bind_Param ("store_id", From);
Query.Bind_Param ("user_id", User);
ADO.Sessions.Entities.Bind_Param (Query, "table",
AWA.Workspaces.Models.WORKSPACE_TABLE, DB);
Local.Find (DB, Query, Found);
if Found then
Into.Path := Local.Get_Path;
return;
end if;
end if;
Query.Set_Query (AWA.Storages.Models.Query_Storage_Get_Storage);
Query.Bind_Param ("store_id", From);
Query.Bind_Param ("user_id", User);
ADO.Sessions.Entities.Bind_Param (Query, "table",
AWA.Workspaces.Models.WORKSPACE_TABLE, DB);
Storage.Find (DB, Query, Found);
if not Found then
raise ADO.Objects.NOT_FOUND;
end if;
Ctx.Start;
Store := Storage_Service'Class (Service).Get_Store (Storage.Get_Storage);
Store.Load (Session => DB,
From => Storage,
Into => Into);
Ctx.Commit;
end Get_Local_File;
procedure Create_Local_File (Service : in Storage_Service;
Into : out Storage_File) is
begin
null;
end Create_Local_File;
-- ------------------------------
-- Deletes the storage instance.
-- ------------------------------
procedure Delete (Service : in Storage_Service;
Storage : in out AWA.Storages.Models.Storage_Ref'Class) is
Ctx : constant Contexts.Service_Context_Access := AWA.Services.Contexts.Current;
DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx);
Id : constant ADO.Identifier := ADO.Objects.Get_Value (Storage.Get_Key);
begin
Log.Info ("Delete storage {0}", ADO.Identifier'Image (Id));
-- Check that the user has the delete storage permission on the given workspace.
AWA.Permissions.Check (Permission => ACL_Delete_Storage.Permission,
Entity => Storage);
Ctx.Start;
Storage_Lifecycle.Notify_Delete (Service, Storage);
Storage.Delete (DB);
Ctx.Commit;
end Delete;
-- ------------------------------
-- Deletes the storage instance.
-- ------------------------------
procedure Delete (Service : in Storage_Service;
Storage : in ADO.Identifier) is
use type Stores.Store_Access;
Ctx : constant Contexts.Service_Context_Access := AWA.Services.Contexts.Current;
DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx);
S : AWA.Storages.Models.Storage_Ref;
Query : ADO.Statements.Query_Statement
:= DB.Create_Statement (AWA.Storages.Models.Query_Storage_Delete_Local);
Store : Stores.Store_Access;
begin
Log.Info ("Delete storage {0}", ADO.Identifier'Image (Storage));
-- Check that the user has the delete storage permission on the given workspace.
AWA.Permissions.Check (Permission => ACL_Delete_Storage.Permission,
Entity => Storage);
Ctx.Start;
S.Load (Id => Storage, Session => DB);
Store := Storage_Service'Class (Service).Get_Store (S.Get_Storage);
if Store = null then
Log.Error ("There is no store associated with storage item {0}",
ADO.Identifier'Image (Storage));
else
Store.Delete (DB, S);
end if;
Storage_Lifecycle.Notify_Delete (Service, S);
-- Delete the storage instance and all storage that refer to it.
declare
Stmt : ADO.Statements.Delete_Statement
:= DB.Create_Statement (AWA.Storages.Models.STORAGE_TABLE);
begin
Stmt.Set_Filter (Filter => "id = ? OR original_id = ?");
Stmt.Add_Param (Value => Storage);
Stmt.Add_Param (Value => Storage);
Stmt.Execute;
end;
-- Delete the local storage instances.
Query.Bind_Param ("store_id", Storage);
Query.Execute;
S.Delete (DB);
Ctx.Commit;
end Delete;
end AWA.Storages.Services;
|
-----------------------------------------------------------------------
-- awa-storages-services -- Storage service
-- Copyright (C) 2012, 2013 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Log.Loggers;
with ADO.Objects;
with ADO.Queries;
with ADO.Statements;
with ADO.Sessions.Entities;
with AWA.Services.Contexts;
with AWA.Workspaces.Models;
with AWA.Workspaces.Modules;
with AWA.Permissions;
with AWA.Storages.Stores.Files;
package body AWA.Storages.Services is
use AWA.Services;
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("AWA.Storages.Services");
-- ------------------------------
-- Get the persistent store that manages the data store identified by <tt>Kind</tt>.
-- ------------------------------
function Get_Store (Service : in Storage_Service;
Kind : in AWA.Storages.Models.Storage_Type)
return AWA.Storages.Stores.Store_Access is
begin
return Service.Stores (Kind);
end Get_Store;
-- ------------------------------
-- Initializes the storage service.
-- ------------------------------
overriding
procedure Initialize (Service : in out Storage_Service;
Module : in AWA.Modules.Module'Class) is
Root : constant String := Module.Get_Config (Stores.Files.Root_Directory_Parameter.P);
Tmp : constant String := Module.Get_Config (Stores.Files.Tmp_Directory_Parameter.P);
begin
AWA.Modules.Module_Manager (Service).Initialize (Module);
Service.Stores (Storages.Models.DATABASE) := Service.Database_Store'Unchecked_Access;
Service.Stores (Storages.Models.FILE) := AWA.Storages.Stores.Files.Create_File_Store (Root);
Service.Stores (Storages.Models.TMP) := AWA.Storages.Stores.Files.Create_File_Store (Tmp);
Service.Database_Store.Tmp := Service.Stores (Storages.Models.TMP);
end Initialize;
-- ------------------------------
-- Create or save the folder.
-- ------------------------------
procedure Save_Folder (Service : in Storage_Service;
Folder : in out AWA.Storages.Models.Storage_Folder_Ref'Class) is
pragma Unreferenced (Service);
Ctx : constant Contexts.Service_Context_Access := AWA.Services.Contexts.Current;
DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx);
Workspace : AWA.Workspaces.Models.Workspace_Ref;
begin
if not Folder.Is_Null then
Workspace := AWA.Workspaces.Models.Workspace_Ref (Folder.Get_Workspace);
end if;
if Workspace.Is_Null then
AWA.Workspaces.Modules.Get_Workspace (DB, Ctx, Workspace);
Folder.Set_Workspace (Workspace);
end if;
-- Check that the user has the create folder permission on the given workspace.
AWA.Permissions.Check (Permission => ACL_Create_Folder.Permission,
Entity => Workspace);
Ctx.Start;
if not Folder.Is_Inserted then
Folder.Set_Create_Date (Ada.Calendar.Clock);
Folder.Set_Owner (Ctx.Get_User);
end if;
Folder.Save (DB);
Ctx.Commit;
end Save_Folder;
-- ------------------------------
-- Load the folder instance identified by the given identifier.
-- ------------------------------
procedure Load_Folder (Service : in Storage_Service;
Folder : in out AWA.Storages.Models.Storage_Folder_Ref'Class;
Id : in ADO.Identifier) is
pragma Unreferenced (Service);
Ctx : constant Contexts.Service_Context_Access := AWA.Services.Contexts.Current;
DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx);
begin
Folder.Load (Session => DB, Id => Id);
end Load_Folder;
-- ------------------------------
-- Load the storage instance identified by the given identifier.
-- ------------------------------
procedure Load_Storage (Service : in Storage_Service;
Storage : in out AWA.Storages.Models.Storage_Ref'Class;
Id : in ADO.Identifier) is
pragma Unreferenced (Service);
Ctx : constant Contexts.Service_Context_Access := AWA.Services.Contexts.Current;
DB : ADO.Sessions.Session := AWA.Services.Contexts.Get_Session (Ctx);
begin
Storage.Load (Session => DB, Id => Id);
end Load_Storage;
-- ------------------------------
-- Save the data object contained in the <b>Data</b> part element into the
-- target storage represented by <b>Into</b>.
-- ------------------------------
procedure Save (Service : in Storage_Service;
Into : in out AWA.Storages.Models.Storage_Ref'Class;
Data : in ASF.Parts.Part'Class;
Storage : in AWA.Storages.Models.Storage_Type) is
begin
Storage_Service'Class (Service).Save (Into, Data.Get_Local_Filename, Storage);
end Save;
-- ------------------------------
-- Save the file pointed to by the <b>Path</b> string in the storage
-- object represented by <b>Into</b> and managed by the storage service.
-- ------------------------------
procedure Save (Service : in Storage_Service;
Into : in out AWA.Storages.Models.Storage_Ref'Class;
Path : in String;
Storage : in AWA.Storages.Models.Storage_Type) is
use type AWA.Storages.Models.Storage_Type;
use type Stores.Store_Access;
Ctx : constant Contexts.Service_Context_Access := AWA.Services.Contexts.Current;
DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx);
Workspace : AWA.Workspaces.Models.Workspace_Ref;
Store : Stores.Store_Access;
Created : Boolean;
begin
Log.Info ("Save {0} in storage space", Path);
Into.Set_Storage (Storage);
Store := Storage_Service'Class (Service).Get_Store (Into.Get_Storage);
if Store = null then
Log.Error ("There is no store for storage {0}", Models.Storage_Type'Image (Storage));
end if;
if not Into.Is_Null then
Workspace := AWA.Workspaces.Models.Workspace_Ref (Into.Get_Workspace);
end if;
if Workspace.Is_Null then
AWA.Workspaces.Modules.Get_Workspace (DB, Ctx, Workspace);
Into.Set_Workspace (Workspace);
end if;
-- Check that the user has the create storage permission on the given workspace.
AWA.Permissions.Check (Permission => ACL_Create_Storage.Permission,
Entity => Workspace);
Ctx.Start;
Created := not Into.Is_Inserted;
if Created then
Into.Set_Create_Date (Ada.Calendar.Clock);
Into.Set_Owner (Ctx.Get_User);
end if;
Into.Save (DB);
Store.Save (DB, Into, Path);
Into.Save (DB);
-- Notify the listeners.
if Created then
Storage_Lifecycle.Notify_Create (Service, Into);
else
Storage_Lifecycle.Notify_Update (Service, Into);
end if;
Ctx.Commit;
end Save;
-- ------------------------------
-- Load the storage content identified by <b>From</b> into the blob descriptor <b>Into</b>.
-- Raises the <b>NOT_FOUND</b> exception if there is no such storage.
-- ------------------------------
procedure Load (Service : in Storage_Service;
From : in ADO.Identifier;
Name : out Ada.Strings.Unbounded.Unbounded_String;
Mime : out Ada.Strings.Unbounded.Unbounded_String;
Date : out Ada.Calendar.Time;
Into : out ADO.Blob_Ref) is
use type AWA.Storages.Models.Storage_Type;
use type AWA.Storages.Stores.Store_Access;
Ctx : constant Contexts.Service_Context_Access := AWA.Services.Contexts.Current;
User : constant ADO.Identifier := Ctx.Get_User_Identifier;
DB : ADO.Sessions.Session := AWA.Services.Contexts.Get_Session (Ctx);
Query : ADO.Statements.Query_Statement
:= DB.Create_Statement (Models.Query_Storage_Get_Data);
Kind : AWA.Storages.Models.Storage_Type;
begin
Query.Bind_Param ("store_id", From);
Query.Bind_Param ("user_id", User);
ADO.Sessions.Entities.Bind_Param (Query, "table",
AWA.Workspaces.Models.WORKSPACE_TABLE, DB);
Query.Execute;
if not Query.Has_Elements then
Log.Warn ("Storage entity {0} not found", ADO.Identifier'Image (From));
raise ADO.Objects.NOT_FOUND;
end if;
Mime := Query.Get_Unbounded_String (0);
Date := Query.Get_Time (1);
Name := Query.Get_Unbounded_String (2);
Kind := AWA.Storages.Models.Storage_Type'Val (Query.Get_Integer (4));
if Kind = AWA.Storages.Models.DATABASE then
Into := Query.Get_Blob (5);
else
declare
Store : Stores.Store_Access;
Storage : AWA.Storages.Models.Storage_Ref;
File : AWA.Storages.Storage_File;
Found : Boolean;
begin
Store := Storage_Service'Class (Service).Get_Store (Kind);
if Store = null then
Log.Error ("There is no store for storage {0}", Models.Storage_Type'Image (Kind));
end if;
Storage.Load (DB, From, Found);
if not Found then
Log.Warn ("Storage entity {0} not found", ADO.Identifier'Image (From));
raise ADO.Objects.NOT_FOUND;
end if;
Store.Load (DB, Storage, File);
Into := ADO.Create_Blob (AWA.Storages.Get_Path (File));
end;
end if;
end Load;
-- Load the storage content into a file. If the data is not stored in a file, a temporary
-- file is created with the data content fetched from the store (ex: the database).
-- The `Mode` parameter indicates whether the file will be read or written.
-- The `Expire` parameter allows to control the expiration of the temporary file.
procedure Get_Local_File (Service : in Storage_Service;
From : in ADO.Identifier;
Mode : in Read_Mode := READ;
Into : out Storage_File) is
use type Stores.Store_Access;
use type Models.Storage_Type;
Ctx : constant Contexts.Service_Context_Access := AWA.Services.Contexts.Current;
User : constant ADO.Identifier := Ctx.Get_User_Identifier;
DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx);
Query : ADO.Queries.Context;
Found : Boolean;
Storage : AWA.Storages.Models.Storage_Ref;
Local : AWA.Storages.Models.Store_Local_Ref;
Store : Stores.Store_Access;
begin
if Mode = READ then
Query.Set_Query (AWA.Storages.Models.Query_Storage_Get_Local);
Query.Bind_Param ("store_id", From);
Query.Bind_Param ("user_id", User);
ADO.Sessions.Entities.Bind_Param (Query, "table",
AWA.Workspaces.Models.WORKSPACE_TABLE, DB);
Local.Find (DB, Query, Found);
if Found then
Into.Path := Local.Get_Path;
Log.Info ("Load local file {0} path {1}", ADO.Identifier'Image (From),
Ada.Strings.Unbounded.To_String (Into.Path));
return;
end if;
end if;
Query.Set_Query (AWA.Storages.Models.Query_Storage_Get_Storage);
Query.Bind_Param ("store_id", From);
Query.Bind_Param ("user_id", User);
ADO.Sessions.Entities.Bind_Param (Query, "table",
AWA.Workspaces.Models.WORKSPACE_TABLE, DB);
Storage.Find (DB, Query, Found);
if not Found then
Log.Info ("File Id {0} not found", ADO.Identifier'Image (From));
raise ADO.Objects.NOT_FOUND;
end if;
Ctx.Start;
Store := Storage_Service'Class (Service).Get_Store (Storage.Get_Storage);
Store.Load (Session => DB,
From => Storage,
Into => Into);
Ctx.Commit;
Log.Info ("Load local file {0} path {1}", ADO.Identifier'Image (From),
Ada.Strings.Unbounded.To_String (Into.Path));
end Get_Local_File;
procedure Create_Local_File (Service : in Storage_Service;
Into : out Storage_File) is
begin
null;
end Create_Local_File;
-- ------------------------------
-- Deletes the storage instance.
-- ------------------------------
procedure Delete (Service : in Storage_Service;
Storage : in out AWA.Storages.Models.Storage_Ref'Class) is
Ctx : constant Contexts.Service_Context_Access := AWA.Services.Contexts.Current;
DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx);
Id : constant ADO.Identifier := ADO.Objects.Get_Value (Storage.Get_Key);
begin
Log.Info ("Delete storage {0}", ADO.Identifier'Image (Id));
-- Check that the user has the delete storage permission on the given workspace.
AWA.Permissions.Check (Permission => ACL_Delete_Storage.Permission,
Entity => Storage);
Ctx.Start;
Storage_Lifecycle.Notify_Delete (Service, Storage);
Storage.Delete (DB);
Ctx.Commit;
end Delete;
-- ------------------------------
-- Deletes the storage instance.
-- ------------------------------
procedure Delete (Service : in Storage_Service;
Storage : in ADO.Identifier) is
use type Stores.Store_Access;
Ctx : constant Contexts.Service_Context_Access := AWA.Services.Contexts.Current;
DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx);
S : AWA.Storages.Models.Storage_Ref;
Query : ADO.Statements.Query_Statement
:= DB.Create_Statement (AWA.Storages.Models.Query_Storage_Delete_Local);
Store : Stores.Store_Access;
begin
Log.Info ("Delete storage {0}", ADO.Identifier'Image (Storage));
-- Check that the user has the delete storage permission on the given workspace.
AWA.Permissions.Check (Permission => ACL_Delete_Storage.Permission,
Entity => Storage);
Ctx.Start;
S.Load (Id => Storage, Session => DB);
Store := Storage_Service'Class (Service).Get_Store (S.Get_Storage);
if Store = null then
Log.Error ("There is no store associated with storage item {0}",
ADO.Identifier'Image (Storage));
else
Store.Delete (DB, S);
end if;
Storage_Lifecycle.Notify_Delete (Service, S);
-- Delete the storage instance and all storage that refer to it.
declare
Stmt : ADO.Statements.Delete_Statement
:= DB.Create_Statement (AWA.Storages.Models.STORAGE_TABLE);
begin
Stmt.Set_Filter (Filter => "id = ? OR original_id = ?");
Stmt.Add_Param (Value => Storage);
Stmt.Add_Param (Value => Storage);
Stmt.Execute;
end;
-- Delete the local storage instances.
Query.Bind_Param ("store_id", Storage);
Query.Execute;
S.Delete (DB);
Ctx.Commit;
end Delete;
end AWA.Storages.Services;
|
Add some log for trouble shotting
|
Add some log for trouble shotting
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
a8fab57c7aa815856a979ef6e4608c4eec2479c4
|
src/security.ads
|
src/security.ads
|
-----------------------------------------------------------------------
-- security -- Security
-- Copyright (C) 2010, 2011, 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
-- == Introduction ==
-- The <tt>Security</tt> package provides security frameworks that allows
-- an application to use OpenID or OAuth security frameworks. This security
-- framework was first developed within the Ada Server Faces project.
--
-- @include security-permissions.ads
-- @include security-openid.ads
-- @include security-oauth.ads
-- @include security-contexts.ads
-- @include security-controllers.ads
package Security is
end Security;
|
-----------------------------------------------------------------------
-- security -- Security
-- Copyright (C) 2010, 2011, 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
-- == Introduction ==
-- The <tt>Security</tt> package provides security frameworks that allows
-- an application to use OpenID or OAuth security frameworks. This security
-- framework was first developed within the Ada Server Faces project.
-- This package defines abstractions that are close or similar to Java
-- security package.
--
-- @include security-permissions.ads
-- @include security-openid.ads
-- @include security-oauth.ads
-- @include security-contexts.ads
-- @include security-controllers.ads
package Security is
end Security;
|
Update the documentation
|
Update the documentation
|
Ada
|
apache-2.0
|
Letractively/ada-security
|
a8874fa3f49d311d2ce4eeeb70c9cf87ca38e0d7
|
awa/plugins/awa-storages/src/awa-storages-services.ads
|
awa/plugins/awa-storages/src/awa-storages-services.ads
|
-----------------------------------------------------------------------
-- awa-storages-services -- Storage service
-- Copyright (C) 2012, 2016 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Calendar;
with Ada.Strings.Unbounded;
with Security.Permissions;
with ADO;
with ASF.Parts;
with AWA.Modules;
with AWA.Modules.Lifecycles;
with AWA.Storages.Models;
with AWA.Storages.Stores;
with AWA.Storages.Stores.Databases;
-- == Storage Service ==
-- The <tt>Storage_Service</tt> provides the operations to access and use the persisent storage.
-- It controls the permissions that grant access to the service for users.
--
-- Other modules can be notified of storage changes by registering a listener
-- on the storage module.
--
-- @include awa-storages-stores.ads
package AWA.Storages.Services is
package ACL_Create_Storage is new Security.Permissions.Definition ("storage-create");
package ACL_Delete_Storage is new Security.Permissions.Definition ("storage-delete");
package ACL_Create_Folder is new Security.Permissions.Definition ("folder-create");
type Read_Mode is (READ, WRITE);
type Expire_Type is (ONE_HOUR, ONE_DAY, TWO_DAYS, ONE_WEEK, ONE_YEAR, NEVER);
package Storage_Lifecycle is
new AWA.Modules.Lifecycles (Element_Type => AWA.Storages.Models.Storage_Ref'Class);
subtype Listener is Storage_Lifecycle.Listener;
-- ------------------------------
-- Storage Service
-- ------------------------------
-- The <b>Storage_Service</b> defines a set of operations to store and retrieve
-- a data object from the persistent storage. The data object is treated as a raw
-- byte stream. The persistent storage can be implemented by a database, a file
-- system or a remote service such as Amazon AWS.
type Storage_Service is new AWA.Modules.Module_Manager with private;
type Storage_Service_Access is access all Storage_Service'Class;
-- Initializes the storage service.
overriding
procedure Initialize (Service : in out Storage_Service;
Module : in AWA.Modules.Module'Class);
-- Get the persistent store that manages the data store identified by <tt>Kind</tt>.
function Get_Store (Service : in Storage_Service;
Kind : in AWA.Storages.Models.Storage_Type)
return AWA.Storages.Stores.Store_Access;
-- Create or save the folder.
procedure Save_Folder (Service : in Storage_Service;
Folder : in out AWA.Storages.Models.Storage_Folder_Ref'Class);
-- Load the folder instance identified by the given identifier.
procedure Load_Folder (Service : in Storage_Service;
Folder : in out AWA.Storages.Models.Storage_Folder_Ref'Class;
Id : in ADO.Identifier);
-- Save the data object contained in the <b>Data</b> part element into the
-- target storage represented by <b>Into</b>.
procedure Save (Service : in Storage_Service;
Into : in out AWA.Storages.Models.Storage_Ref'Class;
Data : in ASF.Parts.Part'Class;
Storage : in AWA.Storages.Models.Storage_Type);
-- Save the file described <b>File</b> in the storage
-- object represented by <b>Into</b> and managed by the storage service.
procedure Save (Service : in Storage_Service;
Into : in out AWA.Storages.Models.Storage_Ref'Class;
File : in AWA.Storages.Storage_File;
Storage : in AWA.Storages.Models.Storage_Type);
-- Save the file pointed to by the <b>Path</b> string in the storage
-- object represented by <b>Into</b> and managed by the storage service.
procedure Save (Service : in Storage_Service;
Into : in out AWA.Storages.Models.Storage_Ref'Class;
Path : in String;
Storage : in AWA.Storages.Models.Storage_Type);
-- Load the storage instance identified by the given identifier.
procedure Load_Storage (Service : in Storage_Service;
Storage : in out AWA.Storages.Models.Storage_Ref'Class;
Id : in ADO.Identifier);
-- Load the storage content identified by <b>From</b> into the blob descriptor <b>Into</b>.
-- Raises the <b>NOT_FOUND</b> exception if there is no such storage.
procedure Load (Service : in Storage_Service;
From : in ADO.Identifier;
Name : out Ada.Strings.Unbounded.Unbounded_String;
Mime : out Ada.Strings.Unbounded.Unbounded_String;
Date : out Ada.Calendar.Time;
Into : out ADO.Blob_Ref);
-- Load the storage content into a file. If the data is not stored in a file, a temporary
-- file is created with the data content fetched from the store (ex: the database).
-- The `Mode` parameter indicates whether the file will be read or written.
-- The `Expire` parameter allows to control the expiration of the temporary file.
procedure Get_Local_File (Service : in Storage_Service;
From : in ADO.Identifier;
Mode : in Read_Mode := READ;
Into : out Storage_File);
procedure Create_Local_File (Service : in Storage_Service;
Into : out Storage_File);
-- Deletes the storage instance.
procedure Delete (Service : in Storage_Service;
Storage : in out AWA.Storages.Models.Storage_Ref'Class);
-- Deletes the storage instance.
procedure Delete (Service : in Storage_Service;
Storage : in ADO.Identifier);
private
type Store_Access_Array is
array (AWA.Storages.Models.Storage_Type) of AWA.Storages.Stores.Store_Access;
type Storage_Service is new AWA.Modules.Module_Manager with record
Stores : Store_Access_Array;
Database_Store : aliased AWA.Storages.Stores.Databases.Database_Store;
end record;
end AWA.Storages.Services;
|
-----------------------------------------------------------------------
-- awa-storages-services -- Storage service
-- Copyright (C) 2012, 2016 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Calendar;
with Ada.Strings.Unbounded;
with Util.Concurrent.Counters;
with Security.Permissions;
with ADO;
with ASF.Parts;
with AWA.Modules;
with AWA.Modules.Lifecycles;
with AWA.Storages.Models;
with AWA.Storages.Stores;
with AWA.Storages.Stores.Databases;
-- == Storage Service ==
-- The <tt>Storage_Service</tt> provides the operations to access and use the persisent storage.
-- It controls the permissions that grant access to the service for users.
--
-- Other modules can be notified of storage changes by registering a listener
-- on the storage module.
--
-- @include awa-storages-stores.ads
package AWA.Storages.Services is
package ACL_Create_Storage is new Security.Permissions.Definition ("storage-create");
package ACL_Delete_Storage is new Security.Permissions.Definition ("storage-delete");
package ACL_Create_Folder is new Security.Permissions.Definition ("folder-create");
type Read_Mode is (READ, WRITE);
type Expire_Type is (ONE_HOUR, ONE_DAY, TWO_DAYS, ONE_WEEK, ONE_YEAR, NEVER);
package Storage_Lifecycle is
new AWA.Modules.Lifecycles (Element_Type => AWA.Storages.Models.Storage_Ref'Class);
subtype Listener is Storage_Lifecycle.Listener;
-- ------------------------------
-- Storage Service
-- ------------------------------
-- The <b>Storage_Service</b> defines a set of operations to store and retrieve
-- a data object from the persistent storage. The data object is treated as a raw
-- byte stream. The persistent storage can be implemented by a database, a file
-- system or a remote service such as Amazon AWS.
type Storage_Service is new AWA.Modules.Module_Manager with private;
type Storage_Service_Access is access all Storage_Service'Class;
-- Initializes the storage service.
overriding
procedure Initialize (Service : in out Storage_Service;
Module : in AWA.Modules.Module'Class);
-- Get the persistent store that manages the data store identified by <tt>Kind</tt>.
function Get_Store (Service : in Storage_Service;
Kind : in AWA.Storages.Models.Storage_Type)
return AWA.Storages.Stores.Store_Access;
-- Create or save the folder.
procedure Save_Folder (Service : in Storage_Service;
Folder : in out AWA.Storages.Models.Storage_Folder_Ref'Class);
-- Load the folder instance identified by the given identifier.
procedure Load_Folder (Service : in Storage_Service;
Folder : in out AWA.Storages.Models.Storage_Folder_Ref'Class;
Id : in ADO.Identifier);
-- Save the data object contained in the <b>Data</b> part element into the
-- target storage represented by <b>Into</b>.
procedure Save (Service : in Storage_Service;
Into : in out AWA.Storages.Models.Storage_Ref'Class;
Data : in ASF.Parts.Part'Class;
Storage : in AWA.Storages.Models.Storage_Type);
-- Save the file described <b>File</b> in the storage
-- object represented by <b>Into</b> and managed by the storage service.
procedure Save (Service : in Storage_Service;
Into : in out AWA.Storages.Models.Storage_Ref'Class;
File : in AWA.Storages.Storage_File;
Storage : in AWA.Storages.Models.Storage_Type);
-- Save the file pointed to by the <b>Path</b> string in the storage
-- object represented by <b>Into</b> and managed by the storage service.
procedure Save (Service : in Storage_Service;
Into : in out AWA.Storages.Models.Storage_Ref'Class;
Path : in String;
Storage : in AWA.Storages.Models.Storage_Type);
-- Load the storage instance identified by the given identifier.
procedure Load_Storage (Service : in Storage_Service;
Storage : in out AWA.Storages.Models.Storage_Ref'Class;
Id : in ADO.Identifier);
-- Load the storage content identified by <b>From</b> into the blob descriptor <b>Into</b>.
-- Raises the <b>NOT_FOUND</b> exception if there is no such storage.
procedure Load (Service : in Storage_Service;
From : in ADO.Identifier;
Name : out Ada.Strings.Unbounded.Unbounded_String;
Mime : out Ada.Strings.Unbounded.Unbounded_String;
Date : out Ada.Calendar.Time;
Into : out ADO.Blob_Ref);
-- Load the storage content into a file. If the data is not stored in a file, a temporary
-- file is created with the data content fetched from the store (ex: the database).
-- The `Mode` parameter indicates whether the file will be read or written.
-- The `Expire` parameter allows to control the expiration of the temporary file.
procedure Get_Local_File (Service : in Storage_Service;
From : in ADO.Identifier;
Mode : in Read_Mode := READ;
Into : out Storage_File);
procedure Create_Local_File (Service : in out Storage_Service;
Into : out AWA.Storages.Storage_File);
-- Deletes the storage instance.
procedure Delete (Service : in Storage_Service;
Storage : in out AWA.Storages.Models.Storage_Ref'Class);
-- Deletes the storage instance.
procedure Delete (Service : in Storage_Service;
Storage : in ADO.Identifier);
private
type Store_Access_Array is
array (AWA.Storages.Models.Storage_Type) of AWA.Storages.Stores.Store_Access;
type Storage_Service is new AWA.Modules.Module_Manager with record
Stores : Store_Access_Array;
Database_Store : aliased AWA.Storages.Stores.Databases.Database_Store;
Temp_Id : Util.Concurrent.Counters.Counter;
end record;
end AWA.Storages.Services;
|
Add a Temp_Id counter for temporary file path generation
|
Add a Temp_Id counter for temporary file path generation
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
684ccae44ebaa78836c92c5ffdb77ad81c745b03
|
examples/common/gui/lcd_std_out.adb
|
examples/common/gui/lcd_std_out.adb
|
------------------------------------------------------------------------------
-- Bareboard drivers examples --
-- --
-- Copyright (C) 2015-2016, AdaCore --
-- --
-- This library is free software; you can redistribute it and/or modify it --
-- under terms of the GNU General Public License as published by the Free --
-- Software Foundation; either version 3, or (at your option) any later --
-- version. This library is distributed in the hope that it will be useful, --
-- but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHAN- --
-- TABILITY or FITNESS FOR A PARTICULAR PURPOSE. --
-- --
-- As a special exception under Section 7 of GPL version 3, you are granted --
-- additional permissions described in the GCC Runtime Library Exception, --
-- version 3.1, as published by the Free Software Foundation. --
-- --
-- You should have received a copy of the GNU General Public License and --
-- a copy of the GCC Runtime Library Exception along with this program; --
-- see the files COPYING3 and COPYING.RUNTIME respectively. If not, see --
-- <http://www.gnu.org/licenses/>. --
-- --
------------------------------------------------------------------------------
with STM32.Board; use STM32.Board;
with Bitmapped_Drawing;
package body LCD_Std_Out is
-- We don't make the current font visible to clients because changing it
-- requires recomputation of the screen layout (eg the char height) and
-- issuance of commands to the LCD component driver (eg to refill).
Current_Font : BMP_Font := Default_Font;
Char_Width : Natural := BMP_Fonts.Char_Width (Current_Font);
Char_Height : Natural := BMP_Fonts.Char_Height (Current_Font);
Max_Width : Natural := LCD_Natural_Width - Char_Width;
-- The last place on the current "line" on the LCD where a char of the
-- current font size can be printed
Max_Height : Natural := LCD_Natural_Height - Char_Height;
-- The last "line" on the LCD where a char of this current font size can be
-- printed
Current_Y : Natural := 0;
-- The current "line" that the text will appear upon. Note this wraps
-- around to the top of the screen.
Char_Count : Natural := 0;
-- The number of characters currently printed on the current line
Initialized : Boolean := False;
procedure Draw_Char (X, Y : Natural; Msg : Character);
-- Convenience routine for call Drawing.Draw_Char
procedure Recompute_Screen_Dimensions (Font : BMP_Font);
-- Determins the max height and width for the specified font, given the
-- current LCD orientation
procedure Check_Initialized with Inline;
-- Ensures that the LCD display is initialized and DMA2D
-- is up and running
------------------------
-- Assert_Initialized --
------------------------
procedure Check_Initialized
is
begin
if Initialized then
return;
end if;
Initialized := True;
if Display.Initialized then
-- Ensure we use polling here: LCD_Std_Out may be called from the
-- Last chance handler, and we don't want unexpected tasks or
-- protected objects calling an entry not meant for that
Display.Set_Mode (HAL.Framebuffer.Polling);
else
Display.Initialize (Mode => HAL.Framebuffer.Polling);
Display.Initialize_Layer (1, HAL.Bitmap.RGB_565);
Clear_Screen;
end if;
end Check_Initialized;
---------------------------------
-- Recompute_Screen_Dimensions --
---------------------------------
procedure Recompute_Screen_Dimensions (Font : BMP_Font) is
begin
Char_Width := BMP_Fonts.Char_Width (Font);
Char_Height := BMP_Fonts.Char_Height (Font);
Max_Width := Display.Get_Width - Char_Width - 1;
Max_Height := Display.Get_Height - Char_Height - 1;
end Recompute_Screen_Dimensions;
--------------
-- Set_Font --
--------------
procedure Set_Font (To : in BMP_Font) is
begin
Current_Font := To;
Recompute_Screen_Dimensions (Current_Font);
end Set_Font;
---------------------
-- Set_Orientation --
---------------------
procedure Set_Orientation (To : in HAL.Framebuffer.Display_Orientation) is
begin
Display.Set_Orientation (To);
Recompute_Screen_Dimensions (Current_Font);
Clear_Screen;
end Set_Orientation;
------------------
-- Clear_Screen --
------------------
procedure Clear_Screen
is
begin
Check_Initialized;
Display.Get_Hidden_Buffer (1).Fill (Current_Background_Color);
Current_Y := 0;
Char_Count := 0;
Display.Update_Layer (1);
end Clear_Screen;
---------
-- Put --
---------
procedure Put (Msg : String) is
begin
for C of Msg loop
if C = ASCII.LF then
New_Line;
else
Put (C);
end if;
end loop;
end Put;
---------------
-- Draw_Char --
---------------
procedure Draw_Char (X, Y : Natural; Msg : Character)
is
begin
Check_Initialized;
Bitmapped_Drawing.Draw_Char
(Display.Get_Hidden_Buffer (1),
Start => (X, Y),
Char => Msg,
Font => Current_Font,
Foreground =>
HAL.Bitmap.Bitmap_Color_To_Word (Display.Get_Color_Mode (1),
Current_Text_Color),
Background =>
HAL.Bitmap.Bitmap_Color_To_Word (Display.Get_Color_Mode (1),
Current_Background_Color));
end Draw_Char;
---------
-- Put --
---------
procedure Put (Msg : Character) is
X : Natural;
begin
if Char_Count * Char_Width > Max_Width then
-- go to the next line down
Current_Y := Current_Y + Char_Height;
if Current_Y > Max_Height then
Current_Y := 0;
end if;
-- and start at beginning of the line
X := 0;
Char_Count := 0;
else
X := Char_Count * Char_Width;
end if;
Draw_Char (X, Current_Y, Msg);
Char_Count := Char_Count + 1;
Display.Update_Layer (1);
end Put;
--------------
-- New_Line --
--------------
procedure New_Line is
begin
Char_Count := 0; -- next char printed will be at the start of a new line
if Current_Y + Char_Height > Max_Height then
Current_Y := 0;
else
Current_Y := Current_Y + Char_Height;
end if;
end New_Line;
--------------
-- Put_Line --
--------------
procedure Put_Line (Msg : String) is
begin
Put (Msg);
New_Line;
end Put_Line;
---------
-- Put --
---------
procedure Put (X, Y : Natural; Msg : Character) is
begin
Draw_Char (X, Y, Msg);
Display.Update_Layer (1);
end Put;
---------
-- Put --
---------
procedure Put (X, Y : Natural; Msg : String) is
Count : Natural := 0;
Next_X : Natural;
begin
for C of Msg loop
Next_X := X + Count * Char_Width;
Draw_Char (Next_X, Y, C);
Count := Count + 1;
end loop;
Display.Update_Layer (1);
end Put;
end LCD_Std_Out;
|
------------------------------------------------------------------------------
-- Bareboard drivers examples --
-- --
-- Copyright (C) 2015-2016, AdaCore --
-- --
-- This library is free software; you can redistribute it and/or modify it --
-- under terms of the GNU General Public License as published by the Free --
-- Software Foundation; either version 3, or (at your option) any later --
-- version. This library is distributed in the hope that it will be useful, --
-- but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHAN- --
-- TABILITY or FITNESS FOR A PARTICULAR PURPOSE. --
-- --
-- As a special exception under Section 7 of GPL version 3, you are granted --
-- additional permissions described in the GCC Runtime Library Exception, --
-- version 3.1, as published by the Free Software Foundation. --
-- --
-- You should have received a copy of the GNU General Public License and --
-- a copy of the GCC Runtime Library Exception along with this program; --
-- see the files COPYING3 and COPYING.RUNTIME respectively. If not, see --
-- <http://www.gnu.org/licenses/>. --
-- --
------------------------------------------------------------------------------
with STM32.Board; use STM32.Board;
with Bitmapped_Drawing;
package body LCD_Std_Out is
-- We don't make the current font visible to clients because changing it
-- requires recomputation of the screen layout (eg the char height) and
-- issuance of commands to the LCD component driver (eg to refill).
Current_Font : BMP_Font := Default_Font;
Char_Width : Natural := BMP_Fonts.Char_Width (Current_Font);
Char_Height : Natural := BMP_Fonts.Char_Height (Current_Font);
Max_Width : Natural := LCD_Natural_Width - Char_Width;
-- The last place on the current "line" on the LCD where a char of the
-- current font size can be printed
Max_Height : Natural := LCD_Natural_Height - Char_Height;
-- The last "line" on the LCD where a char of this current font size can be
-- printed
Current_Y : Natural := 0;
-- The current "line" that the text will appear upon. Note this wraps
-- around to the top of the screen.
Char_Count : Natural := 0;
-- The number of characters currently printed on the current line
Initialized : Boolean := False;
procedure Draw_Char (X, Y : Natural; Msg : Character);
-- Convenience routine for call Drawing.Draw_Char
procedure Recompute_Screen_Dimensions (Font : BMP_Font);
-- Determins the max height and width for the specified font, given the
-- current LCD orientation
procedure Check_Initialized with Inline;
-- Ensures that the LCD display is initialized and DMA2D
-- is up and running
procedure Internal_Put (Msg : String);
-- Puts a new String in the frame buffer
procedure Internal_Put (Msg : Character);
-- Puts a new character in the frame buffer.
------------------------
-- Assert_Initialized --
------------------------
procedure Check_Initialized
is
begin
if Initialized then
return;
end if;
Initialized := True;
if Display.Initialized then
-- Ensure we use polling here: LCD_Std_Out may be called from the
-- Last chance handler, and we don't want unexpected tasks or
-- protected objects calling an entry not meant for that
Display.Set_Mode (HAL.Framebuffer.Polling);
else
Display.Initialize (Mode => HAL.Framebuffer.Polling);
Display.Initialize_Layer (1, HAL.Bitmap.RGB_565);
Clear_Screen;
end if;
end Check_Initialized;
---------------------------------
-- Recompute_Screen_Dimensions --
---------------------------------
procedure Recompute_Screen_Dimensions (Font : BMP_Font) is
begin
Check_Initialized;
Char_Width := BMP_Fonts.Char_Width (Font);
Char_Height := BMP_Fonts.Char_Height (Font);
Max_Width := Display.Get_Width - Char_Width - 1;
Max_Height := Display.Get_Height - Char_Height - 1;
end Recompute_Screen_Dimensions;
--------------
-- Set_Font --
--------------
procedure Set_Font (To : in BMP_Font) is
begin
Current_Font := To;
Recompute_Screen_Dimensions (Current_Font);
end Set_Font;
---------------------
-- Set_Orientation --
---------------------
procedure Set_Orientation (To : in HAL.Framebuffer.Display_Orientation) is
begin
Display.Set_Orientation (To);
Recompute_Screen_Dimensions (Current_Font);
Clear_Screen;
end Set_Orientation;
------------------
-- Clear_Screen --
------------------
procedure Clear_Screen
is
begin
Check_Initialized;
Display.Get_Hidden_Buffer (1).Fill (Current_Background_Color);
Current_Y := 0;
Char_Count := 0;
Display.Update_Layer (1, True);
end Clear_Screen;
------------------
-- Internal_Put --
------------------
procedure Internal_Put (Msg : String) is
begin
for C of Msg loop
if C = ASCII.LF then
New_Line;
else
Internal_Put (C);
end if;
end loop;
end Internal_Put;
---------
-- Put --
---------
procedure Put (Msg : String) is
begin
Internal_Put (Msg);
Display.Update_Layer (1, True);
end Put;
---------------
-- Draw_Char --
---------------
procedure Draw_Char (X, Y : Natural; Msg : Character)
is
begin
Check_Initialized;
Bitmapped_Drawing.Draw_Char
(Display.Get_Hidden_Buffer (1),
Start => (X, Y),
Char => Msg,
Font => Current_Font,
Foreground =>
HAL.Bitmap.Bitmap_Color_To_Word (Display.Get_Color_Mode (1),
Current_Text_Color),
Background =>
HAL.Bitmap.Bitmap_Color_To_Word (Display.Get_Color_Mode (1),
Current_Background_Color));
end Draw_Char;
---------
-- Put --
---------
procedure Internal_Put (Msg : Character) is
X : Natural;
begin
if Char_Count * Char_Width > Max_Width then
-- go to the next line down
Current_Y := Current_Y + Char_Height;
if Current_Y > Max_Height then
Current_Y := 0;
end if;
-- and start at beginning of the line
X := 0;
Char_Count := 0;
else
X := Char_Count * Char_Width;
end if;
Draw_Char (X, Current_Y, Msg);
Char_Count := Char_Count + 1;
end Internal_Put;
---------
-- Put --
---------
procedure Put (Msg : Character) is
begin
Internal_Put (Msg);
Display.Update_Layer (1, True);
end Put;
--------------
-- New_Line --
--------------
procedure New_Line is
begin
Char_Count := 0; -- next char printed will be at the start of a new line
if Current_Y + Char_Height > Max_Height then
Current_Y := 0;
else
Current_Y := Current_Y + Char_Height;
end if;
end New_Line;
--------------
-- Put_Line --
--------------
procedure Put_Line (Msg : String) is
begin
Put (Msg);
New_Line;
end Put_Line;
---------
-- Put --
---------
procedure Put (X, Y : Natural; Msg : Character) is
begin
Draw_Char (X, Y, Msg);
Display.Update_Layer (1, True);
end Put;
---------
-- Put --
---------
procedure Put (X, Y : Natural; Msg : String) is
Count : Natural := 0;
Next_X : Natural;
begin
for C of Msg loop
Next_X := X + Count * Char_Width;
Draw_Char (Next_X, Y, C);
Count := Count + 1;
end loop;
Display.Update_Layer (1, True);
end Put;
end LCD_Std_Out;
|
Fix LCD_Std_Out.
|
Fix LCD_Std_Out.
Some improper use of the framebuffer is now fixed.
|
Ada
|
bsd-3-clause
|
Fabien-Chouteau/Ada_Drivers_Library,lambourg/Ada_Drivers_Library,simonjwright/Ada_Drivers_Library,Fabien-Chouteau/Ada_Drivers_Library,simonjwright/Ada_Drivers_Library,AdaCore/Ada_Drivers_Library,ellamosi/Ada_BMP_Library,AdaCore/Ada_Drivers_Library
|
644eaa4bdf420ed14633a939a72629c294115351
|
src/gen-model-projects.ads
|
src/gen-model-projects.ads
|
-----------------------------------------------------------------------
-- gen-model-projects -- Projects meta data
-- Copyright (C) 2011, 2012, 2013, 2014, 2017, 2018, 2021 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Containers.Vectors;
with Util.Properties;
with Gen.Utils;
with Gen.Utils.GNAT;
package Gen.Model.Projects is
type Project_Definition is tagged;
type Project_Definition_Access is access all Project_Definition'Class;
type Dependency_Type is (NONE, DIRECT, INDIRECT, BOTH);
type Project_Reference is record
Project : Project_Definition_Access := null;
Name : UString;
Kind : Dependency_Type := NONE;
end record;
package Project_Vectors is
new Ada.Containers.Vectors (Element_Type => Project_Reference,
Index_Type => Natural);
-- ------------------------------
-- Project Definition
-- ------------------------------
type Project_Definition is new Definition with record
Path : UString;
Props : Util.Properties.Manager;
Modules : Project_Vectors.Vector;
-- The root project definition.
Root : Project_Definition_Access := null;
-- The list of plugin names that this plugin or project depends on.
Dependencies : Project_Vectors.Vector;
-- The list of GNAT project files used by the project.
Project_Files : Gen.Utils.GNAT.Project_Info_Vectors.Vector;
-- The list of 'dynamo.xml' files used by the project (gathered from GNAT files
-- and by scanning the 'plugins' directory).
Dynamo_Files : Gen.Utils.String_List.Vector;
-- Whether we did a recursive scan of GNAT project files.
Recursive_Scan : Boolean := False;
-- Whether we are doing a recursive operation on the project (prevent from cycles).
Recursing : Boolean := False;
-- Whether we did a recursive scan of Dynamo dependencies.
Depend_Scan : Boolean := False;
-- Whether this project is a plugin.
Is_Plugin : Boolean := False;
-- Whether the project needs the generation for the different databases
Use_Mysql : Boolean := True;
Use_Sqlite : Boolean := True;
Use_Postgresql : Boolean := True;
end record;
-- 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 : Project_Definition;
Name : String) return UBO.Object;
-- Get the project name.
function Get_Project_Name (Project : in Project_Definition) return String;
-- Get the GNAT project file name. The default is to use the Dynamo project
-- name and add the <b>.gpr</b> extension. The <b>gnat_project</b> configuration
-- property allows to override this default.
function Get_GNAT_Project_Name (Project : in Project_Definition) return String;
-- Get the directory path which holds application modules.
-- This is controlled by the <b>modules_dir</b> configuration property.
-- The default is <tt>plugins</tt>.
function Get_Module_Dir (Project : in Project_Definition) return String;
-- Get the directory path which holds database model files.
-- This is controlled by the <b>db_dir</b> configuration property.
-- The default is <tt>db</tt>.
function Get_Database_Dir (Project : in Project_Definition) return String;
-- Find the dependency for the <b>Name</b> plugin.
-- Returns a null dependency if the project does not depend on that plugin.
function Find_Dependency (From : in Project_Definition;
Name : in String) return Project_Reference;
-- Add a dependency to the plugin identified by <b>Name</b>.
procedure Add_Dependency (Into : in out Project_Definition;
Name : in String;
Kind : in Dependency_Type);
-- Add a dependency to the plugin identified by <b>Project</b>.
procedure Add_Dependency (Into : in out Project_Definition;
Project : in Project_Definition_Access;
Kind : in Dependency_Type);
-- Create a project definition instance to record a project with the dynamo XML file path.
procedure Create_Project (Into : in out Project_Definition;
Name : in String;
Path : in String;
Project : out Project_Definition_Access);
-- Add the project in the global project list on the root project instance.
procedure Add_Project (Into : in out Project_Definition;
Project : in Project_Definition_Access);
-- Add the project <b>Name</b> as a module.
procedure Add_Module (Into : in out Project_Definition;
Name : in String);
-- Add the project represented by <b>Project</b> if it is not already part of the modules.
procedure Add_Module (Into : in out Project_Definition;
Project : in Project_Definition_Access);
-- Find the project definition associated with the dynamo XML file <b>Path</b>.
-- Returns null if there is no such project
function Find_Project (From : in Project_Definition;
Path : in String) return Project_Definition_Access;
-- Find the project definition having the name <b>Name</b>.
-- Returns null if there is no such project
function Find_Project_By_Name (From : in Project_Definition;
Name : in String) return Project_Definition_Access;
-- Save the project description and parameters.
procedure Save (Project : in out Project_Definition;
Path : in String);
-- Read the XML project description into the project description.
procedure Read_Project (Project : in out Project_Definition);
-- Scan and read the possible modules used by the application. Modules are stored in the
-- <b>modules</b> directory. Each module is stored in its own directory and has its own
-- <b>dynamo.xml</b> file.
procedure Read_Modules (Project : in out Project_Definition);
-- Update the project definition from the properties.
procedure Update_From_Properties (Project : in out Project_Definition);
-- ------------------------------
-- Root Project Definition
-- ------------------------------
-- The root project is the project that is actually read by Dynamo.
-- It contains the lists of all projects that are necessary and which are found either
-- by scanning GNAT projects or by looking at plugin dependencies.
type Root_Project_Definition is new Project_Definition with record
Projects : Project_Vectors.Vector;
Install_Dir : UString;
end record;
-- Add the project in the global project list on the root project instance.
overriding
procedure Add_Project (Into : in out Root_Project_Definition;
Project : in Project_Definition_Access);
-- Find the project definition having the name <b>Name</b>.
-- Returns null if there is no such project
overriding
function Find_Project_By_Name (From : in Root_Project_Definition;
Name : in String) return Project_Definition_Access;
-- Find the project definition associated with the dynamo XML file <b>Path</b>.
-- Returns null if there is no such project
overriding
function Find_Project (From : in Root_Project_Definition;
Path : in String) return Project_Definition_Access;
-- Read the XML project file. When <b>Recursive</b> is set, read the GNAT project
-- files used by the main project and load all the <b>dynamo.xml</b> files defined
-- by these project.
procedure Read_Project (Project : in out Root_Project_Definition;
File : in String;
Config : in Util.Properties.Manager'Class;
Recursive : in Boolean := False);
private
-- Update the project references after a project is found and initialized.
procedure Update_References (Root : in out Root_Project_Definition;
Project : in Project_Definition_Access);
-- Iterate over the project referenced in the list and execute the <b>Process</b> procedure.
procedure Iterate (List : in out Project_Vectors.Vector;
Process : access procedure (Item : in out Project_Reference));
-- Find a project from the list
function Find_Project (List : in Project_Vectors.Vector;
Name : in String) return Project_Reference;
end Gen.Model.Projects;
|
-----------------------------------------------------------------------
-- gen-model-projects -- Projects meta data
-- Copyright (C) 2011, 2012, 2013, 2014, 2017, 2018, 2021 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Containers.Vectors;
with Util.Properties;
with Gen.Utils;
with Gen.Utils.GNAT;
package Gen.Model.Projects is
type Project_Definition is tagged;
type Project_Definition_Access is access all Project_Definition'Class;
type Dependency_Type is (NONE, DIRECT, INDIRECT, BOTH);
type Project_Reference is record
Project : Project_Definition_Access := null;
Name : UString;
Kind : Dependency_Type := NONE;
end record;
package Project_Vectors is
new Ada.Containers.Vectors (Element_Type => Project_Reference,
Index_Type => Natural);
-- ------------------------------
-- Project Definition
-- ------------------------------
type Project_Definition is new Definition with record
Path : UString;
Props : Util.Properties.Manager;
Modules : Project_Vectors.Vector;
-- The root project definition.
Root : Project_Definition_Access := null;
-- The list of plugin names that this plugin or project depends on.
Dependencies : Project_Vectors.Vector;
-- The list of GNAT project files used by the project.
Project_Files : Gen.Utils.GNAT.Project_Info_Vectors.Vector;
-- The list of 'dynamo.xml' files used by the project (gathered from GNAT files
-- and by scanning the 'plugins' directory).
Dynamo_Files : Gen.Utils.String_List.Vector;
-- Whether we did a recursive scan of GNAT project files.
Recursive_Scan : Boolean := False;
-- Whether we are doing a recursive operation on the project (prevent from cycles).
Recursing : Boolean := False;
-- Whether we did a recursive scan of Dynamo dependencies.
Depend_Scan : Boolean := False;
-- Whether this project is a plugin.
Is_Plugin : Boolean := False;
-- Whether the project needs the generation for the different databases
Use_Mysql : Boolean := True;
Use_Sqlite : Boolean := True;
Use_Postgresql : Boolean := True;
end record;
-- 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 : Project_Definition;
Name : String) return UBO.Object;
-- Get the project name.
function Get_Project_Name (Project : in Project_Definition) return String;
-- Get the GNAT project file name. The default is to use the Dynamo project
-- name and add the <b>.gpr</b> extension. The <b>gnat_project</b> configuration
-- property allows to override this default.
function Get_GNAT_Project_Name (Project : in Project_Definition) return String;
-- Get the directory path which holds application modules.
-- This is controlled by the <b>modules_dir</b> configuration property.
-- The default is <tt>plugins</tt>.
function Get_Module_Dir (Project : in Project_Definition) return String;
-- Get the directory path which holds database model files.
-- This is controlled by the <b>db_dir</b> configuration property.
-- The default is <tt>db</tt>.
function Get_Database_Dir (Project : in Project_Definition) return String;
-- Get the directory path which is the base dir for the 'web, 'config' and 'bundles'.
-- This is controlled by the <b>base_dir</b> configuration property.
-- The default is <tt>.</tt>.
function Get_Base_Dir (Project : in Project_Definition) return String;
-- Find the dependency for the <b>Name</b> plugin.
-- Returns a null dependency if the project does not depend on that plugin.
function Find_Dependency (From : in Project_Definition;
Name : in String) return Project_Reference;
-- Add a dependency to the plugin identified by <b>Name</b>.
procedure Add_Dependency (Into : in out Project_Definition;
Name : in String;
Kind : in Dependency_Type);
-- Add a dependency to the plugin identified by <b>Project</b>.
procedure Add_Dependency (Into : in out Project_Definition;
Project : in Project_Definition_Access;
Kind : in Dependency_Type);
-- Create a project definition instance to record a project with the dynamo XML file path.
procedure Create_Project (Into : in out Project_Definition;
Name : in String;
Path : in String;
Project : out Project_Definition_Access);
-- Add the project in the global project list on the root project instance.
procedure Add_Project (Into : in out Project_Definition;
Project : in Project_Definition_Access);
-- Add the project <b>Name</b> as a module.
procedure Add_Module (Into : in out Project_Definition;
Name : in String);
-- Add the project represented by <b>Project</b> if it is not already part of the modules.
procedure Add_Module (Into : in out Project_Definition;
Project : in Project_Definition_Access);
-- Find the project definition associated with the dynamo XML file <b>Path</b>.
-- Returns null if there is no such project
function Find_Project (From : in Project_Definition;
Path : in String) return Project_Definition_Access;
-- Find the project definition having the name <b>Name</b>.
-- Returns null if there is no such project
function Find_Project_By_Name (From : in Project_Definition;
Name : in String) return Project_Definition_Access;
-- Save the project description and parameters.
procedure Save (Project : in out Project_Definition;
Path : in String);
-- Read the XML project description into the project description.
procedure Read_Project (Project : in out Project_Definition);
-- Scan and read the possible modules used by the application. Modules are stored in the
-- <b>modules</b> directory. Each module is stored in its own directory and has its own
-- <b>dynamo.xml</b> file.
procedure Read_Modules (Project : in out Project_Definition);
-- Update the project definition from the properties.
procedure Update_From_Properties (Project : in out Project_Definition);
-- ------------------------------
-- Root Project Definition
-- ------------------------------
-- The root project is the project that is actually read by Dynamo.
-- It contains the lists of all projects that are necessary and which are found either
-- by scanning GNAT projects or by looking at plugin dependencies.
type Root_Project_Definition is new Project_Definition with record
Projects : Project_Vectors.Vector;
Install_Dir : UString;
end record;
-- Add the project in the global project list on the root project instance.
overriding
procedure Add_Project (Into : in out Root_Project_Definition;
Project : in Project_Definition_Access);
-- Find the project definition having the name <b>Name</b>.
-- Returns null if there is no such project
overriding
function Find_Project_By_Name (From : in Root_Project_Definition;
Name : in String) return Project_Definition_Access;
-- Find the project definition associated with the dynamo XML file <b>Path</b>.
-- Returns null if there is no such project
overriding
function Find_Project (From : in Root_Project_Definition;
Path : in String) return Project_Definition_Access;
-- Read the XML project file. When <b>Recursive</b> is set, read the GNAT project
-- files used by the main project and load all the <b>dynamo.xml</b> files defined
-- by these project.
procedure Read_Project (Project : in out Root_Project_Definition;
File : in String;
Config : in Util.Properties.Manager'Class;
Recursive : in Boolean := False);
private
-- Update the project references after a project is found and initialized.
procedure Update_References (Root : in out Root_Project_Definition;
Project : in Project_Definition_Access);
-- Iterate over the project referenced in the list and execute the <b>Process</b> procedure.
procedure Iterate (List : in out Project_Vectors.Vector;
Process : access procedure (Item : in out Project_Reference));
-- Find a project from the list
function Find_Project (List : in Project_Vectors.Vector;
Name : in String) return Project_Reference;
end Gen.Model.Projects;
|
Declare Get_Base_Dir function
|
Declare Get_Base_Dir function
|
Ada
|
apache-2.0
|
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
|
96651cc24bb08d3268b181f79b3df582b530325a
|
src/ado-sequences-hilo.adb
|
src/ado-sequences-hilo.adb
|
-----------------------------------------------------------------------
-- ADO Sequences -- Database sequence generator
-- Copyright (C) 2009, 2010 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Log;
with Util.Log.Loggers;
with ADO.Sessions;
with ADO.Model;
with ADO.Objects;
package body ADO.Sequences.Hilo is
use Util.Log;
use ADO.Sessions;
use Sequence_Maps;
use ADO.Model;
Log : constant Loggers.Logger := Loggers.Create ("ADO.Sequences.Hilo");
type HiLoGenerator_Access is access all HiLoGenerator'Class;
-- ------------------------------
-- Create a high low sequence generator
-- ------------------------------
function Create_HiLo_Generator
(Sess_Factory : access ADO.Sessions.Factory.Session_Factory'Class)
return Generator_Access is
Result : constant HiLoGenerator_Access := new HiLoGenerator;
begin
Result.Factory := Sess_Factory;
return Result.all'Access;
end Create_HiLo_Generator;
-- ------------------------------
-- Allocate an identifier using the generator.
-- The generator allocates blocks of sequences by using a sequence
-- table stored in the database. One database access is necessary
-- every N allocations.
-- ------------------------------
procedure Allocate (Gen : in out HiLoGenerator;
Id : out Identifier) is
begin
-- Get a new sequence range
if Gen.Next_Id >= Gen.Last_Id then
Allocate_Sequence (Gen);
end if;
Id := Gen.Next_Id;
Gen.Next_Id := Gen.Next_Id + 1;
end Allocate;
-- ------------------------------
-- Allocate a new sequence block.
-- ------------------------------
procedure Allocate_Sequence (Gen : in out HiLoGenerator) is
Name : constant String := Get_Sequence_Name (Gen);
Value : Identifier;
Seq_Block : Sequence_Ref;
DB : Master_Session'Class := Gen.Get_Session;
begin
loop
-- Allocate a new sequence within a transaction.
declare
Params : Parameter_List;
Found : Boolean;
begin
Log.Info ("Allocate sequence range for {0}", Name);
DB.Begin_Transaction;
Params.Set_Filter ("name = ?");
Params.Bind_Param (Position => 1, Value => Name);
Seq_Block.Find (Database => DB, Parameters => Params, Found => Found);
begin
if Found then
Value := Seq_Block.Get_Value;
Seq_Block.Set_Value (Value + Seq_Block.Get_Block_Size);
Seq_Block.Save (DB);
else
Value := 1;
Seq_Block.Set_Name (Name);
Seq_Block.Set_Block_Size (Gen.Block_Size);
Seq_Block.Set_Value (Value + Seq_Block.Get_Block_Size);
Seq_Block.Save (DB);
end if;
DB.Commit;
Gen.Next_Id := Value;
Gen.Last_Id := Seq_Block.Get_Value;
return;
exception
when ADO.Objects.LAZY_LOCK =>
Log.Info ("Sequence table modified, retrying");
DB.Rollback;
end;
exception
when E : others =>
Log.Error ("Cannot allocate sequence range", E);
raise;
end;
end loop;
end Allocate_Sequence;
end ADO.Sequences.Hilo;
|
-----------------------------------------------------------------------
-- ADO Sequences -- Database sequence generator
-- Copyright (C) 2009, 2010 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Log;
with Util.Log.Loggers;
with ADO.Sessions;
with ADO.Model;
with ADO.Objects;
with ADO.SQL;
package body ADO.Sequences.Hilo is
use Util.Log;
use ADO.Sessions;
use Sequence_Maps;
use ADO.Model;
Log : constant Loggers.Logger := Loggers.Create ("ADO.Sequences.Hilo");
type HiLoGenerator_Access is access all HiLoGenerator'Class;
-- ------------------------------
-- Create a high low sequence generator
-- ------------------------------
function Create_HiLo_Generator
(Sess_Factory : access ADO.Sessions.Factory.Session_Factory'Class)
return Generator_Access is
Result : constant HiLoGenerator_Access := new HiLoGenerator;
begin
Result.Factory := Sess_Factory;
return Result.all'Access;
end Create_HiLo_Generator;
-- ------------------------------
-- Allocate an identifier using the generator.
-- The generator allocates blocks of sequences by using a sequence
-- table stored in the database. One database access is necessary
-- every N allocations.
-- ------------------------------
procedure Allocate (Gen : in out HiLoGenerator;
Id : out Identifier) is
begin
-- Get a new sequence range
if Gen.Next_Id >= Gen.Last_Id then
Allocate_Sequence (Gen);
end if;
Id := Gen.Next_Id;
Gen.Next_Id := Gen.Next_Id + 1;
end Allocate;
-- ------------------------------
-- Allocate a new sequence block.
-- ------------------------------
procedure Allocate_Sequence (Gen : in out HiLoGenerator) is
Name : constant String := Get_Sequence_Name (Gen);
Value : Identifier;
Seq_Block : Sequence_Ref;
DB : Master_Session'Class := Gen.Get_Session;
begin
loop
-- Allocate a new sequence within a transaction.
declare
Query : ADO.SQL.Query;
Found : Boolean;
begin
Log.Info ("Allocate sequence range for {0}", Name);
DB.Begin_Transaction;
Query.Set_Filter ("name = ?");
Query.Bind_Param (Position => 1, Value => Name);
Seq_Block.Find (Session => DB, Query => Query, Found => Found);
begin
if Found then
Value := Seq_Block.Get_Value;
Seq_Block.Set_Value (Value + Seq_Block.Get_Block_Size);
Seq_Block.Save (DB);
else
Value := 1;
Seq_Block.Set_Name (Name);
Seq_Block.Set_Block_Size (Gen.Block_Size);
Seq_Block.Set_Value (Value + Seq_Block.Get_Block_Size);
Seq_Block.Save (DB);
end if;
DB.Commit;
Gen.Next_Id := Value;
Gen.Last_Id := Seq_Block.Get_Value;
return;
exception
when ADO.Objects.LAZY_LOCK =>
Log.Info ("Sequence table modified, retrying");
DB.Rollback;
end;
exception
when E : others =>
Log.Error ("Cannot allocate sequence range", E);
raise;
end;
end loop;
end Allocate_Sequence;
end ADO.Sequences.Hilo;
|
Update query parameters for the new model
|
Update query parameters for the new model
|
Ada
|
apache-2.0
|
stcarrez/ada-ado
|
8f10be6d0c77a2c192c54bcdfe854df932ff3a9e
|
awa/regtests/awa-users-services-tests.adb
|
awa/regtests/awa-users-services-tests.adb
|
-----------------------------------------------------------------------
-- users - User creation, password tests
-- Copyright (C) 2009, 2010, 2011 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Test_Caller;
with Util.Measures;
with ADO;
with ADO.Sessions;
with ADO.SQL;
with ADO.Objects;
with Ada.Calendar;
with AWA.Users.Module;
with AWA.Users.Services.Tests.Helpers;
package body AWA.Users.Services.Tests is
use Util.Tests;
use ADO;
use ADO.Objects;
package Caller is new Util.Test_Caller (Test);
procedure Add_Tests (Suite : AUnit.Test_Suites.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test AWA.Users.Services.Create_User",
Test_Create_User'Access);
Caller.Add_Test (Suite, "Test AWA.Users.Services.Close_Session",
Test_Logout_User'Access);
Caller.Add_Test (Suite, "Test AWA.Users.Services.Authenticate, Close_Session",
Test_Login_User'Access);
Caller.Add_Test (Suite, "Test AWA.Users.Services.Lost_Password, Reset_Password",
Test_Reset_Password_User'Access);
Caller.Add_Test (Suite, "Test AWA.Users.Module.Get_User_Module",
Test_Get_Module'Access);
end Add_Tests;
-- ------------------------------
-- Test creation of a user
-- ------------------------------
procedure Test_Create_User (T : in out Test) is
Principal : Helpers.Test_User;
begin
-- Create the user
Helpers.Create_User (Principal);
T.Assert (not Principal.User.Is_Null, "User is created");
T.Assert (Principal.User.Get_Id > 0, "User has an allocated key");
T.Assert (Principal.Email.Get_Id > 0, "Email has an allocated key");
T.Assert (not Principal.Session.Is_Null, "Session must be created");
T.Assert (Principal.Session.Get_End_Date.Is_Null, "Session must be opened");
-- Verify the user session
declare
S1 : Session_Ref;
U1 : User_Ref;
begin
Principal.Manager.Verify_Session (Id => Principal.Session.Get_Id,
Session => S1, User => U1);
t.Assert (not S1.Is_Null, "Null session returned by Verify_Session");
T.Assert (not U1.Is_Null, "Null user returned by Verify_Session");
T.Assert (not S1.Get_Start_Date.Is_Null, "Session must be started");
T.Assert (S1.Get_End_Date.Is_Null, "Session must not be finished");
Util.Tests.Assert_Equals (T, Principal.Session.Get_Start_Date.Value,
S1.Get_Start_Date.Value,
"Invalid start date");
Principal.Manager.Close_Session (Principal.Session.Get_Id);
end;
end Test_Create_User;
-- ------------------------------
-- Test logout of a user
-- ------------------------------
procedure Test_Logout_User (T : in out Test) is
Principal : Helpers.Test_User;
begin
-- Create the user
Helpers.Create_User (Principal);
T.Assert (not Principal.User.Is_Null, "User is created");
T.Assert (Principal.User.Get_Id > 0, "User has an allocated key");
T.Assert (Principal.Email.Get_Id > 0, "Email has an allocated key");
Helpers.Logout (Principal);
-- Verify the user session
declare
S1 : Session_Ref;
U1 : User_Ref;
begin
Principal.Manager.Verify_Session (Id => Principal.Session.Get_Id,
Session => S1, User => U1);
T.Assert (False, "Verify_Session should report a non-existent session");
exception
when Not_Found =>
null;
end;
begin
Helpers.Logout (Principal);
T.Assert (False, "Second logout should report a non-existent session");
exception
when Not_Found =>
null;
end;
end Test_Logout_User;
-- ------------------------------
-- Test creation of a user
-- ------------------------------
procedure Test_Login_User (T : in out Test) is
use type Ada.Calendar.Time;
Principal : Helpers.Test_User;
T1 : constant Ada.Calendar.Time := Ada.Calendar.Clock;
begin
begin
Principal.Email.Set_Email ("[email protected]");
Helpers.Login (Principal);
T.Assert (False, "Login succeeded with an invalid user name");
exception
when Not_Found =>
null;
end;
-- Create the user
Helpers.Create_User (Principal);
Helpers.Logout (Principal);
Helpers.Login (Principal);
T.Assert (not Principal.User.Is_Null, "User is created");
T.Assert (Principal.User.Get_Id > 0, "User has an allocated key");
T.Assert (Principal.Email.Get_Id > 0, "Email has an allocated key");
T.Assert (not Principal.Session.Is_Null, "Session is not created");
-- Verify the user session
declare
S1 : Session_Ref;
U1 : User_Ref;
T2 : constant Ada.Calendar.Time := Ada.Calendar.Clock;
begin
Principal.Manager.Verify_Session (Id => Principal.Session.Get_Id,
Session => S1, User => U1);
T.Assert (not S1.Is_Null, "Null session returned by Verify_Session");
T.Assert (not U1.Is_Null, "Null user returned by Verify_Session");
T.Assert (not S1.Get_Start_Date.Is_Null, "Session start date must not be null");
T.Assert (S1.Get_End_Date.Is_Null, "Session end date must be null");
Util.Tests.Assert_Equals (T, Principal.Session.Get_Start_Date.Value,
S1.Get_Start_Date.Value,
"Invalid start date");
Util.Tests.Assert_Equals (T, T1,
S1.Get_Start_Date.Value,
"Invalid start date 3");
T.Assert (T2 >= S1.Get_Start_Date.Value, "Start date is invalid 1");
T.Assert (T1 <= S1.Get_Start_Date.Value + 1.0, "Start date is invalid 2");
Principal.Manager.Close_Session (Principal.Session.Get_Id);
end;
end Test_Login_User;
-- ------------------------------
-- Test password reset process
-- ------------------------------
procedure Test_Reset_Password_User (T : in out Test) is
Principal : Helpers.Test_User;
Key : AWA.Users.Models.Access_Key_Ref;
begin
-- Create the user
Helpers.Create_User (Principal);
Helpers.Logout (Principal);
-- Start the lost password process.
Principal.Manager.Lost_Password (Email => Principal.Email.Get_Email);
Helpers.Login (Principal);
-- Get the access key to reset the password
declare
DB : ADO.Sessions.Session := Principal.Manager.Get_Session;
Query : ADO.SQL.Query;
Found : Boolean;
begin
-- Find the access key
Query.Set_Filter ("user_id = ?");
Query.Bind_Param (1, Principal.User.Get_Id);
Key.Find (DB, Query, Found);
T.Assert (Found, "Access key for lost_password process not found");
Principal.Manager.Reset_Password (Key => Key.Get_Access_Key,
Password => "newadmin",
IpAddr => "192.168.1.2",
User => Principal.User,
Session => Principal.Session);
-- Search the access key again, it must have been removed.
Key.Find (DB, Query, Found);
T.Assert (not Found, "The access key is still present in the database");
end;
T.Assert (not Principal.User.Is_Null, "User is created");
T.Assert (Principal.User.Get_Id > 0, "User has an allocated key");
T.Assert (Principal.Email.Get_Id > 0, "Email has an allocated key");
T.Assert (not Principal.Session.Is_Null, "Session is not created");
Helpers.Logout (Principal);
end Test_Reset_Password_User;
-- ------------------------------
-- Test Get_User_Module operation
-- ------------------------------
procedure Test_Get_Module (T : in out Test) is
use type AWA.Users.Module.User_Module_Access;
begin
declare
M : constant AWA.Users.Module.User_Module_Access := AWA.Users.Module.Get_User_Module;
begin
T.Assert (M /= null, "Get_User_Module returned null");
end;
declare
S : Util.Measures.Stamp;
M : AWA.Users.Module.User_Module_Access;
begin
for I in 1 .. 1_000 loop
M := AWA.Users.Module.Get_User_Module;
end loop;
Util.Measures.Report (S, "Get_User_Module (1000)");
T.Assert (M /= null, "Get_User_Module returned null");
end;
end Test_Get_Module;
end AWA.Users.Services.Tests;
|
-----------------------------------------------------------------------
-- users - User creation, password tests
-- Copyright (C) 2009, 2010, 2011 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Test_Caller;
with Util.Measures;
with ADO;
with ADO.Sessions;
with ADO.SQL;
with ADO.Objects;
with Ada.Calendar;
with AWA.Users.Module;
with AWA.Users.Services.Tests.Helpers;
package body AWA.Users.Services.Tests is
use Util.Tests;
use ADO;
use ADO.Objects;
package Caller is new Util.Test_Caller (Test);
procedure Add_Tests (Suite : AUnit.Test_Suites.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test AWA.Users.Services.Create_User",
Test_Create_User'Access);
Caller.Add_Test (Suite, "Test AWA.Users.Services.Close_Session",
Test_Logout_User'Access);
Caller.Add_Test (Suite, "Test AWA.Users.Services.Authenticate, Close_Session",
Test_Login_User'Access);
Caller.Add_Test (Suite, "Test AWA.Users.Services.Lost_Password, Reset_Password",
Test_Reset_Password_User'Access);
Caller.Add_Test (Suite, "Test AWA.Users.Module.Get_User_Module",
Test_Get_Module'Access);
end Add_Tests;
-- ------------------------------
-- Test creation of a user
-- ------------------------------
procedure Test_Create_User (T : in out Test) is
Principal : Helpers.Test_User;
begin
-- Create the user
Helpers.Create_User (Principal);
T.Assert (not Principal.User.Is_Null, "User is created");
T.Assert (Principal.User.Get_Id > 0, "User has an allocated key");
T.Assert (Principal.Email.Get_Id > 0, "Email has an allocated key");
T.Assert (not Principal.Session.Is_Null, "Session must be created");
T.Assert (Principal.Session.Get_End_Date.Is_Null, "Session must be opened");
-- Verify the user session
declare
S1 : Session_Ref;
U1 : User_Ref;
begin
Principal.Manager.Verify_Session (Id => Principal.Session.Get_Id,
Session => S1, User => U1);
t.Assert (not S1.Is_Null, "Null session returned by Verify_Session");
T.Assert (not U1.Is_Null, "Null user returned by Verify_Session");
T.Assert (not S1.Get_Start_Date.Is_Null, "Session must be started");
T.Assert (S1.Get_End_Date.Is_Null, "Session must not be finished");
Util.Tests.Assert_Equals (T, Principal.Session.Get_Start_Date.Value,
S1.Get_Start_Date.Value,
"Invalid start date");
Principal.Manager.Close_Session (Principal.Session.Get_Id);
end;
end Test_Create_User;
-- ------------------------------
-- Test logout of a user
-- ------------------------------
procedure Test_Logout_User (T : in out Test) is
Principal : Helpers.Test_User;
begin
-- Create the user
Helpers.Create_User (Principal);
T.Assert (not Principal.User.Is_Null, "User is created");
T.Assert (Principal.User.Get_Id > 0, "User has an allocated key");
T.Assert (Principal.Email.Get_Id > 0, "Email has an allocated key");
Helpers.Logout (Principal);
-- Verify the user session
declare
S1 : Session_Ref;
U1 : User_Ref;
begin
Principal.Manager.Verify_Session (Id => Principal.Session.Get_Id,
Session => S1, User => U1);
T.Assert (False, "Verify_Session should report a non-existent session");
exception
when Not_Found =>
null;
end;
begin
Helpers.Logout (Principal);
T.Assert (False, "Second logout should report a non-existent session");
exception
when Not_Found =>
null;
end;
end Test_Logout_User;
-- ------------------------------
-- Test creation of a user
-- ------------------------------
procedure Test_Login_User (T : in out Test) is
use type Ada.Calendar.Time;
Principal : Helpers.Test_User;
T1 : Ada.Calendar.Time;
begin
begin
Principal.Email.Set_Email ("[email protected]");
Helpers.Login (Principal);
T.Assert (False, "Login succeeded with an invalid user name");
exception
when Not_Found =>
null;
end;
-- Create the user
T1 := Ada.Calendar.Clock;
Helpers.Create_User (Principal);
Helpers.Logout (Principal);
Helpers.Login (Principal);
T.Assert (not Principal.User.Is_Null, "User is created");
T.Assert (Principal.User.Get_Id > 0, "User has an allocated key");
T.Assert (Principal.Email.Get_Id > 0, "Email has an allocated key");
T.Assert (not Principal.Session.Is_Null, "Session is not created");
-- Verify the user session
declare
S1 : Session_Ref;
U1 : User_Ref;
T2 : constant Ada.Calendar.Time := Ada.Calendar.Clock;
begin
Principal.Manager.Verify_Session (Id => Principal.Session.Get_Id,
Session => S1, User => U1);
T.Assert (not S1.Is_Null, "Null session returned by Verify_Session");
T.Assert (not U1.Is_Null, "Null user returned by Verify_Session");
T.Assert (not S1.Get_Start_Date.Is_Null, "Session start date must not be null");
T.Assert (S1.Get_End_Date.Is_Null, "Session end date must be null");
Util.Tests.Assert_Equals (T, Principal.Session.Get_Start_Date.Value,
S1.Get_Start_Date.Value,
"Invalid start date");
T.Assert (S1.Get_Start_Date.Value >= T1, "Start date is invalid 1");
T.Assert (S1.Get_Start_Date.Value >= T2, "Start date is invalid 2");
T.Assert (S1.Get_Start_Date.Value <= T2 + 10.0, "Start date is invalid 3");
Principal.Manager.Close_Session (Principal.Session.Get_Id);
end;
end Test_Login_User;
-- ------------------------------
-- Test password reset process
-- ------------------------------
procedure Test_Reset_Password_User (T : in out Test) is
Principal : Helpers.Test_User;
Key : AWA.Users.Models.Access_Key_Ref;
begin
-- Create the user
Helpers.Create_User (Principal);
Helpers.Logout (Principal);
-- Start the lost password process.
Principal.Manager.Lost_Password (Email => Principal.Email.Get_Email);
Helpers.Login (Principal);
-- Get the access key to reset the password
declare
DB : ADO.Sessions.Session := Principal.Manager.Get_Session;
Query : ADO.SQL.Query;
Found : Boolean;
begin
-- Find the access key
Query.Set_Filter ("user_id = ?");
Query.Bind_Param (1, Principal.User.Get_Id);
Key.Find (DB, Query, Found);
T.Assert (Found, "Access key for lost_password process not found");
Principal.Manager.Reset_Password (Key => Key.Get_Access_Key,
Password => "newadmin",
IpAddr => "192.168.1.2",
User => Principal.User,
Session => Principal.Session);
-- Search the access key again, it must have been removed.
Key.Find (DB, Query, Found);
T.Assert (not Found, "The access key is still present in the database");
end;
T.Assert (not Principal.User.Is_Null, "User is created");
T.Assert (Principal.User.Get_Id > 0, "User has an allocated key");
T.Assert (Principal.Email.Get_Id > 0, "Email has an allocated key");
T.Assert (not Principal.Session.Is_Null, "Session is not created");
Helpers.Logout (Principal);
end Test_Reset_Password_User;
-- ------------------------------
-- Test Get_User_Module operation
-- ------------------------------
procedure Test_Get_Module (T : in out Test) is
use type AWA.Users.Module.User_Module_Access;
begin
declare
M : constant AWA.Users.Module.User_Module_Access := AWA.Users.Module.Get_User_Module;
begin
T.Assert (M /= null, "Get_User_Module returned null");
end;
declare
S : Util.Measures.Stamp;
M : AWA.Users.Module.User_Module_Access;
begin
for I in 1 .. 1_000 loop
M := AWA.Users.Module.Get_User_Module;
end loop;
Util.Measures.Report (S, "Get_User_Module (1000)");
T.Assert (M /= null, "Get_User_Module returned null");
end;
end Test_Get_Module;
end AWA.Users.Services.Tests;
|
Fix test check on dates
|
Fix test check on dates
|
Ada
|
apache-2.0
|
Letractively/ada-awa,tectronics/ada-awa,Letractively/ada-awa,tectronics/ada-awa,Letractively/ada-awa,tectronics/ada-awa
|
36e6b7d535e7d115d2b7fcf0cd3df679931c51ae
|
regtests/security-policies-tests.adb
|
regtests/security-policies-tests.adb
|
-----------------------------------------------------------------------
-- Security-policies-tests - Unit tests for Security.Permissions
-- Copyright (C) 2011, 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Files;
with Util.Test_Caller;
with Util.Measures;
with Security.Contexts;
with Security.Policies.Roles;
-- with Security.Permissions;
with Security.Permissions.Tests;
with Security.Policies.URLs;
package body Security.Policies.Tests is
use Util.Tests;
package Caller is new Util.Test_Caller (Test, "Security.Policies");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test Security.Permissions.Create_Role",
Test_Create_Role'Access);
Caller.Add_Test (Suite, "Test Security.Permissions.Has_Permission",
Test_Has_Permission'Access);
Caller.Add_Test (Suite, "Test Security.Permissions.Read_Policy (empty)",
Test_Read_Empty_Policy'Access);
Caller.Add_Test (Suite, "Test Security.Policies.Add_Policy",
Test_Get_Role_Policy'Access);
Caller.Add_Test (Suite, "Test Security.Policies.Get_Policy",
Test_Get_Role_Policy'Access);
Caller.Add_Test (Suite, "Test Security.Policies.Roles.Get_Role_Policy",
Test_Get_Role_Policy'Access);
Caller.Add_Test (Suite, "Test Security.Policies.Read_Policy",
Test_Read_Policy'Access);
Caller.Add_Test (Suite, "Test Security.Policies.Roles.Set_Roles",
Test_Set_Roles'Access);
Caller.Add_Test (Suite, "Test Security.Policies.Roles.Set_Roles (invalid)",
Test_Set_Invalid_Roles'Access);
-- These tests are identical but registered under different names
-- for the test documentation.
Caller.Add_Test (Suite, "Test Security.Contexts.Has_Permission",
Test_Role_Policy'Access);
Caller.Add_Test (Suite, "Test Security.Controllers.Roles.Has_Permission",
Test_Role_Policy'Access);
Caller.Add_Test (Suite, "Test Security.Permissions.Role_Policy",
Test_Role_Policy'Access);
end Add_Tests;
-- ------------------------------
-- Get the roles assigned to the user.
-- ------------------------------
function Get_Roles (User : in Test_Principal) return Roles.Role_Map is
begin
return User.Roles;
end Get_Roles;
-- ------------------------------
-- Get the principal name.
-- ------------------------------
function Get_Name (From : in Test_Principal) return String is
begin
return Util.Strings.To_String (From.Name);
end Get_Name;
-- ------------------------------
-- Test Create_Role and Get_Role_Name
-- ------------------------------
procedure Test_Create_Role (T : in out Test) is
use Security.Policies.Roles;
M : Security.Policies.Roles.Role_Policy;
Role : Role_Type;
begin
M.Create_Role (Name => "admin",
Role => Role);
Assert_Equals (T, "admin", M.Get_Role_Name (Role), "Invalid name");
for I in Role + 1 .. Role_Type'Last loop
declare
Name : constant String := "admin-" & Role_Type'Image (I);
Role2 : Role_Type;
begin
Role2 := M.Find_Role ("admin");
T.Assert (Role2 = Role, "Find_Role returned an invalid role");
M.Create_Role (Name => Name,
Role => Role2);
Assert_Equals (T, Name, M.Get_Role_Name (Role2), "Invalid name");
end;
end loop;
end Test_Create_Role;
-- ------------------------------
-- Test Set_Roles
-- ------------------------------
procedure Test_Set_Roles (T : in out Test) is
use Security.Policies.Roles;
M : Security.Policies.Roles.Role_Policy;
Admin : Role_Type;
Manager : Role_Type;
Map : Role_Map;
begin
M.Create_Role (Name => "manager",
Role => Manager);
M.Create_Role (Name => "admin",
Role => Admin);
Assert_Equals (T, "admin", M.Get_Role_Name (Admin), "Invalid name");
T.Assert (not Map (Admin), "The admin role must not set in the map");
M.Set_Roles ("admin", Map);
T.Assert (Map (Admin), "The admin role is not set in the map");
T.Assert (not Map (Manager), "The manager role must not be set in the map");
M.Set_Roles ("manager,admin", Map);
T.Assert (Map (Admin), "The admin role is not set in the map");
T.Assert (Map (Manager), "The manager role is not set in the map");
end Test_Set_Roles;
-- ------------------------------
-- Test Set_Roles on an invalid role name
-- ------------------------------
procedure Test_Set_Invalid_Roles (T : in out Test) is
use Security.Policies.Roles;
M : Security.Policies.Roles.Role_Policy;
Map : Role_Map := (others => False);
begin
M.Set_Roles ("manager,admin", Map);
T.Assert (False, "No exception was raised");
exception
when E : Security.Policies.Roles.Invalid_Name =>
null;
end Test_Set_Invalid_Roles;
-- ------------------------------
-- Test Has_Permission
-- ------------------------------
procedure Test_Has_Permission (T : in out Test) is
M : Security.Policies.Policy_Manager (1);
-- Perm : Permissions.Permission_Type;
User : Test_Principal;
begin
-- T.Assert (not M.Has_Permission (User, 1), "User has a non-existing permission");
null;
end Test_Has_Permission;
procedure Configure_Policy (Manager : in out Security.Policies.Policy_Manager;
Name : in String) is
Dir : constant String := "regtests/files/permissions/";
Path : constant String := Util.Tests.Get_Path (Dir);
R : constant Security.Policies.Roles.Role_Policy_Access := new Roles.Role_Policy;
U : constant Security.Policies.URLs.URL_Policy_Access := new URLs.URL_Policy;
begin
Manager.Add_Policy (R.all'Access);
Manager.Add_Policy (U.all'Access);
Manager.Read_Policy (Util.Files.Compose (Path, Name));
end Configure_Policy;
-- ------------------------------
-- Test the Get_Policy, Get_Role_Policy and Add_Policy operations.
-- ------------------------------
procedure Test_Get_Role_Policy (T : in out Test) is
use type Roles.Role_Policy_Access;
M : aliased Security.Policies.Policy_Manager (Max_Policies => 2);
P : Security.Policies.Policy_Access;
R : Security.Policies.Roles.Role_Policy_Access;
begin
P := M.Get_Policy (Security.Policies.Roles.NAME);
T.Assert (P = null, "Get_Policy succeeded");
R := Security.Policies.Roles.Get_Role_Policy (M);
T.Assert (R = null, "Get_Role_Policy succeeded");
R := new Roles.Role_Policy;
M.Add_Policy (R.all'Access);
P := M.Get_Policy (Security.Policies.Roles.NAME);
T.Assert (P /= null, "Role policy not found");
T.Assert (P.all in Roles.Role_Policy'Class, "Invalid role policy");
R := Security.Policies.Roles.Get_Role_Policy (M);
T.Assert (R /= null, "Get_Role_Policy should not return null");
end Test_Get_Role_Policy;
-- ------------------------------
-- Test reading an empty policy file
-- ------------------------------
procedure Test_Read_Empty_Policy (T : in out Test) is
M : aliased Security.Policies.Policy_Manager (Max_Policies => 2);
User : aliased Test_Principal;
Context : aliased Security.Contexts.Security_Context;
P : Security.Policies.Policy_Access;
R : Security.Policies.Roles.Role_Policy_Access;
begin
Configure_Policy (M, "empty.xml");
Context.Set_Context (Manager => M'Unchecked_Access,
Principal => User'Unchecked_Access);
R := Security.Policies.Roles.Get_Role_Policy (M);
declare
Admin : Policies.Roles.Role_Type;
begin
Admin := R.Find_Role ("admin");
T.Fail ("'admin' role was returned");
exception
when Security.Policies.Roles.Invalid_Name =>
null;
end;
T.Assert (not Contexts.Has_Permission (Permissions.Tests.P_Admin.Permission),
"Has_Permission (admin) failed for empty policy");
T.Assert (not Contexts.Has_Permission (Permissions.Tests.P_Create.Permission),
"Has_Permission (create) failed for empty policy");
T.Assert (not Contexts.Has_Permission (Permissions.Tests.P_Update.Permission),
"Has_Permission (update) failed for empty policy");
T.Assert (not Contexts.Has_Permission (Permissions.Tests.P_Delete.Permission),
"Has_Permission (delete) failed for empty policy");
end Test_Read_Empty_Policy;
-- ------------------------------
-- Test reading policy files
-- ------------------------------
procedure Test_Read_Policy (T : in out Test) is
use Security.Permissions.Tests;
M : aliased Security.Policies.Policy_Manager (Max_Policies => 2);
User : aliased Test_Principal;
Admin : Policies.Roles.Role_Type;
Context : aliased Security.Contexts.Security_Context;
R : Security.Policies.Roles.Role_Policy_Access;
begin
Configure_Policy (M, "simple-policy.xml");
Context.Set_Context (Manager => M'Unchecked_Access,
Principal => User'Unchecked_Access);
R := Security.Policies.Roles.Get_Role_Policy (M);
Admin := R.Find_Role ("admin");
T.Assert (not Contexts.Has_Permission (Permission => P_Admin.Permission),
"Permission was granted but user has no role");
User.Roles (Admin) := True;
T.Assert (Contexts.Has_Permission (Permission => P_Admin.Permission),
"Permission was not granted and user has admin role");
declare
S : Util.Measures.Stamp;
Result : Boolean;
begin
for I in 1 .. 1_000 loop
Result := Contexts.Has_Permission (Permission => P_Admin.Permission);
end loop;
Util.Measures.Report (S, "Has_Permission role based (1000 calls)");
T.Assert (Result, "Permission not granted");
end;
declare
S : Util.Measures.Stamp;
begin
for I in 1 .. 1_000 loop
declare
URL : constant String := "/admin/list.html";
P : constant URLs.URL_Permission (URL'Length)
:= URLs.URL_Permission '(Len => URL'Length, URL => URL);
begin
T.Assert (Contexts.Has_Permission (Permission => P),
"Permission not granted");
end;
end loop;
Util.Measures.Report (S, "Has_Permission (1000 calls, cache hit)");
end;
end Test_Read_Policy;
-- ------------------------------
-- Read the policy file <b>File</b> and perform a test on the given URI
-- with a user having the given role.
-- ------------------------------
procedure Check_Policy (T : in out Test;
File : in String;
Role : in String;
URL : in String) is
M : aliased Security.Policies.Policy_Manager (2);
User : aliased Test_Principal;
Admin : Roles.Role_Type;
Context : aliased Security.Contexts.Security_Context;
R : Security.Policies.Roles.Role_Policy_Access;
U : Security.Policies.URLs.URL_Policy_Access;
begin
Configure_Policy (M, File);
Context.Set_Context (Manager => M'Unchecked_Access,
Principal => User'Unchecked_Access);
R := Security.Policies.Roles.Get_Role_Policy (M);
U := Security.Policies.URLs.Get_URL_Policy (M);
Admin := R.Find_Role (Role);
declare
P : constant URLs.URL_Permission (URL'Length)
:= URLs.URL_Permission '(Len => URL'Length, URL => URL);
begin
-- A user without the role should not have the permission.
T.Assert (not U.Has_Permission (Context => Context'Unchecked_Access,
Permission => P),
"Permission was granted for user without role. URL=" & URL);
-- Set the role.
User.Roles (Admin) := True;
T.Assert (U.Has_Permission (Context => Context'Unchecked_Access,
Permission => P),
"Permission was not granted for user with role. URL=" & URL);
end;
end Check_Policy;
-- ------------------------------
-- Test reading policy files and using the <role-permission> controller
-- ------------------------------
procedure Test_Role_Policy (T : in out Test) is
begin
T.Check_Policy (File => "policy-with-role.xml",
Role => "developer",
URL => "/developer/user-should-have-developer-role");
T.Check_Policy (File => "policy-with-role.xml",
Role => "manager",
URL => "/developer/user-should-have-manager-role");
T.Check_Policy (File => "policy-with-role.xml",
Role => "manager",
URL => "/manager/user-should-have-manager-role");
T.Check_Policy (File => "policy-with-role.xml",
Role => "admin",
URL => "/manager/user-should-have-admin-role");
T.Check_Policy (File => "policy-with-role.xml",
Role => "admin",
URL => "/admin/user-should-have-admin-role");
end Test_Role_Policy;
end Security.Policies.Tests;
|
-----------------------------------------------------------------------
-- Security-policies-tests - Unit tests for Security.Permissions
-- Copyright (C) 2011, 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Files;
with Util.Test_Caller;
with Util.Measures;
with Security.Contexts;
with Security.Policies.Roles;
-- with Security.Permissions;
with Security.Permissions.Tests;
with Security.Policies.URLs;
package body Security.Policies.Tests is
use Util.Tests;
package Caller is new Util.Test_Caller (Test, "Security.Policies");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test Security.Permissions.Create_Role",
Test_Create_Role'Access);
Caller.Add_Test (Suite, "Test Security.Permissions.Has_Permission",
Test_Has_Permission'Access);
Caller.Add_Test (Suite, "Test Security.Permissions.Read_Policy (empty)",
Test_Read_Empty_Policy'Access);
Caller.Add_Test (Suite, "Test Security.Policies.Add_Policy",
Test_Get_Role_Policy'Access);
Caller.Add_Test (Suite, "Test Security.Policies.Get_Policy",
Test_Get_Role_Policy'Access);
Caller.Add_Test (Suite, "Test Security.Policies.Roles.Get_Role_Policy",
Test_Get_Role_Policy'Access);
Caller.Add_Test (Suite, "Test Security.Policies.Read_Policy",
Test_Read_Policy'Access);
Caller.Add_Test (Suite, "Test Security.Policies.Roles.Set_Roles",
Test_Set_Roles'Access);
Caller.Add_Test (Suite, "Test Security.Policies.Roles.Set_Roles (invalid)",
Test_Set_Invalid_Roles'Access);
-- These tests are identical but registered under different names
-- for the test documentation.
Caller.Add_Test (Suite, "Test Security.Contexts.Has_Permission",
Test_Role_Policy'Access);
Caller.Add_Test (Suite, "Test Security.Controllers.Roles.Has_Permission",
Test_Role_Policy'Access);
Caller.Add_Test (Suite, "Test Security.Permissions.Role_Policy",
Test_Role_Policy'Access);
end Add_Tests;
-- ------------------------------
-- Get the roles assigned to the user.
-- ------------------------------
function Get_Roles (User : in Test_Principal) return Roles.Role_Map is
begin
return User.Roles;
end Get_Roles;
-- ------------------------------
-- Get the principal name.
-- ------------------------------
function Get_Name (From : in Test_Principal) return String is
begin
return Util.Strings.To_String (From.Name);
end Get_Name;
-- ------------------------------
-- Test Create_Role and Get_Role_Name
-- ------------------------------
procedure Test_Create_Role (T : in out Test) is
use Security.Policies.Roles;
M : Security.Policies.Roles.Role_Policy;
Role : Role_Type;
begin
M.Create_Role (Name => "admin",
Role => Role);
Assert_Equals (T, "admin", M.Get_Role_Name (Role), "Invalid name");
for I in Role + 1 .. Role_Type'Last loop
declare
Name : constant String := "admin-" & Role_Type'Image (I);
Role2 : Role_Type;
begin
Role2 := M.Find_Role ("admin");
T.Assert (Role2 = Role, "Find_Role returned an invalid role");
M.Create_Role (Name => Name,
Role => Role2);
Assert_Equals (T, Name, M.Get_Role_Name (Role2), "Invalid name");
end;
end loop;
end Test_Create_Role;
-- ------------------------------
-- Test Set_Roles
-- ------------------------------
procedure Test_Set_Roles (T : in out Test) is
use Security.Policies.Roles;
M : Security.Policies.Roles.Role_Policy;
Admin : Role_Type;
Manager : Role_Type;
Map : Role_Map;
begin
M.Create_Role (Name => "manager",
Role => Manager);
M.Create_Role (Name => "admin",
Role => Admin);
Assert_Equals (T, "admin", M.Get_Role_Name (Admin), "Invalid name");
T.Assert (not Map (Admin), "The admin role must not set in the map");
M.Set_Roles ("admin", Map);
T.Assert (Map (Admin), "The admin role is not set in the map");
T.Assert (not Map (Manager), "The manager role must not be set in the map");
M.Set_Roles ("manager,admin", Map);
T.Assert (Map (Admin), "The admin role is not set in the map");
T.Assert (Map (Manager), "The manager role is not set in the map");
end Test_Set_Roles;
-- ------------------------------
-- Test Set_Roles on an invalid role name
-- ------------------------------
procedure Test_Set_Invalid_Roles (T : in out Test) is
use Security.Policies.Roles;
M : Security.Policies.Roles.Role_Policy;
Map : Role_Map := (others => False);
begin
M.Set_Roles ("manager,admin", Map);
T.Assert (False, "No exception was raised");
exception
when E : Security.Policies.Roles.Invalid_Name =>
null;
end Test_Set_Invalid_Roles;
-- ------------------------------
-- Test Has_Permission
-- ------------------------------
procedure Test_Has_Permission (T : in out Test) is
M : Security.Policies.Policy_Manager (1);
-- Perm : Permissions.Permission_Type;
User : Test_Principal;
begin
-- T.Assert (not M.Has_Permission (User, 1), "User has a non-existing permission");
null;
end Test_Has_Permission;
procedure Configure_Policy (Manager : in out Security.Policies.Policy_Manager;
Name : in String) is
Dir : constant String := "regtests/files/permissions/";
Path : constant String := Util.Tests.Get_Path (Dir);
R : constant Security.Policies.Roles.Role_Policy_Access := new Roles.Role_Policy;
U : constant Security.Policies.URLs.URL_Policy_Access := new URLs.URL_Policy;
begin
Manager.Add_Policy (R.all'Access);
Manager.Add_Policy (U.all'Access);
Manager.Read_Policy (Util.Files.Compose (Path, Name));
end Configure_Policy;
-- ------------------------------
-- Test the Get_Policy, Get_Role_Policy and Add_Policy operations.
-- ------------------------------
procedure Test_Get_Role_Policy (T : in out Test) is
use type Roles.Role_Policy_Access;
M : aliased Security.Policies.Policy_Manager (Max_Policies => 2);
P : Security.Policies.Policy_Access;
R : Security.Policies.Roles.Role_Policy_Access;
begin
P := M.Get_Policy (Security.Policies.Roles.NAME);
T.Assert (P = null, "Get_Policy succeeded");
R := Security.Policies.Roles.Get_Role_Policy (M);
T.Assert (R = null, "Get_Role_Policy succeeded");
R := new Roles.Role_Policy;
M.Add_Policy (R.all'Access);
P := M.Get_Policy (Security.Policies.Roles.NAME);
T.Assert (P /= null, "Role policy not found");
T.Assert (P.all in Roles.Role_Policy'Class, "Invalid role policy");
R := Security.Policies.Roles.Get_Role_Policy (M);
T.Assert (R /= null, "Get_Role_Policy should not return null");
end Test_Get_Role_Policy;
-- ------------------------------
-- Test reading an empty policy file
-- ------------------------------
procedure Test_Read_Empty_Policy (T : in out Test) is
M : aliased Security.Policies.Policy_Manager (Max_Policies => 2);
User : aliased Test_Principal;
Context : aliased Security.Contexts.Security_Context;
P : Security.Policies.Policy_Access;
R : Security.Policies.Roles.Role_Policy_Access;
begin
Configure_Policy (M, "empty.xml");
Context.Set_Context (Manager => M'Unchecked_Access,
Principal => User'Unchecked_Access);
R := Security.Policies.Roles.Get_Role_Policy (M);
declare
Admin : Policies.Roles.Role_Type;
begin
Admin := R.Find_Role ("admin");
T.Fail ("'admin' role was returned");
exception
when Security.Policies.Roles.Invalid_Name =>
null;
end;
T.Assert (not Contexts.Has_Permission (Permissions.Tests.P_Admin.Permission),
"Has_Permission (admin) failed for empty policy");
T.Assert (not Contexts.Has_Permission (Permissions.Tests.P_Create.Permission),
"Has_Permission (create) failed for empty policy");
T.Assert (not Contexts.Has_Permission (Permissions.Tests.P_Update.Permission),
"Has_Permission (update) failed for empty policy");
T.Assert (not Contexts.Has_Permission (Permissions.Tests.P_Delete.Permission),
"Has_Permission (delete) failed for empty policy");
end Test_Read_Empty_Policy;
-- ------------------------------
-- Test reading policy files
-- ------------------------------
procedure Test_Read_Policy (T : in out Test) is
use Security.Permissions.Tests;
M : aliased Security.Policies.Policy_Manager (Max_Policies => 2);
User : aliased Test_Principal;
Admin : Policies.Roles.Role_Type;
Context : aliased Security.Contexts.Security_Context;
R : Security.Policies.Roles.Role_Policy_Access;
begin
Configure_Policy (M, "simple-policy.xml");
Context.Set_Context (Manager => M'Unchecked_Access,
Principal => User'Unchecked_Access);
R := Security.Policies.Roles.Get_Role_Policy (M);
Admin := R.Find_Role ("admin");
T.Assert (not Contexts.Has_Permission (Permission => P_Admin.Permission),
"Permission was granted but user has no role");
User.Roles (Admin) := True;
T.Assert (Contexts.Has_Permission (Permission => P_Admin.Permission),
"Permission was not granted and user has admin role");
declare
S : Util.Measures.Stamp;
Result : Boolean;
begin
for I in 1 .. 1_000 loop
Result := Contexts.Has_Permission (Permission => P_Admin.Permission);
end loop;
Util.Measures.Report (S, "Has_Permission role based (1000 calls)");
T.Assert (Result, "Permission not granted");
end;
declare
S : Util.Measures.Stamp;
begin
for I in 1 .. 1_000 loop
declare
URL : constant String := "/admin/list.html";
P : constant URLs.URL_Permission (URL'Length)
:= URLs.URL_Permission '(Len => URL'Length, URL => URL);
begin
T.Assert (Contexts.Has_Permission (Permission => P),
"Permission not granted");
end;
end loop;
Util.Measures.Report (S, "Has_Permission (1000 calls, cache hit)");
end;
end Test_Read_Policy;
-- ------------------------------
-- Read the policy file <b>File</b> and perform a test on the given URI
-- with a user having the given role.
-- ------------------------------
procedure Check_Policy (T : in out Test;
File : in String;
Role : in String;
URL : in String) is
M : aliased Security.Policies.Policy_Manager (2);
User : aliased Test_Principal;
Admin : Roles.Role_Type;
Context : aliased Security.Contexts.Security_Context;
R : Security.Policies.Roles.Role_Policy_Access;
U : Security.Policies.URLs.URL_Policy_Access;
begin
Configure_Policy (M, File);
Context.Set_Context (Manager => M'Unchecked_Access,
Principal => User'Unchecked_Access);
R := Security.Policies.Roles.Get_Role_Policy (M);
U := Security.Policies.URLs.Get_URL_Policy (M);
Admin := R.Find_Role (Role);
declare
P : constant URLs.URL_Permission (URL'Length)
:= URLs.URL_Permission '(Len => URL'Length, URL => URL);
begin
-- A user without the role should not have the permission.
T.Assert (not U.Has_Permission (Context => Context,
Permission => P),
"Permission was granted for user without role. URL=" & URL);
-- Set the role.
User.Roles (Admin) := True;
T.Assert (U.Has_Permission (Context => Context,
Permission => P),
"Permission was not granted for user with role. URL=" & URL);
end;
end Check_Policy;
-- ------------------------------
-- Test reading policy files and using the <role-permission> controller
-- ------------------------------
procedure Test_Role_Policy (T : in out Test) is
begin
T.Check_Policy (File => "policy-with-role.xml",
Role => "developer",
URL => "/developer/user-should-have-developer-role");
T.Check_Policy (File => "policy-with-role.xml",
Role => "manager",
URL => "/developer/user-should-have-manager-role");
T.Check_Policy (File => "policy-with-role.xml",
Role => "manager",
URL => "/manager/user-should-have-manager-role");
T.Check_Policy (File => "policy-with-role.xml",
Role => "admin",
URL => "/manager/user-should-have-admin-role");
T.Check_Policy (File => "policy-with-role.xml",
Role => "admin",
URL => "/admin/user-should-have-admin-role");
end Test_Role_Policy;
end Security.Policies.Tests;
|
Simplify calls to Has_Permission
|
Simplify calls to Has_Permission
|
Ada
|
apache-2.0
|
stcarrez/ada-security
|
dbb9527070db99b2efee314d66209b40531a3a7f
|
src/wiki-parsers-dotclear.adb
|
src/wiki-parsers-dotclear.adb
|
-----------------------------------------------------------------------
-- wiki-parsers-dotclear -- Dotclear parser operations
-- Copyright (C) 2011 - 2022 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Wiki.Nodes;
with Wiki.Helpers;
with Wiki.Parsers.Common;
package body Wiki.Parsers.Dotclear is
use Wiki.Helpers;
use Wiki.Nodes;
use Wiki.Strings;
use Wiki.Buffers;
-- Parse an image.
-- Example:
-- ((url|alt text))
-- ((url|alt text|position))
-- ((url|alt text|position||description))
procedure Parse_Image (Parser : in out Parser_Type;
Text : in out Wiki.Buffers.Buffer_Access;
From : in out Positive);
procedure Parse_Preformatted (Parser : in out Parser_Type;
Text : in out Wiki.Buffers.Buffer_Access;
From : in out Positive);
procedure Parse_Preformatted (Parser : in out Parser_Type;
Text : in out Wiki.Buffers.Buffer_Access;
From : in out Positive) is
Count : constant Natural := Count_Occurence (Text, From, '/');
begin
if Count /= 3 then
return;
end if;
-- Extract the format either 'Ada' or '[Ada]'
declare
Pos : Natural := Count + 1;
Buffer : Wiki.Buffers.Buffer_Access := Text;
Space_Count : Natural;
begin
Wiki.Strings.Clear (Parser.Preformat_Format);
Buffers.Skip_Spaces (Buffer, Pos, Space_Count);
if Buffer /= null and then Pos <= Buffer.Last and then Buffer.Content (Pos) = '[' then
Next (Buffer, Pos);
Common.Parse_Token (Buffer, Pos, Parser.Escape_Char, ']', ']',
Parser.Preformat_Format);
if Buffer /= null then
Next (Buffer, Pos);
end if;
else
Common.Parse_Token (Buffer, Pos, Parser.Escape_Char, CR, LF,
Parser.Preformat_Format);
end if;
if Buffer /= null then
Buffers.Skip_Spaces (Buffer, Pos, Space_Count);
end if;
Text := Buffer;
From := Pos;
end;
Parser.Preformat_Indent := 0;
Parser.Preformat_Fence := ' ';
Parser.Preformat_Fcount := 0;
Flush_Text (Parser, Trim => Right);
Pop_Block (Parser);
Push_Block (Parser, N_PREFORMAT);
end Parse_Preformatted;
-- ------------------------------
-- Parse an image.
-- Example:
-- ((url|alt text))
-- ((url|alt text|position))
-- ((url|alt text|position||description))
-- ------------------------------
procedure Parse_Image (Parser : in out Parser_Type;
Text : in out Wiki.Buffers.Buffer_Access;
From : in out Positive) is
procedure Append_Position (Position : in Wiki.Strings.WString);
procedure Append_Position (Position : in Wiki.Strings.WString) is
begin
if Position = "L" or Position = "G" then
Wiki.Attributes.Append (Parser.Attributes, String '("align"), "left");
elsif Position = "R" or Position = "D" then
Wiki.Attributes.Append (Parser.Attributes, String '("align"), "right");
elsif Position = "C" then
Wiki.Attributes.Append (Parser.Attributes, String '("align"), "center");
end if;
end Append_Position;
procedure Append_Position is
new Wiki.Strings.Wide_Wide_Builders.Get (Append_Position);
Link : Wiki.Strings.BString (128);
Alt : Wiki.Strings.BString (128);
Position : Wiki.Strings.BString (128);
Desc : Wiki.Strings.BString (128);
Block : Wiki.Buffers.Buffer_Access := Text;
Pos : Positive := From;
begin
Next (Block, Pos);
if Block = null or else Block.Content (Pos) /= '(' then
Common.Parse_Text (Parser, Text, From);
return;
end if;
Next (Block, Pos);
if Block = null then
Common.Parse_Text (Parser, Text, From, Count => 2);
return;
end if;
Common.Parse_Token (Block, Pos, Parser.Escape_Char, '|', ')', Link);
if Block /= null and then Block.Content (Pos) = '|' then
Next (Block, Pos);
if Block /= null then
Common.Parse_Token (Block, Pos, Parser.Escape_Char, '|', ')', Alt);
end if;
if Block /= null and then Block.Content (Pos) = '|' then
Next (Block, Pos);
if Block /= null then
Common.Parse_Token (Block, Pos, Parser.Escape_Char, '|', ')', Position);
end if;
if Block /= null and then Block.Content (Pos) = '|' then
Next (Block, Pos);
if Block /= null then
Common.Parse_Token (Block, Pos, Parser.Escape_Char, '|', ')', Desc);
end if;
end if;
end if;
end if;
-- Check for the first ')'.
if Block /= null and then Block.Content (Pos) = ')' then
Next (Block, Pos);
end if;
-- Check for the second ')', abort the image and emit the '((' if the '))' is missing.
if Block = null or else Block.Content (Pos) /= ')' then
Common.Parse_Text (Parser, Text, From, Count => 2);
return;
end if;
Next (Block, Pos);
Text := Block;
From := Pos;
Flush_Text (Parser);
if not Parser.Context.Is_Hidden then
Wiki.Attributes.Clear (Parser.Attributes);
Wiki.Attributes.Append (Parser.Attributes, "src", Link);
Append_Position (Position);
Wiki.Attributes.Append (Parser.Attributes, "longdesc", Desc);
Parser.Context.Filters.Add_Image (Parser.Document,
Strings.To_WString (Alt),
Parser.Attributes);
end if;
end Parse_Image;
procedure Parse_Line (Parser : in out Parser_Type;
Text : in Wiki.Buffers.Buffer_Access) is
Pos : Natural := 1;
C : Wiki.Strings.WChar;
Count : Natural;
Buffer : Wiki.Buffers.Buffer_Access := Text;
begin
if Parser.Current_Node = N_PREFORMAT then
if Parser.Preformat_Fcount = 0 then
Count := Count_Occurence (Buffer, 1, '/');
if Count /= 3 then
Common.Append (Parser.Text, Buffer, 1);
return;
end if;
Pop_Block (Parser);
return;
end if;
if Buffer.Content (Pos) = ' ' then
Common.Append (Parser.Text, Buffer, Pos + 1);
return;
end if;
Pop_Block (Parser);
end if;
if Parser.Quote_Level > 0 then
Count := Count_Occurence (Buffer, 1, '>');
if Count = 0 then
loop
Pop_Block (Parser);
exit when Parser.Current_Node = Nodes.N_NONE;
end loop;
else
Pos := Pos + Count;
end if;
end if;
if Parser.Current_Node = N_HEADER then
Pop_Block (Parser);
end if;
C := Buffer.Content (Pos);
case C is
when CR | LF =>
Common.Parse_Paragraph (Parser, Buffer, Pos);
return;
when '!' =>
Common.Parse_Header (Parser, Buffer, Pos, '!');
if Buffer = null then
return;
end if;
when '/' =>
Parse_Preformatted (Parser, Buffer, Pos);
if Buffer = null then
return;
end if;
when ' ' =>
Parser.Preformat_Indent := 1;
Parser.Preformat_Fence := ' ';
Parser.Preformat_Fcount := 1;
Flush_Text (Parser, Trim => Right);
Pop_Block (Parser);
Push_Block (Parser, N_PREFORMAT);
Common.Append (Parser.Text, Buffer, Pos + 1);
return;
when '>' =>
Count := Count_Occurence (Buffer, Pos + 1, '>');
if Parser.Current_Node /= N_BLOCKQUOTE then
Flush_Text (Parser, Trim => Right);
Pop_Block (Parser);
Parser.Quote_Level := Count + 1;
Push_Block (Parser, N_BLOCKQUOTE);
end if;
if not Parser.Context.Is_Hidden then
Parser.Context.Filters.Add_Blockquote (Parser.Document, Parser.Quote_Level);
end if;
Pos := Pos + Count + 1;
when '-' =>
Common.Parse_Horizontal_Rule (Parser, Buffer, Pos, '-');
if Buffer = null then
return;
end if;
when '*' | '#' =>
Common.Parse_List (Parser, Buffer, Pos);
when others =>
if Parser.Current_Node /= N_PARAGRAPH then
Pop_List (Parser);
Push_Block (Parser, N_PARAGRAPH);
end if;
end case;
Main :
while Buffer /= null loop
declare
Last : Natural := Buffer.Last;
begin
while Pos <= Last loop
C := Buffer.Content (Pos);
case C is
when '_' =>
Parse_Format_Double (Parser, Buffer, Pos, '_', Wiki.BOLD);
exit Main when Buffer = null;
when ''' =>
Parse_Format_Double (Parser, Buffer, Pos, ''', Wiki.ITALIC);
exit Main when Buffer = null;
when '-' =>
Parse_Format_Double (Parser, Buffer, Pos, '-', Wiki.STRIKEOUT);
exit Main when Buffer = null;
when '+' =>
Parse_Format_Double (Parser, Buffer, Pos, '+', Wiki.INS);
exit Main when Buffer = null;
when ',' =>
Parse_Format_Double (Parser, Buffer, Pos, ',', Wiki.SUBSCRIPT);
exit Main when Buffer = null;
when '@' =>
Parse_Format_Double (Parser, Buffer, Pos, '@', Wiki.CODE);
exit Main when Buffer = null;
when '^' =>
Parse_Format (Parser, Buffer, Pos, '^', Wiki.SUPERSCRIPT);
exit Main when Buffer = null;
when '{' =>
Common.Parse_Quote (Parser, Buffer, Pos, '{');
exit Main when Buffer = null;
when '(' =>
Parse_Image (Parser, Buffer, Pos);
exit Main when Buffer = null;
when '[' =>
Common.Parse_Link (Parser, Buffer, Pos);
exit Main when Buffer = null;
when '<' =>
Common.Parse_Template (Parser, Buffer, Pos, '<');
exit Main when Buffer = null;
when '%' =>
Count := Count_Occurence (Buffer, Pos, '%');
if Count >= 3 then
Parser.Empty_Line := True;
Flush_Text (Parser, Trim => Right);
if not Parser.Context.Is_Hidden then
Parser.Context.Filters.Add_Node (Parser.Document, Nodes.N_LINE_BREAK);
end if;
-- Skip 3 '%' characters.
for I in 1 .. 3 loop
Next (Buffer, Pos);
end loop;
if Buffer /= null and then Helpers.Is_Newline (Buffer.Content (Pos)) then
Next (Buffer, Pos);
end if;
exit Main when Buffer = null;
else
Append (Parser.Text, C);
Pos := Pos + 1;
end if;
when CR | LF =>
-- if Wiki.Strings.Length (Parser.Text) > 0 then
Append (Parser.Text, ' ');
-- end if;
Pos := Pos + 1;
when '\' =>
Next (Buffer, Pos);
if Buffer = null then
Append (Parser.Text, C);
else
Append (Parser.Text, Buffer.Content (Pos));
Pos := Pos + 1;
Last := Buffer.Last;
end if;
when others =>
Append (Parser.Text, C);
Pos := Pos + 1;
end case;
end loop;
end;
Buffer := Buffer.Next_Block;
Pos := 1;
end loop Main;
end Parse_Line;
end Wiki.Parsers.Dotclear;
|
-----------------------------------------------------------------------
-- wiki-parsers-dotclear -- Dotclear parser operations
-- Copyright (C) 2011 - 2022 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Wiki.Nodes;
with Wiki.Helpers;
with Wiki.Parsers.Common;
package body Wiki.Parsers.Dotclear is
use Wiki.Helpers;
use Wiki.Nodes;
use Wiki.Strings;
use Wiki.Buffers;
-- Parse an image.
-- Example:
-- ((url|alt text))
-- ((url|alt text|position))
-- ((url|alt text|position||description))
procedure Parse_Image (Parser : in out Parser_Type;
Text : in out Wiki.Buffers.Buffer_Access;
From : in out Positive);
procedure Parse_Preformatted (Parser : in out Parser_Type;
Text : in out Wiki.Buffers.Buffer_Access;
From : in out Positive);
procedure Parse_Preformatted (Parser : in out Parser_Type;
Text : in out Wiki.Buffers.Buffer_Access;
From : in out Positive) is
Count : constant Natural := Count_Occurence (Text, From, '/');
begin
if Count /= 3 then
return;
end if;
-- Extract the format either 'Ada' or '[Ada]'
declare
Pos : Natural := Count + 1;
Buffer : Wiki.Buffers.Buffer_Access := Text;
Space_Count : Natural;
begin
Wiki.Strings.Clear (Parser.Preformat_Format);
Buffers.Skip_Spaces (Buffer, Pos, Space_Count);
if Buffer /= null and then Pos <= Buffer.Last and then Buffer.Content (Pos) = '[' then
Next (Buffer, Pos);
Common.Parse_Token (Buffer, Pos, Parser.Escape_Char, ']', ']',
Parser.Preformat_Format);
if Buffer /= null then
Next (Buffer, Pos);
end if;
else
Common.Parse_Token (Buffer, Pos, Parser.Escape_Char, CR, LF,
Parser.Preformat_Format);
end if;
if Buffer /= null then
Buffers.Skip_Spaces (Buffer, Pos, Space_Count);
end if;
Text := Buffer;
From := Pos;
end;
Parser.Preformat_Indent := 0;
Parser.Preformat_Fence := ' ';
Parser.Preformat_Fcount := 0;
Flush_Text (Parser, Trim => Right);
Pop_Block (Parser);
Push_Block (Parser, N_PREFORMAT);
end Parse_Preformatted;
-- ------------------------------
-- Parse an image.
-- Example:
-- ((url|alt text))
-- ((url|alt text|position))
-- ((url|alt text|position||description))
-- ------------------------------
procedure Parse_Image (Parser : in out Parser_Type;
Text : in out Wiki.Buffers.Buffer_Access;
From : in out Positive) is
procedure Append_Position (Position : in Wiki.Strings.WString);
procedure Append_Position (Position : in Wiki.Strings.WString) is
begin
if Position = "L" or Position = "G" then
Wiki.Attributes.Append (Parser.Attributes, String '("align"), "left");
elsif Position = "R" or Position = "D" then
Wiki.Attributes.Append (Parser.Attributes, String '("align"), "right");
elsif Position = "C" then
Wiki.Attributes.Append (Parser.Attributes, String '("align"), "center");
end if;
end Append_Position;
procedure Append_Position is
new Wiki.Strings.Wide_Wide_Builders.Get (Append_Position);
Link : Wiki.Strings.BString (128);
Alt : Wiki.Strings.BString (128);
Position : Wiki.Strings.BString (128);
Desc : Wiki.Strings.BString (128);
Block : Wiki.Buffers.Buffer_Access := Text;
Pos : Positive := From;
begin
Next (Block, Pos);
if Block = null or else Block.Content (Pos) /= '(' then
Common.Parse_Text (Parser, Text, From);
return;
end if;
Next (Block, Pos);
if Block = null then
Common.Parse_Text (Parser, Text, From, Count => 2);
return;
end if;
Common.Parse_Token (Block, Pos, Parser.Escape_Char, '|', ')', Link);
if Block /= null and then Block.Content (Pos) = '|' then
Next (Block, Pos);
if Block /= null then
Common.Parse_Token (Block, Pos, Parser.Escape_Char, '|', ')', Alt);
end if;
if Block /= null and then Block.Content (Pos) = '|' then
Next (Block, Pos);
if Block /= null then
Common.Parse_Token (Block, Pos, Parser.Escape_Char, '|', ')', Position);
end if;
if Block /= null and then Block.Content (Pos) = '|' then
Next (Block, Pos);
if Block /= null then
Common.Parse_Token (Block, Pos, Parser.Escape_Char, '|', ')', Desc);
end if;
end if;
end if;
end if;
-- Check for the first ')'.
if Block /= null and then Block.Content (Pos) = ')' then
Next (Block, Pos);
end if;
-- Check for the second ')', abort the image and emit the '((' if the '))' is missing.
if Block = null or else Block.Content (Pos) /= ')' then
Common.Parse_Text (Parser, Text, From, Count => 2);
return;
end if;
Next (Block, Pos);
Text := Block;
From := Pos;
Flush_Text (Parser);
if not Parser.Context.Is_Hidden then
Wiki.Attributes.Clear (Parser.Attributes);
Wiki.Attributes.Append (Parser.Attributes, "src", Link);
Append_Position (Position);
Wiki.Attributes.Append (Parser.Attributes, "longdesc", Desc);
Parser.Context.Filters.Add_Image (Parser.Document,
Strings.To_WString (Alt),
Parser.Attributes);
end if;
end Parse_Image;
procedure Parse_Line (Parser : in out Parser_Type;
Text : in Wiki.Buffers.Buffer_Access) is
Pos : Natural := 1;
C : Wiki.Strings.WChar;
Count : Natural;
Buffer : Wiki.Buffers.Buffer_Access := Text;
begin
if Parser.In_Blockquote then
Count := Count_Occurence (Buffer, 1, '>');
if Count = 0 then
loop
Pop_Block (Parser);
exit when Parser.Current_Node = Nodes.N_NONE;
end loop;
else
Buffers.Next (Buffer, Pos, Count);
Buffers.Skip_Optional_Space (Buffer, Pos);
if Buffer = null then
return;
end if;
Push_Block (Parser, Nodes.N_BLOCKQUOTE, Count);
end if;
end if;
if Parser.Current_Node = N_PREFORMAT then
if Parser.Preformat_Fcount = 0 then
Count := Count_Occurence (Buffer, 1, '/');
if Count /= 3 then
Common.Append (Parser.Text, Buffer, 1);
return;
end if;
Pop_Block (Parser);
return;
end if;
if Buffer.Content (Pos) = ' ' then
Common.Append (Parser.Text, Buffer, Pos + 1);
return;
end if;
Pop_Block (Parser);
end if;
if Parser.Current_Node = N_HEADER then
Pop_Block (Parser);
end if;
C := Buffer.Content (Pos);
if C = '>' then
Count := Count_Occurence (Buffer, Pos, '>');
Push_Block (Parser, Nodes.N_BLOCKQUOTE, Count);
Buffers.Next (Buffer, Pos, Count);
Buffers.Skip_Optional_Space (Buffer, Pos);
if Buffer = null then
return;
end if;
C := Buffer.Content (Pos);
end if;
case C is
when CR | LF =>
Common.Parse_Paragraph (Parser, Buffer, Pos);
return;
when '!' =>
Common.Parse_Header (Parser, Buffer, Pos, '!');
if Buffer = null then
return;
end if;
when '/' =>
Parse_Preformatted (Parser, Buffer, Pos);
if Buffer = null then
return;
end if;
when ' ' =>
Parser.Preformat_Indent := 1;
Parser.Preformat_Fence := ' ';
Parser.Preformat_Fcount := 1;
Flush_Text (Parser, Trim => Right);
if Parser.Current_Node /= N_BLOCKQUOTE then
Pop_Block (Parser);
end if;
Push_Block (Parser, N_PREFORMAT);
Common.Append (Parser.Text, Buffer, Pos + 1);
return;
when '-' =>
Common.Parse_Horizontal_Rule (Parser, Buffer, Pos, '-');
if Buffer = null then
return;
end if;
when '*' | '#' =>
Common.Parse_List (Parser, Buffer, Pos);
when others =>
if Parser.Current_Node /= N_PARAGRAPH then
Pop_List (Parser);
Push_Block (Parser, N_PARAGRAPH);
end if;
end case;
Main :
while Buffer /= null loop
declare
Last : Natural := Buffer.Last;
begin
while Pos <= Last loop
C := Buffer.Content (Pos);
case C is
when '_' =>
Parse_Format_Double (Parser, Buffer, Pos, '_', Wiki.BOLD);
exit Main when Buffer = null;
when ''' =>
Parse_Format_Double (Parser, Buffer, Pos, ''', Wiki.ITALIC);
exit Main when Buffer = null;
when '-' =>
Parse_Format_Double (Parser, Buffer, Pos, '-', Wiki.STRIKEOUT);
exit Main when Buffer = null;
when '+' =>
Parse_Format_Double (Parser, Buffer, Pos, '+', Wiki.INS);
exit Main when Buffer = null;
when ',' =>
Parse_Format_Double (Parser, Buffer, Pos, ',', Wiki.SUBSCRIPT);
exit Main when Buffer = null;
when '@' =>
Parse_Format_Double (Parser, Buffer, Pos, '@', Wiki.CODE);
exit Main when Buffer = null;
when '^' =>
Parse_Format (Parser, Buffer, Pos, '^', Wiki.SUPERSCRIPT);
exit Main when Buffer = null;
when '{' =>
Common.Parse_Quote (Parser, Buffer, Pos, '{');
exit Main when Buffer = null;
when '(' =>
Parse_Image (Parser, Buffer, Pos);
exit Main when Buffer = null;
when '[' =>
Common.Parse_Link (Parser, Buffer, Pos);
exit Main when Buffer = null;
when '<' =>
Common.Parse_Template (Parser, Buffer, Pos, '<');
exit Main when Buffer = null;
when '%' =>
Count := Count_Occurence (Buffer, Pos, '%');
if Count >= 3 then
Parser.Empty_Line := True;
Flush_Text (Parser, Trim => Right);
if not Parser.Context.Is_Hidden then
Parser.Context.Filters.Add_Node (Parser.Document, Nodes.N_LINE_BREAK);
end if;
-- Skip 3 '%' characters.
for I in 1 .. 3 loop
Next (Buffer, Pos);
end loop;
if Buffer /= null and then Helpers.Is_Newline (Buffer.Content (Pos)) then
Next (Buffer, Pos);
end if;
exit Main when Buffer = null;
else
Append (Parser.Text, C);
Pos := Pos + 1;
end if;
when CR | LF =>
-- if Wiki.Strings.Length (Parser.Text) > 0 then
Append (Parser.Text, ' ');
-- end if;
Pos := Pos + 1;
when '\' =>
Next (Buffer, Pos);
if Buffer = null then
Append (Parser.Text, C);
else
Append (Parser.Text, Buffer.Content (Pos));
Pos := Pos + 1;
Last := Buffer.Last;
end if;
when others =>
Append (Parser.Text, C);
Pos := Pos + 1;
end case;
end loop;
end;
Buffer := Buffer.Next_Block;
Pos := 1;
end loop Main;
end Parse_Line;
end Wiki.Parsers.Dotclear;
|
Update the parsing of blockquotes
|
Update the parsing of blockquotes
|
Ada
|
apache-2.0
|
stcarrez/ada-wiki,stcarrez/ada-wiki
|
d06ebb1e60bca4c7b3ec3362efddb38899459b5f
|
examples/example.adb
|
examples/example.adb
|
with Ada.Text_IO; use Ada.Text_IO;
with YAML;
procedure Example is
procedure Process (S : String);
procedure Put (N : YAML.Node_Ref; Indent : Natural);
procedure Process (S : String) is
P : YAML.Parser_Type;
begin
P.Set_Input_String (S, YAML.UTF8_Encoding);
declare
D : constant YAML.Document_Type := P.Load;
N : constant YAML.Node_Ref := D.Root_Node;
begin
Put (N, 0);
end;
New_Line;
end Process;
procedure Put (N : YAML.Node_Ref; Indent : Natural) is
Prefix : constant String := (1 .. Indent => ' ');
begin
case YAML.Kind (N) is
when YAML.No_Node =>
Put_Line (Prefix & "<null>");
when YAML.Scalar_Node =>
Put_Line (Prefix & String (YAML.Scalar_Value (N)));
when YAML.Sequence_Node =>
for I in 1 .. YAML.Sequence_Length (N) loop
Put_Line (Prefix & "- ");
Put (YAML.Sequence_Item (N, I), Indent + 2);
end loop;
when YAML.Mapping_Node =>
Put_Line ("Pairs:");
for I in 1 .. YAML.Mapping_Length (N) loop
declare
Pair : constant YAML.Node_Pair := YAML.Mapping_Item (N, I);
begin
Put (Prefix & "Key:");
Put (Pair.Key, Indent + 2);
Put (Prefix & "Value:");
Put (Pair.Value, Indent + 2);
end;
end loop;
end case;
end Put;
begin
Process ("1");
Process ("[1, 2, 3, a, null]");
Process ("foo: 1");
end Example;
|
with Ada.Command_Line; use Ada.Command_Line;
with Ada.Text_IO; use Ada.Text_IO;
with YAML;
procedure Example is
procedure Process_String (S : String);
procedure Process_File (Filename : String);
procedure Process (D : YAML.Document_Type);
procedure Put (N : YAML.Node_Ref; Indent : Natural);
procedure Process_String (S : String) is
P : YAML.Parser_Type;
begin
P.Set_Input_String (S, YAML.UTF8_Encoding);
Process (P.Load);
end Process_String;
procedure Process_File (Filename : String) is
P : YAML.Parser_Type;
begin
P.Set_Input_File (Filename, YAML.UTF8_Encoding);
Process (P.Load);
end Process_File;
procedure Process (D : YAML.Document_Type) is
N : constant YAML.Node_Ref := D.Root_Node;
begin
Put (N, 0);
New_Line;
end Process;
procedure Put (N : YAML.Node_Ref; Indent : Natural) is
Prefix : constant String := (1 .. Indent => ' ');
begin
case YAML.Kind (N) is
when YAML.No_Node =>
Put_Line (Prefix & "<null>");
when YAML.Scalar_Node =>
Put_Line (Prefix & String (YAML.Scalar_Value (N)));
when YAML.Sequence_Node =>
for I in 1 .. YAML.Sequence_Length (N) loop
Put_Line (Prefix & "- ");
Put (YAML.Sequence_Item (N, I), Indent + 2);
end loop;
when YAML.Mapping_Node =>
Put_Line ("Pairs:");
for I in 1 .. YAML.Mapping_Length (N) loop
declare
Pair : constant YAML.Node_Pair := YAML.Mapping_Item (N, I);
begin
Put (Prefix & "Key:");
Put (Pair.Key, Indent + 2);
Put (Prefix & "Value:");
Put (Pair.Value, Indent + 2);
end;
end loop;
end case;
end Put;
begin
if Argument_Count = 0 then
Process_String ("1");
Process_String ("[1, 2, 3, a, null]");
Process_String ("foo: 1");
else
for I in 1 .. Argument_Count loop
Process_File (Argument (I));
end loop;
end if;
end Example;
|
enhance to demonstrate the use of Set_Input_File
|
Example: enhance to demonstrate the use of Set_Input_File
|
Ada
|
mit
|
pmderodat/libyaml-ada,pmderodat/libyaml-ada
|
6d56051e38ebf69450651b27ecb71043378a2c28
|
regtests/util-http-clients-tests.adb
|
regtests/util-http-clients-tests.adb
|
-----------------------------------------------------------------------
-- util-http-clients-tests -- Unit tests for HTTP client
-- Copyright (C) 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Unchecked_Deallocation;
with Util.Test_Caller;
with Util.Strings.Transforms;
with Util.Http.Tools;
with Util.Strings;
with Util.Log.Loggers;
package body Util.Http.Clients.Tests is
-- The logger
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Util.Http.Clients.Tests");
package body Http_Tests is
package Caller is new Util.Test_Caller (Http_Test, "Http-" & NAME);
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test Util.Http.Clients." & NAME & ".Get",
Test_Http_Get'Access);
Caller.Add_Test (Suite, "Test Util.Http.Clients." & NAME & ".Post",
Test_Http_Post'Access);
end Add_Tests;
overriding
procedure Set_Up (T : in out Http_Test) is
begin
Test (T).Set_Up;
Register;
end Set_Up;
end Http_Tests;
overriding
procedure Set_Up (T : in out Test) is
begin
Log.Info ("Starting test server");
T.Server := new Test_Server;
T.Server.Start;
end Set_Up;
overriding
procedure Tear_Down (T : in out Test) is
procedure Free is
new Ada.Unchecked_Deallocation (Object => Test_Server'Class,
Name => Test_Server_Access);
begin
if T.Server /= null then
Log.Info ("Stopping test server");
T.Server.Stop;
Free (T.Server);
T.Server := null;
end if;
end Tear_Down;
-- ------------------------------
-- Process the line received by the server.
-- ------------------------------
overriding
procedure Process_Line (Into : in out Test_Server;
Line : in Ada.Strings.Unbounded.Unbounded_String;
Stream : in out Util.Streams.Texts.Reader_Stream'Class;
Client : in out Util.Streams.Sockets.Socket_Stream'Class) is
L : constant String := Ada.Strings.Unbounded.To_String (Line);
Pos : Natural := Util.Strings.Index (L, ' ');
begin
if Pos > 0 and Into.Method = UNKNOWN then
if L (L'First .. Pos - 1) = "GET" then
Into.Method := GET;
elsif L (L'First .. Pos - 1) = "POST" then
Into.Method := POST;
else
Into.Method := UNKNOWN;
end if;
end if;
Pos := Util.Strings.Index (L, ':');
if Pos > 0 then
if L (L'First .. Pos) = "Content-Type:" then
Into.Content_Type
:= Ada.Strings.Unbounded.To_Unbounded_String (L (Pos + 2 .. L'Last - 2));
elsif L (L'First .. Pos) = "Content-Length:" then
Into.Length := Natural'Value (L (Pos + 1 .. L'Last - 2));
end if;
end if;
if L'Length = 2 and then Into.Length > 0 then
for I in 1 .. Into.Length loop
declare
C : Character;
begin
Stream.Read (C);
Ada.Strings.Unbounded.Append (Into.Result, C);
end;
end loop;
declare
Output : Util.Streams.Texts.Print_Stream;
begin
Output.Initialize (Client'Unchecked_Access);
Output.Write ("HTTP/1.1 200 Found" & ASCII.CR & ASCII.LF);
Output.Write ("Content-Length: 4" & ASCII.CR & ASCII.LF);
Output.Write (ASCII.CR & ASCII.LF);
Output.Write ("OK" & ASCII.CR & ASCII.LF);
Output.Flush;
end;
end if;
Log.Info ("Received: {0}", L);
end Process_Line;
-- ------------------------------
-- Get the test server base URI.
-- ------------------------------
function Get_Uri (T : in Test) return String is
begin
return "http://" & T.Server.Get_Host & ":" & Util.Strings.Image (T.Server.Get_Port);
end Get_Uri;
-- ------------------------------
-- Test the http Get operation.
-- ------------------------------
procedure Test_Http_Get (T : in out Test) is
Request : Client;
Reply : Response;
begin
Request.Get ("http://www.google.com", Reply);
T.Assert (Reply.Get_Status = 200 or Reply.Get_Status = 302, "Get status is invalid");
Util.Http.Tools.Save_Response (Util.Tests.Get_Test_Path ("http_get.txt"), Reply, True);
-- Check the content.
declare
Content : constant String := Util.Strings.Transforms.To_Lower_Case (Reply.Get_Body);
begin
Util.Tests.Assert_Matches (T, ".*html.*", Content, "Invalid GET content");
end;
-- Check one header.
declare
Content : constant String := Reply.Get_Header ("Content-Type");
begin
T.Assert (Content'Length > 0, "Empty Content-Type header");
Util.Tests.Assert_Matches (T, ".*text/html.*", Content, "Invalid content type");
end;
end Test_Http_Get;
-- ------------------------------
-- Test the http POST operation.
-- ------------------------------
procedure Test_Http_Post (T : in out Test) is
Request : Client;
Reply : Response;
Uri : constant String := T.Get_Uri;
begin
Log.Info ("Post on " & Uri);
T.Server.Method := UNKNOWN;
Request.Post (Uri & "/post",
"p1=1", Reply);
T.Assert (T.Server.Method = POST, "Invalid method received by server");
Util.Tests.Assert_Equals (T, "application/x-www-form-urlencoded", T.Server.Content_Type,
"Invalid content type received by server");
Util.Tests.Assert_Equals (T, "OK" & ASCII.CR & ASCII.LF, Reply.Get_Body, "Invalid response");
Util.Http.Tools.Save_Response (Util.Tests.Get_Test_Path ("http_post.txt"), Reply, True);
end Test_Http_Post;
end Util.Http.Clients.Tests;
|
-----------------------------------------------------------------------
-- util-http-clients-tests -- Unit tests for HTTP client
-- Copyright (C) 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Unchecked_Deallocation;
with Util.Test_Caller;
with Util.Strings.Transforms;
with Util.Http.Tools;
with Util.Strings;
with Util.Log.Loggers;
package body Util.Http.Clients.Tests is
-- The logger
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Util.Http.Clients.Tests");
package body Http_Tests is
package Caller is new Util.Test_Caller (Http_Test, "Http-" & NAME);
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test Util.Http.Clients." & NAME & ".Get",
Test_Http_Get'Access);
Caller.Add_Test (Suite, "Test Util.Http.Clients." & NAME & ".Post",
Test_Http_Post'Access);
end Add_Tests;
overriding
procedure Set_Up (T : in out Http_Test) is
begin
Test (T).Set_Up;
Register;
end Set_Up;
end Http_Tests;
overriding
procedure Set_Up (T : in out Test) is
begin
Log.Info ("Starting test server");
T.Server := new Test_Server;
T.Server.Start;
end Set_Up;
overriding
procedure Tear_Down (T : in out Test) is
procedure Free is
new Ada.Unchecked_Deallocation (Object => Test_Server'Class,
Name => Test_Server_Access);
begin
if T.Server /= null then
Log.Info ("Stopping test server");
T.Server.Stop;
Free (T.Server);
T.Server := null;
end if;
end Tear_Down;
-- ------------------------------
-- Process the line received by the server.
-- ------------------------------
overriding
procedure Process_Line (Into : in out Test_Server;
Line : in Ada.Strings.Unbounded.Unbounded_String;
Stream : in out Util.Streams.Texts.Reader_Stream'Class;
Client : in out Util.Streams.Sockets.Socket_Stream'Class) is
L : constant String := Ada.Strings.Unbounded.To_String (Line);
Pos : Natural := Util.Strings.Index (L, ' ');
begin
if Pos > 0 and Into.Method = UNKNOWN then
if L (L'First .. Pos - 1) = "GET" then
Into.Method := GET;
elsif L (L'First .. Pos - 1) = "POST" then
Into.Method := POST;
else
Into.Method := UNKNOWN;
end if;
end if;
Pos := Util.Strings.Index (L, ':');
if Pos > 0 then
if L (L'First .. Pos) = "Content-Type:" then
Into.Content_Type
:= Ada.Strings.Unbounded.To_Unbounded_String (L (Pos + 2 .. L'Last - 2));
elsif L (L'First .. Pos) = "Content-Length:" then
Into.Length := Natural'Value (L (Pos + 1 .. L'Last - 2));
end if;
end if;
if L'Length = 2 and then Into.Length > 0 then
for I in 1 .. Into.Length loop
declare
C : Character;
begin
Stream.Read (C);
Ada.Strings.Unbounded.Append (Into.Result, C);
end;
end loop;
declare
Output : Util.Streams.Texts.Print_Stream;
begin
Output.Initialize (Client'Unchecked_Access);
Output.Write ("HTTP/1.1 200 Found" & ASCII.CR & ASCII.LF);
Output.Write ("Content-Length: 4" & ASCII.CR & ASCII.LF);
Output.Write (ASCII.CR & ASCII.LF);
Output.Write ("OK" & ASCII.CR & ASCII.LF);
Output.Flush;
end;
end if;
Log.Info ("Received: {0}", L);
end Process_Line;
-- ------------------------------
-- Get the test server base URI.
-- ------------------------------
function Get_Uri (T : in Test) return String is
begin
return "http://" & T.Server.Get_Host & ":" & Util.Strings.Image (T.Server.Get_Port);
end Get_Uri;
-- ------------------------------
-- Test the http Get operation.
-- ------------------------------
procedure Test_Http_Get (T : in out Test) is
Request : Client;
Reply : Response;
begin
Request.Get ("http://www.google.com", Reply);
T.Assert (Reply.Get_Status = 200 or Reply.Get_Status = 302,
"Get status is invalid: " & Natural'Image (Reply.Get_Status));
Util.Http.Tools.Save_Response (Util.Tests.Get_Test_Path ("http_get.txt"), Reply, True);
-- Check the content.
declare
Content : constant String := Util.Strings.Transforms.To_Lower_Case (Reply.Get_Body);
begin
Util.Tests.Assert_Matches (T, ".*html.*", Content, "Invalid GET content");
end;
-- Check one header.
declare
Content : constant String := Reply.Get_Header ("Content-Type");
begin
T.Assert (Content'Length > 0, "Empty Content-Type header");
Util.Tests.Assert_Matches (T, ".*text/html.*", Content, "Invalid content type");
end;
end Test_Http_Get;
-- ------------------------------
-- Test the http POST operation.
-- ------------------------------
procedure Test_Http_Post (T : in out Test) is
Request : Client;
Reply : Response;
Uri : constant String := T.Get_Uri;
begin
Log.Info ("Post on " & Uri);
T.Server.Method := UNKNOWN;
Request.Post (Uri & "/post",
"p1=1", Reply);
T.Assert (T.Server.Method = POST, "Invalid method received by server");
Util.Tests.Assert_Equals (T, "application/x-www-form-urlencoded", T.Server.Content_Type,
"Invalid content type received by server");
Util.Tests.Assert_Equals (T, "OK" & ASCII.CR & ASCII.LF, Reply.Get_Body, "Invalid response");
Util.Http.Tools.Save_Response (Util.Tests.Get_Test_Path ("http_post.txt"), Reply, True);
end Test_Http_Post;
end Util.Http.Clients.Tests;
|
Update the test to indicate the HTTP response status if an error occurs
|
Update the test to indicate the HTTP response status if an error occurs
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
d75fdae1b92ad9e34a7b8dcd26b749819162cceb
|
awa/plugins/awa-tags/src/awa-tags-beans.ads
|
awa/plugins/awa-tags/src/awa-tags-beans.ads
|
-----------------------------------------------------------------------
-- awa-tags-beans -- Beans for the tags module
-- Copyright (C) 2013 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Ada.Containers.Hashed_Maps;
with Ada.Containers.Ordered_Sets;
with Ada.Finalization;
with Util.Beans.Basic;
with Util.Beans.Objects.Lists;
with Util.Beans.Lists.Strings;
with Util.Strings.Vectors;
with ADO;
with ADO.Utils;
with ADO.Schemas;
with ADO.Sessions;
with AWA.Tags.Models;
with AWA.Tags.Modules;
-- == Tag Beans ==
-- Several bean types are provided to represent and manage a list of tags.
--
-- === Tag_List_Bean ===
-- The <tt>Tag_List_Bean</tt> holds a list of tags and provides operations used by the
-- <tt>awa:tagList</tt> component to add or remove tags within a <tt>h:form</tt> component.
-- A bean can be declared and configured as follows in the XML application configuration file:
--
-- <managed-bean>
-- <managed-bean-name>questionTags</managed-bean-name>
-- <managed-bean-class>AWA.Tags.Beans.Tag_List_Bean</managed-bean-class>
-- <managed-bean-scope>request</managed-bean-scope>
-- <managed-property>
-- <property-name>entity_type</property-name>
-- <property-class>String</property-class>
-- <value>Awa_Question</value>
-- </managed-property>
-- <managed-property>
-- <property-name>permission</property-name>
-- <property-class>String</property-class>
-- <value>question-edit</value>
-- </managed-property>
-- </managed-bean>
--
-- The <tt>entity_type</tt> property defines the name of the database table to which the tags
-- are assigned. The <tt>permission</tt> property defines the permission name that must be used
-- to verify that the user has the permission do add or remove the tag. Such permission is
-- verified only when the <tt>awa:tagList</tt> component is used within a form.
--
-- === Tag_Search_Bean ===
-- The <tt>Tag_Search_Bean</tt> is dedicated to searching for tags that start with a given
-- pattern. The auto complete feature of the <tt>awa:tagList</tt> component can use this
-- bean type to look in the database for tags matching a start pattern. The declaration of the
-- bean should define the database table to search for tags associated with a given database
-- table. This is done in the XML configuration with the <tt>entity_type</tt> property.
--
-- <managed-bean>
-- <managed-bean-name>questionTagSearch</managed-bean-name>
-- <managed-bean-class>AWA.Tags.Beans.Tag_Search_Bean</managed-bean-class>
-- <managed-bean-scope>request</managed-bean-scope>
-- <managed-property>
-- <property-name>entity_type</property-name>
-- <property-class>String</property-class>
-- <value>awa_question</value>
-- </managed-property>
-- </managed-bean>
--
-- === Tag_Info_List_Bean ===
-- The <tt>Tag_Info_List_Bean</tt> holds a collection of tags with their weight. It is used
-- by the <tt>awa:tagCloud</tt> component.
--
-- <managed-bean>
-- <managed-bean-name>questionTagList</managed-bean-name>
-- <managed-bean-class>AWA.Tags.Beans.Tag_Info_List_Bean</managed-bean-class>
-- <managed-bean-scope>request</managed-bean-scope>
-- <managed-property>
-- <property-name>entity_type</property-name>
-- <property-class>String</property-class>
-- <value>awa_question</value>
-- </managed-property>
-- </managed-bean>
--
package AWA.Tags.Beans is
-- Compare two tags on their count and name.
function "<" (Left, Right : in AWA.Tags.Models.Tag_Info) return Boolean;
package Tag_Ordered_Sets is
new Ada.Containers.Ordered_Sets (Element_Type => AWA.Tags.Models.Tag_Info,
"=" => AWA.Tags.Models."=");
type Tag_List_Bean is
new Util.Beans.Objects.Lists.List_Bean and Util.Beans.Basic.Bean with private;
type Tag_List_Bean_Access is access all Tag_List_Bean'Class;
-- Set the value identified by the name.
-- If the name cannot be found, the method should raise the No_Value
-- exception.
overriding
procedure Set_Value (From : in out Tag_List_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object);
-- Set the entity type (database table) onto which the tags are associated.
procedure Set_Entity_Type (Into : in out Tag_List_Bean;
Table : in ADO.Schemas.Class_Mapping_Access);
-- Set the permission to check before removing or adding a tag on the entity.
procedure Set_Permission (Into : in out Tag_List_Bean;
Permission : in String);
-- Load the tags associated with the given database identifier.
procedure Load_Tags (Into : in out Tag_List_Bean;
Session : in ADO.Sessions.Session;
For_Entity_Id : in ADO.Identifier);
-- Set the list of tags to add.
procedure Set_Added (Into : in out Tag_List_Bean;
Tags : in Util.Strings.Vectors.Vector);
-- Set the list of tags to remove.
procedure Set_Deleted (Into : in out Tag_List_Bean;
Tags : in Util.Strings.Vectors.Vector);
-- Update the tags associated with the tag entity represented by <tt>For_Entity_Id</tt>.
-- The list of tags defined by <tt>Set_Deleted</tt> are removed first and the list of
-- tags defined by <tt>Set_Added</tt> are associated with the database entity.
procedure Update_Tags (From : in Tag_List_Bean;
For_Entity_Id : in ADO.Identifier);
-- Create the tag list bean instance.
function Create_Tag_List_Bean (Module : in AWA.Tags.Modules.Tag_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access;
type Tag_Search_Bean is
new Util.Beans.Objects.Lists.List_Bean and Util.Beans.Basic.Bean with private;
type Tag_Search_Bean_Access is access all Tag_Search_Bean'Class;
-- Set the value identified by the name.
-- If the name cannot be found, the method should raise the No_Value
-- exception.
overriding
procedure Set_Value (From : in out Tag_Search_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object);
-- Search the tags that match the search string.
procedure Search_Tags (Into : in out Tag_Search_Bean;
Session : in ADO.Sessions.Session;
Search : in String);
-- Set the entity type (database table) onto which the tags are associated.
procedure Set_Entity_Type (Into : in out Tag_Search_Bean;
Table : in ADO.Schemas.Class_Mapping_Access);
-- Create the tag search bean instance.
function Create_Tag_Search_Bean (Module : in AWA.Tags.Modules.Tag_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access;
type Tag_Info_List_Bean is
new AWA.Tags.Models.Tag_Info_List_Bean and Util.Beans.Basic.Bean with private;
type Tag_Info_List_Bean_Access is access all Tag_Info_List_Bean'Class;
-- Set the value identified by the name.
-- If the name cannot be found, the method should raise the No_Value
-- exception.
overriding
procedure Set_Value (From : in out Tag_Info_List_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object);
-- Load the list of tags.
procedure Load_Tags (Into : in out Tag_Info_List_Bean;
Session : in out ADO.Sessions.Session);
-- Create the tag info list bean instance.
function Create_Tag_Info_List_Bean (Module : in AWA.Tags.Modules.Tag_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access;
-- The <tt>Entity_Tag_Map</tt> contains a list of tags associated with some entities.
-- It allows to retrieve from the database all the tags associated with several entities
-- and get the list of tags for a given entity.
type Entity_Tag_Map is new Ada.Finalization.Limited_Controlled with private;
-- Get the list of tags associated with the given entity.
-- Returns null if the entity does not have any tag.
function Get_Tags (From : in Entity_Tag_Map;
For_Entity : in ADO.Identifier)
return Util.Beans.Lists.Strings.List_Bean_Access;
-- Get the list of tags associated with the given entity.
-- Returns a null object if the entity does not have any tag.
function Get_Tags (From : in Entity_Tag_Map;
For_Entity : in ADO.Identifier)
return Util.Beans.Objects.Object;
-- Release the list of tags.
procedure Clear (List : in out Entity_Tag_Map);
-- Load the list of tags associated with a list of entities.
procedure Load_Tags (Into : in out Entity_Tag_Map;
Session : in out ADO.Sessions.Session'Class;
Entity_Type : in String;
List : in ADO.Utils.Identifier_Vector);
-- Release the list of tags.
overriding
procedure Finalize (List : in out Entity_Tag_Map);
private
type Tag_List_Bean is
new Util.Beans.Objects.Lists.List_Bean and Util.Beans.Basic.Bean with record
Module : AWA.Tags.Modules.Tag_Module_Access;
Entity_Type : Ada.Strings.Unbounded.Unbounded_String;
Permission : Ada.Strings.Unbounded.Unbounded_String;
Current : Natural := 0;
Added : Util.Strings.Vectors.Vector;
Deleted : Util.Strings.Vectors.Vector;
end record;
type Tag_Search_Bean is
new Util.Beans.Objects.Lists.List_Bean and Util.Beans.Basic.Bean with record
Module : AWA.Tags.Modules.Tag_Module_Access;
Entity_Type : Ada.Strings.Unbounded.Unbounded_String;
end record;
type Tag_Info_List_Bean is
new AWA.Tags.Models.Tag_Info_List_Bean and Util.Beans.Basic.Bean with record
Module : AWA.Tags.Modules.Tag_Module_Access;
Entity_Type : Ada.Strings.Unbounded.Unbounded_String;
end record;
package Entity_Tag_Maps is
new Ada.Containers.Hashed_Maps (Key_Type => ADO.Identifier,
Element_Type => Util.Beans.Lists.Strings.List_Bean_Access,
Hash => ADO.Utils.Hash,
Equivalent_Keys => ADO."=",
"=" => Util.Beans.Lists.Strings."=");
type Entity_Tag_Map is new Ada.Finalization.Limited_Controlled with record
Tags : Entity_Tag_Maps.Map;
end record;
end AWA.Tags.Beans;
|
-----------------------------------------------------------------------
-- awa-tags-beans -- Beans for the tags module
-- Copyright (C) 2013 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Ada.Containers.Hashed_Maps;
with Ada.Containers.Ordered_Sets;
with Ada.Finalization;
with Util.Beans.Basic;
with Util.Beans.Objects.Lists;
with Util.Beans.Lists.Strings;
with Util.Strings.Vectors;
with ADO;
with ADO.Utils;
with ADO.Schemas;
with ADO.Sessions;
with AWA.Tags.Models;
with AWA.Tags.Modules;
-- == Tag Beans ==
-- Several bean types are provided to represent and manage a list of tags.
-- The tag module registers the bean constructors when it is initialized.
-- To use them, one must declare a bean definition in the application XML configuration.
--
-- === Tag_List_Bean ===
-- The <tt>Tag_List_Bean</tt> holds a list of tags and provides operations used by the
-- <tt>awa:tagList</tt> component to add or remove tags within a <tt>h:form</tt> component.
-- A bean can be declared and configured as follows in the XML application configuration file:
--
-- <managed-bean>
-- <managed-bean-name>questionTags</managed-bean-name>
-- <managed-bean-class>AWA.Tags.Beans.Tag_List_Bean</managed-bean-class>
-- <managed-bean-scope>request</managed-bean-scope>
-- <managed-property>
-- <property-name>entity_type</property-name>
-- <property-class>String</property-class>
-- <value>awa_question</value>
-- </managed-property>
-- <managed-property>
-- <property-name>permission</property-name>
-- <property-class>String</property-class>
-- <value>question-edit</value>
-- </managed-property>
-- </managed-bean>
--
-- The <tt>entity_type</tt> property defines the name of the database table to which the tags
-- are assigned. The <tt>permission</tt> property defines the permission name that must be used
-- to verify that the user has the permission do add or remove the tag. Such permission is
-- verified only when the <tt>awa:tagList</tt> component is used within a form.
--
-- === Tag_Search_Bean ===
-- The <tt>Tag_Search_Bean</tt> is dedicated to searching for tags that start with a given
-- pattern. The auto complete feature of the <tt>awa:tagList</tt> component can use this
-- bean type to look in the database for tags matching a start pattern. The declaration of the
-- bean should define the database table to search for tags associated with a given database
-- table. This is done in the XML configuration with the <tt>entity_type</tt> property.
--
-- <managed-bean>
-- <managed-bean-name>questionTagSearch</managed-bean-name>
-- <managed-bean-class>AWA.Tags.Beans.Tag_Search_Bean</managed-bean-class>
-- <managed-bean-scope>request</managed-bean-scope>
-- <managed-property>
-- <property-name>entity_type</property-name>
-- <property-class>String</property-class>
-- <value>awa_question</value>
-- </managed-property>
-- </managed-bean>
--
-- === Tag_Info_List_Bean ===
-- The <tt>Tag_Info_List_Bean</tt> holds a collection of tags with their weight. It is used
-- by the <tt>awa:tagCloud</tt> component.
--
-- <managed-bean>
-- <managed-bean-name>questionTagList</managed-bean-name>
-- <managed-bean-class>AWA.Tags.Beans.Tag_Info_List_Bean</managed-bean-class>
-- <managed-bean-scope>request</managed-bean-scope>
-- <managed-property>
-- <property-name>entity_type</property-name>
-- <property-class>String</property-class>
-- <value>awa_question</value>
-- </managed-property>
-- </managed-bean>
--
package AWA.Tags.Beans is
-- Compare two tags on their count and name.
function "<" (Left, Right : in AWA.Tags.Models.Tag_Info) return Boolean;
package Tag_Ordered_Sets is
new Ada.Containers.Ordered_Sets (Element_Type => AWA.Tags.Models.Tag_Info,
"=" => AWA.Tags.Models."=");
type Tag_List_Bean is
new Util.Beans.Objects.Lists.List_Bean and Util.Beans.Basic.Bean with private;
type Tag_List_Bean_Access is access all Tag_List_Bean'Class;
-- Set the value identified by the name.
-- If the name cannot be found, the method should raise the No_Value
-- exception.
overriding
procedure Set_Value (From : in out Tag_List_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object);
-- Set the entity type (database table) onto which the tags are associated.
procedure Set_Entity_Type (Into : in out Tag_List_Bean;
Table : in ADO.Schemas.Class_Mapping_Access);
-- Set the permission to check before removing or adding a tag on the entity.
procedure Set_Permission (Into : in out Tag_List_Bean;
Permission : in String);
-- Load the tags associated with the given database identifier.
procedure Load_Tags (Into : in out Tag_List_Bean;
Session : in ADO.Sessions.Session;
For_Entity_Id : in ADO.Identifier);
-- Set the list of tags to add.
procedure Set_Added (Into : in out Tag_List_Bean;
Tags : in Util.Strings.Vectors.Vector);
-- Set the list of tags to remove.
procedure Set_Deleted (Into : in out Tag_List_Bean;
Tags : in Util.Strings.Vectors.Vector);
-- Update the tags associated with the tag entity represented by <tt>For_Entity_Id</tt>.
-- The list of tags defined by <tt>Set_Deleted</tt> are removed first and the list of
-- tags defined by <tt>Set_Added</tt> are associated with the database entity.
procedure Update_Tags (From : in Tag_List_Bean;
For_Entity_Id : in ADO.Identifier);
-- Create the tag list bean instance.
function Create_Tag_List_Bean (Module : in AWA.Tags.Modules.Tag_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access;
type Tag_Search_Bean is
new Util.Beans.Objects.Lists.List_Bean and Util.Beans.Basic.Bean with private;
type Tag_Search_Bean_Access is access all Tag_Search_Bean'Class;
-- Set the value identified by the name.
-- If the name cannot be found, the method should raise the No_Value
-- exception.
overriding
procedure Set_Value (From : in out Tag_Search_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object);
-- Search the tags that match the search string.
procedure Search_Tags (Into : in out Tag_Search_Bean;
Session : in ADO.Sessions.Session;
Search : in String);
-- Set the entity type (database table) onto which the tags are associated.
procedure Set_Entity_Type (Into : in out Tag_Search_Bean;
Table : in ADO.Schemas.Class_Mapping_Access);
-- Create the tag search bean instance.
function Create_Tag_Search_Bean (Module : in AWA.Tags.Modules.Tag_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access;
type Tag_Info_List_Bean is
new AWA.Tags.Models.Tag_Info_List_Bean and Util.Beans.Basic.Bean with private;
type Tag_Info_List_Bean_Access is access all Tag_Info_List_Bean'Class;
-- Set the value identified by the name.
-- If the name cannot be found, the method should raise the No_Value
-- exception.
overriding
procedure Set_Value (From : in out Tag_Info_List_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object);
-- Load the list of tags.
procedure Load_Tags (Into : in out Tag_Info_List_Bean;
Session : in out ADO.Sessions.Session);
-- Create the tag info list bean instance.
function Create_Tag_Info_List_Bean (Module : in AWA.Tags.Modules.Tag_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access;
-- The <tt>Entity_Tag_Map</tt> contains a list of tags associated with some entities.
-- It allows to retrieve from the database all the tags associated with several entities
-- and get the list of tags for a given entity.
type Entity_Tag_Map is new Ada.Finalization.Limited_Controlled with private;
-- Get the list of tags associated with the given entity.
-- Returns null if the entity does not have any tag.
function Get_Tags (From : in Entity_Tag_Map;
For_Entity : in ADO.Identifier)
return Util.Beans.Lists.Strings.List_Bean_Access;
-- Get the list of tags associated with the given entity.
-- Returns a null object if the entity does not have any tag.
function Get_Tags (From : in Entity_Tag_Map;
For_Entity : in ADO.Identifier)
return Util.Beans.Objects.Object;
-- Release the list of tags.
procedure Clear (List : in out Entity_Tag_Map);
-- Load the list of tags associated with a list of entities.
procedure Load_Tags (Into : in out Entity_Tag_Map;
Session : in out ADO.Sessions.Session'Class;
Entity_Type : in String;
List : in ADO.Utils.Identifier_Vector);
-- Release the list of tags.
overriding
procedure Finalize (List : in out Entity_Tag_Map);
private
type Tag_List_Bean is
new Util.Beans.Objects.Lists.List_Bean and Util.Beans.Basic.Bean with record
Module : AWA.Tags.Modules.Tag_Module_Access;
Entity_Type : Ada.Strings.Unbounded.Unbounded_String;
Permission : Ada.Strings.Unbounded.Unbounded_String;
Current : Natural := 0;
Added : Util.Strings.Vectors.Vector;
Deleted : Util.Strings.Vectors.Vector;
end record;
type Tag_Search_Bean is
new Util.Beans.Objects.Lists.List_Bean and Util.Beans.Basic.Bean with record
Module : AWA.Tags.Modules.Tag_Module_Access;
Entity_Type : Ada.Strings.Unbounded.Unbounded_String;
end record;
type Tag_Info_List_Bean is
new AWA.Tags.Models.Tag_Info_List_Bean and Util.Beans.Basic.Bean with record
Module : AWA.Tags.Modules.Tag_Module_Access;
Entity_Type : Ada.Strings.Unbounded.Unbounded_String;
end record;
package Entity_Tag_Maps is
new Ada.Containers.Hashed_Maps (Key_Type => ADO.Identifier,
Element_Type => Util.Beans.Lists.Strings.List_Bean_Access,
Hash => ADO.Utils.Hash,
Equivalent_Keys => ADO."=",
"=" => Util.Beans.Lists.Strings."=");
type Entity_Tag_Map is new Ada.Finalization.Limited_Controlled with record
Tags : Entity_Tag_Maps.Map;
end record;
end AWA.Tags.Beans;
|
Fix comments and documentation
|
Fix comments and documentation
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
94f9f76533a85434765936a13630b7d1643ec704
|
regtests/util-streams-buffered-encoders-tests.adb
|
regtests/util-streams-buffered-encoders-tests.adb
|
-----------------------------------------------------------------------
-- util-streams-buffered-encoders-tests -- Unit tests for encoding buffered streams
-- Copyright (C) 2017, 2018 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Test_Caller;
with Util.Streams.Files;
with Util.Streams.Texts;
with Ada.Streams.Stream_IO;
package body Util.Streams.Buffered.Encoders.Tests is
use Util.Tests;
use Util.Streams.Files;
use Ada.Streams.Stream_IO;
package Caller is new Util.Test_Caller (Test, "Streams.Buffered.Encoders");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test Util.Streams.Buffered.Encoders.Write, Read",
Test_Base64_Stream'Access);
end Add_Tests;
procedure Test_Base64_Stream (T : in out Test) is
Stream : aliased File_Stream;
Buffer : aliased Util.Streams.Buffered.Encoders.Encoding_Stream;
Print : Util.Streams.Texts.Print_Stream;
Path : constant String := Util.Tests.Get_Test_Path ("regtests/result/test-stream.b64");
Expect : constant String := Util.Tests.Get_Path ("regtests/expect/test-stream.b64");
begin
Print.Initialize (Output => Buffer'Unchecked_Access, Size => 5);
Buffer.Initialize (Output => Stream'Unchecked_Access,
Size => 1024,
Format => Util.Encoders.BASE_64);
Stream.Create (Mode => Out_File, Name => Path);
for I in 1 .. 32 loop
Print.Write ("abcd");
Print.Write (" fghij");
Print.Write (ASCII.LF);
end loop;
Print.Flush;
Stream.Close;
Util.Tests.Assert_Equal_Files (T => T,
Expect => Expect,
Test => Path,
Message => "Base64 stream");
end Test_Base64_Stream;
end Util.Streams.Buffered.Encoders.Tests;
|
-----------------------------------------------------------------------
-- util-streams-buffered-encoders-tests -- Unit tests for encoding buffered streams
-- Copyright (C) 2017, 2018 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Test_Caller;
with Util.Streams.Files;
with Util.Streams.Texts;
with Ada.Streams.Stream_IO;
package body Util.Streams.Buffered.Encoders.Tests is
use Util.Streams.Files;
use Ada.Streams.Stream_IO;
package Caller is new Util.Test_Caller (Test, "Streams.Buffered.Encoders");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test Util.Streams.Buffered.Encoders.Write, Read",
Test_Base64_Stream'Access);
end Add_Tests;
procedure Test_Base64_Stream (T : in out Test) is
Stream : aliased File_Stream;
Buffer : aliased Util.Streams.Buffered.Encoders.Encoding_Stream;
Print : Util.Streams.Texts.Print_Stream;
Path : constant String := Util.Tests.Get_Test_Path ("regtests/result/test-stream.b64");
Expect : constant String := Util.Tests.Get_Path ("regtests/expect/test-stream.b64");
begin
Print.Initialize (Output => Buffer'Unchecked_Access, Size => 5);
Buffer.Initialize (Output => Stream'Unchecked_Access,
Size => 1024,
Format => Util.Encoders.BASE_64);
Stream.Create (Mode => Out_File, Name => Path);
for I in 1 .. 32 loop
Print.Write ("abcd");
Print.Write (" fghij");
Print.Write (ASCII.LF);
end loop;
Print.Flush;
Stream.Close;
Util.Tests.Assert_Equal_Files (T => T,
Expect => Expect,
Test => Path,
Message => "Base64 stream");
end Test_Base64_Stream;
end Util.Streams.Buffered.Encoders.Tests;
|
Remove unused use Util.Tests clause
|
Remove unused use Util.Tests clause
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
d1e2ebad54a05b31906c25f1a6d0010b932452a6
|
jack-port.ads
|
jack-port.ads
|
with Jack.Client;
with System;
package Jack.Port is
--
-- API
--
-- proc_map : jack_port_get_buffer
function Buffer_Address
(Port : in Client.Port_t;
Number_Of_Frames : in Client.Number_Of_Frames_t) return System.Address;
-- proc_map : jack_port_connected
function Connected (Port : in Client.Port_t) return Boolean;
-- proc_map : jack_port_connected_to
function Connected_To
(Port : in Client.Port_t;
Port_Name : in Client.Port_Name_t) return Boolean;
-- proc_map : jack_port_flags
function Flags
(Port : in Client.Port_t) return Client.Port_Flags_t;
-- proc_map : jack_port_type
function Get_Type
(Port : in Client.Port_t) return Client.Port_Type_t;
-- proc_map : jack_get_latency
function Latency
(Port : in Client.Port_t) return Client.Number_Of_Frames_t;
-- proc_map : jack_port_name
function Name
(Port : in Client.Port_t) return Client.Port_Name_t;
-- proc_map : jack_port_short_name
function Short_Name
(Port : in Client.Port_t) return Client.Port_Name_t;
end Jack.Port;
|
with Jack.Client;
with System;
package Jack.Port is
--
-- API
--
-- proc_map : jack_port_get_buffer
function Buffer_Address
(Port : in Client.Port_t;
Number_Of_Frames : in Client.Number_Of_Frames_t) return System.Address;
-- proc_map : jack_port_connected
function Connected (Port : in Client.Port_t) return Boolean;
-- proc_map : jack_port_connected_to
function Connected_To
(Port : in Client.Port_t;
Port_Name : in Client.Port_Name_t) return Boolean;
-- proc_map : jack_port_flags
function Flags
(Port : in Client.Port_t) return Client.Port_Flags_t;
-- proc_map : jack_port_type
function Get_Type
(Port : in Client.Port_t) return Client.Port_Type_t;
-- proc_map : jack_port_get_latency
function Latency
(Port : in Client.Port_t) return Client.Number_Of_Frames_t;
-- proc_map : jack_port_name
function Name
(Port : in Client.Port_t) return Client.Port_Name_t;
-- proc_map : jack_port_short_name
function Short_Name
(Port : in Client.Port_t) return Client.Port_Name_t;
end Jack.Port;
|
Fix proc_map
|
Fix proc_map
|
Ada
|
isc
|
io7m/coreland-jack-ada,io7m/coreland-jack-ada
|
97b31a73709cb03aea0420b28ec4507688972fb6
|
src/asf-routes-servlets-faces.ads
|
src/asf-routes-servlets-faces.ads
|
-----------------------------------------------------------------------
-- asf-routes-servlets-faces -- faces request routing
-- Copyright (C) 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Finalization;
with Ada.Strings.Unbounded;
with ASF.Filters;
with ASF.Servlets;
package ASF.Routes.Servlets.Faces is
type Faces_Route_Type is new Servlet_Route_Type with record
View : Ada.Strings.Unbounded.Unbounded_String;
end record;
type Faces_Route_Type_Access is access all Faces_Route_Type'Class;
-- Release the storage held by the route.
-- overriding
-- procedure Finalize (Route : in out Servlet_Route_Type);
end ASF.Routes.Servlets.Faces;
|
-----------------------------------------------------------------------
-- asf-routes-servlets-faces -- faces request routing
-- Copyright (C) 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
package ASF.Routes.Servlets.Faces is
type Faces_Route_Type is new Servlet_Route_Type with record
View : Ada.Strings.Unbounded.Unbounded_String;
end record;
type Faces_Route_Type_Access is access all Faces_Route_Type'Class;
end ASF.Routes.Servlets.Faces;
|
Remove unused with clauses
|
Remove unused with clauses
|
Ada
|
apache-2.0
|
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
|
df3d9e267ce9b2a5f5b1039bd061821c96bf2eb4
|
matp/src/mat-expressions.ads
|
matp/src/mat-expressions.ads
|
-----------------------------------------------------------------------
-- mat-expressions -- Expressions for event and memory slot selection
-- Copyright (C) 2014, 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Ada.Finalization;
private with Util.Concurrent.Counters;
with MAT.Types;
with MAT.Memory;
with MAT.Events.Targets;
package MAT.Expressions is
type Context_Type is record
Addr : MAT.Types.Target_Addr;
Allocation : MAT.Memory.Allocation;
end record;
type Inside_Type is (INSIDE_FILE,
INSIDE_DIRECT_FILE,
INSIDE_FUNCTION,
INSIDE_DIRECT_FUNCTION);
type Expression_Type is tagged private;
-- Create a NOT expression node.
function Create_Not (Expr : in Expression_Type) return Expression_Type;
-- Create a AND expression node.
function Create_And (Left : in Expression_Type;
Right : in Expression_Type) return Expression_Type;
-- Create a OR expression node.
function Create_Or (Left : in Expression_Type;
Right : in Expression_Type) return Expression_Type;
-- Create an INSIDE expression node.
function Create_Inside (Name : in Ada.Strings.Unbounded.Unbounded_String;
Kind : in Inside_Type) return Expression_Type;
-- Create an size range expression node.
function Create_Size (Min : in MAT.Types.Target_Size;
Max : in MAT.Types.Target_Size) return Expression_Type;
-- Create an addr range expression node.
function Create_Addr (Min : in MAT.Types.Target_Addr;
Max : in MAT.Types.Target_Addr) return Expression_Type;
-- Create an time range expression node.
function Create_Time (Min : in MAT.Types.Target_Tick_Ref;
Max : in MAT.Types.Target_Tick_Ref) return Expression_Type;
-- Create an event ID range expression node.
function Create_Event (Min : in MAT.Events.Targets.Event_Id_Type;
Max : in MAT.Events.Targets.Event_Id_Type) return Expression_Type;
-- Create a thread ID range expression node.
function Create_Thread (Min : in MAT.Types.Target_Thread_Ref;
Max : in MAT.Types.Target_Thread_Ref) return Expression_Type;
-- Create a event type expression check.
function Create_Event_Type (Event_Kind : in MAT.Events.Targets.Probe_Index_Type)
return Expression_Type;
-- Evaluate the expression to check if the memory slot described by the
-- context is selected. Returns True if the memory slot is selected.
function Is_Selected (Node : in Expression_Type;
Addr : in MAT.Types.Target_Addr;
Allocation : in MAT.Memory.Allocation) return Boolean;
-- Evaluate the expression to check if the event described by the
-- context is selected. Returns True if the event is selected.
function Is_Selected (Node : in Expression_Type;
Event : in MAT.Events.Targets.Probe_Event_Type) return Boolean;
-- Parse the string and return the expression tree.
function Parse (Expr : in String) return Expression_Type;
-- Empty expression.
EMPTY : constant Expression_Type;
type yystype is record
low : MAT.Types.Uint64 := 0;
high : MAT.Types.Uint64 := 0;
bval : Boolean := False;
name : Ada.Strings.Unbounded.Unbounded_String;
expr : Expression_Type;
end record;
private
type Kind_Type is (N_NOT, N_OR, N_AND, N_TRUE, N_FALSE,
N_IN_FILE, N_IN_FILE_DIRECT, N_INSIDE,
N_CALL_ADDR, N_CALL_ADDR_DIRECT,
N_IN_FUNC, N_IN_FUNC_DIRECT,
N_RANGE_SIZE, N_RANGE_ADDR,
N_RANGE_TIME, N_EVENT, N_HAS_ADDR,
N_CONDITION, N_THREAD, N_TYPE, N_NO_FREE);
type Node_Type;
type Node_Type_Access is access all Node_Type;
type Node_Type (Kind : Kind_Type) is record
Ref_Counter : Util.Concurrent.Counters.Counter;
case Kind is
when N_NOT =>
Expr : Node_Type_Access;
when N_OR | N_AND =>
Left, Right : Node_Type_Access;
when N_INSIDE | N_IN_FILE | N_IN_FILE_DIRECT | N_IN_FUNC | N_IN_FUNC_DIRECT =>
Name : Ada.Strings.Unbounded.Unbounded_String;
Inside : Inside_Type;
when N_RANGE_SIZE =>
Min_Size : MAT.Types.Target_Size;
Max_Size : MAT.Types.Target_Size;
when N_RANGE_ADDR | N_CALL_ADDR | N_CALL_ADDR_DIRECT | N_HAS_ADDR =>
Min_Addr : MAT.Types.Target_Addr;
Max_Addr : MAT.Types.Target_Addr;
when N_RANGE_TIME =>
Min_Time : MAT.Types.Target_Tick_Ref;
Max_Time : MAT.Types.Target_Tick_Ref;
when N_THREAD =>
Min_Thread : MAT.Types.Target_Thread_Ref;
Max_Thread : MAT.Types.Target_Thread_Ref;
when N_EVENT =>
Min_Event : MAT.Events.Targets.Event_Id_Type;
Max_Event : MAT.Events.Targets.Event_Id_Type;
when N_TYPE =>
Event_Kind : MAT.Events.Targets.Probe_Index_Type;
when others =>
null;
end case;
end record;
-- Evaluate the node against the context. Returns True if the node expression
-- selects the memory slot defined by the context.
function Is_Selected (Node : in Node_Type;
Addr : in MAT.Types.Target_Addr;
Allocation : in MAT.Memory.Allocation) return Boolean;
-- Evaluate the expression to check if the event described by the
-- context is selected. Returns True if the event is selected.
function Is_Selected (Node : in Node_Type;
Event : in MAT.Events.Targets.Probe_Event_Type) return Boolean;
type Expression_Type is new Ada.Finalization.Controlled with record
Node : Node_Type_Access;
end record;
-- Release the reference and destroy the expression tree if it was the last reference.
overriding
procedure Finalize (Obj : in out Expression_Type);
-- Update the reference after an assignment.
overriding
procedure Adjust (Obj : in out Expression_Type);
-- Empty expression.
EMPTY : constant Expression_Type := Expression_Type'(Ada.Finalization.Controlled with
Node => null);
end MAT.Expressions;
|
-----------------------------------------------------------------------
-- mat-expressions -- Expressions for event and memory slot selection
-- Copyright (C) 2014, 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Ada.Finalization;
private with Util.Concurrent.Counters;
with MAT.Types;
with MAT.Memory;
with MAT.Events.Targets;
package MAT.Expressions is
type Context_Type is record
Addr : MAT.Types.Target_Addr;
Allocation : MAT.Memory.Allocation;
end record;
type Inside_Type is (INSIDE_FILE,
INSIDE_DIRECT_FILE,
INSIDE_FUNCTION,
INSIDE_DIRECT_FUNCTION);
type Expression_Type is tagged private;
-- Create a NOT expression node.
function Create_Not (Expr : in Expression_Type) return Expression_Type;
-- Create a AND expression node.
function Create_And (Left : in Expression_Type;
Right : in Expression_Type) return Expression_Type;
-- Create a OR expression node.
function Create_Or (Left : in Expression_Type;
Right : in Expression_Type) return Expression_Type;
-- Create an INSIDE expression node.
function Create_Inside (Name : in Ada.Strings.Unbounded.Unbounded_String;
Kind : in Inside_Type) return Expression_Type;
-- Create an size range expression node.
function Create_Size (Min : in MAT.Types.Target_Size;
Max : in MAT.Types.Target_Size) return Expression_Type;
-- Create an addr range expression node.
function Create_Addr (Min : in MAT.Types.Target_Addr;
Max : in MAT.Types.Target_Addr) return Expression_Type;
-- Create an time range expression node.
function Create_Time (Min : in MAT.Types.Target_Tick_Ref;
Max : in MAT.Types.Target_Tick_Ref) return Expression_Type;
-- Create an event ID range expression node.
function Create_Event (Min : in MAT.Events.Targets.Event_Id_Type;
Max : in MAT.Events.Targets.Event_Id_Type) return Expression_Type;
-- Create a thread ID range expression node.
function Create_Thread (Min : in MAT.Types.Target_Thread_Ref;
Max : in MAT.Types.Target_Thread_Ref) return Expression_Type;
-- Create a event type expression check.
function Create_Event_Type (Event_Kind : in MAT.Events.Targets.Probe_Index_Type)
return Expression_Type;
-- Create an expression node to keep allocation events which don't have any associated free.
function Create_No_Free return Expression_Type;
-- Evaluate the expression to check if the memory slot described by the
-- context is selected. Returns True if the memory slot is selected.
function Is_Selected (Node : in Expression_Type;
Addr : in MAT.Types.Target_Addr;
Allocation : in MAT.Memory.Allocation) return Boolean;
-- Evaluate the expression to check if the event described by the
-- context is selected. Returns True if the event is selected.
function Is_Selected (Node : in Expression_Type;
Event : in MAT.Events.Targets.Probe_Event_Type) return Boolean;
-- Parse the string and return the expression tree.
function Parse (Expr : in String) return Expression_Type;
-- Empty expression.
EMPTY : constant Expression_Type;
type yystype is record
low : MAT.Types.Uint64 := 0;
high : MAT.Types.Uint64 := 0;
bval : Boolean := False;
name : Ada.Strings.Unbounded.Unbounded_String;
expr : Expression_Type;
end record;
private
type Kind_Type is (N_NOT, N_OR, N_AND, N_TRUE, N_FALSE,
N_IN_FILE, N_IN_FILE_DIRECT, N_INSIDE,
N_CALL_ADDR, N_CALL_ADDR_DIRECT,
N_IN_FUNC, N_IN_FUNC_DIRECT,
N_RANGE_SIZE, N_RANGE_ADDR,
N_RANGE_TIME, N_EVENT, N_HAS_ADDR,
N_CONDITION, N_THREAD, N_TYPE, N_NO_FREE);
type Node_Type;
type Node_Type_Access is access all Node_Type;
type Node_Type (Kind : Kind_Type) is record
Ref_Counter : Util.Concurrent.Counters.Counter;
case Kind is
when N_NOT =>
Expr : Node_Type_Access;
when N_OR | N_AND =>
Left, Right : Node_Type_Access;
when N_INSIDE | N_IN_FILE | N_IN_FILE_DIRECT | N_IN_FUNC | N_IN_FUNC_DIRECT =>
Name : Ada.Strings.Unbounded.Unbounded_String;
Inside : Inside_Type;
when N_RANGE_SIZE =>
Min_Size : MAT.Types.Target_Size;
Max_Size : MAT.Types.Target_Size;
when N_RANGE_ADDR | N_CALL_ADDR | N_CALL_ADDR_DIRECT | N_HAS_ADDR =>
Min_Addr : MAT.Types.Target_Addr;
Max_Addr : MAT.Types.Target_Addr;
when N_RANGE_TIME =>
Min_Time : MAT.Types.Target_Tick_Ref;
Max_Time : MAT.Types.Target_Tick_Ref;
when N_THREAD =>
Min_Thread : MAT.Types.Target_Thread_Ref;
Max_Thread : MAT.Types.Target_Thread_Ref;
when N_EVENT =>
Min_Event : MAT.Events.Targets.Event_Id_Type;
Max_Event : MAT.Events.Targets.Event_Id_Type;
when N_TYPE =>
Event_Kind : MAT.Events.Targets.Probe_Index_Type;
when others =>
null;
end case;
end record;
-- Evaluate the node against the context. Returns True if the node expression
-- selects the memory slot defined by the context.
function Is_Selected (Node : in Node_Type;
Addr : in MAT.Types.Target_Addr;
Allocation : in MAT.Memory.Allocation) return Boolean;
-- Evaluate the expression to check if the event described by the
-- context is selected. Returns True if the event is selected.
function Is_Selected (Node : in Node_Type;
Event : in MAT.Events.Targets.Probe_Event_Type) return Boolean;
type Expression_Type is new Ada.Finalization.Controlled with record
Node : Node_Type_Access;
end record;
-- Release the reference and destroy the expression tree if it was the last reference.
overriding
procedure Finalize (Obj : in out Expression_Type);
-- Update the reference after an assignment.
overriding
procedure Adjust (Obj : in out Expression_Type);
-- Empty expression.
EMPTY : constant Expression_Type := Expression_Type'(Ada.Finalization.Controlled with
Node => null);
end MAT.Expressions;
|
Declare the Create_No_Free function
|
Declare the Create_No_Free function
|
Ada
|
apache-2.0
|
stcarrez/mat,stcarrez/mat,stcarrez/mat
|
a0c4e8eb50dbe6f7e78007cc4afcd17077ef4d4d
|
awa/plugins/awa-wikis/regtests/awa-wikis-modules-tests.adb
|
awa/plugins/awa-wikis/regtests/awa-wikis-modules-tests.adb
|
-----------------------------------------------------------------------
-- awa-wikis-modules-tests -- Unit tests for wikis service
-- Copyright (C) 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Test_Caller;
with Util.Strings;
with ASF.Tests;
with ASF.Requests.Mockup;
with ASF.Responses.Mockup;
with AWA.Tests.Helpers;
with AWA.Tests.Helpers.Users;
with AWA.Services.Contexts;
with Security.Contexts;
package body AWA.Wikis.Modules.Tests is
use ASF.Tests;
use Util.Tests;
package Caller is new Util.Test_Caller (Test, "Wikis.Modules");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test AWA.Wikis.Modules.Create_Wiki_Space",
Test_Create_Wiki_Space'Access);
Caller.Add_Test (Suite, "Test AWA.Wikis.Modules.Create_Wiki_Page",
Test_Create_Wiki_Page'Access);
Caller.Add_Test (Suite, "Test AWA.Wikis.Modules.Create_Wiki_Content",
Test_Create_Wiki_Content'Access);
Caller.Add_Test (Suite, "Test AWA.Wikis.Modules.Wiki_Page",
Test_Wiki_Page'Access);
end Add_Tests;
-- ------------------------------
-- Test creation of a wiki space.
-- ------------------------------
procedure Test_Create_Wiki_Space (T : in out Test) is
Sec_Ctx : Security.Contexts.Security_Context;
Context : AWA.Services.Contexts.Service_Context;
W : AWA.Wikis.Models.Wiki_Space_Ref;
W2 : AWA.Wikis.Models.Wiki_Space_Ref;
begin
AWA.Tests.Helpers.Users.Login (Context, Sec_Ctx, "[email protected]");
T.Manager := AWA.Wikis.Modules.Get_Wiki_Module;
T.Assert (T.Manager /= null, "There is no wiki manager");
W.Set_Name ("Test wiki space");
T.Manager.Create_Wiki_Space (W);
T.Assert (W.Is_Inserted, "The new wiki space was not created");
W.Set_Name ("Test wiki space update");
W.Set_Is_Public (True);
T.Manager.Save_Wiki_Space (W);
T.Manager.Load_Wiki_Space (Wiki => W2,
Id => W.Get_Id);
Util.Tests.Assert_Equals (T, "Test wiki space update", String '(W2.Get_Name),
"Invalid wiki space name");
end Test_Create_Wiki_Space;
-- ------------------------------
-- Test creation of a wiki page.
-- ------------------------------
procedure Test_Create_Wiki_Page (T : in out Test) is
Sec_Ctx : Security.Contexts.Security_Context;
Context : AWA.Services.Contexts.Service_Context;
W : AWA.Wikis.Models.Wiki_Space_Ref;
P : AWA.Wikis.Models.Wiki_Page_Ref;
C : AWA.Wikis.Models.Wiki_Content_Ref;
begin
AWA.Tests.Helpers.Users.Login (Context, Sec_Ctx, "[email protected]");
W.Set_Name ("Test wiki space");
T.Manager.Create_Wiki_Space (W);
P.Set_Name ("Private");
P.Set_Title ("The page title");
T.Manager.Create_Wiki_Page (W, P, C);
T.Assert (P.Is_Inserted, "The new wiki page was not created");
C := AWA.Wikis.Models.Null_Wiki_Content;
P := AWA.Wikis.Models.Null_Wiki_Page;
P.Set_Name ("Public");
P.Set_Title ("The page title (public)");
P.Set_Is_Public (True);
T.Manager.Create_Wiki_Page (W, P, C);
T.Assert (P.Is_Inserted, "The new wiki page was not created");
T.Assert (P.Get_Is_Public, "The new wiki page is not public");
end Test_Create_Wiki_Page;
-- ------------------------------
-- Test creation of a wiki page content.
-- ------------------------------
procedure Test_Create_Wiki_Content (T : in out Test) is
Sec_Ctx : Security.Contexts.Security_Context;
Context : AWA.Services.Contexts.Service_Context;
W : AWA.Wikis.Models.Wiki_Space_Ref;
P : AWA.Wikis.Models.Wiki_Page_Ref;
C : AWA.Wikis.Models.Wiki_Content_Ref;
begin
AWA.Tests.Helpers.Users.Login (Context, Sec_Ctx, "[email protected]");
W.Set_Name ("Test wiki space");
T.Manager.Create_Wiki_Space (W);
T.Wiki_Id := W.Get_Id;
P.Set_Name ("PrivatePage");
P.Set_Title ("The page title");
P.Set_Is_Public (False);
T.Manager.Create_Wiki_Page (W, P, C);
T.Private_Id := P.Get_Id;
C := AWA.Wikis.Models.Null_Wiki_Content;
C.Set_Format (AWA.Wikis.Models.FORMAT_MARKDOWN);
C.Set_Content ("-- Title" & ASCII.LF & "A paragraph");
C.Set_Save_Comment ("A first version");
T.Manager.Create_Wiki_Content (P, C);
T.Assert (C.Is_Inserted, "The new wiki content was not created");
T.Assert (not C.Get_Author.Is_Null, "The wiki content has an author");
T.Assert (not C.Get_Page.Is_Null, "The wiki content is associated with the wiki page");
P := AWA.Wikis.Models.Null_Wiki_Page;
C := AWA.Wikis.Models.Null_Wiki_Content;
P.Set_Name ("PublicPage");
P.Set_Title ("The public page title");
P.Set_Is_Public (True);
T.Manager.Create_Wiki_Page (W, P, C);
T.Public_Id := P.Get_Id;
C.Set_Format (AWA.Wikis.Models.FORMAT_MARKDOWN);
C.Set_Content ("-- Title" & ASCII.LF & "A paragraph" & ASCII.LF
& "[Link](http://mylink.com)" & ASCII.LF
& "[Image](my-image.png)");
C.Set_Save_Comment ("A first version");
T.Manager.Create_Wiki_Content (P, C);
T.Assert (C.Is_Inserted, "The new wiki content was not created");
T.Assert (not C.Get_Author.Is_Null, "The wiki content has an author");
T.Assert (not C.Get_Page.Is_Null, "The wiki content is associated with the wiki page");
end Test_Create_Wiki_Content;
procedure Test_Wiki_Page (T : in out Test) is
Request : ASF.Requests.Mockup.Request;
Reply : ASF.Responses.Mockup.Response;
Ident : constant String := Util.Strings.Image (Natural (T.Wiki_Id));
Pub_Ident : constant String := Util.Strings.Image (Natural (T.Public_Id));
begin
ASF.Tests.Do_Get (Request, Reply, "/wikis/view/" & Ident & "/PublicPage", "wiki-public-1.html");
Assert_Equals (T, ASF.Responses.SC_OK, Reply.Get_Status, "Invalid response (PublicPage)");
Assert_Matches (T, ".*The public page title.*", Reply, "Invalid PublicPage page returned",
Status => ASF.Responses.SC_OK);
ASF.Tests.Do_Get (Request, Reply, "/wikis/info/" & Ident & "/" & Pub_Ident,
"wiki-public-info-1.html");
Assert_Equals (T, ASF.Responses.SC_OK, Reply.Get_Status, "Invalid response (PublicPage info)");
Assert_Matches (T, ".*The public page title.*", Reply, "Invalid PublicPage info page returned",
Status => ASF.Responses.SC_OK);
ASF.Tests.Do_Get (Request, Reply, "/wikis/history/" & Ident & "/" & Pub_Ident,
"wiki-public-history-1.html");
Assert_Equals (T, ASF.Responses.SC_OK, Reply.Get_Status, "Invalid response (PublicPage history)");
Assert_Matches (T, ".*The public page title.*", Reply, "Invalid PublicPage info page returned",
Status => ASF.Responses.SC_OK);
Request.Remove_Attribute ("wikiView");
ASF.Tests.Do_Get (Request, Reply, "/wikis/view/" & Ident & "/PrivatePage", "wiki-private-1.html");
Assert_Equals (T, ASF.Responses.SC_OK, Reply.Get_Status, "Invalid response (PrivatePage)");
Assert_Matches (T, ".*Protected Wiki Page.*", Reply, "Invalid PrivatePage page returned",
Status => ASF.Responses.SC_OK);
ASF.Tests.Do_Get (Request, Reply, "/wikis/list/" & Ident & "/recent", "wiki-list-recent-1.html");
Assert_Equals (T, ASF.Responses.SC_OK, Reply.Get_Status, "Invalid response (list/recent)");
ASF.Tests.Do_Get (Request, Reply, "/wikis/list/" & Ident & "/recent/grid", "wiki-list-grid-1.html");
Assert_Equals (T, ASF.Responses.SC_OK, Reply.Get_Status, "Invalid response (list/recent/grid)");
ASF.Tests.Do_Get (Request, Reply, "/wikis/list/" & Ident & "/popular", "wiki-list-popular-1.html");
Assert_Equals (T, ASF.Responses.SC_OK, Reply.Get_Status, "Invalid response (list/popular)");
ASF.Tests.Do_Get (Request, Reply, "/wikis/list/" & Ident & "/popular/grid", "wiki-list-popular-1.html");
Assert_Equals (T, ASF.Responses.SC_OK, Reply.Get_Status, "Invalid response (list/popular/grid)");
end Test_Wiki_Page;
end AWA.Wikis.Modules.Tests;
|
-----------------------------------------------------------------------
-- awa-wikis-modules-tests -- Unit tests for wikis service
-- Copyright (C) 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Test_Caller;
with Util.Strings;
with ASF.Tests;
with ASF.Requests.Mockup;
with ASF.Responses.Mockup;
with AWA.Tests.Helpers;
with AWA.Tests.Helpers.Users;
with AWA.Services.Contexts;
with Security.Contexts;
package body AWA.Wikis.Modules.Tests is
use ASF.Tests;
use Util.Tests;
package Caller is new Util.Test_Caller (Test, "Wikis.Modules");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test AWA.Wikis.Modules.Create_Wiki_Space",
Test_Create_Wiki_Space'Access);
Caller.Add_Test (Suite, "Test AWA.Wikis.Modules.Create_Wiki_Page",
Test_Create_Wiki_Page'Access);
Caller.Add_Test (Suite, "Test AWA.Wikis.Modules.Create_Wiki_Content",
Test_Create_Wiki_Content'Access);
Caller.Add_Test (Suite, "Test AWA.Wikis.Modules.Wiki_Page",
Test_Wiki_Page'Access);
end Add_Tests;
-- ------------------------------
-- Test creation of a wiki space.
-- ------------------------------
procedure Test_Create_Wiki_Space (T : in out Test) is
Sec_Ctx : Security.Contexts.Security_Context;
Context : AWA.Services.Contexts.Service_Context;
W : AWA.Wikis.Models.Wiki_Space_Ref;
W2 : AWA.Wikis.Models.Wiki_Space_Ref;
begin
AWA.Tests.Helpers.Users.Login (Context, Sec_Ctx, "[email protected]");
T.Manager := AWA.Wikis.Modules.Get_Wiki_Module;
T.Assert (T.Manager /= null, "There is no wiki manager");
W.Set_Name ("Test wiki space");
T.Manager.Create_Wiki_Space (W);
T.Assert (W.Is_Inserted, "The new wiki space was not created");
W.Set_Name ("Test wiki space update");
W.Set_Is_Public (True);
T.Manager.Save_Wiki_Space (W);
T.Manager.Load_Wiki_Space (Wiki => W2,
Id => W.Get_Id);
Util.Tests.Assert_Equals (T, "Test wiki space update", String '(W2.Get_Name),
"Invalid wiki space name");
end Test_Create_Wiki_Space;
-- ------------------------------
-- Test creation of a wiki page.
-- ------------------------------
procedure Test_Create_Wiki_Page (T : in out Test) is
Sec_Ctx : Security.Contexts.Security_Context;
Context : AWA.Services.Contexts.Service_Context;
W : AWA.Wikis.Models.Wiki_Space_Ref;
P : AWA.Wikis.Models.Wiki_Page_Ref;
C : AWA.Wikis.Models.Wiki_Content_Ref;
begin
AWA.Tests.Helpers.Users.Login (Context, Sec_Ctx, "[email protected]");
W.Set_Name ("Test wiki space");
T.Manager.Create_Wiki_Space (W);
P.Set_Name ("Private");
P.Set_Title ("The page title");
T.Manager.Create_Wiki_Page (W, P, C);
T.Assert (P.Is_Inserted, "The new wiki page was not created");
C := AWA.Wikis.Models.Null_Wiki_Content;
P := AWA.Wikis.Models.Null_Wiki_Page;
P.Set_Name ("Public");
P.Set_Title ("The page title (public)");
P.Set_Is_Public (True);
T.Manager.Create_Wiki_Page (W, P, C);
T.Assert (P.Is_Inserted, "The new wiki page was not created");
T.Assert (P.Get_Is_Public, "The new wiki page is not public");
end Test_Create_Wiki_Page;
-- ------------------------------
-- Test creation of a wiki page content.
-- ------------------------------
procedure Test_Create_Wiki_Content (T : in out Test) is
Sec_Ctx : Security.Contexts.Security_Context;
Context : AWA.Services.Contexts.Service_Context;
W : AWA.Wikis.Models.Wiki_Space_Ref;
P : AWA.Wikis.Models.Wiki_Page_Ref;
C : AWA.Wikis.Models.Wiki_Content_Ref;
begin
AWA.Tests.Helpers.Users.Login (Context, Sec_Ctx, "[email protected]");
W.Set_Name ("Test wiki space");
T.Manager.Create_Wiki_Space (W);
T.Wiki_Id := W.Get_Id;
P.Set_Name ("PrivatePage");
P.Set_Title ("The page title");
P.Set_Is_Public (False);
T.Manager.Create_Wiki_Page (W, P, C);
T.Private_Id := P.Get_Id;
C := AWA.Wikis.Models.Null_Wiki_Content;
C.Set_Format (AWA.Wikis.Models.FORMAT_MARKDOWN);
C.Set_Content ("-- Title" & ASCII.LF & "A paragraph");
C.Set_Save_Comment ("A first version");
T.Manager.Create_Wiki_Content (P, C);
T.Assert (C.Is_Inserted, "The new wiki content was not created");
T.Assert (not C.Get_Author.Is_Null, "The wiki content has an author");
T.Assert (not C.Get_Page.Is_Null, "The wiki content is associated with the wiki page");
P := AWA.Wikis.Models.Null_Wiki_Page;
C := AWA.Wikis.Models.Null_Wiki_Content;
P.Set_Name ("PublicPage");
P.Set_Title ("The public page title");
P.Set_Is_Public (True);
T.Manager.Create_Wiki_Page (W, P, C);
T.Public_Id := P.Get_Id;
C.Set_Format (AWA.Wikis.Models.FORMAT_MARKDOWN);
C.Set_Content ("-- Title" & ASCII.LF & "A paragraph" & ASCII.LF
& "[Link](http://mylink.com)" & ASCII.LF
& "[Image](my-image.png)");
C.Set_Save_Comment ("A first version");
T.Manager.Create_Wiki_Content (P, C);
T.Assert (C.Is_Inserted, "The new wiki content was not created");
T.Assert (not C.Get_Author.Is_Null, "The wiki content has an author");
T.Assert (not C.Get_Page.Is_Null, "The wiki content is associated with the wiki page");
end Test_Create_Wiki_Content;
-- ------------------------------
-- Test getting the wiki page as well as info, history pages.
-- ------------------------------
procedure Test_Wiki_Page (T : in out Test) is
Request : ASF.Requests.Mockup.Request;
Reply : ASF.Responses.Mockup.Response;
Ident : constant String := Util.Strings.Image (Natural (T.Wiki_Id));
Pub_Ident : constant String := Util.Strings.Image (Natural (T.Public_Id));
begin
ASF.Tests.Do_Get (Request, Reply, "/wikis/view/" & Ident & "/PublicPage", "wiki-public-1.html");
Assert_Equals (T, ASF.Responses.SC_OK, Reply.Get_Status, "Invalid response (PublicPage)");
Assert_Matches (T, ".*The public page title.*", Reply, "Invalid PublicPage page returned",
Status => ASF.Responses.SC_OK);
ASF.Tests.Do_Get (Request, Reply, "/wikis/info/" & Ident & "/" & Pub_Ident,
"wiki-public-info-1.html");
Assert_Equals (T, ASF.Responses.SC_OK, Reply.Get_Status, "Invalid response (PublicPage info)");
Assert_Matches (T, ".*The public page title.*", Reply, "Invalid PublicPage info page returned",
Status => ASF.Responses.SC_OK);
ASF.Tests.Do_Get (Request, Reply, "/wikis/history/" & Ident & "/" & Pub_Ident,
"wiki-public-history-1.html");
Assert_Equals (T, ASF.Responses.SC_OK, Reply.Get_Status, "Invalid response (PublicPage history)");
Assert_Matches (T, ".*The public page title.*", Reply, "Invalid PublicPage info page returned",
Status => ASF.Responses.SC_OK);
Request.Remove_Attribute ("wikiView");
ASF.Tests.Do_Get (Request, Reply, "/wikis/view/" & Ident & "/PrivatePage", "wiki-private-1.html");
Assert_Equals (T, ASF.Responses.SC_OK, Reply.Get_Status, "Invalid response (PrivatePage)");
Assert_Matches (T, ".*Protected Wiki Page.*", Reply, "Invalid PrivatePage page returned",
Status => ASF.Responses.SC_OK);
ASF.Tests.Do_Get (Request, Reply, "/wikis/list/" & Ident & "/recent", "wiki-list-recent-1.html");
Assert_Equals (T, ASF.Responses.SC_OK, Reply.Get_Status, "Invalid response (list/recent)");
ASF.Tests.Do_Get (Request, Reply, "/wikis/list/" & Ident & "/recent/grid", "wiki-list-grid-1.html");
Assert_Equals (T, ASF.Responses.SC_OK, Reply.Get_Status, "Invalid response (list/recent/grid)");
ASF.Tests.Do_Get (Request, Reply, "/wikis/list/" & Ident & "/popular", "wiki-list-popular-1.html");
Assert_Equals (T, ASF.Responses.SC_OK, Reply.Get_Status, "Invalid response (list/popular)");
ASF.Tests.Do_Get (Request, Reply, "/wikis/list/" & Ident & "/popular/grid", "wiki-list-popular-1.html");
Assert_Equals (T, ASF.Responses.SC_OK, Reply.Get_Status, "Invalid response (list/popular/grid)");
end Test_Wiki_Page;
end AWA.Wikis.Modules.Tests;
|
Add some documentation
|
Add some documentation
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
ba867c34f265b2f69fca287891aa6973ef142fd6
|
src/wiki-render-links.adb
|
src/wiki-render-links.adb
|
-----------------------------------------------------------------------
-- wiki-render-links -- Wiki links renderering
-- 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.
-----------------------------------------------------------------------
package body Wiki.Render.Links is
-- ------------------------------
-- Get the image link that must be rendered from the wiki image link.
-- ------------------------------
overriding
procedure Make_Image_Link (Renderer : in Default_Link_Renderer;
Link : in Wiki.Strings.WString;
URI : out Wiki.Strings.UString;
Width : out Natural;
Height : out Natural) is
pragma Unreferenced (Renderer);
begin
URI := Wiki.Strings.To_UString (Link);
Width := 0;
Height := 0;
end Make_Image_Link;
-- ------------------------------
-- Get the page link that must be rendered from the wiki page link.
-- ------------------------------
overriding
procedure Make_Page_Link (Renderer : in Default_Link_Renderer;
Link : in Wiki.Strings.WString;
URI : out Wiki.Strings.UString;
Exists : out Boolean) is
pragma Unreferenced (Renderer);
begin
URI := Wiki.Strings.To_UString (Link);
Exists := True;
end Make_Page_Link;
end Wiki.Render.Links;
|
-----------------------------------------------------------------------
-- wiki-render-links -- Wiki links renderering
-- 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.
-----------------------------------------------------------------------
package body Wiki.Render.Links is
-- ------------------------------
-- Get the image link that must be rendered from the wiki image link.
-- ------------------------------
overriding
procedure Make_Image_Link (Renderer : in out Default_Link_Renderer;
Link : in Wiki.Strings.WString;
URI : out Wiki.Strings.UString;
Width : out Natural;
Height : out Natural) is
pragma Unreferenced (Renderer);
begin
URI := Wiki.Strings.To_UString (Link);
Width := 0;
Height := 0;
end Make_Image_Link;
-- ------------------------------
-- Get the page link that must be rendered from the wiki page link.
-- ------------------------------
overriding
procedure Make_Page_Link (Renderer : in out Default_Link_Renderer;
Link : in Wiki.Strings.WString;
URI : out Wiki.Strings.UString;
Exists : out Boolean) is
pragma Unreferenced (Renderer);
begin
URI := Wiki.Strings.To_UString (Link);
Exists := True;
end Make_Page_Link;
end Wiki.Render.Links;
|
Change the Link_Renderer to use in out parameter
|
Change the Link_Renderer to use in out parameter
|
Ada
|
apache-2.0
|
stcarrez/ada-wiki,stcarrez/ada-wiki
|
0708acf3dfbdb42b847384dd46223b81243a1870
|
mat/src/matp.adb
|
mat/src/matp.adb
|
-----------------------------------------------------------------------
-- mat-types -- Global types
-- Copyright (C) 2014 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.IO_Exceptions;
with Util.Log.Loggers;
with GNAT.Sockets;
with Readline;
with MAT.Commands;
with MAT.Targets;
with MAT.Consoles.Text;
with MAT.Readers.Sockets;
procedure Matp is
procedure Interactive_Loop is
Target : MAT.Targets.Target_Type;
Console : aliased MAT.Consoles.Text.Console_Type;
Server : MAT.Readers.Sockets.Socket_Reader_Type;
Address : GNAT.Sockets.Sock_Addr_Type;
begin
Address.Addr := GNAT.Sockets.Any_Inet_Addr;
Address.Port := 4096;
Target.Console := Console'Unchecked_Access;
Target.Initialize (Server);
Server.Open (Address);
loop
declare
Line : constant String := Readline.Get_Line ("matp>");
begin
MAT.Commands.Execute (Target, Line);
exception
when MAT.Commands.Stop_Interp =>
return;
end;
end loop;
exception
when Ada.IO_Exceptions.End_Error =>
return;
end Interactive_Loop;
begin
Util.Log.Loggers.Initialize ("matp.properties");
Interactive_Loop;
end Matp;
|
-----------------------------------------------------------------------
-- 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 Ada.IO_Exceptions;
with Util.Log.Loggers;
with GNAT.Sockets;
with Readline;
with MAT.Commands;
with MAT.Targets;
with MAT.Consoles.Text;
with MAT.Readers.Streams.Sockets;
procedure Matp is
procedure Interactive_Loop is
Target : MAT.Targets.Target_Type;
Console : aliased MAT.Consoles.Text.Console_Type;
Server : MAT.Readers.Streams.Sockets.Socket_Listener_Type;
Address : GNAT.Sockets.Sock_Addr_Type;
begin
Address.Addr := GNAT.Sockets.Any_Inet_Addr;
Address.Port := 4096;
-- Target.Console := Console'Unchecked_Access;
-- Target.Initialize (Server);
Server.Start (Address);
loop
declare
Line : constant String := Readline.Get_Line ("matp>");
begin
MAT.Commands.Execute (Target, Line);
exception
when MAT.Commands.Stop_Interp =>
exit;
end;
end loop;
Server.Stop;
exception
when Ada.IO_Exceptions.End_Error =>
Server.Stop;
return;
end Interactive_Loop;
begin
Util.Log.Loggers.Initialize ("matp.properties");
Interactive_Loop;
end Matp;
|
Stop the server before leaving the server scope so that the listener task is stopped
|
Stop the server before leaving the server scope so that the listener task is stopped
|
Ada
|
apache-2.0
|
stcarrez/mat,stcarrez/mat,stcarrez/mat
|
e1f181fd8b6eecea42163cd17620d5163bcd9f29
|
awa/plugins/awa-workspaces/regtests/awa-workspaces-tests.adb
|
awa/plugins/awa-workspaces/regtests/awa-workspaces-tests.adb
|
-----------------------------------------------------------------------
-- awa-workspaces-tests -- Unit tests for workspaces and invitations
-- Copyright (C) 2017, 2018 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Test_Caller;
with ASF.Requests.Mockup;
with ASF.Responses.Mockup;
with ASF.Helpers.Beans;
with ASF.Tests;
with AWA.Users.Models;
with AWA.Tests.Helpers.Users;
with AWA.Workspaces.Beans;
package body AWA.Workspaces.Tests is
use Ada.Strings.Unbounded;
use AWA.Tests;
function Get_Invitation_Bean is
new ASF.Helpers.Beans.Get_Request_Bean (Element_Type => Beans.Invitation_Bean,
Element_Access => Beans.Invitation_Bean_Access);
package Caller is new Util.Test_Caller (Test, "Workspaces.Beans");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test AWA.Workspaces.Beans.Send",
Test_Invite_User'Access);
Caller.Add_Test (Suite, "Test AWA.Workspaces.Beans.Delete",
Test_Delete_Member'Access);
Caller.Add_Test (Suite, "Test AWA.Workspaces.Beans.Accept",
Test_Accept_Invitation'Access);
Caller.Add_Test (Suite, "Test AWA.Workspaces.Beans.Accept (with Email)",
Test_Accept_Invitation_With_Email'Access);
Caller.Add_Test (Suite, "Test AWA.Workspaces.Beans.Member_List",
Test_List_Members'Access);
end Add_Tests;
-- ------------------------------
-- Verify the anonymous access for the invitation page.
-- ------------------------------
procedure Verify_Anonymous (T : in out Test;
Key : in String) is
Request : ASF.Requests.Mockup.Request;
Reply : ASF.Responses.Mockup.Response;
begin
ASF.Tests.Do_Get (Request, Reply, "/auth/invitation.html", "invitation-view.html");
ASF.Tests.Assert_Contains (T, "Bad or invalid invitation", Reply,
"This invitation is invalid");
ASF.Tests.Do_Get (Request, Reply, "/auth/invitation.html?key=test", "invitation-bad.html");
ASF.Tests.Assert_Contains (T, "This invitation is invalid or has expired", Reply,
"This invitation is invalid (key)");
ASF.Tests.Do_Get (Request, Reply, "/auth/invitation.html?key=x" & key,
"invitation-bad2.html");
ASF.Tests.Assert_Contains (T, "This invitation is invalid or has expired",
Reply, "This invitation is invalid (key)");
if Key = "" then
return;
end if;
ASF.Tests.Do_Get (Request, Reply, "/auth/invitation.html?key=" & Key, "invitation-ok.html");
ASF.Tests.Assert_Contains (T, "Accept invitation", Reply,
"Accept invitation page is invalid");
end Verify_Anonymous;
-- ------------------------------
-- Test sending an invitation.
-- ------------------------------
procedure Test_Invite_User (T : in out Test) is
use type ADO.Identifier;
use type AWA.Workspaces.Beans.Invitation_Bean_Access;
Request : ASF.Requests.Mockup.Request;
Reply : ASF.Responses.Mockup.Response;
Invite : AWA.Workspaces.Beans.Invitation_Bean_Access;
begin
AWA.Tests.Helpers.Users.Login ("[email protected]", Request);
Request.Set_Parameter ("email", "[email protected]");
Request.Set_Parameter ("message", "I invite you to this application");
Request.Set_Parameter ("send", "1");
Request.Set_Parameter ("invite", "1");
ASF.Tests.Do_Post (Request, Reply, "/workspaces/invite.html", "invite.html");
T.Assert (Reply.Get_Status = ASF.Responses.SC_MOVED_TEMPORARILY,
"Invalid response after invitation creation");
-- Verify the invitation by looking at the inviteUser bean.
Invite := Get_Invitation_Bean (Request, "inviteUser");
T.Assert (Invite /= null, "Null inviteUser bean");
T.Assert (Invite.Get_Id /= ADO.NO_IDENTIFIER, "The invite ID is invalid");
T.Assert (not Invite.Get_Access_Key.Is_Null, "The invite access key is null");
T.Assert (Invite.Get_Member.Is_Inserted, "The invitation has a workspace member");
T.Key := Invite.Get_Access_Key.Get_Access_Key;
T.Verify_Anonymous (Invite.Get_Access_Key.Get_Access_Key);
T.Member_ID := Invite.Get_Member.Get_Id;
end Test_Invite_User;
-- ------------------------------
-- Test deleting the member.
-- ------------------------------
procedure Test_Delete_Member (T : in out Test) is
Request : ASF.Requests.Mockup.Request;
Reply : ASF.Responses.Mockup.Response;
begin
T.Test_Invite_User;
AWA.Tests.Helpers.Users.Login ("[email protected]", Request);
declare
Id : constant String := ADO.Identifier'Image (T.Member_Id);
begin
Request.Set_Parameter ("member-id", Id);
Request.Set_Parameter ("delete", "1");
Request.Set_Parameter ("delete-member-form", "1");
ASF.Tests.Do_Post (Request, Reply, "/workspaces/forms/delete-member.html",
"delete-member.html");
T.Assert (Reply.Get_Status = ASF.Responses.SC_OK,
"Invalid response after delete member operation");
ASF.Tests.Assert_Contains (T, "deleteDialog_" & Id (Id'First + 1 .. Id'Last), Reply,
"Delete member dialog operation response is invalid");
end;
end Test_Delete_Member;
-- ------------------------------
-- Test accepting the invitation.
-- ------------------------------
procedure Test_Accept_Invitation (T : in out Test) is
Request : ASF.Requests.Mockup.Request;
Reply : ASF.Responses.Mockup.Response;
begin
T.Test_Invite_User;
AWA.Tests.Helpers.Users.Recover_Password ("[email protected]");
AWA.Tests.Helpers.Users.Login ("[email protected]", Request);
ASF.Tests.Do_Get (Request, Reply, "/workspaces/accept-invitation.html?key="
& To_String (T.Key),
"accept-member.html");
T.Assert (Reply.Get_Status = ASF.Responses.SC_MOVED_TEMPORARILY,
"Accept invitation page failed");
Util.Tests.Assert_Equals (T, "/asfunit/workspaces/main.html", Reply.Get_Header ("Location"),
"The accept invitation page must redirect to the workspace");
end Test_Accept_Invitation;
-- ------------------------------
-- Test accepting the invitation with a email and password process.
-- ------------------------------
procedure Test_Accept_Invitation_With_Email (T : in out Test) is
Request : ASF.Requests.Mockup.Request;
Reply : ASF.Responses.Mockup.Response;
begin
T.Test_Invite_User;
Request.Set_Parameter ("key", To_String (T.Key));
ASF.Tests.Do_Get (Request, Reply, "/auth/invitation.html?key="
& To_String (T.Key),
"accept-invitation-email-1.html");
ASF.Tests.Assert_Contains (T, "input type=""hidden"" name=""key"" value="""
& To_String (T.Key),
Reply,
"The invitation form must setup the invitation key form");
Request.Set_Parameter ("key", To_String (T.Key));
Request.Set_Parameter ("register", "1");
Request.Set_Parameter ("register-button", "1");
Request.Set_Parameter ("firstName", "Invitee");
Request.Set_Parameter ("lastName", "With_Email");
Request.Set_Parameter ("email", "[email protected]");
Request.Set_Parameter ("email", "[email protected]");
Request.Set_Parameter ("password", "admin");
Request.Set_Parameter ("password2", "admin");
ASF.Tests.Do_Post (Request, Reply, "/auth/invitation.html",
"accept-invitation-email-2.html");
T.Assert (Reply.Get_Status = ASF.Responses.SC_MOVED_TEMPORARILY,
"Accept invitation page failed");
Util.Tests.Assert_Equals (T, "/asfunit/workspaces/accept-invitation.html?key=" &
To_String (T.Key),
Reply.Get_Header ("Location"),
"The accept invitation page must redirect to the workspace");
end Test_Accept_Invitation_With_Email;
-- ------------------------------
-- Test listing the members of the workspace.
-- ------------------------------
procedure Test_List_Members (T : in out Test) is
Request : ASF.Requests.Mockup.Request;
Reply : ASF.Responses.Mockup.Response;
begin
T.Test_Invite_User;
AWA.Tests.Helpers.Users.Login ("[email protected]", Request);
ASF.Tests.Do_Get (Request, Reply, "/workspaces/members.html",
"member-list.html");
ASF.Tests.Assert_Contains (T, "[email protected]", Reply,
"The invited user is listed in the members page");
ASF.Tests.Assert_Contains (T, "[email protected]", Reply,
"The invite user (owner) is listed in the members page");
end Test_List_Members;
end AWA.Workspaces.Tests;
|
-----------------------------------------------------------------------
-- awa-workspaces-tests -- Unit tests for workspaces and invitations
-- Copyright (C) 2017, 2018 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Test_Caller;
with ASF.Requests.Mockup;
with ASF.Responses.Mockup;
with ASF.Helpers.Beans;
with ASF.Tests;
with AWA.Users.Models;
with AWA.Tests.Helpers.Users;
with AWA.Workspaces.Beans;
package body AWA.Workspaces.Tests is
use Ada.Strings.Unbounded;
function Get_Invitation_Bean is
new ASF.Helpers.Beans.Get_Request_Bean (Element_Type => Beans.Invitation_Bean,
Element_Access => Beans.Invitation_Bean_Access);
package Caller is new Util.Test_Caller (Test, "Workspaces.Beans");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test AWA.Workspaces.Beans.Send",
Test_Invite_User'Access);
Caller.Add_Test (Suite, "Test AWA.Workspaces.Beans.Delete",
Test_Delete_Member'Access);
Caller.Add_Test (Suite, "Test AWA.Workspaces.Beans.Accept",
Test_Accept_Invitation'Access);
Caller.Add_Test (Suite, "Test AWA.Workspaces.Beans.Accept (with Email)",
Test_Accept_Invitation_With_Email'Access);
Caller.Add_Test (Suite, "Test AWA.Workspaces.Beans.Member_List",
Test_List_Members'Access);
end Add_Tests;
-- ------------------------------
-- Verify the anonymous access for the invitation page.
-- ------------------------------
procedure Verify_Anonymous (T : in out Test;
Key : in String) is
Request : ASF.Requests.Mockup.Request;
Reply : ASF.Responses.Mockup.Response;
begin
ASF.Tests.Do_Get (Request, Reply, "/auth/invitation.html", "invitation-view.html");
ASF.Tests.Assert_Contains (T, "Bad or invalid invitation", Reply,
"This invitation is invalid");
ASF.Tests.Do_Get (Request, Reply, "/auth/invitation.html?key=test", "invitation-bad.html");
ASF.Tests.Assert_Contains (T, "This invitation is invalid or has expired", Reply,
"This invitation is invalid (key)");
ASF.Tests.Do_Get (Request, Reply, "/auth/invitation.html?key=x" & key,
"invitation-bad2.html");
ASF.Tests.Assert_Contains (T, "This invitation is invalid or has expired",
Reply, "This invitation is invalid (key)");
if Key = "" then
return;
end if;
ASF.Tests.Do_Get (Request, Reply, "/auth/invitation.html?key=" & Key, "invitation-ok.html");
ASF.Tests.Assert_Contains (T, "Accept invitation", Reply,
"Accept invitation page is invalid");
end Verify_Anonymous;
-- ------------------------------
-- Test sending an invitation.
-- ------------------------------
procedure Test_Invite_User (T : in out Test) is
use type ADO.Identifier;
use type AWA.Workspaces.Beans.Invitation_Bean_Access;
Request : ASF.Requests.Mockup.Request;
Reply : ASF.Responses.Mockup.Response;
Invite : AWA.Workspaces.Beans.Invitation_Bean_Access;
begin
AWA.Tests.Helpers.Users.Login ("[email protected]", Request);
Request.Set_Parameter ("email", "[email protected]");
Request.Set_Parameter ("message", "I invite you to this application");
Request.Set_Parameter ("send", "1");
Request.Set_Parameter ("invite", "1");
ASF.Tests.Do_Post (Request, Reply, "/workspaces/invite.html", "invite.html");
T.Assert (Reply.Get_Status = ASF.Responses.SC_MOVED_TEMPORARILY,
"Invalid response after invitation creation");
-- Verify the invitation by looking at the inviteUser bean.
Invite := Get_Invitation_Bean (Request, "inviteUser");
T.Assert (Invite /= null, "Null inviteUser bean");
T.Assert (Invite.Get_Id /= ADO.NO_IDENTIFIER, "The invite ID is invalid");
T.Assert (not Invite.Get_Access_Key.Is_Null, "The invite access key is null");
T.Assert (Invite.Get_Member.Is_Inserted, "The invitation has a workspace member");
T.Key := Invite.Get_Access_Key.Get_Access_Key;
T.Verify_Anonymous (Invite.Get_Access_Key.Get_Access_Key);
T.Member_ID := Invite.Get_Member.Get_Id;
end Test_Invite_User;
-- ------------------------------
-- Test deleting the member.
-- ------------------------------
procedure Test_Delete_Member (T : in out Test) is
Request : ASF.Requests.Mockup.Request;
Reply : ASF.Responses.Mockup.Response;
begin
T.Test_Invite_User;
AWA.Tests.Helpers.Users.Login ("[email protected]", Request);
declare
Id : constant String := ADO.Identifier'Image (T.Member_Id);
begin
Request.Set_Parameter ("member-id", Id);
Request.Set_Parameter ("delete", "1");
Request.Set_Parameter ("delete-member-form", "1");
ASF.Tests.Do_Post (Request, Reply, "/workspaces/forms/delete-member.html",
"delete-member.html");
T.Assert (Reply.Get_Status = ASF.Responses.SC_OK,
"Invalid response after delete member operation");
ASF.Tests.Assert_Contains (T, "deleteDialog_" & Id (Id'First + 1 .. Id'Last), Reply,
"Delete member dialog operation response is invalid");
end;
end Test_Delete_Member;
-- ------------------------------
-- Test accepting the invitation.
-- ------------------------------
procedure Test_Accept_Invitation (T : in out Test) is
Request : ASF.Requests.Mockup.Request;
Reply : ASF.Responses.Mockup.Response;
begin
T.Test_Invite_User;
AWA.Tests.Helpers.Users.Recover_Password ("[email protected]");
AWA.Tests.Helpers.Users.Login ("[email protected]", Request);
ASF.Tests.Do_Get (Request, Reply, "/workspaces/accept-invitation.html?key="
& To_String (T.Key),
"accept-member.html");
T.Assert (Reply.Get_Status = ASF.Responses.SC_MOVED_TEMPORARILY,
"Accept invitation page failed");
Util.Tests.Assert_Equals (T, "/asfunit/workspaces/main.html", Reply.Get_Header ("Location"),
"The accept invitation page must redirect to the workspace");
end Test_Accept_Invitation;
-- ------------------------------
-- Test accepting the invitation with a email and password process.
-- ------------------------------
procedure Test_Accept_Invitation_With_Email (T : in out Test) is
Request : ASF.Requests.Mockup.Request;
Reply : ASF.Responses.Mockup.Response;
begin
T.Test_Invite_User;
Request.Set_Parameter ("key", To_String (T.Key));
ASF.Tests.Do_Get (Request, Reply, "/auth/invitation.html?key="
& To_String (T.Key),
"accept-invitation-email-1.html");
ASF.Tests.Assert_Contains (T, "input type=""hidden"" name=""key"" value="""
& To_String (T.Key),
Reply,
"The invitation form must setup the invitation key form");
Request.Set_Parameter ("key", To_String (T.Key));
Request.Set_Parameter ("register", "1");
Request.Set_Parameter ("register-button", "1");
Request.Set_Parameter ("firstName", "Invitee");
Request.Set_Parameter ("lastName", "With_Email");
Request.Set_Parameter ("email", "[email protected]");
Request.Set_Parameter ("email", "[email protected]");
Request.Set_Parameter ("password", "admin");
Request.Set_Parameter ("password2", "admin");
ASF.Tests.Do_Post (Request, Reply, "/auth/invitation.html",
"accept-invitation-email-2.html");
T.Assert (Reply.Get_Status = ASF.Responses.SC_MOVED_TEMPORARILY,
"Accept invitation page failed");
Util.Tests.Assert_Equals (T, "/asfunit/workspaces/accept-invitation.html?key=" &
To_String (T.Key),
Reply.Get_Header ("Location"),
"The accept invitation page must redirect to the workspace");
end Test_Accept_Invitation_With_Email;
-- ------------------------------
-- Test listing the members of the workspace.
-- ------------------------------
procedure Test_List_Members (T : in out Test) is
Request : ASF.Requests.Mockup.Request;
Reply : ASF.Responses.Mockup.Response;
begin
T.Test_Invite_User;
AWA.Tests.Helpers.Users.Login ("[email protected]", Request);
ASF.Tests.Do_Get (Request, Reply, "/workspaces/members.html",
"member-list.html");
ASF.Tests.Assert_Contains (T, "[email protected]", Reply,
"The invited user is listed in the members page");
ASF.Tests.Assert_Contains (T, "[email protected]", Reply,
"The invite user (owner) is listed in the members page");
end Test_List_Members;
end AWA.Workspaces.Tests;
|
Fix compilation warning
|
Fix compilation warning
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
db9e7416185b86b690e874b119a24b068af9c6ba
|
tests/benchmark.adb
|
tests/benchmark.adb
|
-------------------------------------------------------------------------------
-- Copyright (c) 2015, Daniel King
-- All rights reserved.
--
-- Redistribution and use in source and binary forms, with or without
-- modification, are permitted provided that the following conditions are met:
-- * Redistributions of source code must retain the above copyright
-- notice, this list of conditions and the following disclaimer.
-- * 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.
-- * The name of the copyright holder may not 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 BE LIABLE FOR ANY
-- DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
-- (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
-- LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
-- ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
-- THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-------------------------------------------------------------------------------
with Ada.Real_Time;
with Ada.Text_IO;
with Keccak.Types;
with Keccak.XOF;
with Keccak.Hash;
with Keccak.Duplex;
with Keccak.Keccak_1600;
with SHA3;
with SHAKE;
with RawSHAKE;
procedure Benchmark
is
Benchmark_Data_Size_MiB : constant := 128; -- size of the benchmark data in MiB
Repeat : constant := 10; -- number of benchmark iterations
-- A 1 MiB data chunk to use as an input to the algorithms.
Data_Chunk : constant Keccak.Types.Byte_Array(1 .. 1024*1024) := (others => 16#A7#);
----------------------------------------------------------------------------
-- Print_Number
--
-- Prints a number with the unit B/kiB/MiB/GiB depending on the magnitude
-- of the value. E.g. 1_048_576 would be displayed as 1.0 MiB.
----------------------------------------------------------------------------
procedure Print_Number(Value : in Float;
Suffix : in String;
Aft : in Natural)
is
package Float_IO is new Ada.Text_IO.Float_IO(Float);
begin
if Value >= 1024.0*1024.0*1024.0 then
Float_IO.Put(Value / (1024.0*1024.0*1024.0),
Fore => 0,
Aft => Aft,
Exp => 0);
Ada.Text_IO.Put(" GiB" & Suffix);
elsif Value >= 1024.0*1024.0 then
Float_IO.Put(Value / (1024.0*1024.0),
Fore => 0,
Aft => Aft,
Exp => 0);
Ada.Text_IO.Put(" MiB" & Suffix);
elsif Value >= 1024.0 then
Float_IO.Put(Value / 1024.0,
Fore => 0,
Aft => Aft,
Exp => 0);
Ada.Text_IO.Put(" kiB" & Suffix);
else
Float_IO.Put(Value,
Fore => 0,
Aft => Aft,
Exp => 0);
Ada.Text_IO.Put(" B" & Suffix);
end if;
end Print_Number;
----------------------------------------------------------------------------
-- Print_Time
--
-- Prints a line displaying: the measurement time, the data size, and
-- the performance (bytes per second).
--
-- E.g. Print_Time(1_048_576, Elapsed) where Elapsed represents a Time_Span
-- of 0.123 seconds would be displayed as:
-- "0.123000s, 1.0 MiB, 8.130 MiB/s"
----------------------------------------------------------------------------
procedure Print_Time(Data_Size : in Natural;
Time : in Ada.Real_Time.Time_Span)
is
package Duration_IO is new Ada.Text_IO.Fixed_IO(Duration);
begin
Duration_IO.Put(Ada.Real_Time.To_Duration(Time), Fore => 0, Aft => 6);
Ada.Text_IO.Put("s, ");
Print_Number(Float(Data_Size), "", 0);
Ada.Text_IO.Put(", ");
Print_Number(Float(Data_Size) / Float(Ada.Real_Time.To_Duration(Time)), "/s", 3);
Ada.Text_IO.New_Line;
end Print_Time;
----------------------------------------------------------------------------
-- Hash_Benchmark
--
-- Generic procedure to run a benchmark for any hash algorithm (e.g. SHA3-224,
-- Keccak-256, etc...).
----------------------------------------------------------------------------
generic
Name : String;
with package Hash_Package is new Keccak.Hash(<>);
procedure Hash_Benchmark;
procedure Hash_Benchmark
is
use type Ada.Real_Time.Time;
Ctx : Hash_Package.Context;
Digest : Hash_Package.Digest_Type;
Start_Time : Ada.Real_Time.Time;
End_Time : Ada.Real_Time.Time;
begin
for I in Positive range 1 .. Repeat loop
Start_Time := Ada.Real_Time.Clock;
Hash_Package.Init(Ctx);
for I in Positive range 1 .. Benchmark_Data_Size_MiB loop
Hash_Package.Update(Ctx, Data_Chunk, Data_Chunk'Length*8);
end loop;
Hash_Package.Final(Ctx, Digest);
End_Time := Ada.Real_Time.Clock;
Ada.Text_IO.Put(Name & ", ");
Print_Time(Data_Chunk'Length * Benchmark_Data_Size_MiB,
End_Time - Start_Time);
end loop;
end Hash_Benchmark;
----------------------------------------------------------------------------
-- XOF_Benchmark
--
-- Generic procedure to run a benchmark for any XOF algorithm (e.g. SHAKE128,
-- RawSHAKE256, etc...).
----------------------------------------------------------------------------
generic
Name : String;
with package XOF_Package is new Keccak.XOF(<>);
procedure XOF_Benchmark;
procedure XOF_Benchmark
is
use type Ada.Real_Time.Time;
Ctx : XOF_Package.Context;
Digest : XOF_Package.Byte_Array(1 .. 1024*1024);
Start_Time : Ada.Real_Time.Time;
End_Time : Ada.Real_Time.Time;
begin
-- Benchmark Absorbing
for I in Positive range 1 .. Repeat loop
Start_Time := Ada.Real_Time.Clock;
XOF_Package.Init(Ctx);
for I in Positive range 1 .. Benchmark_Data_Size_MiB loop
XOF_Package.Update(Ctx, Data_Chunk, Data_Chunk'Length*8);
end loop;
End_Time := Ada.Real_Time.Clock;
Ada.Text_IO.Put(Name & " (Absorbing), ");
Print_Time(Data_Chunk'Length * Benchmark_Data_Size_MiB,
End_Time - Start_Time);
end loop;
-- Benchmark squeezing
for I in Positive range 1 .. Repeat loop
Start_Time := Ada.Real_Time.Clock;
for I in Positive range 1 .. Benchmark_Data_Size_MiB loop
XOF_Package.Extract(Ctx, Digest);
end loop;
End_Time := Ada.Real_Time.Clock;
Ada.Text_IO.Put(Name & " (Squeezing), ");
Print_Time(Digest'Length * Benchmark_Data_Size_MiB,
End_Time - Start_Time);
end loop;
end XOF_Benchmark;
----------------------------------------------------------------------------
-- Duplex_Benchmark
--
-- Generic procedure to run a benchmark for any Duplex algorithm.
----------------------------------------------------------------------------
generic
Name : String;
Capacity : Positive;
with package Duplex is new Keccak.Duplex(<>);
procedure Duplex_Benchmark;
procedure Duplex_Benchmark
is
use type Ada.Real_Time.Time;
Ctx : Duplex.Context;
Out_Data : Keccak.Types.Byte_Array(1 .. 1600/8);
Start_Time : Ada.Real_Time.Time;
End_Time : Ada.Real_Time.Time;
Num_Iterations : Natural := (Benchmark_Data_Size_MiB*1024*1024) / ((1600-Capacity)/8);
begin
for I in Positive range 1 .. Repeat loop
Start_Time := Ada.Real_Time.Clock;
Duplex.Init(Ctx, Capacity);
for J in Positive range 1 .. Num_Iterations loop
Duplex.Duplex(Ctx,
Data_Chunk(1 .. Duplex.Rate_Of(Ctx)/8),
Duplex.Rate_Of(Ctx) - Duplex.Min_Padding_Bits,
Out_Data(1 .. Duplex.Rate_Of(Ctx)/8));
end loop;
End_Time := Ada.Real_Time.Clock;
Ada.Text_IO.Put(Name & ", ");
Print_Time((Duplex.Rate_Of(Ctx)/8) * Num_Iterations,
End_Time - Start_Time);
end loop;
end Duplex_Benchmark;
----------------------------------------------------------------------------
-- Benchmark procedure instantiations.
----------------------------------------------------------------------------
procedure Benchmark_SHA_224 is new Hash_Benchmark
("SHA3-224", SHA3.SHA3_224);
procedure Benchmark_SHA_256 is new Hash_Benchmark
("SHA3-256", SHA3.SHA3_256);
procedure Benchmark_SHA_384 is new Hash_Benchmark
("SHA3-384", SHA3.SHA3_384);
procedure Benchmark_SHA_512 is new Hash_Benchmark
("SHA3-512", SHA3.SHA3_512);
procedure Benchmark_Keccak_224 is new Hash_Benchmark
("Keccak-224", SHA3.Keccak_224);
procedure Benchmark_Keccak_256 is new Hash_Benchmark
("Keccak-256", SHA3.Keccak_256);
procedure Benchmark_Keccak_384 is new Hash_Benchmark
("Keccak-384", SHA3.Keccak_384);
procedure Benchmark_Keccak_512 is new Hash_Benchmark
("Keccak-512", SHA3.Keccak_512);
procedure Benchmark_SHAKE128 is new XOF_Benchmark
("SHAKE128", SHAKE.SHAKE128);
procedure Benchmark_SHAKE256 is new XOF_Benchmark
("SHAKE256", SHAKE.SHAKE256);
procedure Benchmark_RawSHAKE128 is new XOF_Benchmark
("RawSHAKE128", RawSHAKE.RawSHAKE128);
procedure Benchmark_RawSHAKE256 is new XOF_Benchmark
("RawSHAKE256", RawSHAKE.RawSHAKE256);
procedure Benchmark_Duplex_r1152c448 is new Duplex_Benchmark
("Duplex r1152c448", 448, Keccak.Keccak_1600.Duplex);
procedure Benchmark_Duplex_r1088c512 is new Duplex_Benchmark
("Duplex r1088c512", 512, Keccak.Keccak_1600.Duplex);
procedure Benchmark_Duplex_r832c768 is new Duplex_Benchmark
("Duplex r832c768", 768, Keccak.Keccak_1600.Duplex);
procedure Benchmark_Duplex_r576c1024 is new Duplex_Benchmark
("Duplex r576c1024", 1024, Keccak.Keccak_1600.Duplex);
begin
Ada.Text_IO.Put_Line("Algorithm,Time,Data Length,Performance");
Benchmark_SHA_224;
Ada.Text_IO.New_Line;
Benchmark_SHA_256;
Ada.Text_IO.New_Line;
Benchmark_SHA_384;
Ada.Text_IO.New_Line;
Benchmark_SHA_512;
Ada.Text_IO.New_Line;
Benchmark_Keccak_224;
Ada.Text_IO.New_Line;
Benchmark_Keccak_256;
Ada.Text_IO.New_Line;
Benchmark_Keccak_384;
Ada.Text_IO.New_Line;
Benchmark_Keccak_512;
Ada.Text_IO.New_Line;
Benchmark_SHAKE128;
Ada.Text_IO.New_Line;
Benchmark_SHAKE256;
Ada.Text_IO.New_Line;
Benchmark_RawSHAKE128;
Ada.Text_IO.New_Line;
Benchmark_RawSHAKE256;
Ada.Text_IO.New_Line;
Benchmark_Duplex_r1152c448;
Ada.Text_IO.New_Line;
Benchmark_Duplex_r1088c512;
Ada.Text_IO.New_Line;
Benchmark_Duplex_r832c768;
Ada.Text_IO.New_Line;
Benchmark_Duplex_r576c1024;
Ada.Text_IO.New_Line;
end Benchmark;
|
-------------------------------------------------------------------------------
-- Copyright (c) 2015, Daniel King
-- All rights reserved.
--
-- Redistribution and use in source and binary forms, with or without
-- modification, are permitted provided that the following conditions are met:
-- * Redistributions of source code must retain the above copyright
-- notice, this list of conditions and the following disclaimer.
-- * 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.
-- * The name of the copyright holder may not 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 BE LIABLE FOR ANY
-- DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
-- (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
-- LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
-- ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
-- THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-------------------------------------------------------------------------------
with Ada.Real_Time;
with Ada.Text_IO;
with Keccak.KeccakF;
with Keccak.Keccak_25;
with Keccak.Keccak_50;
with Keccak.Keccak_100;
with Keccak.Keccak_200;
with Keccak.Keccak_400;
with Keccak.Keccak_800;
with Keccak.Keccak_1600;
with Keccak.Types;
with Keccak.XOF;
with Keccak.Hash;
with Keccak.Duplex;
with Keccak.Keccak_1600;
with SHA3;
with SHAKE;
with RawSHAKE;
procedure Benchmark
is
Benchmark_Data_Size_MiB : constant := 128; -- size of the benchmark data in MiB
Repeat : constant := 10; -- number of benchmark iterations
-- A 1 MiB data chunk to use as an input to the algorithms.
Data_Chunk : constant Keccak.Types.Byte_Array(1 .. 1024*1024) := (others => 16#A7#);
----------------------------------------------------------------------------
-- Print_Number
--
-- Prints a number with the unit B/kiB/MiB/GiB depending on the magnitude
-- of the value. E.g. 1_048_576 would be displayed as 1.0 MiB.
----------------------------------------------------------------------------
procedure Print_Number(Value : in Float;
Suffix : in String;
Aft : in Natural)
is
package Float_IO is new Ada.Text_IO.Float_IO(Float);
begin
if Value >= 1024.0*1024.0*1024.0 then
Float_IO.Put(Value / (1024.0*1024.0*1024.0),
Fore => 0,
Aft => Aft,
Exp => 0);
Ada.Text_IO.Put(" GiB" & Suffix);
elsif Value >= 1024.0*1024.0 then
Float_IO.Put(Value / (1024.0*1024.0),
Fore => 0,
Aft => Aft,
Exp => 0);
Ada.Text_IO.Put(" MiB" & Suffix);
elsif Value >= 1024.0 then
Float_IO.Put(Value / 1024.0,
Fore => 0,
Aft => Aft,
Exp => 0);
Ada.Text_IO.Put(" kiB" & Suffix);
else
Float_IO.Put(Value,
Fore => 0,
Aft => Aft,
Exp => 0);
Ada.Text_IO.Put(" B" & Suffix);
end if;
end Print_Number;
----------------------------------------------------------------------------
-- Print_Time
--
-- Prints a line displaying: the measurement time, the data size, and
-- the performance (bytes per second).
--
-- E.g. Print_Time(1_048_576, Elapsed) where Elapsed represents a Time_Span
-- of 0.123 seconds would be displayed as:
-- "0.123000s, 1.0 MiB, 8.130 MiB/s"
----------------------------------------------------------------------------
procedure Print_Time(Data_Size : in Natural;
Time : in Ada.Real_Time.Time_Span)
is
package Duration_IO is new Ada.Text_IO.Fixed_IO(Duration);
begin
Duration_IO.Put(Ada.Real_Time.To_Duration(Time), Fore => 0, Aft => 6);
Ada.Text_IO.Put("s, ");
Print_Number(Float(Data_Size), "", 0);
Ada.Text_IO.Put(", ");
Print_Number(Float(Data_Size) / Float(Ada.Real_Time.To_Duration(Time)), "/s", 3);
Ada.Text_IO.New_Line;
end Print_Time;
----------------------------------------------------------------------------
-- Hash_Benchmark
--
-- Generic procedure to run a benchmark for any hash algorithm (e.g. SHA3-224,
-- Keccak-256, etc...).
----------------------------------------------------------------------------
generic
Name : String;
with package Hash_Package is new Keccak.Hash(<>);
procedure Hash_Benchmark;
procedure Hash_Benchmark
is
use type Ada.Real_Time.Time;
Ctx : Hash_Package.Context;
Digest : Hash_Package.Digest_Type;
Start_Time : Ada.Real_Time.Time;
End_Time : Ada.Real_Time.Time;
begin
for I in Positive range 1 .. Repeat loop
Start_Time := Ada.Real_Time.Clock;
Hash_Package.Init(Ctx);
for I in Positive range 1 .. Benchmark_Data_Size_MiB loop
Hash_Package.Update(Ctx, Data_Chunk, Data_Chunk'Length*8);
end loop;
Hash_Package.Final(Ctx, Digest);
End_Time := Ada.Real_Time.Clock;
Ada.Text_IO.Put(Name & ", ");
Print_Time(Data_Chunk'Length * Benchmark_Data_Size_MiB,
End_Time - Start_Time);
end loop;
end Hash_Benchmark;
----------------------------------------------------------------------------
-- XOF_Benchmark
--
-- Generic procedure to run a benchmark for any XOF algorithm (e.g. SHAKE128,
-- RawSHAKE256, etc...).
----------------------------------------------------------------------------
generic
Name : String;
with package XOF_Package is new Keccak.XOF(<>);
procedure XOF_Benchmark;
procedure XOF_Benchmark
is
use type Ada.Real_Time.Time;
Ctx : XOF_Package.Context;
Digest : XOF_Package.Byte_Array(1 .. 1024*1024);
Start_Time : Ada.Real_Time.Time;
End_Time : Ada.Real_Time.Time;
begin
-- Benchmark Absorbing
for I in Positive range 1 .. Repeat loop
Start_Time := Ada.Real_Time.Clock;
XOF_Package.Init(Ctx);
for I in Positive range 1 .. Benchmark_Data_Size_MiB loop
XOF_Package.Update(Ctx, Data_Chunk, Data_Chunk'Length*8);
end loop;
End_Time := Ada.Real_Time.Clock;
Ada.Text_IO.Put(Name & " (Absorbing), ");
Print_Time(Data_Chunk'Length * Benchmark_Data_Size_MiB,
End_Time - Start_Time);
end loop;
-- Benchmark squeezing
for I in Positive range 1 .. Repeat loop
Start_Time := Ada.Real_Time.Clock;
for I in Positive range 1 .. Benchmark_Data_Size_MiB loop
XOF_Package.Extract(Ctx, Digest);
end loop;
End_Time := Ada.Real_Time.Clock;
Ada.Text_IO.Put(Name & " (Squeezing), ");
Print_Time(Digest'Length * Benchmark_Data_Size_MiB,
End_Time - Start_Time);
end loop;
end XOF_Benchmark;
----------------------------------------------------------------------------
-- Duplex_Benchmark
--
-- Generic procedure to run a benchmark for any Duplex algorithm.
----------------------------------------------------------------------------
generic
Name : String;
Capacity : Positive;
with package Duplex is new Keccak.Duplex(<>);
procedure Duplex_Benchmark;
procedure Duplex_Benchmark
is
use type Ada.Real_Time.Time;
Ctx : Duplex.Context;
Out_Data : Keccak.Types.Byte_Array(1 .. 1600/8);
Start_Time : Ada.Real_Time.Time;
End_Time : Ada.Real_Time.Time;
Num_Iterations : Natural := (Benchmark_Data_Size_MiB*1024*1024) / ((1600-Capacity)/8);
begin
for I in Positive range 1 .. Repeat loop
Start_Time := Ada.Real_Time.Clock;
Duplex.Init(Ctx, Capacity);
for J in Positive range 1 .. Num_Iterations loop
Duplex.Duplex(Ctx,
Data_Chunk(1 .. Duplex.Rate_Of(Ctx)/8),
Duplex.Rate_Of(Ctx) - Duplex.Min_Padding_Bits,
Out_Data(1 .. Duplex.Rate_Of(Ctx)/8));
end loop;
End_Time := Ada.Real_Time.Clock;
Ada.Text_IO.Put(Name & ", ");
Print_Time((Duplex.Rate_Of(Ctx)/8) * Num_Iterations,
End_Time - Start_Time);
end loop;
end Duplex_Benchmark;
------------------------------------------------------------------------- ---
-- KeccakF_Benchmark
--
-- Generic procedure to run a benchmark for a KeccakF permutation.
----------------------------------------------------------------------------
generic
Name : String;
with package KeccakF is new Keccak.KeccakF(<>);
procedure KeccakF_Benchmark;
procedure KeccakF_Benchmark
is
use type Ada.Real_Time.Time;
package Duration_IO is new Ada.Text_IO.Fixed_IO(Duration);
package Integer_IO is new Ada.Text_IO.Integer_IO(Integer);
State : KeccakF.State;
Start_Time : Ada.Real_Time.Time;
End_Time : Ada.Real_Time.Time;
Num_Iterations : Natural := 1_000_000;
begin
KeccakF.Init(State);
for I in Positive range 1 .. Repeat loop
Start_Time := Ada.Real_Time.Clock;
for J in Positive range 1 .. Num_Iterations loop
KeccakF.Permute(State);
end loop;
End_Time := Ada.Real_Time.Clock;
Ada.Text_IO.Put(Name & ", ");
Duration_IO.Put(Ada.Real_Time.To_Duration(End_Time - Start_Time), Fore => 0, Aft => 6);
Ada.Text_IO.Put("s, ");
Integer_IO.Put(Item => Num_Iterations, Width => 0);
Ada.Text_IO.Put(" calls, ");
Duration_IO.Put((Ada.Real_Time.To_Duration(End_Time - Start_Time) * 1_000_000) / Num_Iterations, Fore => 0);
Ada.Text_IO.Put_Line(" us/call");
end loop;
end KeccakF_Benchmark;
----------------------------------------------------------------------------
-- Benchmark procedure instantiations.
----------------------------------------------------------------------------
procedure Benchmark_SHA_224 is new Hash_Benchmark
("SHA3-224", SHA3.SHA3_224);
procedure Benchmark_SHA_256 is new Hash_Benchmark
("SHA3-256", SHA3.SHA3_256);
procedure Benchmark_SHA_384 is new Hash_Benchmark
("SHA3-384", SHA3.SHA3_384);
procedure Benchmark_SHA_512 is new Hash_Benchmark
("SHA3-512", SHA3.SHA3_512);
procedure Benchmark_Keccak_224 is new Hash_Benchmark
("Keccak-224", SHA3.Keccak_224);
procedure Benchmark_Keccak_256 is new Hash_Benchmark
("Keccak-256", SHA3.Keccak_256);
procedure Benchmark_Keccak_384 is new Hash_Benchmark
("Keccak-384", SHA3.Keccak_384);
procedure Benchmark_Keccak_512 is new Hash_Benchmark
("Keccak-512", SHA3.Keccak_512);
procedure Benchmark_SHAKE128 is new XOF_Benchmark
("SHAKE128", SHAKE.SHAKE128);
procedure Benchmark_SHAKE256 is new XOF_Benchmark
("SHAKE256", SHAKE.SHAKE256);
procedure Benchmark_RawSHAKE128 is new XOF_Benchmark
("RawSHAKE128", RawSHAKE.RawSHAKE128);
procedure Benchmark_RawSHAKE256 is new XOF_Benchmark
("RawSHAKE256", RawSHAKE.RawSHAKE256);
procedure Benchmark_Duplex_r1152c448 is new Duplex_Benchmark
("Duplex r1152c448", 448, Keccak.Keccak_1600.Duplex);
procedure Benchmark_Duplex_r1088c512 is new Duplex_Benchmark
("Duplex r1088c512", 512, Keccak.Keccak_1600.Duplex);
procedure Benchmark_Duplex_r832c768 is new Duplex_Benchmark
("Duplex r832c768", 768, Keccak.Keccak_1600.Duplex);
procedure Benchmark_Duplex_r576c1024 is new Duplex_Benchmark
("Duplex r576c1024", 1024, Keccak.Keccak_1600.Duplex);
procedure Benchmark_KeccakF_25 is new KeccakF_Benchmark
("KeccakF[25]", Keccak.Keccak_25.KeccakF_25);
procedure Benchmark_KeccakF_50 is new KeccakF_Benchmark
("KeccakF[50]", Keccak.Keccak_50.KeccakF_50);
procedure Benchmark_KeccakF_100 is new KeccakF_Benchmark
("KeccakF[100]", Keccak.Keccak_100.KeccakF_100);
procedure Benchmark_KeccakF_200 is new KeccakF_Benchmark
("KeccakF[200]", Keccak.Keccak_200.KeccakF_200);
procedure Benchmark_KeccakF_400 is new KeccakF_Benchmark
("KeccakF[400]", Keccak.Keccak_400.KeccakF_400);
procedure Benchmark_KeccakF_800 is new KeccakF_Benchmark
("KeccakF[800]", Keccak.Keccak_800.KeccakF_800);
procedure Benchmark_KeccakF_1600 is new KeccakF_Benchmark
("KeccakF[1600]", Keccak.Keccak_1600.KeccakF_1600);
begin
Ada.Text_IO.Put_Line("Algorithm,Time,Data Length,Performance");
Benchmark_SHA_224;
Ada.Text_IO.New_Line;
Benchmark_SHA_256;
Ada.Text_IO.New_Line;
Benchmark_SHA_384;
Ada.Text_IO.New_Line;
Benchmark_SHA_512;
Ada.Text_IO.New_Line;
Benchmark_Keccak_224;
Ada.Text_IO.New_Line;
Benchmark_Keccak_256;
Ada.Text_IO.New_Line;
Benchmark_Keccak_384;
Ada.Text_IO.New_Line;
Benchmark_Keccak_512;
Ada.Text_IO.New_Line;
Benchmark_SHAKE128;
Ada.Text_IO.New_Line;
Benchmark_SHAKE256;
Ada.Text_IO.New_Line;
Benchmark_RawSHAKE128;
Ada.Text_IO.New_Line;
Benchmark_RawSHAKE256;
Ada.Text_IO.New_Line;
Benchmark_Duplex_r1152c448;
Ada.Text_IO.New_Line;
Benchmark_Duplex_r1088c512;
Ada.Text_IO.New_Line;
Benchmark_Duplex_r832c768;
Ada.Text_IO.New_Line;
Benchmark_Duplex_r576c1024;
Ada.Text_IO.New_Line;
Benchmark_KeccakF_1600;
Ada.Text_IO.New_Line;
Benchmark_KeccakF_800;
Ada.Text_IO.New_Line;
Benchmark_KeccakF_400;
Ada.Text_IO.New_Line;
Benchmark_KeccakF_200;
Ada.Text_IO.New_Line;
Benchmark_KeccakF_100;
Ada.Text_IO.New_Line;
Benchmark_KeccakF_50;
Ada.Text_IO.New_Line;
Benchmark_KeccakF_25;
Ada.Text_IO.New_Line;
end Benchmark;
|
Add Keccak permutations to the benchmark
|
Add Keccak permutations to the benchmark
|
Ada
|
bsd-3-clause
|
damaki/libkeccak
|
8c2afb6aa7c65efd95807691a4fdf684f82f5647
|
regtests/gen-testsuite.adb
|
regtests/gen-testsuite.adb
|
-----------------------------------------------------------------------
-- gen-testsuite -- Testsuite for gen
-- Copyright (C) 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Directories;
with Ada.Strings.Unbounded;
with Gen.Artifacts.XMI.Tests;
with Gen.Integration.Tests;
package body Gen.Testsuite is
Tests : aliased Util.Tests.Test_Suite;
Dir : Ada.Strings.Unbounded.Unbounded_String;
function Suite return Util.Tests.Access_Test_Suite is
Result : constant Util.Tests.Access_Test_Suite := Tests'Access;
begin
Gen.Artifacts.XMI.Tests.Add_Tests (Result);
Gen.Integration.Tests.Add_Tests (Result);
return Result;
end Suite;
-- ------------------------------
-- Get the test root directory.
-- ------------------------------
function Get_Test_Directory return String is
begin
return Ada.Strings.Unbounded.To_String (Dir);
end Get_Test_Directory;
procedure Initialize (Props : in Util.Properties.Manager) is
begin
Dir := Ada.Strings.Unbounded.To_Unbounded_String (Ada.Directories.Current_Directory);
end Initialize;
end Gen.Testsuite;
|
-----------------------------------------------------------------------
-- gen-testsuite -- Testsuite for gen
-- Copyright (C) 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Directories;
with Ada.Strings.Unbounded;
with Gen.Artifacts.XMI.Tests;
with Gen.Integration.Tests;
package body Gen.Testsuite is
Tests : aliased Util.Tests.Test_Suite;
Dir : Ada.Strings.Unbounded.Unbounded_String;
function Suite return Util.Tests.Access_Test_Suite is
Result : constant Util.Tests.Access_Test_Suite := Tests'Access;
begin
Gen.Artifacts.XMI.Tests.Add_Tests (Result);
Gen.Integration.Tests.Add_Tests (Result);
return Result;
end Suite;
-- ------------------------------
-- Get the test root directory.
-- ------------------------------
function Get_Test_Directory return String is
begin
return Ada.Strings.Unbounded.To_String (Dir);
end Get_Test_Directory;
procedure Initialize (Props : in Util.Properties.Manager) is
pragma Unreferenced (Props);
begin
Dir := Ada.Strings.Unbounded.To_Unbounded_String (Ada.Directories.Current_Directory);
end Initialize;
end Gen.Testsuite;
|
Fix compilation warning
|
Fix compilation warning
|
Ada
|
apache-2.0
|
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
|
612ec05d0d1b0d551db8506f532d90cdd5c320f5
|
awa/plugins/awa-blogs/src/awa-blogs-beans.ads
|
awa/plugins/awa-blogs/src/awa-blogs-beans.ads
|
-----------------------------------------------------------------------
-- awa-blogs-beans -- Beans for blog module
-- Copyright (C) 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2019 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Calendar;
with Ada.Strings.Unbounded;
with Ada.Containers.Indefinite_Hashed_Maps;
with Ada.Strings.Wide_Wide_Hash;
with Ada.Strings.Wide_Wide_Unbounded;
with Util.Beans.Basic;
with Util.Beans.Objects;
with ADO;
with ADO.Objects;
with Wiki.Strings;
with AWA.Blogs.Modules;
with AWA.Blogs.Models;
with AWA.Tags.Beans;
with AWA.Counters.Beans;
with AWA.Events;
with AWA.Components.Wikis;
-- == Ada Beans ==
-- Several bean types are provided to represent and manage the blogs and their posts.
-- The blog module registers the bean constructors when it is initialized.
-- To use them, one must declare a bean definition in the application XML configuration.
package AWA.Blogs.Beans is
-- Attributes exposed by <b>Post_Bean</b>
BLOG_ID_ATTR : constant String := "blogId";
POST_ID_ATTR : constant String := "id";
POST_UID_ATTR : constant String := "uid";
POST_TITLE_ATTR : constant String := "title";
POST_TEXT_ATTR : constant String := "text";
POST_URI_ATTR : constant String := "uri";
POST_STATUS_ATTR : constant String := "status";
POST_USERNAME_ATTR : constant String := "username";
POST_IMAGE_ATTR : constant String := "image";
POST_DESCRIPTION_ATTR : constant String := "description";
POST_TAG_ATTR : constant String := "tags";
POST_ALLOW_COMMENTS_ATTR : constant String := "allow_comments";
COUNTER_ATTR : constant String := "counter";
use Ada.Strings.Wide_Wide_Unbounded;
package Image_Info_Maps is
new Ada.Containers.Indefinite_Hashed_Maps (Key_Type => Wiki.Strings.WString,
Element_Type => Models.Image_Info,
Hash => Ada.Strings.Wide_Wide_Hash,
Equivalent_Keys => "=",
"=" => Models."=");
type Post_Links_Bean is new AWA.Components.Wikis.Link_Renderer_Bean with record
-- The wiki space identifier.
Post_Id : ADO.Identifier;
Images : Image_Info_Maps.Map;
end record;
procedure Make_Image_Link (Renderer : in out Post_Links_Bean;
Link : in Wiki.Strings.WString;
Info : in AWA.Blogs.Models.Image_Info;
URI : out Unbounded_Wide_Wide_String;
Width : in out Natural;
Height : in out Natural);
procedure Find_Image_Link (Renderer : in out Post_Links_Bean;
Link : in Wiki.Strings.WString;
URI : out Unbounded_Wide_Wide_String;
Width : in out Natural;
Height : in out Natural);
-- Get the image link that must be rendered from the wiki image link.
overriding
procedure Make_Image_Link (Renderer : in out Post_Links_Bean;
Link : in Wiki.Strings.WString;
URI : out Unbounded_Wide_Wide_String;
Width : in out Natural;
Height : in out Natural);
-- Get the page link that must be rendered from the wiki page link.
overriding
procedure Make_Page_Link (Renderer : in out Post_Links_Bean;
Link : in Wiki.Strings.WString;
URI : out Unbounded_Wide_Wide_String;
Exists : out Boolean);
-- ------------------------------
-- Blog Bean
-- ------------------------------
-- The <b>Blog_Bean</b> holds the information about the current blog.
-- It allows to create the blog as well as update its primary title.
type Blog_Bean is new AWA.Blogs.Models.Blog_Bean with record
Module : AWA.Blogs.Modules.Blog_Module_Access := null;
end record;
type Blog_Bean_Access is access all Blog_Bean'Class;
-- Get the value identified by the name.
overriding
function Get_Value (From : in Blog_Bean;
Name : in String) return Util.Beans.Objects.Object;
-- Set the value identified by the name.
overriding
procedure Set_Value (From : in out Blog_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object);
-- Create a new blog.
overriding
procedure Create (Bean : in out Blog_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String);
-- Load the blog information.
overriding
procedure Load (Bean : in out Blog_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String);
-- Handle an event to create the blog entry automatically.
overriding
procedure Create_Default (Bean : in out Blog_Bean;
Event : in AWA.Events.Module_Event'Class);
-- Create the Blog_Bean bean instance.
function Create_Blog_Bean (Module : in AWA.Blogs.Modules.Blog_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access;
-- ------------------------------
-- Post Bean
-- ------------------------------
-- The <b>Post_Bean</b> is used to create, update or display a post associated with a blog.
type Post_Bean is new AWA.Blogs.Models.Post_Bean with record
Module : AWA.Blogs.Modules.Blog_Module_Access := null;
Blog_Id : ADO.Identifier := ADO.NO_IDENTIFIER;
-- List of tags associated with the post.
Tags : aliased AWA.Tags.Beans.Tag_List_Bean;
Tags_Bean : Util.Beans.Basic.Readonly_Bean_Access;
-- The post page links.
Links : aliased Post_Links_Bean;
Links_Bean : Util.Beans.Basic.Readonly_Bean_Access;
-- The read post counter associated with the post.
Counter : aliased AWA.Counters.Beans.Counter_Bean (Of_Type => ADO.Objects.KEY_INTEGER,
Of_Class => Models.POST_TABLE);
Counter_Bean : Util.Beans.Basic.Readonly_Bean_Access;
-- The post description generated from the content.
Description : Ada.Strings.Unbounded.Unbounded_String;
Image_Link : Wiki.Strings.UString;
end record;
type Post_Bean_Access is access all Post_Bean'Class;
-- Build the URI from the post title and the post date.
function Get_Predefined_Uri (Title : in String;
Date : in Ada.Calendar.Time) return String;
-- Make the post description from the summary or the content.
procedure Make_Description (From : in out Post_Bean);
-- Get the value identified by the name.
overriding
function Get_Value (From : in Post_Bean;
Name : in String) return Util.Beans.Objects.Object;
-- Set the value identified by the name.
overriding
procedure Set_Value (From : in out Post_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object);
-- Load the post.
procedure Load_Post (Post : in out Post_Bean;
Id : in ADO.Identifier);
-- Create or save the post.
overriding
procedure Save (Bean : in out Post_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String);
-- Delete a post.
overriding
procedure Delete (Bean : in out Post_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String);
-- Load the post from the URI for the public display.
overriding
procedure Load (Bean : in out Post_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String);
-- Load the post from the URI for the administrator.
overriding
procedure Load_Admin (Bean : in out Post_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String);
-- Load the post from the URI either with visible comments or with all comments.
procedure Load (Bean : in out Post_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String;
Publish_Only : in Boolean);
-- Create the Post_Bean bean instance.
function Create_Post_Bean (Module : in AWA.Blogs.Modules.Blog_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access;
-- ------------------------------
-- Post List Bean
-- ------------------------------
-- The <b>Post_List_Bean</b> gives a list of visible posts to be displayed to users.
-- The list can be filtered by a given tag. The list pagination is supported.
type Post_List_Bean is new AWA.Blogs.Models.Post_List_Bean with record
Posts : aliased AWA.Blogs.Models.Post_Info_List_Bean;
Service : Modules.Blog_Module_Access := null;
Tags : AWA.Tags.Beans.Entity_Tag_Map;
Posts_Bean : AWA.Blogs.Models.Post_Info_List_Bean_Access;
-- The post page links.
Links : aliased Post_Links_Bean;
Links_Bean : access Post_Links_Bean;
-- The read post counter associated with the post.
Counter : aliased AWA.Counters.Beans.Counter_Bean (Of_Type => ADO.Objects.KEY_INTEGER,
Of_Class => Models.POST_TABLE);
Counter_Bean : AWA.Counters.Beans.Counter_Bean_Access;
end record;
type Post_List_Bean_Access is access all Post_List_Bean'Class;
-- Get the value identified by the name.
overriding
function Get_Value (From : in Post_List_Bean;
Name : in String) return Util.Beans.Objects.Object;
-- Set the value identified by the name.
overriding
procedure Set_Value (From : in out Post_List_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object);
overriding
procedure Load (From : in out Post_List_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String);
-- Load the list of posts. If a tag was set, filter the list of posts with the tag.
procedure Load_List (Into : in out Post_List_Bean);
-- Create the Post_List_Bean bean instance.
function Create_Post_List_Bean (Module : in AWA.Blogs.Modules.Blog_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access;
-- Get a select item list which contains a list of post status.
function Create_Status_List (Module : in AWA.Blogs.Modules.Blog_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access;
type Init_Flag is (INIT_BLOG_LIST, INIT_POST_LIST, INIT_COMMENT_LIST);
type Init_Map is array (Init_Flag) of Boolean;
-- ------------------------------
-- Admin List Bean
-- ------------------------------
-- The <b>Blog_Admin_Bean</b> is used for the administration of a blog. It gives the
-- list of posts that are created, published or not.
type Blog_Admin_Bean is new Util.Beans.Basic.Bean with record
Module : AWA.Blogs.Modules.Blog_Module_Access := null;
-- The blog identifier.
Blog_Id : ADO.Identifier := ADO.NO_IDENTIFIER;
-- List of blogs.
Blog_List : aliased AWA.Blogs.Models.Blog_Info_List_Bean;
Blog_List_Bean : AWA.Blogs.Models.Blog_Info_List_Bean_Access;
-- List of posts.
Post_List : aliased AWA.Blogs.Models.Admin_Post_Info_List_Bean;
Post_List_Bean : AWA.Blogs.Models.Admin_Post_Info_List_Bean_Access;
-- List of comments.
Comment_List : aliased AWA.Blogs.Models.Comment_Info_List_Bean;
Comment_List_Bean : AWA.Blogs.Models.Comment_Info_List_Bean_Access;
-- Initialization flags.
Init_Flags : aliased Init_Map := (others => False);
Flags : access Init_Map;
end record;
type Blog_Admin_Bean_Access is access all Blog_Admin_Bean;
-- Get the blog identifier.
function Get_Blog_Id (List : in Blog_Admin_Bean) return ADO.Identifier;
-- Load the posts associated with the current blog.
procedure Load_Posts (List : in Blog_Admin_Bean);
-- Load the comments associated with the current blog.
procedure Load_Comments (List : in Blog_Admin_Bean);
overriding
function Get_Value (List : in Blog_Admin_Bean;
Name : in String) return Util.Beans.Objects.Object;
-- Set the value identified by the name.
overriding
procedure Set_Value (From : in out Blog_Admin_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object);
-- Load the list of blogs.
procedure Load_Blogs (List : in Blog_Admin_Bean);
-- Create the Blog_Admin_Bean bean instance.
function Create_Blog_Admin_Bean (Module : in AWA.Blogs.Modules.Blog_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access;
-- ------------------------------
-- Blog Statistics Bean
-- ------------------------------
-- The <b>Blog_Stat_Bean</b> is used to report various statistics about the blog or some post.
type Blog_Stat_Bean is new AWA.Blogs.Models.Stat_List_Bean with record
Module : AWA.Blogs.Modules.Blog_Module_Access := null;
Stats : aliased AWA.Blogs.Models.Month_Stat_Info_List_Bean;
Stats_Bean : AWA.Blogs.Models.Month_Stat_Info_List_Bean_Access;
end record;
type Blog_Stat_Bean_Access is access all Blog_Stat_Bean;
overriding
function Get_Value (List : in Blog_Stat_Bean;
Name : in String) return Util.Beans.Objects.Object;
-- Set the value identified by the name.
overriding
procedure Set_Value (From : in out Blog_Stat_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object);
-- Load the statistics information.
overriding
procedure Load (List : in out Blog_Stat_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String);
-- Create the Blog_Stat_Bean bean instance.
function Create_Blog_Stat_Bean (Module : in AWA.Blogs.Modules.Blog_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access;
end AWA.Blogs.Beans;
|
-----------------------------------------------------------------------
-- awa-blogs-beans -- Beans for blog module
-- Copyright (C) 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2019 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Calendar;
with Ada.Strings.Unbounded;
with Ada.Containers.Indefinite_Hashed_Maps;
with Ada.Strings.Wide_Wide_Hash;
with Ada.Strings.Wide_Wide_Unbounded;
with Util.Beans.Basic;
with Util.Beans.Objects;
with ADO;
with ADO.Objects;
with Wiki.Strings;
with ASF.Helpers.Beans;
with AWA.Blogs.Modules;
with AWA.Blogs.Models;
with AWA.Tags.Beans;
with AWA.Counters.Beans;
with AWA.Events;
with AWA.Components.Wikis;
-- == Ada Beans ==
-- Several bean types are provided to represent and manage the blogs and their posts.
-- The blog module registers the bean constructors when it is initialized.
-- To use them, one must declare a bean definition in the application XML configuration.
package AWA.Blogs.Beans is
-- Attributes exposed by <b>Post_Bean</b>
BLOG_ID_ATTR : constant String := "blogId";
POST_ID_ATTR : constant String := "id";
POST_UID_ATTR : constant String := "uid";
POST_TITLE_ATTR : constant String := "title";
POST_TEXT_ATTR : constant String := "text";
POST_URI_ATTR : constant String := "uri";
POST_STATUS_ATTR : constant String := "status";
POST_USERNAME_ATTR : constant String := "username";
POST_IMAGE_ATTR : constant String := "image";
POST_DESCRIPTION_ATTR : constant String := "description";
POST_TAG_ATTR : constant String := "tags";
POST_ALLOW_COMMENTS_ATTR : constant String := "allow_comments";
COUNTER_ATTR : constant String := "counter";
use Ada.Strings.Wide_Wide_Unbounded;
-- Get a select item list which contains a list of blog post formats.
function Create_Format_List_Bean (Module : in AWA.Blogs.Modules.Blog_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access;
package Image_Info_Maps is
new Ada.Containers.Indefinite_Hashed_Maps (Key_Type => Wiki.Strings.WString,
Element_Type => Models.Image_Info,
Hash => Ada.Strings.Wide_Wide_Hash,
Equivalent_Keys => "=",
"=" => Models."=");
type Post_Links_Bean is new AWA.Components.Wikis.Link_Renderer_Bean with record
-- The wiki space identifier.
Post_Id : ADO.Identifier;
Images : Image_Info_Maps.Map;
end record;
procedure Make_Image_Link (Renderer : in out Post_Links_Bean;
Link : in Wiki.Strings.WString;
Info : in AWA.Blogs.Models.Image_Info;
URI : out Unbounded_Wide_Wide_String;
Width : in out Natural;
Height : in out Natural);
procedure Find_Image_Link (Renderer : in out Post_Links_Bean;
Link : in Wiki.Strings.WString;
URI : out Unbounded_Wide_Wide_String;
Width : in out Natural;
Height : in out Natural);
-- Get the image link that must be rendered from the wiki image link.
overriding
procedure Make_Image_Link (Renderer : in out Post_Links_Bean;
Link : in Wiki.Strings.WString;
URI : out Unbounded_Wide_Wide_String;
Width : in out Natural;
Height : in out Natural);
-- Get the page link that must be rendered from the wiki page link.
overriding
procedure Make_Page_Link (Renderer : in out Post_Links_Bean;
Link : in Wiki.Strings.WString;
URI : out Unbounded_Wide_Wide_String;
Exists : out Boolean);
-- ------------------------------
-- Blog Bean
-- ------------------------------
-- The <b>Blog_Bean</b> holds the information about the current blog.
-- It allows to create the blog as well as update its primary title.
type Blog_Bean is new AWA.Blogs.Models.Blog_Bean with record
Module : AWA.Blogs.Modules.Blog_Module_Access := null;
end record;
type Blog_Bean_Access is access all Blog_Bean'Class;
-- Get the value identified by the name.
overriding
function Get_Value (From : in Blog_Bean;
Name : in String) return Util.Beans.Objects.Object;
-- Set the value identified by the name.
overriding
procedure Set_Value (From : in out Blog_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object);
-- Create a new blog.
overriding
procedure Create (Bean : in out Blog_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String);
-- Load the blog information.
overriding
procedure Load (Bean : in out Blog_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String);
-- Handle an event to create the blog entry automatically.
overriding
procedure Create_Default (Bean : in out Blog_Bean;
Event : in AWA.Events.Module_Event'Class);
-- Create the Blog_Bean bean instance.
function Create_Blog_Bean (Module : in AWA.Blogs.Modules.Blog_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access;
function Get_Blog_Bean is
new ASF.Helpers.Beans.Get_Bean (Element_Type => Blog_Bean,
Element_Access => Blog_Bean_Access);
-- ------------------------------
-- Post Bean
-- ------------------------------
-- The <b>Post_Bean</b> is used to create, update or display a post associated with a blog.
type Post_Bean is new AWA.Blogs.Models.Post_Bean with record
Module : AWA.Blogs.Modules.Blog_Module_Access := null;
Blog_Id : ADO.Identifier := ADO.NO_IDENTIFIER;
-- List of tags associated with the post.
Tags : aliased AWA.Tags.Beans.Tag_List_Bean;
Tags_Bean : Util.Beans.Basic.Readonly_Bean_Access;
-- The post page links.
Links : aliased Post_Links_Bean;
Links_Bean : Util.Beans.Basic.Readonly_Bean_Access;
-- The read post counter associated with the post.
Counter : aliased AWA.Counters.Beans.Counter_Bean (Of_Type => ADO.Objects.KEY_INTEGER,
Of_Class => Models.POST_TABLE);
Counter_Bean : Util.Beans.Basic.Readonly_Bean_Access;
-- The post description generated from the content.
Description : Ada.Strings.Unbounded.Unbounded_String;
Image_Link : Wiki.Strings.UString;
end record;
type Post_Bean_Access is access all Post_Bean'Class;
-- Build the URI from the post title and the post date.
function Get_Predefined_Uri (Title : in String;
Date : in Ada.Calendar.Time) return String;
-- Make the post description from the summary or the content.
procedure Make_Description (From : in out Post_Bean);
-- Get the value identified by the name.
overriding
function Get_Value (From : in Post_Bean;
Name : in String) return Util.Beans.Objects.Object;
-- Set the value identified by the name.
overriding
procedure Set_Value (From : in out Post_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object);
-- Load the post.
procedure Load_Post (Post : in out Post_Bean;
Id : in ADO.Identifier);
-- Create or save the post.
overriding
procedure Save (Bean : in out Post_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String);
-- Delete a post.
overriding
procedure Delete (Bean : in out Post_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String);
-- Load the post from the URI for the public display.
overriding
procedure Load (Bean : in out Post_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String);
-- Setup the bean to create a new post.
overriding
procedure Setup (Bean : in out Post_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String);
-- Load the post from the URI for the administrator.
overriding
procedure Load_Admin (Bean : in out Post_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String);
-- Load the post from the URI either with visible comments or with all comments.
procedure Load (Bean : in out Post_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String;
Publish_Only : in Boolean);
-- Create the Post_Bean bean instance.
function Create_Post_Bean (Module : in AWA.Blogs.Modules.Blog_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access;
-- ------------------------------
-- Post List Bean
-- ------------------------------
-- The <b>Post_List_Bean</b> gives a list of visible posts to be displayed to users.
-- The list can be filtered by a given tag. The list pagination is supported.
type Post_List_Bean is new AWA.Blogs.Models.Post_List_Bean with record
Posts : aliased AWA.Blogs.Models.Post_Info_List_Bean;
Service : Modules.Blog_Module_Access := null;
Tags : AWA.Tags.Beans.Entity_Tag_Map;
Posts_Bean : AWA.Blogs.Models.Post_Info_List_Bean_Access;
-- The post page links.
Links : aliased Post_Links_Bean;
Links_Bean : access Post_Links_Bean;
-- The read post counter associated with the post.
Counter : aliased AWA.Counters.Beans.Counter_Bean (Of_Type => ADO.Objects.KEY_INTEGER,
Of_Class => Models.POST_TABLE);
Counter_Bean : AWA.Counters.Beans.Counter_Bean_Access;
end record;
type Post_List_Bean_Access is access all Post_List_Bean'Class;
-- Get the value identified by the name.
overriding
function Get_Value (From : in Post_List_Bean;
Name : in String) return Util.Beans.Objects.Object;
-- Set the value identified by the name.
overriding
procedure Set_Value (From : in out Post_List_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object);
overriding
procedure Load (From : in out Post_List_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String);
-- Load the list of posts. If a tag was set, filter the list of posts with the tag.
procedure Load_List (Into : in out Post_List_Bean);
-- Create the Post_List_Bean bean instance.
function Create_Post_List_Bean (Module : in AWA.Blogs.Modules.Blog_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access;
-- Get a select item list which contains a list of post status.
function Create_Status_List (Module : in AWA.Blogs.Modules.Blog_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access;
type Init_Flag is (INIT_BLOG_LIST, INIT_POST_LIST, INIT_COMMENT_LIST);
type Init_Map is array (Init_Flag) of Boolean;
-- ------------------------------
-- Admin List Bean
-- ------------------------------
-- The <b>Blog_Admin_Bean</b> is used for the administration of a blog. It gives the
-- list of posts that are created, published or not.
type Blog_Admin_Bean is new Util.Beans.Basic.Bean with record
Module : AWA.Blogs.Modules.Blog_Module_Access := null;
-- The blog identifier.
Blog_Id : ADO.Identifier := ADO.NO_IDENTIFIER;
-- List of blogs.
Blog_List : aliased AWA.Blogs.Models.Blog_Info_List_Bean;
Blog_List_Bean : AWA.Blogs.Models.Blog_Info_List_Bean_Access;
-- List of posts.
Post_List : aliased AWA.Blogs.Models.Admin_Post_Info_List_Bean;
Post_List_Bean : AWA.Blogs.Models.Admin_Post_Info_List_Bean_Access;
-- List of comments.
Comment_List : aliased AWA.Blogs.Models.Comment_Info_List_Bean;
Comment_List_Bean : AWA.Blogs.Models.Comment_Info_List_Bean_Access;
-- Initialization flags.
Init_Flags : aliased Init_Map := (others => False);
Flags : access Init_Map;
end record;
type Blog_Admin_Bean_Access is access all Blog_Admin_Bean;
-- Get the blog identifier.
function Get_Blog_Id (List : in Blog_Admin_Bean) return ADO.Identifier;
-- Load the posts associated with the current blog.
procedure Load_Posts (List : in Blog_Admin_Bean);
-- Load the comments associated with the current blog.
procedure Load_Comments (List : in Blog_Admin_Bean);
overriding
function Get_Value (List : in Blog_Admin_Bean;
Name : in String) return Util.Beans.Objects.Object;
-- Set the value identified by the name.
overriding
procedure Set_Value (From : in out Blog_Admin_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object);
-- Load the list of blogs.
procedure Load_Blogs (List : in Blog_Admin_Bean);
-- Create the Blog_Admin_Bean bean instance.
function Create_Blog_Admin_Bean (Module : in AWA.Blogs.Modules.Blog_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access;
-- ------------------------------
-- Blog Statistics Bean
-- ------------------------------
-- The <b>Blog_Stat_Bean</b> is used to report various statistics about the blog or some post.
type Blog_Stat_Bean is new AWA.Blogs.Models.Stat_List_Bean with record
Module : AWA.Blogs.Modules.Blog_Module_Access := null;
Stats : aliased AWA.Blogs.Models.Month_Stat_Info_List_Bean;
Stats_Bean : AWA.Blogs.Models.Month_Stat_Info_List_Bean_Access;
end record;
type Blog_Stat_Bean_Access is access all Blog_Stat_Bean;
overriding
function Get_Value (List : in Blog_Stat_Bean;
Name : in String) return Util.Beans.Objects.Object;
-- Set the value identified by the name.
overriding
procedure Set_Value (From : in out Blog_Stat_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object);
-- Load the statistics information.
overriding
procedure Load (List : in out Blog_Stat_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String);
-- Create the Blog_Stat_Bean bean instance.
function Create_Blog_Stat_Bean (Module : in AWA.Blogs.Modules.Blog_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access;
end AWA.Blogs.Beans;
|
Add Create_Format_List_Bean function and override Setup procedure for the Post_Bean
|
Add Create_Format_List_Bean function and override Setup procedure for the Post_Bean
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
72f58089f3da3dfe96ee9135497dc1bd647c9206
|
opengl-types.ads
|
opengl-types.ads
|
with Ada.Numerics.Generic_Real_Arrays;
with OpenGL.Thin;
package OpenGL.Types is
package Float_Arrays is new Ada.Numerics.Generic_Real_Arrays
(Real => OpenGL.Thin.Float_t);
package Double_Arrays is new Ada.Numerics.Generic_Real_Arrays
(Real => OpenGL.Thin.Double_t);
type Vector_3f_t is new Float_Arrays.Real_Vector (1 .. 3);
type Vector_4f_t is new Float_Arrays.Real_Vector (1 .. 3);
subtype Float_t is Thin.Float_t;
subtype Double_t is Thin.Double_t;
subtype Clamped_Double_t is Double_t range 0.0 .. 1.0;
subtype Clamped_Float_t is Float_t range 0.0 .. 1.0;
end OpenGL.Types;
|
with Ada.Numerics.Generic_Real_Arrays;
with OpenGL.Thin;
package OpenGL.Types is
package Float_Arrays is new Ada.Numerics.Generic_Real_Arrays
(Real => OpenGL.Thin.Float_t);
package Double_Arrays is new Ada.Numerics.Generic_Real_Arrays
(Real => OpenGL.Thin.Double_t);
type Vector_2f_t is new Float_Arrays.Real_Vector (1 .. 2);
type Vector_3f_t is new Float_Arrays.Real_Vector (1 .. 3);
type Vector_4f_t is new Float_Arrays.Real_Vector (1 .. 4);
subtype Float_t is Thin.Float_t;
subtype Double_t is Thin.Double_t;
subtype Clamped_Double_t is Double_t range 0.0 .. 1.0;
subtype Clamped_Float_t is Float_t range 0.0 .. 1.0;
end OpenGL.Types;
|
update vector types.
|
update vector types.
|
Ada
|
isc
|
io7m/coreland-opengl-ada,io7m/coreland-opengl-ada
|
11d9a364bee1a2f889b8178e867880c87a43a521
|
src/os-linux/util-systems-os.ads
|
src/os-linux/util-systems-os.ads
|
-----------------------------------------------------------------------
-- util-system-os -- Unix system operations
-- Copyright (C) 2011, 2012, 2014 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with System;
with Interfaces.C;
with Interfaces.C.Strings;
with Util.Processes;
with Util.Systems.Constants;
with Util.Systems.Types;
-- The <b>Util.Systems.Os</b> package defines various types and operations which are specific
-- to the OS (Unix).
package Util.Systems.Os is
-- The directory separator.
Directory_Separator : constant Character := '/';
subtype Ptr is Interfaces.C.Strings.chars_ptr;
subtype Ptr_Array is Interfaces.C.Strings.chars_ptr_array;
type Ptr_Ptr_Array is access all Ptr_Array;
type File_Type is new Integer;
-- Standard file streams Posix, X/Open standard values.
STDIN_FILENO : constant File_Type := 0;
STDOUT_FILENO : constant File_Type := 1;
STDERR_FILENO : constant File_Type := 2;
-- File is not opened
NO_FILE : constant File_Type := -1;
-- The following values should be externalized. They are valid for GNU/Linux.
F_SETFL : constant Interfaces.C.int := Util.Systems.Constants.F_SETFL;
FD_CLOEXEC : constant Interfaces.C.int := Util.Systems.Constants.FD_CLOEXEC;
-- These values are specific to Linux.
O_RDONLY : constant Interfaces.C.int := Util.Systems.Constants.O_RDONLY;
O_WRONLY : constant Interfaces.C.int := Util.Systems.Constants.O_WRONLY;
O_RDWR : constant Interfaces.C.int := Util.Systems.Constants.O_RDWR;
O_CREAT : constant Interfaces.C.int := Util.Systems.Constants.O_CREAT;
O_EXCL : constant Interfaces.C.int := Util.Systems.Constants.O_EXCL;
O_TRUNC : constant Interfaces.C.int := Util.Systems.Constants.O_TRUNC;
O_APPEND : constant Interfaces.C.int := Util.Systems.Constants.O_APPEND;
type Size_T is mod 2 ** Standard'Address_Size;
type Ssize_T is range -(2 ** (Standard'Address_Size - 1))
.. +(2 ** (Standard'Address_Size - 1)) - 1;
function Close (Fd : in File_Type) return Integer;
pragma Import (C, Close, "close");
function Read (Fd : in File_Type;
Buf : in System.Address;
Size : in Size_T) return Ssize_T;
pragma Import (C, Read, "read");
function Write (Fd : in File_Type;
Buf : in System.Address;
Size : in Size_T) return Ssize_T;
pragma Import (C, Write, "write");
-- System exit without any process cleaning.
-- (destructors, finalizers, atexit are not called)
procedure Sys_Exit (Code : in Integer);
pragma Import (C, Sys_Exit, "_exit");
-- Fork a new process
function Sys_Fork return Util.Processes.Process_Identifier;
pragma Import (C, Sys_Fork, "fork");
-- Fork a new process (vfork implementation)
function Sys_VFork return Util.Processes.Process_Identifier;
pragma Import (C, Sys_VFork, "fork");
-- Execute a process with the given arguments.
function Sys_Execvp (File : in Ptr;
Args : in Ptr_Array) return Integer;
pragma Import (C, Sys_Execvp, "execvp");
-- Wait for the process <b>Pid</b> to finish and return
function Sys_Waitpid (Pid : in Integer;
Status : in System.Address;
Options : in Integer) return Integer;
pragma Import (C, Sys_Waitpid, "waitpid");
-- Create a bi-directional pipe
function Sys_Pipe (Fds : in System.Address) return Integer;
pragma Import (C, Sys_Pipe, "pipe");
-- Make <b>fd2</b> the copy of <b>fd1</b>
function Sys_Dup2 (Fd1, Fd2 : in File_Type) return Integer;
pragma Import (C, Sys_Dup2, "dup2");
-- Close a file
function Sys_Close (Fd : in File_Type) return Integer;
pragma Import (C, Sys_Close, "close");
-- Open a file
function Sys_Open (Path : in Ptr;
Flags : in Interfaces.C.int;
Mode : in Interfaces.C.int) return File_Type;
pragma Import (C, Sys_Open, "open");
-- Change the file settings
function Sys_Fcntl (Fd : in File_Type;
Cmd : in Interfaces.C.int;
Flags : in Interfaces.C.int) return Integer;
pragma Import (C, Sys_Fcntl, "fcntl");
function Sys_Kill (Pid : in Integer;
Signal : in Integer) return Integer;
pragma Import (C, Sys_Kill, "kill");
function Sys_Stat (Path : in Ptr;
Stat : access Util.Systems.Types.Stat_Type) return Integer;
pragma Import (C, Sys_Stat, "stat");
function Sys_Fstat (Fs : in File_Type;
Stat : access Util.Systems.Types.Stat_Type) return Integer;
pragma Import (C, Sys_Fstat, "fstat");
end Util.Systems.Os;
|
-----------------------------------------------------------------------
-- util-system-os -- Unix system operations
-- Copyright (C) 2011, 2012, 2014 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with System;
with Interfaces.C;
with Interfaces.C.Strings;
with Util.Processes;
with Util.Systems.Constants;
with Util.Systems.Types;
-- The <b>Util.Systems.Os</b> package defines various types and operations which are specific
-- to the OS (Unix).
package Util.Systems.Os is
-- The directory separator.
Directory_Separator : constant Character := '/';
subtype Ptr is Interfaces.C.Strings.chars_ptr;
subtype Ptr_Array is Interfaces.C.Strings.chars_ptr_array;
type Ptr_Ptr_Array is access all Ptr_Array;
type File_Type is new Integer;
-- Standard file streams Posix, X/Open standard values.
STDIN_FILENO : constant File_Type := 0;
STDOUT_FILENO : constant File_Type := 1;
STDERR_FILENO : constant File_Type := 2;
-- File is not opened
NO_FILE : constant File_Type := -1;
-- The following values should be externalized. They are valid for GNU/Linux.
F_SETFL : constant Interfaces.C.int := Util.Systems.Constants.F_SETFL;
FD_CLOEXEC : constant Interfaces.C.int := Util.Systems.Constants.FD_CLOEXEC;
-- These values are specific to Linux.
O_RDONLY : constant Interfaces.C.int := Util.Systems.Constants.O_RDONLY;
O_WRONLY : constant Interfaces.C.int := Util.Systems.Constants.O_WRONLY;
O_RDWR : constant Interfaces.C.int := Util.Systems.Constants.O_RDWR;
O_CREAT : constant Interfaces.C.int := Util.Systems.Constants.O_CREAT;
O_EXCL : constant Interfaces.C.int := Util.Systems.Constants.O_EXCL;
O_TRUNC : constant Interfaces.C.int := Util.Systems.Constants.O_TRUNC;
O_APPEND : constant Interfaces.C.int := Util.Systems.Constants.O_APPEND;
type Size_T is mod 2 ** Standard'Address_Size;
type Ssize_T is range -(2 ** (Standard'Address_Size - 1))
.. +(2 ** (Standard'Address_Size - 1)) - 1;
function Close (Fd : in File_Type) return Integer;
pragma Import (C, Close, "close");
function Read (Fd : in File_Type;
Buf : in System.Address;
Size : in Size_T) return Ssize_T;
pragma Import (C, Read, "read");
function Write (Fd : in File_Type;
Buf : in System.Address;
Size : in Size_T) return Ssize_T;
pragma Import (C, Write, "write");
-- System exit without any process cleaning.
-- (destructors, finalizers, atexit are not called)
procedure Sys_Exit (Code : in Integer);
pragma Import (C, Sys_Exit, "_exit");
-- Fork a new process
function Sys_Fork return Util.Processes.Process_Identifier;
pragma Import (C, Sys_Fork, "fork");
-- Fork a new process (vfork implementation)
function Sys_VFork return Util.Processes.Process_Identifier;
pragma Import (C, Sys_VFork, "fork");
-- Execute a process with the given arguments.
function Sys_Execvp (File : in Ptr;
Args : in Ptr_Array) return Integer;
pragma Import (C, Sys_Execvp, "execvp");
-- Wait for the process <b>Pid</b> to finish and return
function Sys_Waitpid (Pid : in Integer;
Status : in System.Address;
Options : in Integer) return Integer;
pragma Import (C, Sys_Waitpid, "waitpid");
-- Create a bi-directional pipe
function Sys_Pipe (Fds : in System.Address) return Integer;
pragma Import (C, Sys_Pipe, "pipe");
-- Make <b>fd2</b> the copy of <b>fd1</b>
function Sys_Dup2 (Fd1, Fd2 : in File_Type) return Integer;
pragma Import (C, Sys_Dup2, "dup2");
-- Close a file
function Sys_Close (Fd : in File_Type) return Integer;
pragma Import (C, Sys_Close, "close");
-- Open a file
function Sys_Open (Path : in Ptr;
Flags : in Interfaces.C.int;
Mode : in Interfaces.C.int) return File_Type;
pragma Import (C, Sys_Open, "open");
-- Change the file settings
function Sys_Fcntl (Fd : in File_Type;
Cmd : in Interfaces.C.int;
Flags : in Interfaces.C.int) return Integer;
pragma Import (C, Sys_Fcntl, "fcntl");
function Sys_Kill (Pid : in Integer;
Signal : in Integer) return Integer;
pragma Import (C, Sys_Kill, "kill");
function Sys_Stat (Path : in Ptr;
Stat : access Util.Systems.Types.Stat_Type) return Integer;
pragma Import (C, Sys_Stat, Util.Systems.Types.STAT_NAME);
function Sys_Fstat (Fs : in File_Type;
Stat : access Util.Systems.Types.Stat_Type) return Integer;
pragma Import (C, Sys_Fstat, Util.Systems.Types.FSTAT_NAME);
end Util.Systems.Os;
|
Use the generated system call name for stat() and fstat()
|
Use the generated system call name for stat() and fstat()
|
Ada
|
apache-2.0
|
flottokarotto/ada-util,Letractively/ada-util,flottokarotto/ada-util,Letractively/ada-util
|
ae37d999e32d1f53e8d1baa4b9011d3f3fb012a0
|
samples/openid.adb
|
samples/openid.adb
|
-----------------------------------------------------------------------
-- openid -- Example of OpenID 2.0 Authentication
-- 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.Text_IO;
with Ada.Exceptions;
with Ada.IO_Exceptions;
with ASF.Server.Web;
with ASF.Applications;
with ASF.Applications.Main;
with ASF.Servlets.Faces;
with ASF.Servlets.Files;
with ASF.Servlets.Measures;
with ASF.Filters.Dump;
with Util.Beans.Objects;
with Util.Log.Loggers;
with Users;
with AWS.Net.SSL;
with Security.Openid;
with Security.Openid.Servlets;
procedure Openid is
use ASF.Applications;
Log : Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Openid");
CONTEXT_PATH : constant String := "/openid";
CONFIG_PATH : constant String := "samples.properties";
User : aliased Users.User_Info;
App : aliased ASF.Applications.Main.Application;
Factory : ASF.Applications.Main.Application_Factory;
C : ASF.Applications.Config;
-- Application servlets.
Faces : aliased ASF.Servlets.Faces.Faces_Servlet;
Files : aliased ASF.Servlets.Files.File_Servlet;
Perf : aliased ASF.Servlets.Measures.Measure_Servlet;
Auth : aliased Security.Openid.Servlets.Request_Auth_Servlet;
Verify_Auth : aliased Security.Openid.Servlets.Verify_Auth_Servlet;
-- Debug filters.
Dump : aliased ASF.Filters.Dump.Dump_Filter;
-- Web application server
WS : ASF.Server.Web.AWS_Container;
begin
if not AWS.Net.SSL.Is_Supported then
Log.Error ("SSL is not supported by AWS.");
Log.Error ("SSL is required for the OpenID connector to connect to OpenID providers.");
Log.Error ("Please, rebuild AWS with SSL support.");
return;
end if;
begin
C.Load_Properties (CONFIG_PATH);
exception
when Ada.IO_Exceptions.Name_Error =>
Log.Error ("Cannot read application configuration file {0}", CONFIG_PATH);
end;
App.Initialize (C, Factory);
App.Register ("samplesMsg", "samples");
App.Set_Global ("contextPath", "/openid");
-- Declare a global bean to identify this sample from within the XHTML files.
App.Set_Global ("sampleName", "openid");
App.Set_Global ("version", "0.1");
App.Set_Global ("user", Util.Beans.Objects.To_Object (User'Unchecked_Access,
Util.Beans.Objects.STATIC));
-- Register the servlets and filters
App.Add_Servlet (Name => "faces", Server => Faces'Unchecked_Access);
App.Add_Servlet (Name => "files", Server => Files'Unchecked_Access);
App.Add_Servlet (Name => "auth", Server => Auth'Unchecked_Access);
App.Add_Servlet (Name => "verify-auth", Server => Verify_Auth'Unchecked_Access);
App.Add_Servlet (Name => "perf", Server => Perf'Unchecked_Access);
-- Register the filters
App.Add_Filter (Name => "perf", Filter => Perf'Unchecked_Access);
App.Add_Filter (Name => "dump", Filter => Dump'Unchecked_Access);
-- Define servlet mappings
App.Add_Mapping (Name => "faces", Pattern => "*.html");
App.Add_Mapping (Name => "files", Pattern => "*.css");
App.Add_Mapping (Name => "files", Pattern => "*.js");
App.Add_Mapping (Name => "files", Pattern => "*.png");
App.Add_Mapping (Name => "files", Pattern => "*.jpg");
App.Add_Mapping (Name => "verify-auth", Pattern => "/auth/verify");
App.Add_Mapping (Name => "auth", Pattern => "/auth/auth/*");
App.Add_Mapping (Name => "perf", Pattern => "/statistics.xml");
-- Install the debug filter.
App.Add_Filter_Mapping (Name => "perf", Pattern => "*.html");
App.Add_Filter_Mapping (Name => "dump", Pattern => "*.html");
App.Add_Filter_Mapping (Name => "perf", Pattern => "*.css");
App.Add_Filter_Mapping (Name => "dump", Pattern => "*.css");
App.Add_Filter_Mapping (Name => "perf", Pattern => "*.png");
App.Add_Filter_Mapping (Name => "dump", Pattern => "*.png");
App.Add_Filter_Mapping (Name => "perf", Pattern => "*.jpg");
App.Add_Filter_Mapping (Name => "dump", Pattern => "*.jpg");
App.Add_Filter_Mapping (Name => "perf", Pattern => "/auth/verify");
App.Add_Filter_Mapping (Name => "dump", Pattern => "/auth/verify");
App.Add_Filter_Mapping (Name => "perf", Pattern => "/auth/auth/*");
App.Add_Filter_Mapping (Name => "dump", Pattern => "/auth/auth/*");
WS.Register_Application (CONTEXT_PATH, App'Unchecked_Access);
Log.Info ("Connect you browser to: http://localhost:8080/openid/auth/login.html");
WS.Start;
delay 600.0;
App.Close;
exception
when E : others =>
Ada.Text_IO.Put_Line ("Exception in server: " &
Ada.Exceptions.Exception_Name (E) & ": " &
Ada.Exceptions.Exception_Message (E));
end Openid;
|
-----------------------------------------------------------------------
-- openid -- Example of OpenID 2.0 Authentication
-- Copyright (C) 2011, 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Text_IO;
with Ada.Exceptions;
with Ada.IO_Exceptions;
with ASF.Server.Web;
with ASF.Applications;
with ASF.Applications.Main;
with ASF.Servlets.Faces;
with ASF.Servlets.Files;
with ASF.Servlets.Measures;
with ASF.Filters.Dump;
with Util.Beans.Objects;
with Util.Log.Loggers;
with Users;
with AWS.Net.SSL;
with Security.Openid;
with Security.Openid.Servlets;
procedure Openid is
use ASF.Applications;
Log : Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Openid");
CONTEXT_PATH : constant String := "/openid";
CONFIG_PATH : constant String := "samples.properties";
App : aliased ASF.Applications.Main.Application;
Factory : ASF.Applications.Main.Application_Factory;
C : ASF.Applications.Config;
-- Application servlets.
Faces : aliased ASF.Servlets.Faces.Faces_Servlet;
Files : aliased ASF.Servlets.Files.File_Servlet;
Perf : aliased ASF.Servlets.Measures.Measure_Servlet;
Auth : aliased Security.Openid.Servlets.Request_Auth_Servlet;
Verify_Auth : aliased Security.Openid.Servlets.Verify_Auth_Servlet;
-- Debug filters.
Dump : aliased ASF.Filters.Dump.Dump_Filter;
-- Web application server
WS : ASF.Server.Web.AWS_Container;
begin
if not AWS.Net.SSL.Is_Supported then
Log.Error ("SSL is not supported by AWS.");
Log.Error ("SSL is required for the OpenID connector to connect to OpenID providers.");
Log.Error ("Please, rebuild AWS with SSL support.");
return;
end if;
begin
C.Load_Properties (CONFIG_PATH);
exception
when Ada.IO_Exceptions.Name_Error =>
Log.Error ("Cannot read application configuration file {0}", CONFIG_PATH);
end;
App.Initialize (C, Factory);
App.Register ("samplesMsg", "samples");
App.Set_Global ("contextPath", "/openid");
-- Declare a global bean to identify this sample from within the XHTML files.
App.Set_Global ("sampleName", "openid");
App.Set_Global ("version", "0.1");
App.Set_Global ("user", Util.Beans.Objects.To_Object (Users.User'Access,
Util.Beans.Objects.STATIC));
-- Register the servlets and filters
App.Add_Servlet (Name => "faces", Server => Faces'Unchecked_Access);
App.Add_Servlet (Name => "files", Server => Files'Unchecked_Access);
App.Add_Servlet (Name => "auth", Server => Auth'Unchecked_Access);
App.Add_Servlet (Name => "verify-auth", Server => Verify_Auth'Unchecked_Access);
App.Add_Servlet (Name => "perf", Server => Perf'Unchecked_Access);
-- Register the filters
App.Add_Filter (Name => "perf", Filter => Perf'Unchecked_Access);
App.Add_Filter (Name => "dump", Filter => Dump'Unchecked_Access);
-- Define servlet mappings
App.Add_Mapping (Name => "faces", Pattern => "*.html");
App.Add_Mapping (Name => "files", Pattern => "*.css");
App.Add_Mapping (Name => "files", Pattern => "*.js");
App.Add_Mapping (Name => "files", Pattern => "*.png");
App.Add_Mapping (Name => "files", Pattern => "*.jpg");
App.Add_Mapping (Name => "verify-auth", Pattern => "/auth/verify");
App.Add_Mapping (Name => "auth", Pattern => "/auth/auth/*");
App.Add_Mapping (Name => "perf", Pattern => "/statistics.xml");
-- Install the debug filter.
App.Add_Filter_Mapping (Name => "perf", Pattern => "*.html");
App.Add_Filter_Mapping (Name => "dump", Pattern => "*.html");
App.Add_Filter_Mapping (Name => "perf", Pattern => "*.css");
App.Add_Filter_Mapping (Name => "dump", Pattern => "*.css");
App.Add_Filter_Mapping (Name => "perf", Pattern => "*.png");
App.Add_Filter_Mapping (Name => "dump", Pattern => "*.png");
App.Add_Filter_Mapping (Name => "perf", Pattern => "*.jpg");
App.Add_Filter_Mapping (Name => "dump", Pattern => "*.jpg");
App.Add_Filter_Mapping (Name => "perf", Pattern => "/auth/verify");
App.Add_Filter_Mapping (Name => "dump", Pattern => "/auth/verify");
App.Add_Filter_Mapping (Name => "perf", Pattern => "/auth/auth/*");
App.Add_Filter_Mapping (Name => "dump", Pattern => "/auth/auth/*");
WS.Register_Application (CONTEXT_PATH, App'Unchecked_Access);
Log.Info ("Connect you browser to: http://localhost:8080/openid/auth/login.html");
WS.Start;
delay 600.0;
App.Close;
exception
when E : others =>
Ada.Text_IO.Put_Line ("Exception in server: " &
Ada.Exceptions.Exception_Name (E) & ": " &
Ada.Exceptions.Exception_Message (E));
end Openid;
|
Use the user bean defined in the Users package
|
Use the user bean defined in the Users package
|
Ada
|
apache-2.0
|
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
|
eafc2ac7693dd9126d094895fe754b7606d24251
|
src/babel-files-queues.adb
|
src/babel-files-queues.adb
|
-----------------------------------------------------------------------
-- babel-files-queues -- File and directory queues
-- Copyright (C) 2014 Stephane.Carrez
-- Written by Stephane.Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Ada.Calendar;
with Ada.Directories;
with Ada.Containers.Vectors;
with Util.Encoders.SHA1;
with Util.Concurrent.Fifos;
with Util.Strings.Vectors;
with ADO;
with Babel.Base.Models;
package body Babel.Files.Queues is
-- ------------------------------
-- Returns true if there is a directory in the queue.
-- ------------------------------
function Has_Directory (Queue : in Directory_Queue) return Boolean is
begin
return not Queue.Directories.Is_Empty;
end Has_Directory;
-- ------------------------------
-- Get the next directory from the queue.
-- ------------------------------
procedure Peek_Directory (Queue : in out Directory_Queue;
Directory : out Directory_Type) is
begin
Directory := Queue.Directories.Last_Element;
Queue.Directories.Delete_Last;
end Peek_Directory;
end Babel.Files.Queues;
|
-----------------------------------------------------------------------
-- babel-files-queues -- File and directory queues
-- Copyright (C) 2014 Stephane.Carrez
-- Written by Stephane.Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Ada.Calendar;
with Ada.Directories;
with Ada.Containers.Vectors;
with Util.Encoders.SHA1;
with Util.Concurrent.Fifos;
with Util.Strings.Vectors;
with ADO;
with Babel.Base.Models;
package body Babel.Files.Queues is
-- ------------------------------
-- Returns true if there is a directory in the queue.
-- ------------------------------
function Has_Directory (Queue : in Directory_Queue) return Boolean is
begin
return not Queue.Directories.Is_Empty;
end Has_Directory;
-- ------------------------------
-- Get the next directory from the queue.
-- ------------------------------
procedure Peek_Directory (Queue : in out Directory_Queue;
Directory : out Directory_Type) is
begin
Directory := Queue.Directories.Last_Element;
Queue.Directories.Delete_Last;
end Peek_Directory;
-- ------------------------------
-- Add the directory in the queue.
-- ------------------------------
procedure Add_Directory (Queue : in out Directory_Queue;
Directory : in Directory_Type) is
begin
Queue.Directories.Append (Directory);
end Add_Directory;
end Babel.Files.Queues;
|
Implement the Add_Directory operation
|
Implement the Add_Directory operation
|
Ada
|
apache-2.0
|
stcarrez/babel
|
423fb6f56818476ab96745020f64304268bd212b
|
awa/plugins/awa-wikis/regtests/awa-wikis-modules-tests.adb
|
awa/plugins/awa-wikis/regtests/awa-wikis-modules-tests.adb
|
-----------------------------------------------------------------------
-- awa-wikis-modules-tests -- Unit tests for wikis service
-- Copyright (C) 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.Test_Caller;
with Util.Strings;
with ASF.Tests;
with ASF.Requests.Mockup;
with ASF.Responses.Mockup;
with AWA.Tests.Helpers;
with AWA.Tests.Helpers.Users;
with AWA.Services.Contexts;
with Security.Contexts;
package body AWA.Wikis.Modules.Tests is
use ASF.Tests;
use Util.Tests;
use type ADO.Identifier;
package Caller is new Util.Test_Caller (Test, "Wikis.Modules");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test AWA.Wikis.Modules.Create_Wiki_Space",
Test_Create_Wiki_Space'Access);
Caller.Add_Test (Suite, "Test AWA.Wikis.Modules.Create_Wiki_Page",
Test_Create_Wiki_Page'Access);
Caller.Add_Test (Suite, "Test AWA.Wikis.Modules.Create_Wiki_Content",
Test_Create_Wiki_Content'Access);
Caller.Add_Test (Suite, "Test AWA.Wikis.Modules.Wiki_Page",
Test_Wiki_Page'Access);
Caller.Add_Test (Suite, "Test AWA.Wikis.Beans.Save",
Test_Update_Page'Access);
end Add_Tests;
-- ------------------------------
-- Test creation of a wiki space.
-- ------------------------------
procedure Test_Create_Wiki_Space (T : in out Test) is
Sec_Ctx : Security.Contexts.Security_Context;
Context : AWA.Services.Contexts.Service_Context;
W : AWA.Wikis.Models.Wiki_Space_Ref;
W2 : AWA.Wikis.Models.Wiki_Space_Ref;
begin
AWA.Tests.Helpers.Users.Login (Context, Sec_Ctx, "[email protected]");
T.Manager := AWA.Wikis.Modules.Get_Wiki_Module;
T.Assert (T.Manager /= null, "There is no wiki manager");
W.Set_Name ("Test wiki space");
T.Manager.Create_Wiki_Space (W);
T.Assert (W.Is_Inserted, "The new wiki space was not created");
W.Set_Name ("Test wiki space update");
W.Set_Is_Public (True);
T.Manager.Save_Wiki_Space (W);
T.Manager.Load_Wiki_Space (Wiki => W2,
Id => W.Get_Id);
Util.Tests.Assert_Equals (T, "Test wiki space update", String '(W2.Get_Name),
"Invalid wiki space name");
end Test_Create_Wiki_Space;
-- ------------------------------
-- Test creation of a wiki page.
-- ------------------------------
procedure Test_Create_Wiki_Page (T : in out Test) is
Sec_Ctx : Security.Contexts.Security_Context;
Context : AWA.Services.Contexts.Service_Context;
W : AWA.Wikis.Models.Wiki_Space_Ref;
P : AWA.Wikis.Models.Wiki_Page_Ref;
C : AWA.Wikis.Models.Wiki_Content_Ref;
begin
AWA.Tests.Helpers.Users.Login (Context, Sec_Ctx, "[email protected]");
T.Manager := AWA.Wikis.Modules.Get_Wiki_Module;
T.Assert (T.Manager /= null, "There is no wiki manager");
W.Set_Name ("Test wiki space");
T.Manager.Create_Wiki_Space (W);
P.Set_Name ("Private");
P.Set_Title ("The page title");
C.Set_Content ("Something");
T.Manager.Create_Wiki_Page (W, P, C);
T.Assert (P.Is_Inserted, "The new wiki page was not created");
P.Set_Content (AWA.Wikis.Models.Null_Wiki_Content);
C := AWA.Wikis.Models.Null_Wiki_Content;
P := AWA.Wikis.Models.Null_Wiki_Page;
P.Set_Name ("Public");
P.Set_Title ("The page title (public)");
P.Set_Is_Public (True);
T.Manager.Create_Wiki_Page (W, P, C);
T.Assert (P.Is_Inserted, "The new wiki page was not created");
T.Assert (P.Get_Is_Public, "The new wiki page is not public");
P.Set_Content (AWA.Wikis.Models.Null_Wiki_Content);
end Test_Create_Wiki_Page;
-- ------------------------------
-- Test creation of a wiki page content.
-- ------------------------------
procedure Test_Create_Wiki_Content (T : in out Test) is
Sec_Ctx : Security.Contexts.Security_Context;
Context : AWA.Services.Contexts.Service_Context;
W : AWA.Wikis.Models.Wiki_Space_Ref;
P : AWA.Wikis.Models.Wiki_Page_Ref;
C : AWA.Wikis.Models.Wiki_Content_Ref;
begin
AWA.Tests.Helpers.Users.Login (Context, Sec_Ctx, "[email protected]");
T.Manager := AWA.Wikis.Modules.Get_Wiki_Module;
T.Assert (T.Manager /= null, "There is no wiki manager");
W.Set_Name ("Test wiki space");
T.Manager.Create_Wiki_Space (W);
T.Wiki_Id := W.Get_Id;
P.Set_Name ("PrivatePage");
P.Set_Title ("The page title");
P.Set_Is_Public (False);
T.Manager.Create_Wiki_Page (W, P, C);
T.Private_Id := P.Get_Id;
C := AWA.Wikis.Models.Null_Wiki_Content;
C.Set_Format (AWA.Wikis.Models.FORMAT_MARKDOWN);
C.Set_Content ("-- Title" & ASCII.LF & "A paragraph");
C.Set_Save_Comment ("A first version");
T.Manager.Create_Wiki_Content (P, C);
T.Assert (C.Is_Inserted, "The new wiki content was not created");
T.Assert (not C.Get_Author.Is_Null, "The wiki content has an author");
T.Assert (C.Get_Page_Id /= ADO.NO_IDENTIFIER,
"The wiki content is associated with the wiki page");
P := AWA.Wikis.Models.Null_Wiki_Page;
C := AWA.Wikis.Models.Null_Wiki_Content;
P.Set_Name ("PublicPage");
P.Set_Title ("The public page title");
P.Set_Is_Public (True);
T.Manager.Create_Wiki_Page (W, P, C);
T.Public_Id := P.Get_Id;
C.Set_Format (AWA.Wikis.Models.FORMAT_MARKDOWN);
C.Set_Content ("-- Title" & ASCII.LF & "A paragraph" & ASCII.LF
& "[Link](http://mylink.com)" & ASCII.LF
& "[Image](my-image.png)");
C.Set_Save_Comment ("A first version");
T.Manager.Create_Wiki_Content (P, C);
T.Assert (C.Is_Inserted, "The new wiki content was not created");
T.Assert (not C.Get_Author.Is_Null, "The wiki content has an author");
T.Assert (C.Get_Page_Id /= ADO.NO_IDENTIFIER,
"The wiki content is associated with the wiki page");
end Test_Create_Wiki_Content;
-- ------------------------------
-- Test getting the wiki page as well as info, history pages.
-- ------------------------------
procedure Test_Wiki_Page (T : in out Test) is
Request : ASF.Requests.Mockup.Request;
Reply : ASF.Responses.Mockup.Response;
Ident : constant String := Util.Strings.Image (Natural (T.Wiki_Id));
Pub_Ident : constant String := Util.Strings.Image (Natural (T.Public_Id));
begin
ASF.Tests.Do_Get (Request, Reply, "/wikis/view/" & Ident & "/PublicPage",
"wiki-public-1.html");
Assert_Equals (T, ASF.Responses.SC_OK, Reply.Get_Status,
"Invalid response (PublicPage)");
Assert_Matches (T, ".*The public page title.*", Reply,
"Invalid PublicPage page returned",
Status => ASF.Responses.SC_OK);
ASF.Tests.Do_Get (Request, Reply, "/wikis/info/" & Ident & "/" & Pub_Ident,
"wiki-public-info-1.html");
Assert_Equals (T, ASF.Responses.SC_OK, Reply.Get_Status,
"Invalid response (PublicPage info)");
Assert_Matches (T, ".*The public page title.*", Reply,
"Invalid PublicPage info page returned",
Status => ASF.Responses.SC_OK);
ASF.Tests.Do_Get (Request, Reply, "/wikis/history/" & Ident & "/" & Pub_Ident,
"wiki-public-history-1.html");
Assert_Equals (T, ASF.Responses.SC_OK, Reply.Get_Status,
"Invalid response (PublicPage history)");
Assert_Matches (T, ".*The public page title.*", Reply,
"Invalid PublicPage info page returned",
Status => ASF.Responses.SC_OK);
Request.Remove_Attribute ("wikiView");
ASF.Tests.Do_Get (Request, Reply, "/wikis/view/" & Ident & "/PrivatePage",
"wiki-private-1.html");
Assert_Equals (T, ASF.Responses.SC_OK, Reply.Get_Status, "Invalid response (PrivatePage)");
Assert_Matches (T, ".*Protected Wiki Page.*", Reply, "Invalid PrivatePage page returned",
Status => ASF.Responses.SC_OK);
ASF.Tests.Do_Get (Request, Reply, "/wikis/list/" & Ident & "/recent",
"wiki-list-recent-1.html");
Assert_Equals (T, ASF.Responses.SC_OK, Reply.Get_Status,
"Invalid response (list/recent)");
ASF.Tests.Do_Get (Request, Reply, "/wikis/list/" & Ident & "/recent/grid",
"wiki-list-grid-1.html");
Assert_Equals (T, ASF.Responses.SC_OK, Reply.Get_Status,
"Invalid response (list/recent/grid)");
ASF.Tests.Do_Get (Request, Reply, "/wikis/list/" & Ident & "/popular",
"wiki-list-popular-1.html");
Assert_Equals (T, ASF.Responses.SC_OK, Reply.Get_Status,
"Invalid response (list/popular)");
ASF.Tests.Do_Get (Request, Reply, "/wikis/list/" & Ident & "/popular/grid",
"wiki-list-popular-1.html");
Assert_Equals (T, ASF.Responses.SC_OK, Reply.Get_Status,
"Invalid response (list/popular/grid)");
end Test_Wiki_Page;
-- ------------------------------
-- Test updating the wiki page through a POST request.
-- ------------------------------
procedure Test_Update_Page (T : in out Test) is
Request : ASF.Requests.Mockup.Request;
Reply : ASF.Responses.Mockup.Response;
Ident : constant String := Util.Strings.Image (Natural (T.Wiki_Id));
Pub_Ident : constant String := Util.Strings.Image (Natural (T.Public_Id));
begin
AWA.Tests.Helpers.Users.Login ("[email protected]", Request);
Request.Set_Parameter ("title", "The Blog Title");
Request.Set_Parameter ("page-id", Pub_Ident);
Request.Set_Parameter ("page-wiki-id", Ident);
Request.Set_Parameter ("name", "NewPageName");
Request.Set_Parameter ("page-title", "New Page Title");
Request.Set_Parameter ("text", "== Title ==" & ASCII.LF & "A paragraph" & ASCII.LF
& "[[http://mylink.com|Link]]" & ASCII.LF
& "[[Image:my-image.png|My Picture]]" & ASCII.LF
& "== Last header ==" & ASCII.LF);
Request.Set_Parameter ("comment", "Update through test post simulation");
Request.Set_Parameter ("page-is-public", "TRUE");
Request.Set_Parameter ("wiki-format", "FORMAT_MEDIAWIKI");
Request.Set_Parameter ("qtags[1]", "Test-Tag");
Request.Set_Parameter ("save", "1");
Request.Set_Parameter ("post", "1");
ASF.Tests.Do_Post (Request, Reply, "/wikis/edit/" & Ident & "/PublicPage",
"update-wiki.html");
T.Assert (Reply.Get_Status = ASF.Responses.SC_MOVED_TEMPORARILY,
"Invalid response after wiki update");
declare
Result : constant String
:= AWA.Tests.Helpers.Extract_Redirect (Reply, "/asfunit/wikis/view/");
begin
Util.Tests.Assert_Equals (T, Ident & "/NewPageName", Result,
"The page name was not updated");
ASF.Tests.Do_Get (Request, Reply, "/wikis/view/" & Result, "wiki-public-2.html");
Assert_Equals (T, ASF.Responses.SC_OK, Reply.Get_Status,
"Invalid response (NewPageName)");
Assert_Matches (T, ".*Last header.*", Reply,
"Last header is present in the response",
Status => ASF.Responses.SC_OK);
ASF.Tests.Do_Get (Request, Reply, "/wikis/info/" & Ident & "/"
& Pub_Ident, "wiki-info-2.html");
Assert_Equals (T, ASF.Responses.SC_OK, Reply.Get_Status,
"Invalid response (info NewPageName)");
Assert_Matches (T, ".*wiki-image-name.*my-image.png.*", Reply,
"The info page must list the image",
Status => ASF.Responses.SC_OK);
end;
end Test_Update_Page;
end AWA.Wikis.Modules.Tests;
|
-----------------------------------------------------------------------
-- awa-wikis-modules-tests -- Unit tests for wikis service
-- Copyright (C) 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.Test_Caller;
with Util.Strings;
with ASF.Tests;
with ASF.Requests.Mockup;
with ASF.Responses.Mockup;
with AWA.Tests.Helpers;
with AWA.Tests.Helpers.Users;
with AWA.Services.Contexts;
with Security.Contexts;
package body AWA.Wikis.Modules.Tests is
use ASF.Tests;
use Util.Tests;
use type ADO.Identifier;
package Caller is new Util.Test_Caller (Test, "Wikis.Modules");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test AWA.Wikis.Modules.Create_Wiki_Space",
Test_Create_Wiki_Space'Access);
Caller.Add_Test (Suite, "Test AWA.Wikis.Modules.Create_Wiki_Page",
Test_Create_Wiki_Page'Access);
Caller.Add_Test (Suite, "Test AWA.Wikis.Modules.Create_Wiki_Content",
Test_Create_Wiki_Content'Access);
Caller.Add_Test (Suite, "Test AWA.Wikis.Modules.Wiki_Page",
Test_Wiki_Page'Access);
Caller.Add_Test (Suite, "Test AWA.Wikis.Beans.Save",
Test_Update_Page'Access);
end Add_Tests;
-- ------------------------------
-- Test creation of a wiki space.
-- ------------------------------
procedure Test_Create_Wiki_Space (T : in out Test) is
Sec_Ctx : Security.Contexts.Security_Context;
Context : AWA.Services.Contexts.Service_Context;
W : AWA.Wikis.Models.Wiki_Space_Ref;
W2 : AWA.Wikis.Models.Wiki_Space_Ref;
begin
AWA.Tests.Helpers.Users.Login (Context, Sec_Ctx, "[email protected]");
T.Manager := AWA.Wikis.Modules.Get_Wiki_Module;
T.Assert (T.Manager /= null, "There is no wiki manager");
W.Set_Name ("Test wiki space");
T.Manager.Create_Wiki_Space (W);
T.Assert (W.Is_Inserted, "The new wiki space was not created");
W.Set_Name ("Test wiki space update");
W.Set_Is_Public (True);
T.Manager.Save_Wiki_Space (W);
T.Manager.Load_Wiki_Space (Wiki => W2,
Id => W.Get_Id);
Util.Tests.Assert_Equals (T, "Test wiki space update", String '(W2.Get_Name),
"Invalid wiki space name");
end Test_Create_Wiki_Space;
-- ------------------------------
-- Test creation of a wiki page.
-- ------------------------------
procedure Test_Create_Wiki_Page (T : in out Test) is
Sec_Ctx : Security.Contexts.Security_Context;
Context : AWA.Services.Contexts.Service_Context;
W : AWA.Wikis.Models.Wiki_Space_Ref;
P : AWA.Wikis.Models.Wiki_Page_Ref;
C : AWA.Wikis.Models.Wiki_Content_Ref;
begin
AWA.Tests.Helpers.Users.Login (Context, Sec_Ctx, "[email protected]");
T.Manager := AWA.Wikis.Modules.Get_Wiki_Module;
T.Assert (T.Manager /= null, "There is no wiki manager");
W.Set_Name ("Test wiki space");
T.Manager.Create_Wiki_Space (W);
P.Set_Name ("Private");
P.Set_Title ("The page title");
C.Set_Content ("Something");
T.Manager.Create_Wiki_Page (W, P, C);
T.Assert (P.Is_Inserted, "The new wiki page was not created");
P.Set_Content (AWA.Wikis.Models.Null_Wiki_Content);
C := AWA.Wikis.Models.Null_Wiki_Content;
P := AWA.Wikis.Models.Null_Wiki_Page;
P.Set_Name ("Public");
P.Set_Title ("The page title (public)");
P.Set_Is_Public (True);
T.Manager.Create_Wiki_Page (W, P, C);
T.Assert (P.Is_Inserted, "The new wiki page was not created");
T.Assert (P.Get_Is_Public, "The new wiki page is not public");
P.Set_Content (AWA.Wikis.Models.Null_Wiki_Content);
end Test_Create_Wiki_Page;
-- ------------------------------
-- Test creation of a wiki page content.
-- ------------------------------
procedure Test_Create_Wiki_Content (T : in out Test) is
Sec_Ctx : Security.Contexts.Security_Context;
Context : AWA.Services.Contexts.Service_Context;
W : AWA.Wikis.Models.Wiki_Space_Ref;
P : AWA.Wikis.Models.Wiki_Page_Ref;
C : AWA.Wikis.Models.Wiki_Content_Ref;
begin
AWA.Tests.Helpers.Users.Login (Context, Sec_Ctx, "[email protected]");
T.Manager := AWA.Wikis.Modules.Get_Wiki_Module;
T.Assert (T.Manager /= null, "There is no wiki manager");
W.Set_Name ("Test wiki space");
T.Manager.Create_Wiki_Space (W);
T.Wiki_Id := W.Get_Id;
P.Set_Name ("PrivatePage");
P.Set_Title ("The page title");
P.Set_Is_Public (False);
T.Manager.Create_Wiki_Page (W, P, C);
T.Private_Id := P.Get_Id;
C := AWA.Wikis.Models.Null_Wiki_Content;
C.Set_Format (AWA.Wikis.Models.FORMAT_MARKDOWN);
C.Set_Content ("-- Title" & ASCII.LF & "A paragraph");
C.Set_Save_Comment ("A first version");
T.Manager.Create_Wiki_Content (P, C);
T.Assert (C.Is_Inserted, "The new wiki content was not created");
T.Assert (not C.Get_Author.Is_Null, "The wiki content has an author");
T.Assert (C.Get_Page_Id /= ADO.NO_IDENTIFIER,
"The wiki content is associated with the wiki page");
P := AWA.Wikis.Models.Null_Wiki_Page;
C := AWA.Wikis.Models.Null_Wiki_Content;
P.Set_Name ("PublicPage");
P.Set_Title ("The public page title");
P.Set_Is_Public (True);
T.Manager.Create_Wiki_Page (W, P, C);
T.Public_Id := P.Get_Id;
C.Set_Format (AWA.Wikis.Models.FORMAT_MARKDOWN);
C.Set_Content ("-- Title" & ASCII.LF & "A paragraph" & ASCII.LF
& "[Link](http://mylink.com)" & ASCII.LF
& "[Image](my-image.png)");
C.Set_Save_Comment ("A first version");
T.Manager.Create_Wiki_Content (P, C);
T.Assert (C.Is_Inserted, "The new wiki content was not created");
T.Assert (not C.Get_Author.Is_Null, "The wiki content has an author");
T.Assert (C.Get_Page_Id /= ADO.NO_IDENTIFIER,
"The wiki content is associated with the wiki page");
end Test_Create_Wiki_Content;
-- ------------------------------
-- Test getting the wiki page as well as info, history pages.
-- ------------------------------
procedure Test_Wiki_Page (T : in out Test) is
Request : ASF.Requests.Mockup.Request;
Reply : ASF.Responses.Mockup.Response;
Ident : constant String := Util.Strings.Image (Natural (T.Wiki_Id));
Pub_Ident : constant String := Util.Strings.Image (Natural (T.Public_Id));
begin
ASF.Tests.Do_Get (Request, Reply, "/wikis/view/" & Ident & "/PublicPage",
"wiki-public-1.html");
Assert_Equals (T, ASF.Responses.SC_OK, Reply.Get_Status,
"Invalid response (PublicPage)");
Assert_Matches (T, ".*The public page title.*", Reply,
"Invalid PublicPage page returned",
Status => ASF.Responses.SC_OK);
ASF.Tests.Do_Get (Request, Reply, "/wikis/info/" & Ident & "/" & Pub_Ident,
"wiki-public-info-1.html");
Assert_Equals (T, ASF.Responses.SC_OK, Reply.Get_Status,
"Invalid response (PublicPage info)");
Assert_Matches (T, ".*The public page title.*", Reply,
"Invalid PublicPage info page returned",
Status => ASF.Responses.SC_OK);
ASF.Tests.Do_Get (Request, Reply, "/wikis/history/" & Ident & "/" & Pub_Ident,
"wiki-public-history-1.html");
Assert_Equals (T, ASF.Responses.SC_OK, Reply.Get_Status,
"Invalid response (PublicPage history)");
Assert_Matches (T, ".*The public page title.*", Reply,
"Invalid PublicPage info page returned",
Status => ASF.Responses.SC_OK);
Request.Remove_Attribute ("wikiView");
ASF.Tests.Do_Get (Request, Reply, "/wikis/view/" & Ident & "/PrivatePage",
"wiki-private-1.html");
Assert_Equals (T, ASF.Responses.SC_FORBIDDEN, Reply.Get_Status, "Invalid response (PrivatePage)");
Assert_Matches (T, ".*Protected Wiki Page.*", Reply, "Invalid PrivatePage page returned",
Status => ASF.Responses.SC_FORBIDDEN);
ASF.Tests.Do_Get (Request, Reply, "/wikis/list/" & Ident & "/recent",
"wiki-list-recent-1.html");
Assert_Equals (T, ASF.Responses.SC_OK, Reply.Get_Status,
"Invalid response (list/recent)");
ASF.Tests.Do_Get (Request, Reply, "/wikis/list/" & Ident & "/recent/grid",
"wiki-list-grid-1.html");
Assert_Equals (T, ASF.Responses.SC_OK, Reply.Get_Status,
"Invalid response (list/recent/grid)");
ASF.Tests.Do_Get (Request, Reply, "/wikis/list/" & Ident & "/popular",
"wiki-list-popular-1.html");
Assert_Equals (T, ASF.Responses.SC_OK, Reply.Get_Status,
"Invalid response (list/popular)");
ASF.Tests.Do_Get (Request, Reply, "/wikis/list/" & Ident & "/popular/grid",
"wiki-list-popular-1.html");
Assert_Equals (T, ASF.Responses.SC_OK, Reply.Get_Status,
"Invalid response (list/popular/grid)");
end Test_Wiki_Page;
-- ------------------------------
-- Test updating the wiki page through a POST request.
-- ------------------------------
procedure Test_Update_Page (T : in out Test) is
Request : ASF.Requests.Mockup.Request;
Reply : ASF.Responses.Mockup.Response;
Ident : constant String := Util.Strings.Image (Natural (T.Wiki_Id));
Pub_Ident : constant String := Util.Strings.Image (Natural (T.Public_Id));
begin
AWA.Tests.Helpers.Users.Login ("[email protected]", Request);
Request.Set_Parameter ("title", "The Blog Title");
Request.Set_Parameter ("page-id", Pub_Ident);
Request.Set_Parameter ("page-wiki-id", Ident);
Request.Set_Parameter ("name", "NewPageName");
Request.Set_Parameter ("page-title", "New Page Title");
Request.Set_Parameter ("text", "== Title ==" & ASCII.LF & "A paragraph" & ASCII.LF
& "[[http://mylink.com|Link]]" & ASCII.LF
& "[[Image:my-image.png|My Picture]]" & ASCII.LF
& "== Last header ==" & ASCII.LF);
Request.Set_Parameter ("comment", "Update through test post simulation");
Request.Set_Parameter ("page-is-public", "TRUE");
Request.Set_Parameter ("wiki-format", "FORMAT_MEDIAWIKI");
Request.Set_Parameter ("qtags[1]", "Test-Tag");
Request.Set_Parameter ("save", "1");
Request.Set_Parameter ("post", "1");
ASF.Tests.Do_Post (Request, Reply, "/wikis/edit/" & Ident & "/PublicPage",
"update-wiki.html");
T.Assert (Reply.Get_Status = ASF.Responses.SC_MOVED_TEMPORARILY,
"Invalid response after wiki update");
declare
Result : constant String
:= AWA.Tests.Helpers.Extract_Redirect (Reply, "/asfunit/wikis/view/");
begin
Util.Tests.Assert_Equals (T, Ident & "/NewPageName", Result,
"The page name was not updated");
ASF.Tests.Do_Get (Request, Reply, "/wikis/view/" & Result, "wiki-public-2.html");
Assert_Equals (T, ASF.Responses.SC_OK, Reply.Get_Status,
"Invalid response (NewPageName)");
Assert_Matches (T, ".*Last header.*", Reply,
"Last header is present in the response",
Status => ASF.Responses.SC_OK);
ASF.Tests.Do_Get (Request, Reply, "/wikis/info/" & Ident & "/"
& Pub_Ident, "wiki-info-2.html");
Assert_Equals (T, ASF.Responses.SC_OK, Reply.Get_Status,
"Invalid response (info NewPageName)");
Assert_Matches (T, ".*wiki-image-name.*my-image.png.*", Reply,
"The info page must list the image",
Status => ASF.Responses.SC_OK);
end;
end Test_Update_Page;
end AWA.Wikis.Modules.Tests;
|
Fix the wiki test page to verify that a 403 error is returned for protected page
|
Fix the wiki test page to verify that a 403 error is returned for protected page
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
22ffb7321030cc63986c5cb94a8a7507259b4007
|
regtests/asf-converters-tests.ads
|
regtests/asf-converters-tests.ads
|
-----------------------------------------------------------------------
-- asf-converters-tests - Unit tests for ASF.Converters
-- Copyright (C) 2014, 2018 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Tests;
with ASF.Contexts.Faces.Tests;
package ASF.Converters.Tests is
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite);
type Test is new ASF.Contexts.Faces.Tests.Test with null record;
-- Test the date short converter.
procedure Test_Date_Short_Converter (T : in out Test);
-- Test the date medium converter.
procedure Test_Date_Medium_Converter (T : in out Test);
-- Test the date long converter.
procedure Test_Date_Long_Converter (T : in out Test);
-- Test the date full converter.
procedure Test_Date_Full_Converter (T : in out Test);
-- Test the time short converter.
procedure Test_Time_Short_Converter (T : in out Test);
-- Test the time short converter.
procedure Test_Time_Medium_Converter (T : in out Test);
-- Test the time long converter.
procedure Test_Time_Long_Converter (T : in out Test);
-- Test converter reporting conversion errors when converting a string back to a date.
procedure Test_Date_Converter_Error (T : in out Test);
end ASF.Converters.Tests;
|
-----------------------------------------------------------------------
-- asf-converters-tests - Unit tests for ASF.Converters
-- Copyright (C) 2014, 2018, 2019 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Tests;
with ASF.Contexts.Faces.Tests;
package ASF.Converters.Tests is
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite);
type Test is new ASF.Contexts.Faces.Tests.Test with null record;
-- Test the date short converter.
procedure Test_Date_Short_Converter (T : in out Test);
-- Test the date medium converter.
procedure Test_Date_Medium_Converter (T : in out Test);
-- Test the date long converter.
procedure Test_Date_Long_Converter (T : in out Test);
-- Test the date full converter.
procedure Test_Date_Full_Converter (T : in out Test);
-- Test the time short converter.
procedure Test_Time_Short_Converter (T : in out Test);
-- Test the time short converter.
procedure Test_Time_Medium_Converter (T : in out Test);
-- Test the time long converter.
procedure Test_Time_Long_Converter (T : in out Test);
-- Test converter reporting conversion errors when converting a string back to a date.
procedure Test_Date_Converter_Error (T : in out Test);
-- Test number converter.
procedure Test_Number_Converter (T : in out Test);
end ASF.Converters.Tests;
|
Declare Test_Number_Converter procedure
|
Declare Test_Number_Converter procedure
|
Ada
|
apache-2.0
|
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
|
b8d99d444be9277ac70b052bc3f94fc20e4bcfe5
|
awa/awaunit/awa-tests-helpers.ads
|
awa/awaunit/awa-tests-helpers.ads
|
-----------------------------------------------------------------------
-- awa-tests-helpers - Helpers for AWA unit tests
-- Copyright (C) 2011, 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with ASF.Responses.Mockup;
with Ada.Strings.Unbounded;
package AWA.Tests.Helpers is
-- Extract from the Location header the part that is after the given base string.
-- If the Location header does not start with the base string, returns the empty
-- string.
function Extract_Redirect (Reply : in ASF.Responses.Mockup.Response'Class;
Base : in String) return String;
function Extract_Redirect (Reply : in ASF.Responses.Mockup.Response'Class;
Base : in String) return Ada.Strings.Unbounded.Unbounded_String;
end AWA.Tests.Helpers;
|
-----------------------------------------------------------------------
-- awa-tests-helpers - Helpers for AWA unit tests
-- Copyright (C) 2011, 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with ASF.Responses.Mockup;
with Ada.Strings.Unbounded;
package AWA.Tests.Helpers is
-- Extract from the Location header the part that is after the given base string.
-- If the Location header does not start with the base string, returns the empty
-- string.
function Extract_Redirect (Reply : in ASF.Responses.Mockup.Response'Class;
Base : in String) return String;
function Extract_Redirect (Reply : in ASF.Responses.Mockup.Response'Class;
Base : in String) return Ada.Strings.Unbounded.Unbounded_String;
-- Extract from the response content a link with a given title.
function Extract_Link (Content : in String;
Title : in String) return String;
end AWA.Tests.Helpers;
|
Declare the Extract_Link function to extract a href from a HTML response
|
Declare the Extract_Link function to extract a href from a HTML response
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
8586413e457f122f6485b52579cf8cabc9a68d37
|
src/ado.ads
|
src/ado.ads
|
-----------------------------------------------------------------------
-- ADO Databases -- Database Objects
-- Copyright (C) 2009, 2010, 2011 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Ada.Calendar;
with Util.Refs;
with Util.Streams.Buffered;
package ADO is
type Int64 is range -2**63 .. 2**63 - 1;
for Int64'Size use 64;
type Unsigned64 is mod 2**64;
for Unsigned64'Size use 64;
DEFAULT_TIME : constant Ada.Calendar.Time;
-- ------------------------------
-- Database Identifier
-- ------------------------------
--
type Identifier is range -2**47 .. 2**47 - 1;
NO_IDENTIFIER : constant Identifier := -1;
type Entity_Type is range 0 .. 2**16 - 1;
NO_ENTITY_TYPE : constant Entity_Type := 0;
type Object_Id is record
Id : Identifier;
Kind : Entity_Type;
end record;
pragma Pack (Object_Id);
-- ------------------------------
-- Nullable Types
-- ------------------------------
-- Most database allow to store a NULL instead of an actual integer, date or string value.
-- Unlike Java, there is no easy way to distinguish between a NULL and an actual valid value.
-- The <b>Nullable_T</b> types provide a way to specify and check whether a value is null
-- or not.
-- An integer which can be null.
type Nullable_Integer is record
Value : Integer := 0;
Is_Null : Boolean := True;
end record;
-- A string which can be null.
type Nullable_String is record
Value : Ada.Strings.Unbounded.Unbounded_String;
Is_Null : Boolean := True;
end record;
-- A date which can be null.
type Nullable_Time is record
Value : Ada.Calendar.Time;
Is_Null : Boolean := True;
end record;
-- ------------------------------
-- Blob data type
-- ------------------------------
-- The <b>Blob</b> type is used to represent database blobs. The data is stored
-- in an <b>Ada.Streams.Stream_Element_Array</b> pointed to by the <b>Data</b> member.
-- The query statement and bind parameter will use a <b>Blob_Ref</b> which represents
-- a reference to the blob data. This is intended to minimize data copy.
type Blob is new Util.Refs.Ref_Entity with record
Data : Util.Streams.Buffered.Buffer_Access := null;
end record;
type Blob_Access is access all Blob;
package Blob_References is new Util.Refs.References (Blob, Blob_Access);
subtype Blob_Ref is Blob_References.Ref;
private
DEFAULT_TIME : constant Ada.Calendar.Time := Ada.Calendar.Time_Of (Year => 1901,
Month => 1,
Day => 1,
Seconds => 0.0);
end ADO;
|
-----------------------------------------------------------------------
-- ADO Databases -- Database Objects
-- Copyright (C) 2009, 2010, 2011 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Ada.Calendar;
with Util.Refs;
with Util.Streams.Buffered;
package ADO is
type Int64 is range -2**63 .. 2**63 - 1;
for Int64'Size use 64;
type Unsigned64 is mod 2**64;
for Unsigned64'Size use 64;
DEFAULT_TIME : constant Ada.Calendar.Time;
-- ------------------------------
-- Database Identifier
-- ------------------------------
--
type Identifier is range -2**47 .. 2**47 - 1;
NO_IDENTIFIER : constant Identifier := -1;
type Entity_Type is range 0 .. 2**16 - 1;
NO_ENTITY_TYPE : constant Entity_Type := 0;
type Object_Id is record
Id : Identifier;
Kind : Entity_Type;
end record;
pragma Pack (Object_Id);
-- ------------------------------
-- Nullable Types
-- ------------------------------
-- Most database allow to store a NULL instead of an actual integer, date or string value.
-- Unlike Java, there is no easy way to distinguish between a NULL and an actual valid value.
-- The <b>Nullable_T</b> types provide a way to specify and check whether a value is null
-- or not.
-- An integer which can be null.
type Nullable_Integer is record
Value : Integer := 0;
Is_Null : Boolean := True;
end record;
-- A string which can be null.
type Nullable_String is record
Value : Ada.Strings.Unbounded.Unbounded_String;
Is_Null : Boolean := True;
end record;
-- A date which can be null.
type Nullable_Time is record
Value : Ada.Calendar.Time;
Is_Null : Boolean := True;
end record;
-- ------------------------------
-- Blob data type
-- ------------------------------
-- The <b>Blob</b> type is used to represent database blobs. The data is stored
-- in an <b>Ada.Streams.Stream_Element_Array</b> pointed to by the <b>Data</b> member.
-- The query statement and bind parameter will use a <b>Blob_Ref</b> which represents
-- a reference to the blob data. This is intended to minimize data copy.
type Blob is new Util.Refs.Ref_Entity with record
Data : Util.Streams.Buffered.Buffer_Access := null;
end record;
type Blob_Access is access all Blob;
package Blob_References is new Util.Refs.References (Blob, Blob_Access);
subtype Blob_Ref is Blob_References.Ref;
private
DEFAULT_TIME : constant Ada.Calendar.Time := Ada.Calendar.Time_Of (Year => 1901,
Month => 1,
Day => 2,
Seconds => 0.0);
end ADO;
|
Change default time to avoid timezone issues
|
Change default time to avoid timezone issues
|
Ada
|
apache-2.0
|
Letractively/ada-ado
|
df8a9d5d1e735ab215aa569efaa8536f09329559
|
mat/src/memory/mat-memory-targets.adb
|
mat/src/memory/mat-memory-targets.adb
|
-----------------------------------------------------------------------
-- Memory Events - Definition and Analysis of memory events
-- Copyright (C) 2014 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with MAT.Memory.Readers;
package body MAT.Memory.Targets is
-- Initialize the target memory object to manage the memory slots, the stack frames
-- and setup the reader to analyze the memory events.
procedure Initialize (Memory : in out Target_Memory;
Reader : in out MAT.Readers.Manager_Base'Class) is
Memory_Reader : constant MAT.Memory.Readers.Memory_Reader_Access
:= new MAT.Memory.Readers.Memory_Servant;
begin
Memory.Reader := Memory_Reader.all'Access;
MAT.Memory.Readers.Register (Reader, Memory_Reader);
end Initialize;
end MAT.Memory.Targets;
|
-----------------------------------------------------------------------
-- Memory Events - Definition and Analysis of memory events
-- Copyright (C) 2014 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Log.Loggers;
with MAT.Memory.Readers;
package body MAT.Memory.Targets is
-- The logger
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("MAT.Memory.Targets");
-- ------------------------------
-- Initialize the target memory object to manage the memory slots, the stack frames
-- and setup the reader to analyze the memory events.
-- ------------------------------
procedure Initialize (Memory : in out Target_Memory;
Reader : in out MAT.Readers.Manager_Base'Class) is
Memory_Reader : constant MAT.Memory.Readers.Memory_Reader_Access
:= new MAT.Memory.Readers.Memory_Servant;
begin
Memory.Reader := Memory_Reader.all'Access;
Memory_Reader.Data := Memory'Unrestricted_Access;
MAT.Memory.Readers.Register (Reader, Memory_Reader);
end Initialize;
-- ------------------------------
-- Collect the information about memory slot sizes allocated by the application.
-- ------------------------------
procedure Size_Information (Memory : in Target_Memory;
Sizes : in out Size_Info_Map) is
Iter : Allocation_Cursor := Memory.Memory_Slots.First;
procedure Update_Count (Size : in MAT.Types.Target_Size;
Info : in out Size_Info_Type) is
begin
Info.Count := Info.Count + 1;
end Update_Count;
procedure Collect (Addr : in MAT.Types.Target_Addr;
Slot : in Allocation) is
Pos : Size_Info_Cursor := Sizes.Find (Slot.Size);
begin
if Size_Info_Maps.Has_Element (Pos) then
Sizes.Update_Element (Pos, Update_Count'Access);
else
declare
Info : Size_Info_Type;
begin
Info.Count := 1;
Sizes.Insert (Slot.Size, Info);
end;
end if;
end Collect;
begin
while Allocation_Maps.Has_Element (Iter) loop
Allocation_Maps.Query_Element (Iter, Collect'Access);
Allocation_Maps.Next (Iter);
end loop;
end Size_Information;
end MAT.Memory.Targets;
|
Implement the Size_Information procedure
|
Implement the Size_Information procedure
|
Ada
|
apache-2.0
|
stcarrez/mat,stcarrez/mat,stcarrez/mat
|
da3ed458bd392dc574805079c375ffb14f0c64cc
|
regtests/ado-objects-tests.adb
|
regtests/ado-objects-tests.adb
|
-----------------------------------------------------------------------
-- ADO Objects Tests -- Tests for ADO.Objects
-- Copyright (C) 2011, 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Test_Caller;
with ADO.Sessions;
with Regtests.Simple.Model;
with Regtests.Comments;
package body ADO.Objects.Tests is
use Util.Tests;
use type Ada.Containers.Hash_Type;
function Get_Allocate_Key (N : Identifier) return Object_Key;
function Get_Allocate_Key (N : Identifier) return Object_Key is
Result : Object_Key (Of_Type => KEY_INTEGER,
Of_Class => Regtests.Simple.Model.ALLOCATE_TABLE'Access);
begin
Set_Value (Result, N);
return Result;
end Get_Allocate_Key;
-- ------------------------------
-- Various tests on Hash and key comparison
-- ------------------------------
procedure Test_Key (T : in out Test) is
K1 : constant Object_Key := Get_Allocate_Key (1);
K2 : Object_Key (Of_Type => KEY_STRING,
Of_Class => Regtests.Simple.Model.USER_TABLE'Access);
K3 : Object_Key := K1;
K4 : Object_Key (Of_Type => KEY_INTEGER,
Of_Class => Regtests.Simple.Model.USER_TABLE'Access);
begin
T.Assert (not (K1 = K2), "Key on different tables must be different");
T.Assert (not (K2 = K4), "Key with different type must be different");
T.Assert (K1 = K3, "Keys are identical");
T.Assert (Equivalent_Elements (K1, K3), "Keys are identical");
T.Assert (Equivalent_Elements (K3, K1), "Keys are identical");
T.Assert (Hash (K1) = Hash (K3), "Hash of identical keys should be identical");
Set_Value (K3, 2);
T.Assert (not (K1 = K3), "Keys should be different");
T.Assert (Hash (K1) /= Hash (K3), "Hash should be different");
T.Assert (Hash (K1) /= Hash (K2), "Hash should be different");
Set_Value (K4, 1);
T.Assert (Hash (K1) /= Hash (K4),
"Hash on key with same value and different tables should be different");
T.Assert (not (K4 = K1), "Key on different tables should be different");
Set_Value (K2, 1);
T.Assert (Hash (K1) /= Hash (K2), "Hash should be different");
end Test_Key;
-- ------------------------------
-- Check:
-- Object_Ref := (reference counting)
-- Object_Ref.Copy
-- Object_Ref.Get_xxx generated method
-- Object_Ref.Set_xxx generated method
-- Object_Ref.=
-- ------------------------------
procedure Test_Object_Ref (T : in out Test) is
use type Regtests.Simple.Model.User_Ref;
Obj1 : Regtests.Simple.Model.User_Ref;
Null_Obj : Regtests.Simple.Model.User_Ref;
begin
T.Assert (Obj1 = Null_Obj, "Two null objects are identical");
for I in 1 .. 10 loop
Obj1.Set_Name ("User name");
T.Assert (Obj1.Get_Name = "User name", "User_Ref.Set_Name invalid result");
T.Assert (Obj1 /= Null_Obj, "Object is not identical as the null object");
declare
Obj2 : constant Regtests.Simple.Model.User_Ref := Obj1;
Obj3 : Regtests.Simple.Model.User_Ref;
begin
Obj1.Copy (Obj3);
Obj3.Set_Id (2);
-- Check the copy
T.Assert (Obj2.Get_Name = "User name", "Object_Ref.Copy invalid copy");
T.Assert (Obj3.Get_Name = "User name", "Object_Ref.Copy invalid copy");
T.Assert (Obj2 = Obj1, "Object_Ref.'=' invalid comparison after assignment");
T.Assert (Obj3 /= Obj1, "Object_Ref.'=' invalid comparison after copy");
-- Change original, make sure it's the same of Obj2.
Obj1.Set_Name ("Second name");
T.Assert (Obj2.Get_Name = "Second name", "Object_Ref.Copy invalid copy");
T.Assert (Obj2 = Obj1, "Object_Ref.'=' invalid comparison after assignment");
-- The copy is not modified
T.Assert (Obj3.Get_Name = "User name", "Object_Ref.Copy invalid copy");
end;
end loop;
end Test_Object_Ref;
-- ------------------------------
-- Test creation of an object with lazy loading.
-- ------------------------------
procedure Test_Create_Object (T : in out Test) is
User : Regtests.Simple.Model.User_Ref;
Cmt : Regtests.Comments.Comment_Ref;
begin
-- Create an object within a transaction.
declare
S : ADO.Sessions.Master_Session := Regtests.Get_Master_Database;
begin
S.Begin_Transaction;
User.Set_Name ("Joe");
User.Set_Value (0);
User.Save (S);
S.Commit;
end;
-- Load it from another session.
declare
S : ADO.Sessions.Master_Session := Regtests.Get_Master_Database;
U2 : Regtests.Simple.Model.User_Ref;
begin
U2.Load (S, User.Get_Id);
Assert_Equals (T, "Joe", Ada.Strings.Unbounded.To_String (U2.Get_Name),
"Cannot load created object");
Assert_Equals (T, Integer (0), Integer (U2.Get_Value), "Invalid load");
T.Assert (User.Get_Key = U2.Get_Key, "Invalid key after load");
end;
-- Create a comment for the user.
declare
S : ADO.Sessions.Master_Session := Regtests.Get_Master_Database;
begin
S.Begin_Transaction;
Cmt.Set_Message (Ada.Strings.Unbounded.To_Unbounded_String ("A comment from Joe"));
Cmt.Set_User (User);
Cmt.Set_Entity_Id (2);
Cmt.Set_Entity_Type (1);
Cmt.Set_Date (ADO.DEFAULT_TIME);
Cmt.Save (S);
S.Commit;
end;
-- Load that comment.
declare
S : ADO.Sessions.Master_Session := Regtests.Get_Master_Database;
C2 : Regtests.Comments.Comment_Ref;
begin
C2.Load (S, Cmt.Get_Id);
T.Assert (not C2.Is_Null, "Loading of object failed");
T.Assert (Cmt.Get_Key = C2.Get_Key, "Invalid key after load");
T.Assert_Equals ("A comment from Joe", Ada.Strings.Unbounded.To_String (C2.Get_Message),
"Invalid message");
T.Assert (not C2.Get_User.Is_Null, "User associated with the comment should not be null");
-- T.Assert (not C2.Get_Entity_Type.Is_Null, "Entity type was not set");
-- Check that we can access the user name (lazy load)
Assert_Equals (T, "Joe", Ada.Strings.Unbounded.To_String (C2.Get_User.Get_Name),
"Cannot load created object");
end;
end Test_Create_Object;
-- ------------------------------
-- Test creation and deletion of an object record
-- ------------------------------
procedure Test_Delete_Object (T : in out Test) is
User : Regtests.Simple.Model.User_Ref;
begin
-- Create an object within a transaction.
declare
S : ADO.Sessions.Master_Session := Regtests.Get_Master_Database;
begin
S.Begin_Transaction;
User.Set_Name ("Joe (delete)");
User.Set_Value (0);
User.Save (S);
S.Commit;
end;
-- Load it and delete it from another session.
declare
S : ADO.Sessions.Master_Session := Regtests.Get_Master_Database;
U2 : Regtests.Simple.Model.User_Ref;
begin
U2.Load (S, User.Get_Id);
S.Begin_Transaction;
U2.Delete (S);
S.Commit;
end;
-- Try to load the deleted object.
declare
S : ADO.Sessions.Master_Session := Regtests.Get_Master_Database;
U2 : Regtests.Simple.Model.User_Ref;
begin
U2.Load (S, User.Get_Id);
T.Assert (False, "Load of a deleted object should raise NOT_FOUND");
exception
when ADO.Objects.NOT_FOUND =>
null;
end;
end Test_Delete_Object;
-- ------------------------------
-- Test Is_Inserted and Is_Null
-- ------------------------------
procedure Test_Is_Inserted (T : in out Test) is
User : Regtests.Simple.Model.User_Ref;
begin
T.Assert (not User.Is_Inserted, "A null object should not be marked as INSERTED");
T.Assert (User.Is_Null, "A null object should be marked as NULL");
-- Create an object within a transaction.
declare
S : ADO.Sessions.Master_Session := Regtests.Get_Master_Database;
begin
S.Begin_Transaction;
User.Set_Name ("John");
T.Assert (not User.Is_Null, "User should not be NULL");
T.Assert (not User.Is_Inserted, "User was not saved and not yet inserted in database");
User.Set_Value (1);
User.Save (S);
S.Commit;
T.Assert (User.Is_Inserted, "After a save operation, the user should be marked INSERTED");
T.Assert (not User.Is_Null, "User should not be NULL");
end;
declare
S : ADO.Sessions.Master_Session := Regtests.Get_Master_Database;
John : Regtests.Simple.Model.User_Ref;
begin
John.Load (S, User.Get_Id);
T.Assert (John.Is_Inserted, "After a load, the object should be marked INSERTED");
T.Assert (not John.Is_Null, "After a load, the object should not be NULL");
end;
end Test_Is_Inserted;
package Caller is new Util.Test_Caller (Test, "ADO.Objects");
-- ------------------------------
-- Add the tests in the test suite
-- ------------------------------
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test ADO.Objects.Hash", Test_Key'Access);
Caller.Add_Test (Suite, "Test Object_Ref.Get/Set", Test_Object_Ref'Access);
Caller.Add_Test (Suite, "Test ADO.Objects.Create", Test_Create_Object'Access);
Caller.Add_Test (Suite, "Test ADO.Objects.Delete", Test_Delete_Object'Access);
Caller.Add_Test (Suite, "Test ADO.Objects.Is_Created", Test_Is_Inserted'Access);
end Add_Tests;
end ADO.Objects.Tests;
|
-----------------------------------------------------------------------
-- ADO Objects Tests -- Tests for ADO.Objects
-- Copyright (C) 2011, 2012, 2013, 2014 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Test_Caller;
with ADO.Sessions;
with Regtests.Simple.Model;
with Regtests.Comments;
package body ADO.Objects.Tests is
use Util.Tests;
use type Ada.Containers.Hash_Type;
function Get_Allocate_Key (N : Identifier) return Object_Key;
function Get_Allocate_Key (N : Identifier) return Object_Key is
Result : Object_Key (Of_Type => KEY_INTEGER,
Of_Class => Regtests.Simple.Model.ALLOCATE_TABLE'Access);
begin
Set_Value (Result, N);
return Result;
end Get_Allocate_Key;
-- ------------------------------
-- Various tests on Hash and key comparison
-- ------------------------------
procedure Test_Key (T : in out Test) is
K1 : constant Object_Key := Get_Allocate_Key (1);
K2 : Object_Key (Of_Type => KEY_STRING,
Of_Class => Regtests.Simple.Model.USER_TABLE'Access);
K3 : Object_Key := K1;
K4 : Object_Key (Of_Type => KEY_INTEGER,
Of_Class => Regtests.Simple.Model.USER_TABLE'Access);
begin
T.Assert (not (K1 = K2), "Key on different tables must be different");
T.Assert (not (K2 = K4), "Key with different type must be different");
T.Assert (K1 = K3, "Keys are identical");
T.Assert (Equivalent_Elements (K1, K3), "Keys are identical");
T.Assert (Equivalent_Elements (K3, K1), "Keys are identical");
T.Assert (Hash (K1) = Hash (K3), "Hash of identical keys should be identical");
Set_Value (K3, 2);
T.Assert (not (K1 = K3), "Keys should be different");
T.Assert (Hash (K1) /= Hash (K3), "Hash should be different");
T.Assert (Hash (K1) /= Hash (K2), "Hash should be different");
Set_Value (K4, 1);
T.Assert (Hash (K1) /= Hash (K4),
"Hash on key with same value and different tables should be different");
T.Assert (not (K4 = K1), "Key on different tables should be different");
Set_Value (K2, 1);
T.Assert (Hash (K1) /= Hash (K2), "Hash should be different");
end Test_Key;
-- ------------------------------
-- Check:
-- Object_Ref := (reference counting)
-- Object_Ref.Copy
-- Object_Ref.Get_xxx generated method
-- Object_Ref.Set_xxx generated method
-- Object_Ref.=
-- ------------------------------
procedure Test_Object_Ref (T : in out Test) is
use type Regtests.Simple.Model.User_Ref;
Obj1 : Regtests.Simple.Model.User_Ref;
Null_Obj : Regtests.Simple.Model.User_Ref;
begin
T.Assert (Obj1 = Null_Obj, "Two null objects are identical");
for I in 1 .. 10 loop
Obj1.Set_Name ("User name");
T.Assert (Obj1.Get_Name = "User name", "User_Ref.Set_Name invalid result");
T.Assert (Obj1 /= Null_Obj, "Object is not identical as the null object");
declare
Obj2 : constant Regtests.Simple.Model.User_Ref := Obj1;
Obj3 : Regtests.Simple.Model.User_Ref;
begin
Obj1.Copy (Obj3);
Obj3.Set_Id (2);
-- Check the copy
T.Assert (Obj2.Get_Name = "User name", "Object_Ref.Copy invalid copy");
T.Assert (Obj3.Get_Name = "User name", "Object_Ref.Copy invalid copy");
T.Assert (Obj2 = Obj1, "Object_Ref.'=' invalid comparison after assignment");
T.Assert (Obj3 /= Obj1, "Object_Ref.'=' invalid comparison after copy");
-- Change original, make sure it's the same of Obj2.
Obj1.Set_Name ("Second name");
T.Assert (Obj2.Get_Name = "Second name", "Object_Ref.Copy invalid copy");
T.Assert (Obj2 = Obj1, "Object_Ref.'=' invalid comparison after assignment");
-- The copy is not modified
T.Assert (Obj3.Get_Name = "User name", "Object_Ref.Copy invalid copy");
end;
end loop;
end Test_Object_Ref;
-- ------------------------------
-- Test creation of an object with lazy loading.
-- ------------------------------
procedure Test_Create_Object (T : in out Test) is
User : Regtests.Simple.Model.User_Ref;
Cmt : Regtests.Comments.Comment_Ref;
begin
-- Create an object within a transaction.
declare
S : ADO.Sessions.Master_Session := Regtests.Get_Master_Database;
begin
S.Begin_Transaction;
User.Set_Name ("Joe");
User.Set_Value (0);
User.Save (S);
S.Commit;
end;
-- Load it from another session.
declare
S : ADO.Sessions.Master_Session := Regtests.Get_Master_Database;
U2 : Regtests.Simple.Model.User_Ref;
begin
U2.Load (S, User.Get_Id);
Assert_Equals (T, "Joe", Ada.Strings.Unbounded.To_String (U2.Get_Name),
"Cannot load created object");
Assert_Equals (T, Integer (0), Integer (U2.Get_Value), "Invalid load");
T.Assert (User.Get_Key = U2.Get_Key, "Invalid key after load");
end;
-- Create a comment for the user.
declare
S : ADO.Sessions.Master_Session := Regtests.Get_Master_Database;
begin
S.Begin_Transaction;
Cmt.Set_Message (Ada.Strings.Unbounded.To_Unbounded_String ("A comment from Joe"));
Cmt.Set_User (User);
Cmt.Set_Entity_Id (2);
Cmt.Set_Entity_Type (1);
-- Cmt.Set_Date (ADO.DEFAULT_TIME);
Cmt.Set_Date (Ada.Calendar.Clock);
Cmt.Save (S);
S.Commit;
end;
-- Load that comment.
declare
S : ADO.Sessions.Master_Session := Regtests.Get_Master_Database;
C2 : Regtests.Comments.Comment_Ref;
begin
C2.Load (S, Cmt.Get_Id);
T.Assert (not C2.Is_Null, "Loading of object failed");
T.Assert (Cmt.Get_Key = C2.Get_Key, "Invalid key after load");
T.Assert_Equals ("A comment from Joe", Ada.Strings.Unbounded.To_String (C2.Get_Message),
"Invalid message");
T.Assert (not C2.Get_User.Is_Null, "User associated with the comment should not be null");
-- T.Assert (not C2.Get_Entity_Type.Is_Null, "Entity type was not set");
-- Check that we can access the user name (lazy load)
Assert_Equals (T, "Joe", Ada.Strings.Unbounded.To_String (C2.Get_User.Get_Name),
"Cannot load created object");
end;
end Test_Create_Object;
-- ------------------------------
-- Test creation and deletion of an object record
-- ------------------------------
procedure Test_Delete_Object (T : in out Test) is
User : Regtests.Simple.Model.User_Ref;
begin
-- Create an object within a transaction.
declare
S : ADO.Sessions.Master_Session := Regtests.Get_Master_Database;
begin
S.Begin_Transaction;
User.Set_Name ("Joe (delete)");
User.Set_Value (0);
User.Save (S);
S.Commit;
end;
-- Load it and delete it from another session.
declare
S : ADO.Sessions.Master_Session := Regtests.Get_Master_Database;
U2 : Regtests.Simple.Model.User_Ref;
begin
U2.Load (S, User.Get_Id);
S.Begin_Transaction;
U2.Delete (S);
S.Commit;
end;
-- Try to load the deleted object.
declare
S : ADO.Sessions.Master_Session := Regtests.Get_Master_Database;
U2 : Regtests.Simple.Model.User_Ref;
begin
U2.Load (S, User.Get_Id);
T.Assert (False, "Load of a deleted object should raise NOT_FOUND");
exception
when ADO.Objects.NOT_FOUND =>
null;
end;
end Test_Delete_Object;
-- ------------------------------
-- Test Is_Inserted and Is_Null
-- ------------------------------
procedure Test_Is_Inserted (T : in out Test) is
User : Regtests.Simple.Model.User_Ref;
begin
T.Assert (not User.Is_Inserted, "A null object should not be marked as INSERTED");
T.Assert (User.Is_Null, "A null object should be marked as NULL");
-- Create an object within a transaction.
declare
S : ADO.Sessions.Master_Session := Regtests.Get_Master_Database;
begin
S.Begin_Transaction;
User.Set_Name ("John");
T.Assert (not User.Is_Null, "User should not be NULL");
T.Assert (not User.Is_Inserted, "User was not saved and not yet inserted in database");
User.Set_Value (1);
User.Save (S);
S.Commit;
T.Assert (User.Is_Inserted, "After a save operation, the user should be marked INSERTED");
T.Assert (not User.Is_Null, "User should not be NULL");
end;
declare
S : ADO.Sessions.Master_Session := Regtests.Get_Master_Database;
John : Regtests.Simple.Model.User_Ref;
begin
John.Load (S, User.Get_Id);
T.Assert (John.Is_Inserted, "After a load, the object should be marked INSERTED");
T.Assert (not John.Is_Null, "After a load, the object should not be NULL");
end;
end Test_Is_Inserted;
package Caller is new Util.Test_Caller (Test, "ADO.Objects");
-- ------------------------------
-- Add the tests in the test suite
-- ------------------------------
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test ADO.Objects.Hash", Test_Key'Access);
Caller.Add_Test (Suite, "Test Object_Ref.Get/Set", Test_Object_Ref'Access);
Caller.Add_Test (Suite, "Test ADO.Objects.Create", Test_Create_Object'Access);
Caller.Add_Test (Suite, "Test ADO.Objects.Delete", Test_Delete_Object'Access);
Caller.Add_Test (Suite, "Test ADO.Objects.Is_Created", Test_Is_Inserted'Access);
end Add_Tests;
end ADO.Objects.Tests;
|
Fix the unit test for the setting of a time stamp
|
Fix the unit test for the setting of a time stamp
|
Ada
|
apache-2.0
|
stcarrez/ada-ado
|
b6b3f237663892b8121a8caf7bc5b9138db1833f
|
src/util-encoders-base64.adb
|
src/util-encoders-base64.adb
|
-----------------------------------------------------------------------
-- util-encoders-base64 -- Encode/Decode a stream in base64adecimal
-- Copyright (C) 2009, 2010, 2011, 2012, 2013, 2016 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Streams;
package body Util.Encoders.Base64 is
use Interfaces;
use Ada;
use type Ada.Streams.Stream_Element_Offset;
-- ------------------------------
-- Encode the 64-bit value to LEB128 and then base64url.
-- ------------------------------
function Encode (Value : in Interfaces.Unsigned_64) return String is
E : Encoder;
Data : Ada.Streams.Stream_Element_Array (1 .. 10);
Last : Ada.Streams.Stream_Element_Offset;
Encoded : Ada.Streams.Stream_Element_Offset;
Result : String (1 .. 16);
Buf : Ada.Streams.Stream_Element_Array (1 .. Result'Length);
for Buf'Address use Result'Address;
pragma Import (Ada, Buf);
begin
-- Encode the integer to LEB128 in the data buffer.
Encode_LEB128 (Into => Data,
Pos => Data'First,
Val => Value,
Last => Last);
-- Encode the data buffer in base64url.
E.Set_URL_Mode (True);
E.Transform (Data => Data (Data'First .. Last),
Into => Buf,
Last => Last,
Encoded => Encoded);
-- Strip the '=' or '==' at end of base64url.
if Result (Positive (Last)) /= '=' then
return Result (Result'First .. Positive (Last));
elsif Result (Positive (Last) - 1) /= '=' then
return Result (Result'First .. Positive (Last) - 1);
else
return Result (Result'First .. Positive (Last) - 2);
end if;
end Encode;
-- ------------------------------
-- Decode the base64url string and then the LEB128 integer.
-- Raise the Encoding_Error if the string is invalid and cannot be decoded.
-- ------------------------------
function Decode (Value : in String) return Interfaces.Unsigned_64 is
D : Decoder;
Buf : Ada.Streams.Stream_Element_Array (1 .. Value'Length + 2);
R : Ada.Streams.Stream_Element_Array (1 .. Value'Length + 2);
Last : Ada.Streams.Stream_Element_Offset;
Encoded : Ada.Streams.Stream_Element_Offset;
Result : Interfaces.Unsigned_64;
End_Pos : constant Ada.Streams.Stream_Element_Offset
:= Value'Length + ((4 - (Value'Length mod 4)) mod 4);
begin
Util.Streams.Copy (Into => Buf (1 .. Value'Length), From => Value);
-- Set back the '=' for the base64url (pad to multiple of 4.
Buf (Value'Length + 1) := Character'Pos ('=');
Buf (Value'Length + 2) := Character'Pos ('=');
-- Decode using base64url
D.Set_URL_Mode (True);
D.Transform (Data => Buf (Buf'First .. End_Pos),
Into => R,
Last => Last,
Encoded => Encoded);
if Encoded /= End_Pos then
raise Encoding_Error with "Input string is too short";
end if;
-- Decode the LEB128 number.
Decode_LEB128 (From => R (R'First .. Last),
Pos => R'First,
Val => Result,
Last => Encoded);
-- Check that everything was decoded.
if Last + 1 /= Encoded then
raise Encoding_Error with "Input string contains garbage at the end";
end if;
return Result;
end Decode;
-- ------------------------------
-- Encodes the binary input stream represented by <b>Data</b> into
-- the a base64 output stream <b>Into</b>.
--
-- If the transformer does not have enough room to write the result,
-- it must return in <b>Encoded</b> the index of the last encoded
-- position in the <b>Data</b> stream.
--
-- The transformer returns in <b>Last</b> the last valid position
-- in the output stream <b>Into</b>.
--
-- The <b>Encoding_Error</b> exception is raised if the input
-- stream cannot be transformed.
-- ------------------------------
overriding
procedure Transform (E : in Encoder;
Data : in Ada.Streams.Stream_Element_Array;
Into : out Ada.Streams.Stream_Element_Array;
Last : out Ada.Streams.Stream_Element_Offset;
Encoded : out Ada.Streams.Stream_Element_Offset) is
Pos : Ada.Streams.Stream_Element_Offset := Into'First;
I : Ada.Streams.Stream_Element_Offset := Data'First;
C1, C2 : Unsigned_8;
Alphabet : constant Alphabet_Access := E.Alphabet;
begin
while I <= Data'Last loop
if Pos + 4 > Into'Last + 1 then
Last := Pos - 1;
Encoded := I - 1;
return;
end if;
-- Encode the first byte, add padding if necessary.
C1 := Unsigned_8 (Data (I));
Into (Pos) := Alphabet (Shift_Right (C1, 2));
if I = Data'Last then
Into (Pos + 1) := Alphabet (Shift_Left (C1 and 3, 4));
Into (Pos + 2) := Character'Pos ('=');
Into (Pos + 3) := Character'Pos ('=');
Last := Pos + 3;
Encoded := Data'Last;
return;
end if;
-- Encode the second byte, add padding if necessary.
C2 := Unsigned_8 (Data (I + 1));
Into (Pos + 1) := Alphabet (Shift_Left (C1 and 16#03#, 4) or Shift_Right (C2, 4));
if I = Data'Last - 1 then
Into (Pos + 2) := Alphabet (Shift_Left (C2 and 16#0F#, 2));
Into (Pos + 3) := Character'Pos ('=');
Last := Pos + 3;
Encoded := Data'Last;
return;
end if;
-- Encode the third byte
C1 := Unsigned_8 (Data (I + 2));
Into (Pos + 2) := Alphabet (Shift_Left (C2 and 16#0F#, 2) or Shift_Right (C1, 6));
Into (Pos + 3) := Alphabet (C1 and 16#03F#);
Pos := Pos + 4;
I := I + 3;
end loop;
Last := Pos - 1;
Encoded := Data'Last;
end Transform;
-- ------------------------------
-- Set the encoder to use the base64 URL alphabet when <b>Mode</b> is True.
-- The URL alphabet uses the '-' and '_' instead of the '+' and '/' characters.
-- ------------------------------
procedure Set_URL_Mode (E : in out Encoder;
Mode : in Boolean) is
begin
if Mode then
E.Alphabet := BASE64_URL_ALPHABET'Access;
else
E.Alphabet := BASE64_ALPHABET'Access;
end if;
end Set_URL_Mode;
-- ------------------------------
-- Create a base64 encoder using the URL alphabet.
-- The URL alphabet uses the '-' and '_' instead of the '+' and '/' characters.
-- ------------------------------
function Create_URL_Encoder return Transformer_Access is
begin
return new Encoder '(Alphabet => BASE64_URL_ALPHABET'Access);
end Create_URL_Encoder;
-- ------------------------------
-- Decodes the base64 input stream represented by <b>Data</b> into
-- the binary output stream <b>Into</b>.
--
-- If the transformer does not have enough room to write the result,
-- it must return in <b>Encoded</b> the index of the last encoded
-- position in the <b>Data</b> stream.
--
-- The transformer returns in <b>Last</b> the last valid position
-- in the output stream <b>Into</b>.
--
-- The <b>Encoding_Error</b> exception is raised if the input
-- stream cannot be transformed.
-- ------------------------------
overriding
procedure Transform (E : in Decoder;
Data : in Ada.Streams.Stream_Element_Array;
Into : out Ada.Streams.Stream_Element_Array;
Last : out Ada.Streams.Stream_Element_Offset;
Encoded : out Ada.Streams.Stream_Element_Offset) is
use Ada.Streams;
Pos : Ada.Streams.Stream_Element_Offset := Into'First;
I : Ada.Streams.Stream_Element_Offset := Data'First;
C1, C2 : Ada.Streams.Stream_Element;
Val1, Val2 : Unsigned_8;
Values : constant Alphabet_Values_Access := E.Values;
begin
while I <= Data'Last loop
if Pos + 3 > Into'Last + 1 then
Last := Pos - 1;
Encoded := I - 1;
return;
end if;
-- Decode the first two bytes to produce the first output byte
C1 := Data (I);
Val1 := Values (C1);
if (Val1 and 16#C0#) /= 0 then
raise Encoding_Error with "Invalid character '" & Character'Val (C1) & "'";
end if;
C2 := Data (I + 1);
Val2 := Values (C2);
if (Val2 and 16#C0#) /= 0 then
raise Encoding_Error with "Invalid character '" & Character'Val (C2) & "'";
end if;
Into (Pos) := Stream_Element (Shift_Left (Val1, 2) or Shift_Right (Val2, 4));
if I + 2 > Data'Last then
Encoded := I + 1;
Last := Pos;
return;
end if;
-- Decode the next byte
C1 := Data (I + 2);
Val1 := Values (C1);
if (Val1 and 16#C0#) /= 0 then
if C1 /= Character'Pos ('=') then
raise Encoding_Error with "Invalid character '" & Character'Val (C1) & "'";
end if;
Encoded := I + 3;
Last := Pos;
return;
end if;
Into (Pos + 1) := Stream_Element (Shift_Left (Val2, 4) or Shift_Right (Val1, 2));
if I + 3 > Data'Last then
Encoded := I + 2;
Last := Pos + 1;
return;
end if;
C2 := Data (I + 3);
Val2 := Values (C2);
if (Val2 and 16#C0#) /= 0 then
if C2 /= Character'Pos ('=') then
raise Encoding_Error with "Invalid character '" & Character'Val (C2) & "'";
end if;
Encoded := I + 3;
Last := Pos + 1;
return;
end if;
Into (Pos + 2) := Stream_Element (Shift_Left (Val1, 6) or Val2);
Pos := Pos + 3;
I := I + 4;
end loop;
Last := Pos - 1;
Encoded := Data'Last;
end Transform;
-- ------------------------------
-- Set the decoder to use the base64 URL alphabet when <b>Mode</b> is True.
-- The URL alphabet uses the '-' and '_' instead of the '+' and '/' characters.
-- ------------------------------
procedure Set_URL_Mode (E : in out Decoder;
Mode : in Boolean) is
begin
if Mode then
E.Values := BASE64_URL_VALUES'Access;
else
E.Values := BASE64_VALUES'Access;
end if;
end Set_URL_Mode;
-- ------------------------------
-- Create a base64 decoder using the URL alphabet.
-- The URL alphabet uses the '-' and '_' instead of the '+' and '/' characters.
-- ------------------------------
function Create_URL_Decoder return Transformer_Access is
begin
return new Decoder '(Values => BASE64_URL_VALUES'Access);
end Create_URL_Decoder;
end Util.Encoders.Base64;
|
-----------------------------------------------------------------------
-- util-encoders-base64 -- Encode/Decode a stream in base64adecimal
-- Copyright (C) 2009, 2010, 2011, 2012, 2013, 2016, 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Streams;
package body Util.Encoders.Base64 is
use Interfaces;
use Ada;
use type Ada.Streams.Stream_Element_Offset;
-- ------------------------------
-- Encode the 64-bit value to LEB128 and then base64url.
-- ------------------------------
function Encode (Value : in Interfaces.Unsigned_64) return String is
E : Encoder;
Data : Ada.Streams.Stream_Element_Array (1 .. 10);
Last : Ada.Streams.Stream_Element_Offset;
Encoded : Ada.Streams.Stream_Element_Offset;
Result : String (1 .. 16);
Buf : Ada.Streams.Stream_Element_Array (1 .. Result'Length);
for Buf'Address use Result'Address;
pragma Import (Ada, Buf);
begin
-- Encode the integer to LEB128 in the data buffer.
Encode_LEB128 (Into => Data,
Pos => Data'First,
Val => Value,
Last => Last);
-- Encode the data buffer in base64url.
E.Set_URL_Mode (True);
E.Transform (Data => Data (Data'First .. Last),
Into => Buf,
Last => Last,
Encoded => Encoded);
-- Strip the '=' or '==' at end of base64url.
if Result (Positive (Last)) /= '=' then
return Result (Result'First .. Positive (Last));
elsif Result (Positive (Last) - 1) /= '=' then
return Result (Result'First .. Positive (Last) - 1);
else
return Result (Result'First .. Positive (Last) - 2);
end if;
end Encode;
-- ------------------------------
-- Decode the base64url string and then the LEB128 integer.
-- Raise the Encoding_Error if the string is invalid and cannot be decoded.
-- ------------------------------
function Decode (Value : in String) return Interfaces.Unsigned_64 is
D : Decoder;
Buf : Ada.Streams.Stream_Element_Array (1 .. Value'Length + 2);
R : Ada.Streams.Stream_Element_Array (1 .. Value'Length + 2);
Last : Ada.Streams.Stream_Element_Offset;
Encoded : Ada.Streams.Stream_Element_Offset;
Result : Interfaces.Unsigned_64;
End_Pos : constant Ada.Streams.Stream_Element_Offset
:= Value'Length + ((4 - (Value'Length mod 4)) mod 4);
begin
Util.Streams.Copy (Into => Buf (1 .. Value'Length), From => Value);
-- Set back the '=' for the base64url (pad to multiple of 4.
Buf (Value'Length + 1) := Character'Pos ('=');
Buf (Value'Length + 2) := Character'Pos ('=');
-- Decode using base64url
D.Set_URL_Mode (True);
D.Transform (Data => Buf (Buf'First .. End_Pos),
Into => R,
Last => Last,
Encoded => Encoded);
if Encoded /= End_Pos then
raise Encoding_Error with "Input string is too short";
end if;
-- Decode the LEB128 number.
Decode_LEB128 (From => R (R'First .. Last),
Pos => R'First,
Val => Result,
Last => Encoded);
-- Check that everything was decoded.
if Last + 1 /= Encoded then
raise Encoding_Error with "Input string contains garbage at the end";
end if;
return Result;
end Decode;
-- ------------------------------
-- Encodes the binary input stream represented by <b>Data</b> into
-- the a base64 output stream <b>Into</b>.
--
-- If the transformer does not have enough room to write the result,
-- it must return in <b>Encoded</b> the index of the last encoded
-- position in the <b>Data</b> stream.
--
-- The transformer returns in <b>Last</b> the last valid position
-- in the output stream <b>Into</b>.
--
-- The <b>Encoding_Error</b> exception is raised if the input
-- stream cannot be transformed.
-- ------------------------------
overriding
procedure Transform (E : in out Encoder;
Data : in Ada.Streams.Stream_Element_Array;
Into : out Ada.Streams.Stream_Element_Array;
Last : out Ada.Streams.Stream_Element_Offset;
Encoded : out Ada.Streams.Stream_Element_Offset) is
Pos : Ada.Streams.Stream_Element_Offset := Into'First;
I : Ada.Streams.Stream_Element_Offset := Data'First;
C1, C2 : Unsigned_8;
Alphabet : constant Alphabet_Access := E.Alphabet;
begin
while I <= Data'Last loop
if Pos + 4 > Into'Last + 1 then
Last := Pos - 1;
Encoded := I - 1;
return;
end if;
-- Encode the first byte, add padding if necessary.
C1 := Unsigned_8 (Data (I));
Into (Pos) := Alphabet (Shift_Right (C1, 2));
if I = Data'Last then
Into (Pos + 1) := Alphabet (Shift_Left (C1 and 3, 4));
Into (Pos + 2) := Character'Pos ('=');
Into (Pos + 3) := Character'Pos ('=');
Last := Pos + 3;
Encoded := Data'Last;
return;
end if;
-- Encode the second byte, add padding if necessary.
C2 := Unsigned_8 (Data (I + 1));
Into (Pos + 1) := Alphabet (Shift_Left (C1 and 16#03#, 4) or Shift_Right (C2, 4));
if I = Data'Last - 1 then
Into (Pos + 2) := Alphabet (Shift_Left (C2 and 16#0F#, 2));
Into (Pos + 3) := Character'Pos ('=');
Last := Pos + 3;
Encoded := Data'Last;
return;
end if;
-- Encode the third byte
C1 := Unsigned_8 (Data (I + 2));
Into (Pos + 2) := Alphabet (Shift_Left (C2 and 16#0F#, 2) or Shift_Right (C1, 6));
Into (Pos + 3) := Alphabet (C1 and 16#03F#);
Pos := Pos + 4;
I := I + 3;
end loop;
Last := Pos - 1;
Encoded := Data'Last;
end Transform;
-- ------------------------------
-- Set the encoder to use the base64 URL alphabet when <b>Mode</b> is True.
-- The URL alphabet uses the '-' and '_' instead of the '+' and '/' characters.
-- ------------------------------
procedure Set_URL_Mode (E : in out Encoder;
Mode : in Boolean) is
begin
if Mode then
E.Alphabet := BASE64_URL_ALPHABET'Access;
else
E.Alphabet := BASE64_ALPHABET'Access;
end if;
end Set_URL_Mode;
-- ------------------------------
-- Create a base64 encoder using the URL alphabet.
-- The URL alphabet uses the '-' and '_' instead of the '+' and '/' characters.
-- ------------------------------
function Create_URL_Encoder return Transformer_Access is
begin
return new Encoder '(Alphabet => BASE64_URL_ALPHABET'Access);
end Create_URL_Encoder;
-- ------------------------------
-- Decodes the base64 input stream represented by <b>Data</b> into
-- the binary output stream <b>Into</b>.
--
-- If the transformer does not have enough room to write the result,
-- it must return in <b>Encoded</b> the index of the last encoded
-- position in the <b>Data</b> stream.
--
-- The transformer returns in <b>Last</b> the last valid position
-- in the output stream <b>Into</b>.
--
-- The <b>Encoding_Error</b> exception is raised if the input
-- stream cannot be transformed.
-- ------------------------------
overriding
procedure Transform (E : in out Decoder;
Data : in Ada.Streams.Stream_Element_Array;
Into : out Ada.Streams.Stream_Element_Array;
Last : out Ada.Streams.Stream_Element_Offset;
Encoded : out Ada.Streams.Stream_Element_Offset) is
use Ada.Streams;
Pos : Ada.Streams.Stream_Element_Offset := Into'First;
I : Ada.Streams.Stream_Element_Offset := Data'First;
C1, C2 : Ada.Streams.Stream_Element;
Val1, Val2 : Unsigned_8;
Values : constant Alphabet_Values_Access := E.Values;
begin
while I <= Data'Last loop
if Pos + 3 > Into'Last + 1 then
Last := Pos - 1;
Encoded := I - 1;
return;
end if;
-- Decode the first two bytes to produce the first output byte
C1 := Data (I);
Val1 := Values (C1);
if (Val1 and 16#C0#) /= 0 then
raise Encoding_Error with "Invalid character '" & Character'Val (C1) & "'";
end if;
C2 := Data (I + 1);
Val2 := Values (C2);
if (Val2 and 16#C0#) /= 0 then
raise Encoding_Error with "Invalid character '" & Character'Val (C2) & "'";
end if;
Into (Pos) := Stream_Element (Shift_Left (Val1, 2) or Shift_Right (Val2, 4));
if I + 2 > Data'Last then
Encoded := I + 1;
Last := Pos;
return;
end if;
-- Decode the next byte
C1 := Data (I + 2);
Val1 := Values (C1);
if (Val1 and 16#C0#) /= 0 then
if C1 /= Character'Pos ('=') then
raise Encoding_Error with "Invalid character '" & Character'Val (C1) & "'";
end if;
Encoded := I + 3;
Last := Pos;
return;
end if;
Into (Pos + 1) := Stream_Element (Shift_Left (Val2, 4) or Shift_Right (Val1, 2));
if I + 3 > Data'Last then
Encoded := I + 2;
Last := Pos + 1;
return;
end if;
C2 := Data (I + 3);
Val2 := Values (C2);
if (Val2 and 16#C0#) /= 0 then
if C2 /= Character'Pos ('=') then
raise Encoding_Error with "Invalid character '" & Character'Val (C2) & "'";
end if;
Encoded := I + 3;
Last := Pos + 1;
return;
end if;
Into (Pos + 2) := Stream_Element (Shift_Left (Val1, 6) or Val2);
Pos := Pos + 3;
I := I + 4;
end loop;
Last := Pos - 1;
Encoded := Data'Last;
end Transform;
-- ------------------------------
-- Set the decoder to use the base64 URL alphabet when <b>Mode</b> is True.
-- The URL alphabet uses the '-' and '_' instead of the '+' and '/' characters.
-- ------------------------------
procedure Set_URL_Mode (E : in out Decoder;
Mode : in Boolean) is
begin
if Mode then
E.Values := BASE64_URL_VALUES'Access;
else
E.Values := BASE64_VALUES'Access;
end if;
end Set_URL_Mode;
-- ------------------------------
-- Create a base64 decoder using the URL alphabet.
-- The URL alphabet uses the '-' and '_' instead of the '+' and '/' characters.
-- ------------------------------
function Create_URL_Decoder return Transformer_Access is
begin
return new Decoder '(Values => BASE64_URL_VALUES'Access);
end Create_URL_Decoder;
end Util.Encoders.Base64;
|
Change the Transformer interface to accept in out parameter for the Transformer
|
Change the Transformer interface to accept in out parameter for the Transformer
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
197e5f7deae4c08c304881808c0d493a01379141
|
src/security-oauth-jwt.adb
|
src/security-oauth-jwt.adb
|
-----------------------------------------------------------------------
-- security-oauth-jwt -- OAuth Java Web Token
-- Copyright (C) 2013 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Calendar.Conversions;
with Interfaces.C;
with Util.Encoders;
with Util.Strings;
with Util.Serialize.IO;
with Util.Properties.JSON;
with Util.Log.Loggers;
package body Security.OAuth.JWT is
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Security.OAuth.JWT");
function Get_Time (From : in Util.Properties.Manager;
Name : in String) return Ada.Calendar.Time;
-- Decode the part using base64url and parse the JSON content into the property manager.
procedure Decode_Part (Into : in out Util.Properties.Manager;
Name : in String;
Data : in String);
function Get_Time (From : in Util.Properties.Manager;
Name : in String) return Ada.Calendar.Time is
Value : constant String := From.Get (Name);
begin
return Ada.Calendar.Conversions.To_Ada_Time (Interfaces.C.long'Value (Value));
end Get_Time;
-- ------------------------------
-- Get the issuer claim from the token (the "iss" claim).
-- ------------------------------
function Get_Issuer (From : in Token) return String is
begin
return From.Claims.Get ("iss");
end Get_Issuer;
-- ------------------------------
-- Get the subject claim from the token (the "sub" claim).
-- ------------------------------
function Get_Subject (From : in Token) return String is
begin
return From.Claims.Get ("sub");
end Get_Subject;
-- ------------------------------
-- Get the audience claim from the token (the "aud" claim).
-- ------------------------------
function Get_Audience (From : in Token) return String is
begin
return From.Claims.Get ("aud");
end Get_Audience;
-- ------------------------------
-- Get the expiration claim from the token (the "exp" claim).
-- ------------------------------
function Get_Expiration (From : in Token) return Ada.Calendar.Time is
begin
return Get_Time (From.Claims, "exp");
end Get_Expiration;
-- ------------------------------
-- Get the not before claim from the token (the "nbf" claim).
-- ------------------------------
function Get_Not_Before (From : in Token) return Ada.Calendar.Time is
begin
return Get_Time (From.Claims, "nbf");
end Get_Not_Before;
-- ------------------------------
-- Get the issued at claim from the token (the "iat" claim).
-- ------------------------------
function Get_Issued_At (From : in Token) return Ada.Calendar.Time is
begin
return Get_Time (From.Claims, "iat");
end Get_Issued_At;
-- ------------------------------
-- Get the authentication time claim from the token (the "auth_time" claim).
-- ------------------------------
function Get_Authentication_Time (From : in Token) return Ada.Calendar.Time is
begin
return Get_Time (From.Claims, "auth_time");
end Get_Authentication_Time;
-- ------------------------------
-- Get the JWT ID claim from the token (the "jti" claim).
-- ------------------------------
function Get_JWT_ID (From : in Token) return String is
begin
return From.Claims.Get ("jti");
end Get_JWT_ID;
-- ------------------------------
-- Get the authorized clients claim from the token (the "azp" claim).
-- ------------------------------
function Get_Authorized_Presenters (From : in Token) return String is
begin
return From.Claims.Get ("azp");
end Get_Authorized_Presenters;
-- ------------------------------
-- Get the claim with the given name from the token.
-- ------------------------------
function Get_Claim (From : in Token;
Name : in String;
Default : in String := "") return String is
begin
return From.Claims.Get (Name, Default);
end Get_Claim;
-- ------------------------------
-- Decode the part using base64url and parse the JSON content into the property manager.
-- ------------------------------
procedure Decode_Part (Into : in out Util.Properties.Manager;
Name : in String;
Data : in String) is
Decoder : constant Util.Encoders.Encoder := Util.Encoders.Create (Util.Encoders.BASE_64_URL);
Content : constant String := Decoder.Decode (Data);
begin
Log.Debug ("Decoding {0}: {1}", Name, Content);
Util.Properties.JSON.Parse_JSON (Into, Content);
end Decode_Part;
-- ------------------------------
-- Decode a string representing an encoded JWT token according to the JWT specification:
--
-- Section 7. Rules for Creating and Validating a JWT
--
-- The JWT token is composed of 3 parts encoded in Base64url and separated by '.' .
-- The first part represents the header, the second part the claims and the last part
-- the signature. The <tt>Decode</tt> operation splits the parts, decodes them,
-- parses the JSON content represented by the header and the claims.
-- The <tt>Decode</tt> operation does not verify the signature (yet!).
--
-- Return the decoded token or raise an exception.
-- ------------------------------
function Decode (Content : in String) return Token is
Pos1 : constant Natural := Util.Strings.Index (Content, '.');
Pos2 : Natural;
Result : Token;
begin
if Pos1 = 0 then
Log.Error ("Invalid JWT token: missing '.' separator. JWT: {0}", Content);
raise Invalid_Token with "Missing header separator";
end if;
Pos2 := Util.Strings.Index (Content, '.', Pos1 + 1);
if Pos2 = 0 then
Log.Error ("Invalid JWT token: missing second '.' separator. JWT: {0}", Content);
raise Invalid_Token with "Missing signature separator";
end if;
Decode_Part (Result.Header, "header", Content (Content'First .. Pos1 - 1));
Decode_Part (Result.Claims, "claims", Content (Pos1 + 1 .. Pos2 - 1));
return Result;
exception
when Util.Serialize.IO.Parse_Error =>
raise Invalid_Token with "Invalid JSON content";
end Decode;
end Security.OAuth.JWT;
|
-----------------------------------------------------------------------
-- security-oauth-jwt -- OAuth Java Web Token
-- Copyright (C) 2013, 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Calendar.Conversions;
with Interfaces.C;
with Util.Encoders;
with Util.Strings;
with Util.Serialize.IO;
with Util.Properties.JSON;
with Util.Log.Loggers;
package body Security.OAuth.JWT is
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Security.OAuth.JWT");
function Get_Time (From : in Util.Properties.Manager;
Name : in String) return Ada.Calendar.Time;
-- Decode the part using base64url and parse the JSON content into the property manager.
procedure Decode_Part (Into : in out Util.Properties.Manager;
Name : in String;
Data : in String);
function Get_Time (From : in Util.Properties.Manager;
Name : in String) return Ada.Calendar.Time is
Value : constant String := From.Get (Name);
begin
return Ada.Calendar.Conversions.To_Ada_Time (Interfaces.C.long'Value (Value));
end Get_Time;
-- ------------------------------
-- Get the issuer claim from the token (the "iss" claim).
-- ------------------------------
function Get_Issuer (From : in Token) return String is
begin
return From.Claims.Get ("iss");
end Get_Issuer;
-- ------------------------------
-- Get the subject claim from the token (the "sub" claim).
-- ------------------------------
function Get_Subject (From : in Token) return String is
begin
return From.Claims.Get ("sub");
end Get_Subject;
-- ------------------------------
-- Get the audience claim from the token (the "aud" claim).
-- ------------------------------
function Get_Audience (From : in Token) return String is
begin
return From.Claims.Get ("aud");
end Get_Audience;
-- ------------------------------
-- Get the expiration claim from the token (the "exp" claim).
-- ------------------------------
function Get_Expiration (From : in Token) return Ada.Calendar.Time is
begin
return Get_Time (From.Claims, "exp");
end Get_Expiration;
-- ------------------------------
-- Get the not before claim from the token (the "nbf" claim).
-- ------------------------------
function Get_Not_Before (From : in Token) return Ada.Calendar.Time is
begin
return Get_Time (From.Claims, "nbf");
end Get_Not_Before;
-- ------------------------------
-- Get the issued at claim from the token (the "iat" claim).
-- ------------------------------
function Get_Issued_At (From : in Token) return Ada.Calendar.Time is
begin
return Get_Time (From.Claims, "iat");
end Get_Issued_At;
-- ------------------------------
-- Get the authentication time claim from the token (the "auth_time" claim).
-- ------------------------------
function Get_Authentication_Time (From : in Token) return Ada.Calendar.Time is
begin
return Get_Time (From.Claims, "auth_time");
end Get_Authentication_Time;
-- ------------------------------
-- Get the JWT ID claim from the token (the "jti" claim).
-- ------------------------------
function Get_JWT_ID (From : in Token) return String is
begin
return From.Claims.Get ("jti");
end Get_JWT_ID;
-- ------------------------------
-- Get the authorized clients claim from the token (the "azp" claim).
-- ------------------------------
function Get_Authorized_Presenters (From : in Token) return String is
begin
return From.Claims.Get ("azp");
end Get_Authorized_Presenters;
-- ------------------------------
-- Get the claim with the given name from the token.
-- ------------------------------
function Get_Claim (From : in Token;
Name : in String;
Default : in String := "") return String is
begin
return From.Claims.Get (Name, Default);
end Get_Claim;
-- ------------------------------
-- Decode the part using base64url and parse the JSON content into the property manager.
-- ------------------------------
procedure Decode_Part (Into : in out Util.Properties.Manager;
Name : in String;
Data : in String) is
Decoder : constant Util.Encoders.Decoder := Util.Encoders.Create (Util.Encoders.BASE_64_URL);
Content : constant String := Decoder.Decode (Data);
begin
Log.Debug ("Decoding {0}: {1}", Name, Content);
Util.Properties.JSON.Parse_JSON (Into, Content);
end Decode_Part;
-- ------------------------------
-- Decode a string representing an encoded JWT token according to the JWT specification:
--
-- Section 7. Rules for Creating and Validating a JWT
--
-- The JWT token is composed of 3 parts encoded in Base64url and separated by '.' .
-- The first part represents the header, the second part the claims and the last part
-- the signature. The <tt>Decode</tt> operation splits the parts, decodes them,
-- parses the JSON content represented by the header and the claims.
-- The <tt>Decode</tt> operation does not verify the signature (yet!).
--
-- Return the decoded token or raise an exception.
-- ------------------------------
function Decode (Content : in String) return Token is
Pos1 : constant Natural := Util.Strings.Index (Content, '.');
Pos2 : Natural;
Result : Token;
begin
if Pos1 = 0 then
Log.Error ("Invalid JWT token: missing '.' separator. JWT: {0}", Content);
raise Invalid_Token with "Missing header separator";
end if;
Pos2 := Util.Strings.Index (Content, '.', Pos1 + 1);
if Pos2 = 0 then
Log.Error ("Invalid JWT token: missing second '.' separator. JWT: {0}", Content);
raise Invalid_Token with "Missing signature separator";
end if;
Decode_Part (Result.Header, "header", Content (Content'First .. Pos1 - 1));
Decode_Part (Result.Claims, "claims", Content (Pos1 + 1 .. Pos2 - 1));
return Result;
exception
when Util.Serialize.IO.Parse_Error =>
raise Invalid_Token with "Invalid JSON content";
end Decode;
end Security.OAuth.JWT;
|
Use the new Decoder implementation
|
Use the new Decoder implementation
|
Ada
|
apache-2.0
|
stcarrez/ada-security
|
953edb96041e1d28c01f4af2917dca2774c1fe21
|
1-base/lace/source/text/lace-text-cursor.adb
|
1-base/lace/source/text/lace-text-cursor.adb
|
with
ada.Characters.latin_1,
ada.Characters.handling,
ada.Strings.fixed,
ada.Strings.Maps;
package body lace.text.Cursor
is
use ada.Strings;
Integer_Numerals : constant maps.character_Set := maps.to_Set ("+-0123456789");
Float_Numerals : constant maps.character_Set := maps.to_Set ("+-0123456789.");
--------
-- Forge
--
function First (of_Text : access constant Text.item) return Cursor.item
is
the_Cursor : constant Cursor.item := (of_Text.all'unchecked_Access, 1);
begin
return the_Cursor;
end First;
-------------
-- Attributes
--
function at_End (Self : in Item) return Boolean
is
begin
return Self.Current = 0;
end at_End;
function has_Element (Self : in Item) return Boolean
is
begin
return not at_End (Self)
and Self.Current <= Self.Target.Length;
end has_Element;
procedure advance (Self : in out Item; Delimiter : in String := " ";
Repeat : in Natural := 0;
skip_Delimiter : in Boolean := True;
Case_sensitive : in Boolean := True)
is
begin
for Count in 1 .. Repeat + 1
loop
declare
use ada.Characters.handling;
delimiter_Position : Natural;
begin
if Case_sensitive
then
delimiter_Position := fixed.Index (Self.Target.Data (1 .. Self.Target.Length),
Delimiter,
From => Self.Current);
else
delimiter_Position := fixed.Index (to_Lower (Self.Target.Data (1 .. Self.Target.Length)),
to_Lower (Delimiter),
From => Self.Current);
end if;
if delimiter_Position = 0
then
Self.Current := 0;
return;
else
if skip_Delimiter
then
Self.Current := delimiter_Position + Delimiter'Length;
elsif Count = Repeat + 1
then
Self.Current := delimiter_Position - 1;
else
Self.Current := delimiter_Position + Delimiter'Length - 1;
end if;
end if;
end;
end loop;
exception
when constraint_Error =>
raise at_end_Error;
end advance;
procedure skip_White (Self : in out Item)
is
begin
while has_Element (Self)
and then ( Self.Target.Data (Self.Current) = ' '
or Self.Target.Data (Self.Current) = ada.Characters.Latin_1.CR
or Self.Target.Data (Self.Current) = ada.Characters.Latin_1.LF
or Self.Target.Data (Self.Current) = ada.Characters.Latin_1.HT)
loop
Self.Current := Self.Current + 1;
end loop;
end skip_White;
procedure skip_Line (Self : in out Item)
is
Line : String := next_Line (Self) with Unreferenced;
begin
null;
end skip_Line;
function next_Token (Self : in out Item;
Delimiter : in Character := ' ';
Trim : in Boolean := False) return String
is
begin
return next_Token (Self, "" & Delimiter, Trim);
end next_Token;
function next_Token (Self : in out item; Delimiter : in String;
Trim : in Boolean := False) return String
is
begin
if at_End (Self)
then
raise at_end_Error;
end if;
declare
use ada.Strings.fixed;
delimiter_Position : constant Natural := Index (Self.Target.Data, Delimiter, from => Self.Current);
begin
if delimiter_Position = 0
then
return the_Token : constant String := (if Trim then fixed.Trim (Self.Target.Data (Self.Current .. Self.Target.Length), Both)
else Self.Target.Data (Self.Current .. Self.Target.Length))
do
Self.Current := 0;
end return;
end if;
return the_Token : constant String := (if Trim then fixed.Trim (Self.Target.Data (Self.Current .. delimiter_Position - 1), Both)
else Self.Target.Data (Self.Current .. delimiter_Position - 1))
do
Self.Current := delimiter_Position + Delimiter'Length;
end return;
end;
end next_Token;
function next_Line (Self : in out item; Trim : in Boolean := False) return String
is
use ada.Characters;
begin
return next_Token (Self, Delimiter => latin_1.LF,
Trim => Trim);
end next_Line;
procedure skip_Token (Self : in out Item; Delimiter : in String := " ")
is
ignored_Token : String := Self.next_Token (Delimiter);
begin
null;
end skip_Token;
function get_Integer (Self : in out Item) return Integer
is
use ada.Strings.fixed;
Text : String (1 .. Self.Length);
First : Positive;
Last : Natural;
begin
Text := Self.Target.Data (Self.Current .. Self.Target.Length);
find_Token (Text, integer_Numerals, Inside, First, Last);
if Last = 0 then
raise No_Data_Error;
end if;
Self.Current := Self.Current + Last;
return Integer'Value (Text (First .. Last));
end get_Integer;
function get_Integer (Self : in out Item) return long_Integer
is
use ada.Strings.fixed;
Text : String (1 .. Self.Length);
First : Positive;
Last : Natural;
begin
Text := Self.Target.Data (Self.Current .. Self.Target.Length);
find_Token (Text, integer_Numerals, Inside, First, Last);
if Last = 0 then
raise No_Data_Error;
end if;
Self.Current := Self.Current + Last;
return long_Integer'Value (Text (First .. Last));
end get_Integer;
function get_Real (Self : in out Item) return long_Float
is
use ada.Strings.fixed;
Text : String (1 .. Self.Length);
First : Positive;
Last : Natural;
begin
Text := Self.Target.Data (Self.Current .. Self.Target.Length);
find_Token (Text, float_Numerals, Inside, First, Last);
if Last = 0 then
raise No_Data_Error;
end if;
Self.Current := Self.Current + Last;
return long_Float'Value (Text (First .. Last));
end get_Real;
function Length (Self : in Item) return Natural
is
begin
return Self.Target.Length - Self.Current + 1;
end Length;
function peek (Self : in Item; Length : in Natural := Remaining) return String
is
Last : constant Natural := (if Length = Natural'Last then Self.Target.Length
else Self.Current + Length - 1);
begin
if at_End (Self)
then
return "";
end if;
return Self.Target.Data (Self.Current .. Last);
end peek;
function peek_Line (Self : in Item) return String
is
C : Cursor.item := Self;
begin
return next_Line (C);
end peek_Line;
end lace.text.Cursor;
|
with
ada.Characters.latin_1,
ada.Characters.handling,
ada.Strings.fixed,
ada.Strings.Maps;
package body lace.text.Cursor
is
use ada.Strings;
Integer_Numerals : constant maps.character_Set := maps.to_Set ("+-0123456789");
Float_Numerals : constant maps.character_Set := maps.to_Set ("+-0123456789.");
--------
-- Forge
--
function First (of_Text : access constant Text.item) return Cursor.item
is
the_Cursor : constant Cursor.item := (of_Text.all'unchecked_Access, 1);
begin
return the_Cursor;
end First;
-------------
-- Attributes
--
function at_End (Self : in Item) return Boolean
is
begin
return Self.Current = 0;
end at_End;
function has_Element (Self : in Item) return Boolean
is
begin
return not at_End (Self)
and Self.Current <= Self.Target.Length;
end has_Element;
procedure advance (Self : in out Item; Delimiter : in String := " ";
Repeat : in Natural := 0;
skip_Delimiter : in Boolean := True;
Case_sensitive : in Boolean := True)
is
begin
for Count in 1 .. Repeat + 1
loop
declare
use ada.Characters.handling;
delimiter_Position : Natural;
begin
if Case_sensitive
then
delimiter_Position := fixed.Index (Self.Target.Data (1 .. Self.Target.Length),
Delimiter,
From => Self.Current);
else
delimiter_Position := fixed.Index (to_Lower (Self.Target.Data (1 .. Self.Target.Length)),
to_Lower (Delimiter),
From => Self.Current);
end if;
if delimiter_Position = 0
then
Self.Current := 0;
return;
else
if skip_Delimiter
then
Self.Current := delimiter_Position + Delimiter'Length;
elsif Count = Repeat + 1
then
Self.Current := delimiter_Position - 1;
else
Self.Current := delimiter_Position + Delimiter'Length - 1;
end if;
end if;
end;
end loop;
exception
when constraint_Error =>
raise at_end_Error;
end advance;
procedure skip_White (Self : in out Item)
is
begin
while has_Element (Self)
and then ( Self.Target.Data (Self.Current) = ' '
or Self.Target.Data (Self.Current) = ada.Characters.Latin_1.CR
or Self.Target.Data (Self.Current) = ada.Characters.Latin_1.LF
or Self.Target.Data (Self.Current) = ada.Characters.Latin_1.HT)
loop
Self.Current := Self.Current + 1;
end loop;
end skip_White;
procedure skip_Line (Self : in out Item)
is
Line : String := next_Line (Self) with Unreferenced;
begin
null;
end skip_Line;
function next_Token (Self : in out Item;
Delimiter : in Character := ' ';
Trim : in Boolean := False) return String
is
begin
return next_Token (Self, "" & Delimiter, Trim);
end next_Token;
function next_Token (Self : in out item; Delimiter : in String;
Trim : in Boolean := False) return String
is
begin
if at_End (Self)
then
raise at_end_Error;
end if;
declare
use ada.Strings.fixed;
delimiter_Position : constant Natural := Index (Self.Target.Data, Delimiter, from => Self.Current);
begin
if delimiter_Position = 0
then
return the_Token : constant String := (if Trim then fixed.Trim (Self.Target.Data (Self.Current .. Self.Target.Length), Both)
else Self.Target.Data (Self.Current .. Self.Target.Length))
do
Self.Current := 0;
end return;
end if;
return the_Token : constant String := (if Trim then fixed.Trim (Self.Target.Data (Self.Current .. delimiter_Position - 1), Both)
else Self.Target.Data (Self.Current .. delimiter_Position - 1))
do
Self.Current := delimiter_Position + Delimiter'Length;
end return;
end;
end next_Token;
function next_Line (Self : in out item; Trim : in Boolean := False) return String
is
use ada.Characters;
Token : constant String := next_Token (Self, Delimiter => latin_1.LF,
Trim => Trim);
begin
if Token (Token'Last) = latin_1.CR
then
return Token (Token'First .. Token'Last - 1);
else
return Token;
end if;
end next_Line;
procedure skip_Token (Self : in out Item; Delimiter : in String := " ")
is
ignored_Token : String := Self.next_Token (Delimiter);
begin
null;
end skip_Token;
function get_Integer (Self : in out Item) return Integer
is
use ada.Strings.fixed;
Text : String (1 .. Self.Length);
First : Positive;
Last : Natural;
begin
Text := Self.Target.Data (Self.Current .. Self.Target.Length);
find_Token (Text, integer_Numerals, Inside, First, Last);
if Last = 0 then
raise No_Data_Error;
end if;
Self.Current := Self.Current + Last;
return Integer'Value (Text (First .. Last));
end get_Integer;
function get_Integer (Self : in out Item) return long_Integer
is
use ada.Strings.fixed;
Text : String (1 .. Self.Length);
First : Positive;
Last : Natural;
begin
Text := Self.Target.Data (Self.Current .. Self.Target.Length);
find_Token (Text, integer_Numerals, Inside, First, Last);
if Last = 0 then
raise No_Data_Error;
end if;
Self.Current := Self.Current + Last;
return long_Integer'Value (Text (First .. Last));
end get_Integer;
function get_Real (Self : in out Item) return long_Float
is
use ada.Strings.fixed;
Text : String (1 .. Self.Length);
First : Positive;
Last : Natural;
begin
Text := Self.Target.Data (Self.Current .. Self.Target.Length);
find_Token (Text, float_Numerals, Inside, First, Last);
if Last = 0 then
raise No_Data_Error;
end if;
Self.Current := Self.Current + Last;
return long_Float'Value (Text (First .. Last));
end get_Real;
function Length (Self : in Item) return Natural
is
begin
return Self.Target.Length - Self.Current + 1;
end Length;
function peek (Self : in Item; Length : in Natural := Remaining) return String
is
Last : constant Natural := (if Length = Natural'Last then Self.Target.Length
else Self.Current + Length - 1);
begin
if at_End (Self)
then
return "";
end if;
return Self.Target.Data (Self.Current .. Last);
end peek;
function peek_Line (Self : in Item) return String
is
C : Cursor.item := Self;
begin
return next_Line (C);
end peek_Line;
end lace.text.Cursor;
|
Handle 'CR/LF' end of lines.
|
lace.text.cursor: Handle 'CR/LF' end of lines.
|
Ada
|
isc
|
charlie5/lace,charlie5/lace,charlie5/lace
|
7212b92892339278a7f1ee4aba362fe5dc5f2379
|
mat/src/mat-targets.adb
|
mat/src/mat-targets.adb
|
-----------------------------------------------------------------------
-- Clients - Abstract representation of client information
-- 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.Text_IO;
with Ada.Command_Line;
with GNAT.Command_Line;
with Readline;
with Util.Strings;
with Util.Log.Loggers;
with MAT.Commands;
with MAT.Targets.Readers;
package body MAT.Targets is
-- ------------------------------
-- Get the console instance.
-- ------------------------------
function Console (Target : in Target_Type) return MAT.Consoles.Console_Access is
begin
return Target.Console;
end Console;
-- ------------------------------
-- Set the console instance.
-- ------------------------------
procedure Console (Target : in out Target_Type;
Console : in MAT.Consoles.Console_Access) is
begin
Target.Console := Console;
end Console;
-- ------------------------------
-- Get the current process instance.
-- ------------------------------
function Process (Target : in Target_Type) return Target_Process_Type_Access is
begin
return Target.Current;
end Process;
-- ------------------------------
-- Initialize the target object to manage the memory slots, the stack frames
-- and setup the reader to analyze the memory and other events.
-- ------------------------------
procedure Initialize (Target : in out Target_Type;
Reader : in out MAT.Readers.Manager_Base'Class) is
begin
MAT.Targets.Readers.Initialize (Target => Target,
Reader => Reader);
end Initialize;
-- ------------------------------
-- Create a process instance to hold and keep track of memory and other information about
-- the given process ID.
-- ------------------------------
procedure Create_Process (Target : in out Target_Type;
Pid : in MAT.Types.Target_Process_Ref;
Path : in Ada.Strings.Unbounded.Unbounded_String;
Process : out Target_Process_Type_Access) is
Path_String : constant String := Ada.Strings.Unbounded.To_String (Path);
begin
Process := Target.Find_Process (Pid);
if Process = null then
Process := new Target_Process_Type;
Process.Pid := Pid;
Process.Path := Path;
Process.Symbols := MAT.Symbols.Targets.Target_Symbols_Refs.Create;
Target.Processes.Insert (Pid, Process);
Target.Console.Notice (MAT.Consoles.N_PID_INFO,
"Process" & MAT.Types.Target_Process_Ref'Image (Pid) & " created");
Target.Console.Notice (MAT.Consoles.N_PATH_INFO,
"Path " & Path_String);
end if;
if Target.Current = null then
Target.Current := Process;
end if;
if Target.Options.Load_Symbols then
MAT.Commands.Symbol_Command (Target, Path_String);
end if;
end Create_Process;
-- ------------------------------
-- Find the process instance from the process ID.
-- ------------------------------
function Find_Process (Target : in Target_Type;
Pid : in MAT.Types.Target_Process_Ref)
return Target_Process_Type_Access is
Pos : constant Process_Cursor := Target.Processes.Find (Pid);
begin
if Process_Maps.Has_Element (Pos) then
return Process_Maps.Element (Pos);
else
return null;
end if;
end Find_Process;
-- ------------------------------
-- Iterate over the list of connected processes and execute the <tt>Process</tt> procedure.
-- ------------------------------
procedure Iterator (Target : in Target_Type;
Process : access procedure (Proc : in Target_Process_Type'Class)) is
Iter : Process_Cursor := Target.Processes.First;
begin
while Process_Maps.Has_Element (Iter) loop
Process (Process_Maps.Element (Iter).all);
Process_Maps.Next (Iter);
end loop;
end Iterator;
-- ------------------------------
-- 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 is
Pos : constant Natural := Util.Strings.Index (Param, ':');
Result : GNAT.Sockets.Sock_Addr_Type;
begin
if Pos > 0 then
Result.Port := GNAT.Sockets.Port_Type'Value (Param (Pos + 1 .. Param'Last));
Result.Addr := GNAT.Sockets.Inet_Addr (Param (Param'First .. Pos - 1));
else
Result.Port := GNAT.Sockets.Port_Type'Value (Param);
Result.Addr := GNAT.Sockets.Any_Inet_Addr;
end if;
return Result;
end To_Sock_Addr_Type;
-- ------------------------------
-- Print the application usage.
-- ------------------------------
procedure Usage is
use Ada.Text_IO;
begin
Put_Line ("Usage: mat [-i] [-nw] [-ns] [-b [ip:]port] [file.mat]");
Put_Line ("-i Enable the interactive mode");
Put_Line ("-nw Disable the graphical mode");
Put_Line ("-b [ip:]port Define the port and local address to bind");
Put_Line ("-ns Disable the automatic symbols loading");
Ada.Command_Line.Set_Exit_Status (2);
raise Usage_Error;
end Usage;
-- ------------------------------
-- Parse the command line arguments and configure the target instance.
-- ------------------------------
procedure Initialize_Options (Target : in out MAT.Targets.Target_Type) is
begin
Util.Log.Loggers.Initialize ("matp.properties");
GNAT.Command_Line.Initialize_Option_Scan (Stop_At_First_Non_Switch => True,
Section_Delimiters => "targs");
loop
case GNAT.Command_Line.Getopt ("i nw ns b:") is
when ASCII.NUL =>
exit;
when 'i' =>
Target.Options.Interactive := True;
when 'b' =>
Target.Options.Address := To_Sock_Addr_Type (GNAT.Command_Line.Parameter);
when 'n' =>
if GNAT.Command_Line.Full_Switch = "nw" then
Target.Options.Graphical := False;
else
Target.Options.Load_Symbols := False;
end if;
when '*' =>
exit;
when others =>
Usage;
end case;
end loop;
exception
when Usage_Error =>
raise;
when others =>
Usage;
end Initialize_Options;
-- ------------------------------
-- 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) is
begin
loop
declare
Line : constant String := Readline.Get_Line ("matp>");
begin
MAT.Commands.Execute (Target, Line);
exception
when MAT.Commands.Stop_Interp =>
exit;
end;
end loop;
end Interactive;
-- ------------------------------
-- Start the server to listen to MAT event socket streams.
-- ------------------------------
procedure Start (Target : in out Target_Type) is
begin
Target.Server.Start (Target.Options.Address);
end Start;
-- ------------------------------
-- Stop the server thread.
-- ------------------------------
procedure Stop (Target : in out Target_Type) is
begin
Target.Server.Stop;
end Stop;
end MAT.Targets;
|
-----------------------------------------------------------------------
-- Clients - Abstract representation of client information
-- 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.Text_IO;
with Ada.Command_Line;
with GNAT.Command_Line;
with Readline;
with Util.Strings;
with Util.Log.Loggers;
with MAT.Commands;
with MAT.Targets.Readers;
package body MAT.Targets is
-- ------------------------------
-- Get the console instance.
-- ------------------------------
function Console (Target : in Target_Type) return MAT.Consoles.Console_Access is
begin
return Target.Console;
end Console;
-- ------------------------------
-- Set the console instance.
-- ------------------------------
procedure Console (Target : in out Target_Type;
Console : in MAT.Consoles.Console_Access) is
begin
Target.Console := Console;
end Console;
-- ------------------------------
-- Get the current process instance.
-- ------------------------------
function Process (Target : in Target_Type) return Target_Process_Type_Access is
begin
return Target.Current;
end Process;
-- ------------------------------
-- Initialize the target object to manage the memory slots, the stack frames
-- and setup the reader to analyze the memory and other events.
-- ------------------------------
procedure Initialize (Target : in out Target_Type;
Reader : in out MAT.Readers.Manager_Base'Class) is
begin
MAT.Targets.Readers.Initialize (Target => Target,
Reader => Reader);
end Initialize;
-- ------------------------------
-- Create a process instance to hold and keep track of memory and other information about
-- the given process ID.
-- ------------------------------
procedure Create_Process (Target : in out Target_Type;
Pid : in MAT.Types.Target_Process_Ref;
Path : in Ada.Strings.Unbounded.Unbounded_String;
Process : out Target_Process_Type_Access) is
Path_String : constant String := Ada.Strings.Unbounded.To_String (Path);
begin
Process := Target.Find_Process (Pid);
if Process = null then
Process := new Target_Process_Type;
Process.Pid := Pid;
Process.Path := Path;
Process.Symbols := MAT.Symbols.Targets.Target_Symbols_Refs.Create;
Target.Processes.Insert (Pid, Process);
Target.Console.Notice (MAT.Consoles.N_PID_INFO,
"Process" & MAT.Types.Target_Process_Ref'Image (Pid) & " created");
Target.Console.Notice (MAT.Consoles.N_PATH_INFO,
"Path " & Path_String);
end if;
if Target.Current = null then
Target.Current := Process;
end if;
if Target.Options.Load_Symbols then
MAT.Commands.Symbol_Command (Target, Path_String);
end if;
end Create_Process;
-- ------------------------------
-- Find the process instance from the process ID.
-- ------------------------------
function Find_Process (Target : in Target_Type;
Pid : in MAT.Types.Target_Process_Ref)
return Target_Process_Type_Access is
Pos : constant Process_Cursor := Target.Processes.Find (Pid);
begin
if Process_Maps.Has_Element (Pos) then
return Process_Maps.Element (Pos);
else
return null;
end if;
end Find_Process;
-- ------------------------------
-- Iterate over the list of connected processes and execute the <tt>Process</tt> procedure.
-- ------------------------------
procedure Iterator (Target : in Target_Type;
Process : access procedure (Proc : in Target_Process_Type'Class)) is
Iter : Process_Cursor := Target.Processes.First;
begin
while Process_Maps.Has_Element (Iter) loop
Process (Process_Maps.Element (Iter).all);
Process_Maps.Next (Iter);
end loop;
end Iterator;
-- ------------------------------
-- 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 is
Pos : constant Natural := Util.Strings.Index (Param, ':');
Result : GNAT.Sockets.Sock_Addr_Type;
begin
if Pos > 0 then
Result.Port := GNAT.Sockets.Port_Type'Value (Param (Pos + 1 .. Param'Last));
Result.Addr := GNAT.Sockets.Inet_Addr (Param (Param'First .. Pos - 1));
else
Result.Port := GNAT.Sockets.Port_Type'Value (Param);
Result.Addr := GNAT.Sockets.Any_Inet_Addr;
end if;
return Result;
end To_Sock_Addr_Type;
-- ------------------------------
-- Print the application usage.
-- ------------------------------
procedure Usage is
use Ada.Text_IO;
begin
Put_Line ("Usage: mat [-i] [-nw] [-ns] [-b [ip:]port] [file.mat]");
Put_Line ("-i Enable the interactive mode");
Put_Line ("-nw Disable the graphical mode");
Put_Line ("-b [ip:]port Define the port and local address to bind");
Put_Line ("-ns Disable the automatic symbols loading");
Ada.Command_Line.Set_Exit_Status (2);
raise Usage_Error;
end Usage;
-- ------------------------------
-- Parse the command line arguments and configure the target instance.
-- ------------------------------
procedure Initialize_Options (Target : in out MAT.Targets.Target_Type) is
begin
Util.Log.Loggers.Initialize ("matp.properties");
GNAT.Command_Line.Initialize_Option_Scan (Stop_At_First_Non_Switch => True,
Section_Delimiters => "targs");
loop
case GNAT.Command_Line.Getopt ("i nw ns b:") is
when ASCII.NUL =>
exit;
when 'i' =>
Target.Options.Interactive := True;
when 'b' =>
Target.Options.Address := To_Sock_Addr_Type (GNAT.Command_Line.Parameter);
when 'n' =>
if GNAT.Command_Line.Full_Switch = "nw" then
Target.Options.Graphical := False;
else
Target.Options.Load_Symbols := False;
end if;
when '*' =>
exit;
when others =>
Usage;
end case;
end loop;
exception
when Usage_Error =>
raise;
when others =>
Usage;
end Initialize_Options;
-- ------------------------------
-- 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) is
begin
loop
declare
Line : constant String := Readline.Get_Line ("matp>");
begin
MAT.Commands.Execute (Target, Line);
exception
when MAT.Commands.Stop_Interp =>
exit;
end;
end loop;
end Interactive;
-- ------------------------------
-- Start the server to listen to MAT event socket streams.
-- ------------------------------
procedure Start (Target : in out Target_Type) is
begin
Target.Server.Start (Target'Unchecked_Access, Target.Options.Address);
end Start;
-- ------------------------------
-- Stop the server thread.
-- ------------------------------
procedure Stop (Target : in out Target_Type) is
begin
Target.Server.Stop;
end Stop;
end MAT.Targets;
|
Update the call to Start socket listener
|
Update the call to Start socket listener
|
Ada
|
apache-2.0
|
stcarrez/mat,stcarrez/mat,stcarrez/mat
|
c20772a91d8d8341aa92ab534271d607bef40f3a
|
src/cbap.ads
|
src/cbap.ads
|
------------------------------------------------------------------------------
-- EMAIL: <[email protected]> --
-- License: ISC License (see COPYING file) --
-- --
-- Copyright © 2015 darkestkhan --
------------------------------------------------------------------------------
-- Permission to use, copy, modify, and/or 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.Containers.Indefinite_Vectors;
------------------------------------------------------------------------------
-- Small and simple callback based library for processing program arguments --
------------------------------------------------------------------------------
---------------------------------------------------------------------------
-- U S A G E --
---------------------------------------------------------------------------
-- First register all callbacks you are interested in, then call
-- Process_Arguments.
--
-- NOTE: "=" sign can't be part of argument name for registered callback.
--
-- Only one callback can be registered per argument, otherwise
-- Constraint_Error is propagated.
---------------------------------------------------------------------------
---------------------------------------------------------------------------
-- Leading single hyphen and double hyphen are stripped (if present) when
-- processing arguments that are placed before first "--" argument,
-- so ie. "--help", "-help" and "help" are functionally
-- equivalent, treated as if "help" was actually passed in all 3 cases.
-- (you should register callback just for "help", if you register it for
-- "--help" then actually passed argument would have to be "----help" in order
-- for it to trigger said callback)
--
-- In addition if you registered callback as case insensitive, then
-- (using above example) "Help", "HELP", "help" and "HeLp" all would result in
-- call to said callback.
--
-- If Argument_Type is Variable then callback will receive part of argument
-- that is after "=" sign. (ie. "OS=Linux" argument would result in callback
-- receiving only "Linux" as its argument).
--
-- For Variable, case insensitive callbacks simple rule applies:
-- only variable name is case insensitive, with actual value (when passed to
-- program) being unchanged.
--
-- All arguments with no associated callback are added to Unknown_Arguments
-- vector as long as they appear before first "--" argument.
--
-- All arguments after first "--" (standalone double hyphen) are added to
-- Input_Argument vector (this includes another "--"), w/o any kind of
-- hyphen stripping being performed on them.
--
-- NOTE: No care is taken to ensure that all Input_Arguments
-- (or Unknown_Arguments) are unique.
---------------------------------------------------------------------------
package CBAP is
---------------------------------------------------------------------------
-- Yes, I do realize this is actually vector...
package Argument_Lists is new
Ada.Containers.Indefinite_Vectors (Positive, String);
-- List of all arguments for which callbacks where not registered.
Unknown_Arguments : Argument_Lists.Vector := Argument_Lists.Empty_Vector;
-- List of all arguments after first "--" argument.
Input_Arguments : Argument_Lists.Vector := Argument_Lists.Empty_Vector;
-- Argument_Types decides if argument is just a simple value, or a variable
-- with value assigned to it (difference between "--val" and "--var=val")
type Argument_Types is (Value, Variable);
-- Argument is useful mostly for Variable type of arguments.
type Callbacks is not null access procedure (Argument: in String);
---------------------------------------------------------------------------
-- Register callbacks for processing arguments.
-- @Callback : Action to be performed in case appropriate argument is
-- detected.
-- @Called_On : Argument for which callback is to be performed.
-- @Argument_Type : {Value, Variable}. Value is simple argument that needs no
-- additional parsing. Variable is argument of "Arg_Name=Some_Val" form.
-- When callback is triggered, Value is passed to callback as input, in
-- case of Variable it is content of argument after first "=" that is
-- passed to callback.
-- @Case_Sensitive: Whether or not case is significant. When False all forms
-- of argument are treated as if written in lower case.
procedure Register
( Callback : in Callbacks;
Called_On : in String;
Argument_Type : in Argument_Types := Value;
Case_Sensitive: in Boolean := True
);
-- Raised if Called_On contains "=".
Incorrect_Called_On: exception;
---------------------------------------------------------------------------
-- Parse arguments supplied to program, calling callbacks when argument with
-- associated callback is detected.
-- NOTE: Process_Arguments will call callbacks however many times argument
-- with associated callback is called. So if you have callback for "help",
-- then ./program help help help
-- will result in 3 calls to said callback.
procedure Process_Arguments;
---------------------------------------------------------------------------
end CBAP;
|
------------------------------------------------------------------------------
-- EMAIL: <[email protected]> --
-- License: ISC License (see COPYING file) --
-- --
-- Copyright © 2015 darkestkhan --
------------------------------------------------------------------------------
-- Permission to use, copy, modify, and/or 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.Containers.Indefinite_Vectors;
------------------------------------------------------------------------------
-- Small and simple callback based library for processing program arguments --
------------------------------------------------------------------------------
---------------------------------------------------------------------------
-- U S A G E --
---------------------------------------------------------------------------
-- First register all callbacks you are interested in, then call
-- Process_Arguments.
--
-- NOTE: "=" sign can't be part of argument name for registered callback.
--
-- Only one callback can be registered per argument, otherwise
-- Constraint_Error is propagated.
---------------------------------------------------------------------------
---------------------------------------------------------------------------
-- Leading single hyphen and double hyphen are stripped (if present) when
-- processing arguments that are placed before first "--" argument,
-- so ie. "--help", "-help" and "help" are functionally
-- equivalent, treated as if "help" was actually passed in all 3 cases.
-- (you should register callback just for "help", if you register it for
-- "--help" then actually passed argument would have to be "----help" in order
-- for it to trigger said callback)
--
-- In addition if you registered callback as case insensitive, then
-- (using above example) "Help", "HELP", "help" and "HeLp" all would result in
-- call to said callback.
--
-- If Argument_Type is Variable then callback will receive part of argument
-- that is after "=" sign. (ie. "OS=Linux" argument would result in callback
-- receiving only "Linux" as its argument).
--
-- For Variable, case insensitive callbacks simple rule applies:
-- only variable name is case insensitive, with actual value (when passed to
-- program) being unchanged.
--
-- All arguments with no associated callback are added to Unknown_Arguments
-- vector as long as they appear before first "--" argument.
--
-- All arguments after first "--" (standalone double hyphen) are added to
-- Input_Argument vector (this includes another "--"), w/o any kind of
-- hyphen stripping being performed on them.
--
-- NOTE: No care is taken to ensure that all Input_Arguments
-- (or Unknown_Arguments) are unique.
---------------------------------------------------------------------------
package CBAP is
---------------------------------------------------------------------------
-- Yes, I do realize this is actually vector...
package Argument_Lists is new
Ada.Containers.Indefinite_Vectors (Positive, String);
-- List of all arguments (before first "--" argument) for which callbacks
-- where not registered.
Unknown_Arguments : Argument_Lists.Vector := Argument_Lists.Empty_Vector;
-- List of all arguments after first "--" argument.
Input_Arguments : Argument_Lists.Vector := Argument_Lists.Empty_Vector;
-- Argument_Types decides if argument is just a simple value, or a variable
-- with value assigned to it (difference between "--val" and "--var=val")
type Argument_Types is (Value, Variable);
-- Argument is useful mostly for Variable type of arguments.
type Callbacks is not null access procedure (Argument: in String);
---------------------------------------------------------------------------
-- Register callbacks for processing arguments.
-- @Callback : Action to be performed in case appropriate argument is
-- detected.
-- @Called_On : Argument for which callback is to be performed.
-- @Argument_Type : {Value, Variable}. Value is simple argument that needs no
-- additional parsing. Variable is argument of "Arg_Name=Some_Val" form.
-- When callback is triggered, Value is passed to callback as input, in
-- case of Variable it is content of argument after first "=" that is
-- passed to callback.
-- @Case_Sensitive: Whether or not case is significant. When False all forms
-- of argument are treated as if written in lower case.
procedure Register
( Callback : in Callbacks;
Called_On : in String;
Argument_Type : in Argument_Types := Value;
Case_Sensitive: in Boolean := True
);
-- Raised if Called_On contains "=".
Incorrect_Called_On: exception;
---------------------------------------------------------------------------
-- Parse arguments supplied to program, calling callbacks when argument with
-- associated callback is detected.
-- NOTE: Process_Arguments will call callbacks however many times argument
-- with associated callback is called. So if you have callback for "help",
-- then ./program help help help
-- will result in 3 calls to said callback.
procedure Process_Arguments;
---------------------------------------------------------------------------
end CBAP;
|
Update comment.
|
Update comment.
Signed-off-by: darkestkhan <[email protected]>
|
Ada
|
isc
|
darkestkhan/cbap
|
a43baed9e4f38580083d5bfd5679c698392f79ea
|
src/gen-artifacts-distribs.ads
|
src/gen-artifacts-distribs.ads
|
-----------------------------------------------------------------------
-- gen-artifacts-distribs -- Artifact for distributions
-- Copyright (C) 2012, 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Ada.Containers.Vectors;
with Ada.Containers.Indefinite_Vectors;
with Ada.Containers.Indefinite_Ordered_Maps;
with GNAT.Regpat;
with DOM.Core;
with Gen.Model.Packages;
with Util.Log;
-- The <b>Gen.Artifacts.Distribs</b> package is an artifact for the generation of
-- application distributions.
--
-- 1/ The package.xml file contains a set of rules which describe how to build the distribution.
-- This file is read and distribution rules are collected in the <b>Rules</b> artifact.
--
-- 2/ The list of source paths to scan is obtained by looking at the GNAT project files
-- and looking at components which have a <b>dynamo.xml</b> configuration file.
--
-- 3/ The source paths are then scanned and a complete tree of source files is created
-- in the <b>Trees</b> artifact member.
--
-- 4/ The source paths are matched against the distribution rules and each distribution rule
-- is filled with the source files that they match.
--
-- 5/ The distribution rules are executed in the order defined in the <b>package.xml</b> file.
-- Each distribution rule can have its own way to make the distribution for the set of
-- files that matched the rule definition. A distribution rule can copy the file, another
-- can concatenate the source files, another can do some transformation on the source files
-- and prepare it for the distribution.
--
package Gen.Artifacts.Distribs is
-- ------------------------------
-- Distribution artifact
-- ------------------------------
type Artifact is new Gen.Artifacts.Artifact with private;
-- After the configuration file is read, processes the node whose root
-- is passed in <b>Node</b> and initializes the <b>Model</b> with the information.
overriding
procedure Initialize (Handler : in out Artifact;
Path : in String;
Node : in DOM.Core.Node;
Model : in out Gen.Model.Packages.Model_Definition'Class;
Context : in out Generator'Class);
-- Prepare the model after all the configuration files have been read and before
-- actually invoking the generation.
overriding
procedure Prepare (Handler : in out Artifact;
Model : in out Gen.Model.Packages.Model_Definition'Class;
Context : in out Generator'Class);
private
type Directory_List;
type Directory_List_Access is access all Directory_List;
-- A <b>File_Record</b> refers to a source file that must be processed by a distribution
-- rule. It is linked to the directory which contains it through the <b>Dir</b> member.
-- The <b>Name</b> refers to the file name part.
type File_Record (Length : Natural) is record
Dir : Directory_List_Access;
Name : String (1 .. Length);
end record;
package File_Record_Vectors is
new Ada.Containers.Indefinite_Vectors (Index_Type => Positive,
Element_Type => File_Record);
subtype File_Vector is File_Record_Vectors.Vector;
subtype File_Cursor is File_Record_Vectors.Cursor;
-- Get the first source path from the list.
function Get_Source_Path (From : in File_Vector;
Use_First_File : in Boolean := False) return String;
-- The file tree represents the target distribution tree that must be built.
-- Each key represent a target file and it is associated with a <b>File_Vector</b> which
-- represents the list of source files that must be used to build the target.
package File_Tree is
new Ada.Containers.Indefinite_Ordered_Maps (Key_Type => String,
Element_Type => File_Vector,
"<" => "<",
"=" => File_Record_Vectors."=");
package Directory_List_Vector is
new Ada.Containers.Vectors (Index_Type => Positive,
Element_Type => Directory_List_Access);
-- The <b>Directory_List<b> describes the content of a source directory.
type Directory_List (Length : Positive;
Path_Length : Natural)
is record
Files : File_Record_Vectors.Vector;
Directories : Directory_List_Vector.Vector;
Rel_Pos : Positive := 1;
Name : String (1 .. Length);
Path : String (1 .. Path_Length);
end record;
-- Get the relative path of the directory.
function Get_Relative_Path (Dir : in Directory_List) return String;
-- Strip the base part of the path
function Get_Strip_Path (Base : in String;
Path : in String) return String;
-- Build a regular expression pattern from a pattern string.
function Make_Regexp (Pattern : in String) return String;
-- Build a regular expression pattern from a pattern string.
function Make_Regexp (Pattern : in String) return GNAT.Regpat.Pattern_Matcher;
-- Scan the directory whose root path is <b>Path</b> and with the relative path
-- <b>Rel_Path</b> and build in <b>Dir</b> the list of files and directories.
procedure Scan (Path : in String;
Rel_Path : in String;
Dir : in Directory_List_Access);
type Match_Rule is record
Base_Dir : Ada.Strings.Unbounded.Unbounded_String;
Match : Ada.Strings.Unbounded.Unbounded_String;
end record;
package Match_Rule_Vector is
new Ada.Containers.Vectors (Index_Type => Positive,
Element_Type => Match_Rule);
-- ------------------------------
-- Distribution rule
-- ------------------------------
-- The <b>Distrib_Rule</b> represents a distribution rule that must be executed on
-- a given file or set of files.
type Distrib_Rule is abstract tagged record
Dir : Ada.Strings.Unbounded.Unbounded_String;
Matches : Match_Rule_Vector.Vector;
Files : File_Tree.Map;
Level : Util.Log.Level_Type := Util.Log.DEBUG_LEVEL;
end record;
type Distrib_Rule_Access is access all Distrib_Rule'Class;
-- Get a name to qualify the installation rule (used for logs).
function Get_Install_Name (Rule : in Distrib_Rule) return String is abstract;
-- Install the file <b>File</b> according to the distribution rule.
procedure Install (Rule : in Distrib_Rule;
Target : in String;
File : in File_Vector;
Context : in out Generator'Class) is abstract;
-- Scan the directory tree whose root is defined by <b>Dir</b> and find the files
-- that match the current rule.
procedure Scan (Rule : in out Distrib_Rule;
Dir : in Directory_List);
procedure Scan (Rule : in out Distrib_Rule;
Dir : in Directory_List;
Base_Dir : in String;
Pattern : in String);
procedure Execute (Rule : in out Distrib_Rule;
Path : in String;
Context : in out Generator'Class);
-- Get the target path associate with the given source file for the distribution rule.
function Get_Target_Path (Rule : in Distrib_Rule;
Base : in String;
File : in File_Record) return String;
-- Get the source path of the file.
function Get_Source_Path (Rule : in Distrib_Rule;
File : in File_Record) return String;
-- Add the file to be processed by the distribution rule. The file has a relative
-- path represented by <b>Path</b>. The path is relative from the base directory
-- specified in <b>Base_Dir</b>.
procedure Add_Source_File (Rule : in out Distrib_Rule;
Path : in String;
File : in File_Record);
-- Create a distribution rule identified by <b>Kind</b>.
-- The distribution rule is configured according to the DOM tree whose node is <b>Node</b>.
function Create_Rule (Kind : in String;
Node : in DOM.Core.Node) return Distrib_Rule_Access;
-- A list of rules that define how to build the distribution.
package Distrib_Rule_Vectors is
new Ada.Containers.Vectors (Index_Type => Positive,
Element_Type => Distrib_Rule_Access);
type Artifact is new Gen.Artifacts.Artifact with record
Rules : Distrib_Rule_Vectors.Vector;
Trees : Directory_List_Vector.Vector;
end record;
end Gen.Artifacts.Distribs;
|
-----------------------------------------------------------------------
-- gen-artifacts-distribs -- Artifact for distributions
-- Copyright (C) 2012, 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Ada.Containers.Vectors;
with Ada.Containers.Indefinite_Vectors;
with Ada.Containers.Indefinite_Ordered_Maps;
with GNAT.Regpat;
with DOM.Core;
with Gen.Model.Packages;
with Util.Log;
-- The <b>Gen.Artifacts.Distribs</b> package is an artifact for the generation of
-- application distributions.
--
-- 1/ The package.xml file contains a set of rules which describe how to build the distribution.
-- This file is read and distribution rules are collected in the <b>Rules</b> artifact.
--
-- 2/ The list of source paths to scan is obtained by looking at the GNAT project files
-- and looking at components which have a <b>dynamo.xml</b> configuration file.
--
-- 3/ The source paths are then scanned and a complete tree of source files is created
-- in the <b>Trees</b> artifact member.
--
-- 4/ The source paths are matched against the distribution rules and each distribution rule
-- is filled with the source files that they match.
--
-- 5/ The distribution rules are executed in the order defined in the <b>package.xml</b> file.
-- Each distribution rule can have its own way to make the distribution for the set of
-- files that matched the rule definition. A distribution rule can copy the file, another
-- can concatenate the source files, another can do some transformation on the source files
-- and prepare it for the distribution.
--
package Gen.Artifacts.Distribs is
-- ------------------------------
-- Distribution artifact
-- ------------------------------
type Artifact is new Gen.Artifacts.Artifact with private;
-- After the configuration file is read, processes the node whose root
-- is passed in <b>Node</b> and initializes the <b>Model</b> with the information.
overriding
procedure Initialize (Handler : in out Artifact;
Path : in String;
Node : in DOM.Core.Node;
Model : in out Gen.Model.Packages.Model_Definition'Class;
Context : in out Generator'Class);
-- Prepare the model after all the configuration files have been read and before
-- actually invoking the generation.
overriding
procedure Prepare (Handler : in out Artifact;
Model : in out Gen.Model.Packages.Model_Definition'Class;
Context : in out Generator'Class);
private
type Directory_List;
type Directory_List_Access is access all Directory_List;
-- A <b>File_Record</b> refers to a source file that must be processed by a distribution
-- rule. It is linked to the directory which contains it through the <b>Dir</b> member.
-- The <b>Name</b> refers to the file name part.
type File_Record (Length : Natural) is record
Dir : Directory_List_Access;
Name : String (1 .. Length);
end record;
package File_Record_Vectors is
new Ada.Containers.Indefinite_Vectors (Index_Type => Positive,
Element_Type => File_Record);
subtype File_Vector is File_Record_Vectors.Vector;
subtype File_Cursor is File_Record_Vectors.Cursor;
-- Get the first source path from the list.
function Get_Source_Path (From : in File_Vector;
Use_First_File : in Boolean := False) return String;
-- The file tree represents the target distribution tree that must be built.
-- Each key represent a target file and it is associated with a <b>File_Vector</b> which
-- represents the list of source files that must be used to build the target.
package File_Tree is
new Ada.Containers.Indefinite_Ordered_Maps (Key_Type => String,
Element_Type => File_Vector,
"<" => "<",
"=" => File_Record_Vectors."=");
package Directory_List_Vector is
new Ada.Containers.Vectors (Index_Type => Positive,
Element_Type => Directory_List_Access);
-- The <b>Directory_List<b> describes the content of a source directory.
type Directory_List (Length : Positive;
Path_Length : Natural)
is record
Files : File_Record_Vectors.Vector;
Directories : Directory_List_Vector.Vector;
Rel_Pos : Positive := 1;
Name : String (1 .. Length);
Path : String (1 .. Path_Length);
end record;
-- Get the relative path of the directory.
function Get_Relative_Path (Dir : in Directory_List) return String;
-- Strip the base part of the path
function Get_Strip_Path (Base : in String;
Path : in String) return String;
-- Build a regular expression pattern from a pattern string.
function Make_Regexp (Pattern : in String) return String;
-- Build a regular expression pattern from a pattern string.
function Make_Regexp (Pattern : in String) return GNAT.Regpat.Pattern_Matcher;
-- Scan the directory whose root path is <b>Path</b> and with the relative path
-- <b>Rel_Path</b> and build in <b>Dir</b> the list of files and directories.
procedure Scan (Path : in String;
Rel_Path : in String;
Dir : in Directory_List_Access);
type Match_Rule is record
Base_Dir : Ada.Strings.Unbounded.Unbounded_String;
Match : Ada.Strings.Unbounded.Unbounded_String;
end record;
package Match_Rule_Vector is
new Ada.Containers.Vectors (Index_Type => Positive,
Element_Type => Match_Rule);
-- ------------------------------
-- Distribution rule
-- ------------------------------
-- The <b>Distrib_Rule</b> represents a distribution rule that must be executed on
-- a given file or set of files.
type Distrib_Rule is abstract tagged record
Dir : Ada.Strings.Unbounded.Unbounded_String;
Matches : Match_Rule_Vector.Vector;
Excludes : Match_Rule_Vector.Vector;
Files : File_Tree.Map;
Level : Util.Log.Level_Type := Util.Log.DEBUG_LEVEL;
end record;
type Distrib_Rule_Access is access all Distrib_Rule'Class;
-- Get a name to qualify the installation rule (used for logs).
function Get_Install_Name (Rule : in Distrib_Rule) return String is abstract;
-- Install the file <b>File</b> according to the distribution rule.
procedure Install (Rule : in Distrib_Rule;
Target : in String;
File : in File_Vector;
Context : in out Generator'Class) is abstract;
-- Scan the directory tree whose root is defined by <b>Dir</b> and find the files
-- that match the current rule.
procedure Scan (Rule : in out Distrib_Rule;
Dir : in Directory_List);
procedure Scan (Rule : in out Distrib_Rule;
Dir : in Directory_List;
Base_Dir : in String;
Pattern : in String;
Exclude : in Boolean);
procedure Execute (Rule : in out Distrib_Rule;
Path : in String;
Context : in out Generator'Class);
-- Get the target path associate with the given source file for the distribution rule.
function Get_Target_Path (Rule : in Distrib_Rule;
Base : in String;
File : in File_Record) return String;
-- Get the source path of the file.
function Get_Source_Path (Rule : in Distrib_Rule;
File : in File_Record) return String;
-- Add the file to be processed by the distribution rule. The file has a relative
-- path represented by <b>Path</b>. The path is relative from the base directory
-- specified in <b>Base_Dir</b>.
procedure Add_Source_File (Rule : in out Distrib_Rule;
Path : in String;
File : in File_Record);
-- Remove the file to be processed by the distribution rule. This is the opposite of
-- <tt>Add_Source_File</tt> and used for the <exclude name="xxx"/> rules.
procedure Remove_Source_File (Rule : in out Distrib_Rule;
Path : in String;
File : in File_Record);
-- Create a distribution rule identified by <b>Kind</b>.
-- The distribution rule is configured according to the DOM tree whose node is <b>Node</b>.
function Create_Rule (Kind : in String;
Node : in DOM.Core.Node) return Distrib_Rule_Access;
-- A list of rules that define how to build the distribution.
package Distrib_Rule_Vectors is
new Ada.Containers.Vectors (Index_Type => Positive,
Element_Type => Distrib_Rule_Access);
type Artifact is new Gen.Artifacts.Artifact with record
Rules : Distrib_Rule_Vectors.Vector;
Trees : Directory_List_Vector.Vector;
end record;
end Gen.Artifacts.Distribs;
|
Add Excludes patterns to the rule definition Declare Remove_Source_File procedure to exclude some files
|
Add Excludes patterns to the rule definition
Declare Remove_Source_File procedure to exclude some files
|
Ada
|
apache-2.0
|
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
|
b45e7b02c0f3845f1124430c52737f8a53ea3d4f
|
src/gen-commands-templates.ads
|
src/gen-commands-templates.ads
|
-----------------------------------------------------------------------
-- gen-commands-templates -- Template based command
-- Copyright (C) 2011, 2013, 2014 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Containers.Vectors;
with Util.Strings.Sets;
with Util.Strings.Vectors;
package Gen.Commands.Templates is
-- ------------------------------
-- Template Generic Command
-- ------------------------------
-- This command adds a XHTML page to the web application.
type Command is new Gen.Commands.Command with private;
type Command_Access is access all Command'Class;
-- Execute the command with the arguments.
procedure Execute (Cmd : in Command;
Generator : in out Gen.Generator.Handler);
-- Write the help associated with the command.
procedure Help (Cmd : in Command;
Generator : in out Gen.Generator.Handler);
-- Read the template commands defined in dynamo configuration directory.
procedure Read_Commands (Generator : in out Gen.Generator.Handler);
private
type Param is record
Name : Ada.Strings.Unbounded.Unbounded_String;
Argument : Ada.Strings.Unbounded.Unbounded_String;
Value : Ada.Strings.Unbounded.Unbounded_String;
Is_Optional : Boolean := False;
end record;
package Param_Vectors is
new Ada.Containers.Vectors (Index_Type => Positive,
Element_Type => Param);
type Patch is record
Template : Ada.Strings.Unbounded.Unbounded_String;
After : Util.Strings.Vectors.Vector;
Missing : Util.Strings.Vectors.Vector;
Before : Ada.Strings.Unbounded.Unbounded_String;
Optional : Boolean := False;
end record;
package Patch_Vectors is
new Ada.Containers.Vectors (Index_Type => Positive,
Element_Type => Patch);
type Command is new Gen.Commands.Command with record
Name : Ada.Strings.Unbounded.Unbounded_String;
Title : Ada.Strings.Unbounded.Unbounded_String;
Usage : Ada.Strings.Unbounded.Unbounded_String;
Help_Msg : Ada.Strings.Unbounded.Unbounded_String;
Base_Dir : Ada.Strings.Unbounded.Unbounded_String;
Templates : Util.Strings.Sets.Set;
Patches : Patch_Vectors.Vector;
Params : Param_Vectors.Vector;
end record;
end Gen.Commands.Templates;
|
-----------------------------------------------------------------------
-- gen-commands-templates -- Template based command
-- Copyright (C) 2011, 2013, 2014 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Containers.Vectors;
with Util.Strings.Sets;
with Util.Strings.Vectors;
package Gen.Commands.Templates is
-- ------------------------------
-- Template Generic Command
-- ------------------------------
-- This command adds a XHTML page to the web application.
type Command is new Gen.Commands.Command with private;
type Command_Access is access all Command'Class;
-- Execute the command with the arguments.
procedure Execute (Cmd : in Command;
Generator : in out Gen.Generator.Handler);
-- Write the help associated with the command.
procedure Help (Cmd : in Command;
Generator : in out Gen.Generator.Handler);
-- Read the template commands defined in dynamo configuration directory.
procedure Read_Commands (Generator : in out Gen.Generator.Handler);
private
type Param is record
Name : Ada.Strings.Unbounded.Unbounded_String;
Argument : Ada.Strings.Unbounded.Unbounded_String;
Value : Ada.Strings.Unbounded.Unbounded_String;
Is_Optional : Boolean := False;
end record;
package Param_Vectors is
new Ada.Containers.Vectors (Index_Type => Positive,
Element_Type => Param);
type Patch is record
Template : Ada.Strings.Unbounded.Unbounded_String;
After : Util.Strings.Vectors.Vector;
Missing : Util.Strings.Vectors.Vector;
Before : Ada.Strings.Unbounded.Unbounded_String;
Title : Ada.Strings.Unbounded.Unbounded_String;
Optional : Boolean := False;
end record;
package Patch_Vectors is
new Ada.Containers.Vectors (Index_Type => Positive,
Element_Type => Patch);
type Command is new Gen.Commands.Command with record
Name : Ada.Strings.Unbounded.Unbounded_String;
Title : Ada.Strings.Unbounded.Unbounded_String;
Usage : Ada.Strings.Unbounded.Unbounded_String;
Help_Msg : Ada.Strings.Unbounded.Unbounded_String;
Base_Dir : Ada.Strings.Unbounded.Unbounded_String;
Templates : Util.Strings.Sets.Set;
Patches : Patch_Vectors.Vector;
Params : Param_Vectors.Vector;
end record;
end Gen.Commands.Templates;
|
Add a title for each patch so that we can report some clever error/info message
|
Add a title for each patch so that we can report some clever error/info message
|
Ada
|
apache-2.0
|
Letractively/ada-gen,Letractively/ada-gen,Letractively/ada-gen,Letractively/ada-gen
|
5db9cb9d0addff8222cad99baec279a7c690b5cf
|
matp/src/frames/mat-frames-targets.adb
|
matp/src/frames/mat-frames-targets.adb
|
-----------------------------------------------------------------------
-- mat-frames-targets - Representation of stack frames
-- Copyright (C) 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
package body MAT.Frames.Targets is
-- ------------------------------
-- 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 Insert (Frame : in out Target_Frames;
Pc : in Frame_Table;
Result : out Frame_Type) is
begin
Frame.Frames.Insert (Pc, Result);
end Insert;
protected body Frames_Type is
-- ------------------------------
-- 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 Insert (Pc : in Frame_Table;
Result : out Frame_Type) is
begin
MAT.Frames.Insert (Root, Pc, Result);
end Insert;
-- ------------------------------
-- Clear and destroy all the frame instances.
-- ------------------------------
procedure Clear is
begin
Destroy (Root);
end Clear;
end Frames_Type;
-- ------------------------------
-- Release all the stack frames.
-- ------------------------------
overriding
procedure Finalize (Frames : in out Target_Frames) is
begin
Frames.Frames.Clear;
end Finalize;
end MAT.Frames.Targets;
|
-----------------------------------------------------------------------
-- mat-frames-targets - Representation of stack frames
-- Copyright (C) 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
package body MAT.Frames.Targets is
-- ------------------------------
-- 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 Insert (Frame : in out Target_Frames;
Pc : in Frame_Table;
Result : out Frame_Type) is
begin
Frame.Frames.Insert (Pc, Result);
end Insert;
-- ------------------------------
-- Get the number of different stack frames which have been registered.
-- ------------------------------
function Get_Frame_Count (Frame : in Target_Frames) return Natural is
begin
return Frame.Frames.Get_Frame_Count;
end Get_Frame_Count;
protected body Frames_Type is
-- ------------------------------
-- 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 Insert (Pc : in Frame_Table;
Result : out Frame_Type) is
begin
MAT.Frames.Insert (Root, Pc, Result);
end Insert;
-- ------------------------------
-- Clear and destroy all the frame instances.
-- ------------------------------
procedure Clear is
begin
Destroy (Root);
end Clear;
end Frames_Type;
-- ------------------------------
-- Release all the stack frames.
-- ------------------------------
overriding
procedure Finalize (Frames : in out Target_Frames) is
begin
Frames.Frames.Clear;
end Finalize;
end MAT.Frames.Targets;
|
Implement the Get_Frame_Count function
|
Implement the Get_Frame_Count function
|
Ada
|
apache-2.0
|
stcarrez/mat,stcarrez/mat,stcarrez/mat
|
0ae360f821617433d5fbca364033112f1978826c
|
awa/plugins/awa-storages/src/awa-storages-services.ads
|
awa/plugins/awa-storages/src/awa-storages-services.ads
|
-----------------------------------------------------------------------
-- awa-storages-services -- Storage service
-- Copyright (C) 2012, 2016 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Calendar;
with Ada.Strings.Unbounded;
with Util.Concurrent.Counters;
with Security.Permissions;
with ADO;
with ASF.Parts;
with AWA.Modules;
with AWA.Modules.Lifecycles;
with AWA.Storages.Models;
with AWA.Storages.Stores;
with AWA.Storages.Stores.Databases;
-- == Storage Service ==
-- The <tt>Storage_Service</tt> provides the operations to access and use the persisent storage.
-- It controls the permissions that grant access to the service for users.
--
-- Other modules can be notified of storage changes by registering a listener
-- on the storage module.
--
-- @include awa-storages-stores.ads
package AWA.Storages.Services is
package ACL_Create_Storage is new Security.Permissions.Definition ("storage-create");
package ACL_Delete_Storage is new Security.Permissions.Definition ("storage-delete");
package ACL_Create_Folder is new Security.Permissions.Definition ("folder-create");
type Read_Mode is (READ, WRITE);
type Expire_Type is (ONE_HOUR, ONE_DAY, TWO_DAYS, ONE_WEEK, ONE_YEAR, NEVER);
package Storage_Lifecycle is
new AWA.Modules.Lifecycles (Element_Type => AWA.Storages.Models.Storage_Ref'Class);
subtype Listener is Storage_Lifecycle.Listener;
-- ------------------------------
-- Storage Service
-- ------------------------------
-- The <b>Storage_Service</b> defines a set of operations to store and retrieve
-- a data object from the persistent storage. The data object is treated as a raw
-- byte stream. The persistent storage can be implemented by a database, a file
-- system or a remote service such as Amazon AWS.
type Storage_Service is new AWA.Modules.Module_Manager with private;
type Storage_Service_Access is access all Storage_Service'Class;
-- Initializes the storage service.
overriding
procedure Initialize (Service : in out Storage_Service;
Module : in AWA.Modules.Module'Class);
-- Get the persistent store that manages the data store identified by <tt>Kind</tt>.
function Get_Store (Service : in Storage_Service;
Kind : in AWA.Storages.Models.Storage_Type)
return AWA.Storages.Stores.Store_Access;
-- Create or save the folder.
procedure Save_Folder (Service : in Storage_Service;
Folder : in out AWA.Storages.Models.Storage_Folder_Ref'Class);
-- Load the folder instance identified by the given identifier.
procedure Load_Folder (Service : in Storage_Service;
Folder : in out AWA.Storages.Models.Storage_Folder_Ref'Class;
Id : in ADO.Identifier);
-- Save the data object contained in the <b>Data</b> part element into the
-- target storage represented by <b>Into</b>.
procedure Save (Service : in Storage_Service;
Into : in out AWA.Storages.Models.Storage_Ref'Class;
Data : in ASF.Parts.Part'Class;
Storage : in AWA.Storages.Models.Storage_Type);
-- Save the file described <b>File</b> in the storage
-- object represented by <b>Into</b> and managed by the storage service.
procedure Save (Service : in Storage_Service;
Into : in out AWA.Storages.Models.Storage_Ref'Class;
File : in AWA.Storages.Storage_File;
Storage : in AWA.Storages.Models.Storage_Type);
-- Save the file pointed to by the <b>Path</b> string in the storage
-- object represented by <b>Into</b> and managed by the storage service.
procedure Save (Service : in Storage_Service;
Into : in out AWA.Storages.Models.Storage_Ref'Class;
Path : in String;
Storage : in AWA.Storages.Models.Storage_Type);
-- Load the storage instance identified by the given identifier.
procedure Load_Storage (Service : in Storage_Service;
Storage : in out AWA.Storages.Models.Storage_Ref'Class;
Id : in ADO.Identifier);
-- Load the storage instance stored in a folder and identified by a name.
procedure Load_Storage (Service : in Storage_Service;
Storage : in out AWA.Storages.Models.Storage_Ref'Class;
Folder : in ADO.Identifier;
Name : in String;
Found : out Boolean);
-- Load the storage content identified by <b>From</b> into the blob descriptor <b>Into</b>.
-- Raises the <b>NOT_FOUND</b> exception if there is no such storage.
procedure Load (Service : in Storage_Service;
From : in ADO.Identifier;
Name : out Ada.Strings.Unbounded.Unbounded_String;
Mime : out Ada.Strings.Unbounded.Unbounded_String;
Date : out Ada.Calendar.Time;
Into : out ADO.Blob_Ref);
-- Load the storage content into a file. If the data is not stored in a file, a temporary
-- file is created with the data content fetched from the store (ex: the database).
-- The `Mode` parameter indicates whether the file will be read or written.
-- The `Expire` parameter allows to control the expiration of the temporary file.
procedure Get_Local_File (Service : in Storage_Service;
From : in ADO.Identifier;
Mode : in Read_Mode := READ;
Into : in out Storage_File);
procedure Create_Local_File (Service : in out Storage_Service;
Into : in out AWA.Storages.Storage_File);
-- Deletes the storage instance.
procedure Delete (Service : in Storage_Service;
Storage : in out AWA.Storages.Models.Storage_Ref'Class);
-- Deletes the storage instance.
procedure Delete (Service : in Storage_Service;
Storage : in ADO.Identifier);
-- Publish or not the storage instance.
procedure Publish (Service : in Storage_Service;
Id : in ADO.Identifier;
State : in Boolean;
File : in out AWA.Storages.Models.Storage_Ref'Class);
private
type Store_Access_Array is
array (AWA.Storages.Models.Storage_Type) of AWA.Storages.Stores.Store_Access;
type Storage_Service is new AWA.Modules.Module_Manager with record
Stores : Store_Access_Array;
Database_Store : aliased AWA.Storages.Stores.Databases.Database_Store;
Temp_Id : Util.Concurrent.Counters.Counter;
end record;
end AWA.Storages.Services;
|
-----------------------------------------------------------------------
-- awa-storages-services -- Storage service
-- Copyright (C) 2012, 2016, 2019 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Calendar;
with Ada.Strings.Unbounded;
with Util.Concurrent.Counters;
with Security.Permissions;
with ADO;
with ASF.Parts;
with AWA.Modules;
with AWA.Modules.Lifecycles;
with AWA.Storages.Models;
with AWA.Storages.Stores;
with AWA.Storages.Stores.Databases;
-- == Storage Service ==
-- The <tt>Storage_Service</tt> provides the operations to access and use the persisent storage.
-- It controls the permissions that grant access to the service for users.
--
-- Other modules can be notified of storage changes by registering a listener
-- on the storage module.
--
-- @include awa-storages-stores.ads
package AWA.Storages.Services is
package ACL_Create_Storage is new Security.Permissions.Definition ("storage-create");
package ACL_Delete_Storage is new Security.Permissions.Definition ("storage-delete");
package ACL_Create_Folder is new Security.Permissions.Definition ("folder-create");
type Read_Mode is (READ, WRITE);
type Expire_Type is (ONE_HOUR, ONE_DAY, TWO_DAYS, ONE_WEEK, ONE_YEAR, NEVER);
package Storage_Lifecycle is
new AWA.Modules.Lifecycles (Element_Type => AWA.Storages.Models.Storage_Ref'Class);
subtype Listener is Storage_Lifecycle.Listener;
-- ------------------------------
-- Storage Service
-- ------------------------------
-- The <b>Storage_Service</b> defines a set of operations to store and retrieve
-- a data object from the persistent storage. The data object is treated as a raw
-- byte stream. The persistent storage can be implemented by a database, a file
-- system or a remote service such as Amazon AWS.
type Storage_Service is new AWA.Modules.Module_Manager with private;
type Storage_Service_Access is access all Storage_Service'Class;
-- Initializes the storage service.
overriding
procedure Initialize (Service : in out Storage_Service;
Module : in AWA.Modules.Module'Class);
-- Get the persistent store that manages the data store identified by <tt>Kind</tt>.
function Get_Store (Service : in Storage_Service;
Kind : in AWA.Storages.Models.Storage_Type)
return AWA.Storages.Stores.Store_Access;
-- Create or save the folder.
procedure Save_Folder (Service : in Storage_Service;
Folder : in out AWA.Storages.Models.Storage_Folder_Ref'Class);
-- Load the folder instance identified by the given identifier.
procedure Load_Folder (Service : in Storage_Service;
Folder : in out AWA.Storages.Models.Storage_Folder_Ref'Class;
Id : in ADO.Identifier);
-- Save the data object contained in the <b>Data</b> part element into the
-- target storage represented by <b>Into</b>.
procedure Save (Service : in Storage_Service;
Into : in out AWA.Storages.Models.Storage_Ref'Class;
Data : in ASF.Parts.Part'Class;
Storage : in AWA.Storages.Models.Storage_Type);
-- Save the file described <b>File</b> in the storage
-- object represented by <b>Into</b> and managed by the storage service.
procedure Save (Service : in Storage_Service;
Into : in out AWA.Storages.Models.Storage_Ref'Class;
File : in AWA.Storages.Storage_File;
Storage : in AWA.Storages.Models.Storage_Type);
-- Save the file pointed to by the <b>Path</b> string in the storage
-- object represented by <b>Into</b> and managed by the storage service.
procedure Save (Service : in Storage_Service;
Into : in out AWA.Storages.Models.Storage_Ref'Class;
Path : in String;
Storage : in AWA.Storages.Models.Storage_Type);
-- Load the storage instance identified by the given identifier.
procedure Load_Storage (Service : in Storage_Service;
Storage : in out AWA.Storages.Models.Storage_Ref'Class;
Id : in ADO.Identifier);
-- Load the storage instance stored in a folder and identified by a name.
procedure Load_Storage (Service : in Storage_Service;
Storage : in out AWA.Storages.Models.Storage_Ref'Class;
Folder : in ADO.Identifier;
Name : in String;
Found : out Boolean);
-- Load the storage content identified by <b>From</b> into the blob descriptor <b>Into</b>.
-- Raises the <b>NOT_FOUND</b> exception if there is no such storage.
procedure Load (Service : in Storage_Service;
From : in ADO.Identifier;
Name : out Ada.Strings.Unbounded.Unbounded_String;
Mime : out Ada.Strings.Unbounded.Unbounded_String;
Date : out Ada.Calendar.Time;
Into : out ADO.Blob_Ref);
procedure Load (Service : in Storage_Service;
From : in ADO.Identifier;
Kind : in AWA.Storages.Models.Storage_Type;
Into : out ADO.Blob_Ref);
-- Load the storage content into a file. If the data is not stored in a file, a temporary
-- file is created with the data content fetched from the store (ex: the database).
-- The `Mode` parameter indicates whether the file will be read or written.
-- The `Expire` parameter allows to control the expiration of the temporary file.
procedure Get_Local_File (Service : in Storage_Service;
From : in ADO.Identifier;
Mode : in Read_Mode := READ;
Into : in out Storage_File);
procedure Create_Local_File (Service : in out Storage_Service;
Into : in out AWA.Storages.Storage_File);
-- Deletes the storage instance.
procedure Delete (Service : in Storage_Service;
Storage : in out AWA.Storages.Models.Storage_Ref'Class);
-- Deletes the storage instance.
procedure Delete (Service : in Storage_Service;
Storage : in ADO.Identifier);
-- Publish or not the storage instance.
procedure Publish (Service : in Storage_Service;
Id : in ADO.Identifier;
State : in Boolean;
File : in out AWA.Storages.Models.Storage_Ref'Class);
private
type Store_Access_Array is
array (AWA.Storages.Models.Storage_Type) of AWA.Storages.Stores.Store_Access;
type Storage_Service is new AWA.Modules.Module_Manager with record
Stores : Store_Access_Array;
Database_Store : aliased AWA.Storages.Stores.Databases.Database_Store;
Temp_Id : Util.Concurrent.Counters.Counter;
end record;
end AWA.Storages.Services;
|
Declare the Load procedure
|
Declare the Load procedure
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
3c0fb7bce034ae58c8e2c61df28ae4e6abf23604
|
src/aws/aws-attachments-extend.adb
|
src/aws/aws-attachments-extend.adb
|
-----------------------------------------------------------------------
-- aws-attachments-extend -- ASF extensions for AWS attachments
-- 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;
package body AWS.Attachments.Extend is
use Ada.Strings.Unbounded;
-- ------------------------------
-- Get the length of the data content.
-- ------------------------------
function Get_Length (E : in Element) return Natural is
begin
case E.Kind is
when Data =>
return E.Data.Length;
when others =>
return 0;
end case;
end Get_Length;
-- ------------------------------
-- Get the name of the attachement.
-- ------------------------------
function Get_Name (E : in Element) return String is
begin
case E.Kind is
when Data =>
return To_String (E.Data.Content_Id);
when others =>
return "";
end case;
end Get_Name;
end AWS.Attachments.Extend;
|
-----------------------------------------------------------------------
-- aws-attachments-extend -- ASF extensions for AWS attachments
-- 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.
-----------------------------------------------------------------------
package body AWS.Attachments.Extend is
-- ------------------------------
-- Get the length of the data content.
-- ------------------------------
function Get_Length (E : in Element) return Natural is
begin
case E.Kind is
when Data =>
return E.Data.Length;
when others =>
return 0;
end case;
end Get_Length;
-- ------------------------------
-- Get the name of the attachement.
-- ------------------------------
function Get_Name (E : in Element) return String is
begin
case E.Kind is
when Data =>
return To_String (E.Data.Content_Id);
when others =>
return "";
end case;
end Get_Name;
end AWS.Attachments.Extend;
|
Fix compilation warning
|
Fix compilation warning
|
Ada
|
apache-2.0
|
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
|
1dff369a60b0b779b8070ef36544b24d5f97703d
|
regtests/security-policies-tests.adb
|
regtests/security-policies-tests.adb
|
-----------------------------------------------------------------------
-- Security-policies-tests - Unit tests for Security.Permissions
-- Copyright (C) 2011, 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Tests;
with Util.Files;
with Util.Test_Caller;
with Util.Measures;
with Security.Contexts;
with Security.Policies.Roles;
with Security.Permissions.Tests;
package body Security.Policies.Tests is
use Util.Tests;
package Caller is new Util.Test_Caller (Test, "Security.Policies");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test Security.Permissions.Create_Role",
Test_Create_Role'Access);
Caller.Add_Test (Suite, "Test Security.Permissions.Has_Permission",
Test_Has_Permission'Access);
Caller.Add_Test (Suite, "Test Security.Permissions.Read_Policy (empty)",
Test_Read_Empty_Policy'Access);
Caller.Add_Test (Suite, "Test Security.Policies.Add_Policy",
Test_Get_Role_Policy'Access);
Caller.Add_Test (Suite, "Test Security.Policies.Get_Policy",
Test_Get_Role_Policy'Access);
Caller.Add_Test (Suite, "Test Security.Policies.Roles.Get_Role_Policy",
Test_Get_Role_Policy'Access);
Caller.Add_Test (Suite, "Test Security.Policies.Read_Policy",
Test_Read_Policy'Access);
Caller.Add_Test (Suite, "Test Security.Policies.Roles.Set_Roles",
Test_Set_Roles'Access);
Caller.Add_Test (Suite, "Test Security.Policies.Roles.Set_Roles (invalid)",
Test_Set_Invalid_Roles'Access);
-- These tests are identical but registered under different names
-- for the test documentation.
Caller.Add_Test (Suite, "Test Security.Contexts.Has_Permission",
Test_Role_Policy'Access);
Caller.Add_Test (Suite, "Test Security.Controllers.Roles.Has_Permission",
Test_Role_Policy'Access);
Caller.Add_Test (Suite, "Test Security.Permissions.Role_Policy",
Test_Role_Policy'Access);
end Add_Tests;
-- ------------------------------
-- Get the roles assigned to the user.
-- ------------------------------
function Get_Roles (User : in Test_Principal) return Roles.Role_Map is
begin
return User.Roles;
end Get_Roles;
-- ------------------------------
-- Get the principal name.
-- ------------------------------
function Get_Name (From : in Test_Principal) return String is
begin
return Util.Strings.To_String (From.Name);
end Get_Name;
-- ------------------------------
-- Test Create_Role and Get_Role_Name
-- ------------------------------
procedure Test_Create_Role (T : in out Test) is
use Security.Policies.Roles;
M : Security.Policies.Roles.Role_Policy;
Role : Role_Type;
begin
M.Create_Role (Name => "admin",
Role => Role);
Assert_Equals (T, "admin", M.Get_Role_Name (Role), "Invalid name");
for I in Role + 1 .. Role_Type'Last loop
declare
Name : constant String := "admin-" & Role_Type'Image (I);
Role2 : Role_Type;
begin
Role2 := M.Find_Role ("admin");
T.Assert (Role2 = Role, "Find_Role returned an invalid role");
M.Create_Role (Name => Name,
Role => Role2);
Assert_Equals (T, Name, M.Get_Role_Name (Role2), "Invalid name");
end;
end loop;
end Test_Create_Role;
-- ------------------------------
-- Test Set_Roles
-- ------------------------------
procedure Test_Set_Roles (T : in out Test) is
use Security.Policies.Roles;
M : Security.Policies.Roles.Role_Policy;
Admin : Role_Type;
Manager : Role_Type;
Map : Role_Map := (others => False);
begin
M.Create_Role (Name => "manager",
Role => Manager);
M.Create_Role (Name => "admin",
Role => Admin);
Assert_Equals (T, "admin", M.Get_Role_Name (Admin), "Invalid name");
T.Assert (not Map (Admin), "The admin role must not set in the map");
M.Set_Roles ("admin", Map);
T.Assert (Map (Admin), "The admin role is not set in the map");
T.Assert (not Map (Manager), "The manager role must not be set in the map");
Map := (others => False);
M.Set_Roles ("manager,admin", Map);
T.Assert (Map (Admin), "The admin role is not set in the map");
T.Assert (Map (Manager), "The manager role is not set in the map");
end Test_Set_Roles;
-- ------------------------------
-- Test Set_Roles on an invalid role name
-- ------------------------------
procedure Test_Set_Invalid_Roles (T : in out Test) is
use Security.Policies.Roles;
M : Security.Policies.Roles.Role_Policy;
Map : Role_Map := (others => False);
begin
M.Set_Roles ("manager,admin", Map);
T.Assert (False, "No exception was raised");
exception
when E : Security.Policies.Roles.Invalid_Name =>
null;
end Test_Set_Invalid_Roles;
-- ------------------------------
-- Test Has_Permission
-- ------------------------------
procedure Test_Has_Permission (T : in out Test) is
M : Security.Policies.Policy_Manager (1);
-- Perm : Permissions.Permission_Type;
User : Test_Principal;
begin
-- T.Assert (not M.Has_Permission (User, 1), "User has a non-existing permission");
null;
end Test_Has_Permission;
procedure Configure_Policy (Manager : in out Security.Policies.Policy_Manager;
Name : in String) is
Dir : constant String := "regtests/files/permissions/";
Path : constant String := Util.Tests.Get_Path (Dir);
R : Security.Policies.Roles.Role_Policy_Access := new Roles.Role_Policy;
U : Security.Policies.URLs.URL_Policy_Access := new URLs.URL_Policy;
begin
Manager.Add_Policy (R.all'Access);
Manager.Add_Policy (U.all'Access);
Manager.Read_Policy (Util.Files.Compose (Path, Name));
end Configure_Policy;
-- ------------------------------
-- Test the Get_Policy, Get_Role_Policy and Add_Policy operations.
-- ------------------------------
procedure Test_Get_Role_Policy (T : in out Test) is
use type Roles.Role_Policy_Access;
M : aliased Security.Policies.Policy_Manager (Max_Policies => 2);
P : Security.Policies.Policy_Access;
R : Security.Policies.Roles.Role_Policy_Access;
begin
P := M.Get_Policy (Security.Policies.Roles.NAME);
T.Assert (P = null, "Get_Policy succeeded");
R := Security.Policies.Roles.Get_Role_Policy (M);
T.Assert (R = null, "Get_Role_Policy succeeded");
R := new Roles.Role_Policy;
M.Add_Policy (R.all'Access);
P := M.Get_Policy (Security.Policies.Roles.NAME);
T.Assert (P /= null, "Role policy not found");
T.Assert (P.all in Roles.Role_Policy'Class, "Invalid role policy");
R := Security.Policies.Roles.Get_Role_Policy (M);
T.Assert (R /= null, "Get_Role_Policy should not return null");
end Test_Get_Role_Policy;
-- ------------------------------
-- Test reading an empty policy file
-- ------------------------------
procedure Test_Read_Empty_Policy (T : in out Test) is
M : aliased Security.Policies.Policy_Manager (Max_Policies => 2);
User : aliased Test_Principal;
Context : aliased Security.Contexts.Security_Context;
P : Security.Policies.Policy_Access;
R : Security.Policies.Roles.Role_Policy_Access;
begin
Configure_Policy (M, "empty.xml");
Context.Set_Context (Manager => M'Unchecked_Access,
Principal => User'Unchecked_Access);
R := Security.Policies.Roles.Get_Role_Policy (M);
declare
Admin : Policies.Roles.Role_Type;
begin
Admin := R.Find_Role ("admin");
T.Fail ("'admin' role was returned");
exception
when Security.Policies.Roles.Invalid_Name =>
null;
end;
T.Assert (not Contexts.Has_Permission (Permissions.Tests.P_Admin.Permission),
"Has_Permission (admin) failed for empty policy");
T.Assert (not Contexts.Has_Permission (Permissions.Tests.P_Create.Permission),
"Has_Permission (create) failed for empty policy");
T.Assert (not Contexts.Has_Permission (Permissions.Tests.P_Update.Permission),
"Has_Permission (update) failed for empty policy");
T.Assert (not Contexts.Has_Permission (Permissions.Tests.P_Delete.Permission),
"Has_Permission (delete) failed for empty policy");
end Test_Read_Empty_Policy;
-- ------------------------------
-- Test reading policy files
-- ------------------------------
procedure Test_Read_Policy (T : in out Test) is
use Security.Permissions.Tests;
M : aliased Security.Policies.Policy_Manager (Max_Policies => 2);
User : aliased Test_Principal;
Admin : Policies.Roles.Role_Type;
Manager_Perm : Policies.Roles.Role_Type;
Context : aliased Security.Contexts.Security_Context;
R : Security.Policies.Roles.Role_Policy_Access := new Roles.Role_Policy;
begin
Configure_Policy (M, "simple-policy.xml");
Context.Set_Context (Manager => M'Unchecked_Access,
Principal => User'Unchecked_Access);
R := Security.Policies.Roles.Get_Role_Policy (M);
Admin := R.Find_Role ("admin");
T.Assert (not Contexts.Has_Permission (Permission => P_Admin.Permission),
"Permission was granted but user has no role");
User.Roles (Admin) := True;
T.Assert (Contexts.Has_Permission (Permission => P_Admin.Permission),
"Permission was not granted and user has admin role");
declare
S : Util.Measures.Stamp;
Result : Boolean;
begin
for I in 1 .. 1_000 loop
Result := Contexts.Has_Permission (Permission => P_Admin.Permission);
end loop;
Util.Measures.Report (S, "Has_Permission role based (1000 calls)");
T.Assert (Result, "Permission not granted");
end;
declare
use Security.Permissions.Tests;
S : Util.Measures.Stamp;
begin
for I in 1 .. 1_000 loop
declare
URI : constant String := "/admin/home/list.html";
P : constant URLs.URI_Permission (URI'Length)
:= URLs.URI_Permission '(Len => URI'Length, URI => URI);
begin
T.Assert (Contexts.Has_Permission (Permission => P_Admin.Permission),
"Permission not granted");
end;
end loop;
Util.Measures.Report (S, "Has_Permission (1000 calls, cache hit)");
end;
end Test_Read_Policy;
-- ------------------------------
-- Read the policy file <b>File</b> and perform a test on the given URI
-- with a user having the given role.
-- ------------------------------
procedure Check_Policy (T : in out Test;
File : in String;
Role : in String;
URI : in String) is
M : aliased Security.Policies.Policy_Manager (2);
User : aliased Test_Principal;
Admin : Roles.Role_Type;
Context : aliased Security.Contexts.Security_Context;
P : Security.Policies.Policy_Access;
R : Security.Policies.Roles.Role_Policy_Access;
U : Security.Policies.URLs.URL_Policy_Access;
begin
Configure_Policy (M, File);
Context.Set_Context (Manager => M'Unchecked_Access,
Principal => User'Unchecked_Access);
R := Security.Policies.Roles.Get_Role_Policy (M);
U := Security.Policies.URLs.Get_URL_Policy (M);
Admin := R.Find_Role (Role);
declare
P : constant URLs.URI_Permission (URI'Length)
:= URLs.URI_Permission '(Len => URI'Length, URI => URI);
begin
-- A user without the role should not have the permission.
T.Assert (not U.Has_Permission (Context => Context'Unchecked_Access,
Permission => P),
"Permission was granted for user without role. URI=" & URI);
-- Set the role.
User.Roles (Admin) := True;
T.Assert (U.Has_Permission (Context => Context'Unchecked_Access,
Permission => P),
"Permission was not granted for user with role. URI=" & URI);
end;
end Check_Policy;
-- ------------------------------
-- Test reading policy files and using the <role-permission> controller
-- ------------------------------
procedure Test_Role_Policy (T : in out Test) is
begin
T.Check_Policy (File => "policy-with-role.xml",
Role => "developer",
URI => "/developer/user-should-have-developer-role");
T.Check_Policy (File => "policy-with-role.xml",
Role => "manager",
URI => "/developer/user-should-have-manager-role");
T.Check_Policy (File => "policy-with-role.xml",
Role => "manager",
URI => "/manager/user-should-have-manager-role");
T.Check_Policy (File => "policy-with-role.xml",
Role => "admin",
URI => "/manager/user-should-have-admin-role");
T.Check_Policy (File => "policy-with-role.xml",
Role => "admin",
URI => "/admin/user-should-have-admin-role");
end Test_Role_Policy;
end Security.Policies.Tests;
|
-----------------------------------------------------------------------
-- Security-policies-tests - Unit tests for Security.Permissions
-- Copyright (C) 2011, 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Tests;
with Util.Files;
with Util.Test_Caller;
with Util.Measures;
with Security.Contexts;
with Security.Policies.Roles;
with Security.Permissions.Tests;
package body Security.Policies.Tests is
use Util.Tests;
package Caller is new Util.Test_Caller (Test, "Security.Policies");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test Security.Permissions.Create_Role",
Test_Create_Role'Access);
Caller.Add_Test (Suite, "Test Security.Permissions.Has_Permission",
Test_Has_Permission'Access);
Caller.Add_Test (Suite, "Test Security.Permissions.Read_Policy (empty)",
Test_Read_Empty_Policy'Access);
Caller.Add_Test (Suite, "Test Security.Policies.Add_Policy",
Test_Get_Role_Policy'Access);
Caller.Add_Test (Suite, "Test Security.Policies.Get_Policy",
Test_Get_Role_Policy'Access);
Caller.Add_Test (Suite, "Test Security.Policies.Roles.Get_Role_Policy",
Test_Get_Role_Policy'Access);
Caller.Add_Test (Suite, "Test Security.Policies.Read_Policy",
Test_Read_Policy'Access);
Caller.Add_Test (Suite, "Test Security.Policies.Roles.Set_Roles",
Test_Set_Roles'Access);
Caller.Add_Test (Suite, "Test Security.Policies.Roles.Set_Roles (invalid)",
Test_Set_Invalid_Roles'Access);
-- These tests are identical but registered under different names
-- for the test documentation.
Caller.Add_Test (Suite, "Test Security.Contexts.Has_Permission",
Test_Role_Policy'Access);
Caller.Add_Test (Suite, "Test Security.Controllers.Roles.Has_Permission",
Test_Role_Policy'Access);
Caller.Add_Test (Suite, "Test Security.Permissions.Role_Policy",
Test_Role_Policy'Access);
end Add_Tests;
-- ------------------------------
-- Get the roles assigned to the user.
-- ------------------------------
function Get_Roles (User : in Test_Principal) return Roles.Role_Map is
begin
return User.Roles;
end Get_Roles;
-- ------------------------------
-- Get the principal name.
-- ------------------------------
function Get_Name (From : in Test_Principal) return String is
begin
return Util.Strings.To_String (From.Name);
end Get_Name;
-- ------------------------------
-- Test Create_Role and Get_Role_Name
-- ------------------------------
procedure Test_Create_Role (T : in out Test) is
use Security.Policies.Roles;
M : Security.Policies.Roles.Role_Policy;
Role : Role_Type;
begin
M.Create_Role (Name => "admin",
Role => Role);
Assert_Equals (T, "admin", M.Get_Role_Name (Role), "Invalid name");
for I in Role + 1 .. Role_Type'Last loop
declare
Name : constant String := "admin-" & Role_Type'Image (I);
Role2 : Role_Type;
begin
Role2 := M.Find_Role ("admin");
T.Assert (Role2 = Role, "Find_Role returned an invalid role");
M.Create_Role (Name => Name,
Role => Role2);
Assert_Equals (T, Name, M.Get_Role_Name (Role2), "Invalid name");
end;
end loop;
end Test_Create_Role;
-- ------------------------------
-- Test Set_Roles
-- ------------------------------
procedure Test_Set_Roles (T : in out Test) is
use Security.Policies.Roles;
M : Security.Policies.Roles.Role_Policy;
Admin : Role_Type;
Manager : Role_Type;
Map : Role_Map := (others => False);
begin
M.Create_Role (Name => "manager",
Role => Manager);
M.Create_Role (Name => "admin",
Role => Admin);
Assert_Equals (T, "admin", M.Get_Role_Name (Admin), "Invalid name");
T.Assert (not Map (Admin), "The admin role must not set in the map");
M.Set_Roles ("admin", Map);
T.Assert (Map (Admin), "The admin role is not set in the map");
T.Assert (not Map (Manager), "The manager role must not be set in the map");
Map := (others => False);
M.Set_Roles ("manager,admin", Map);
T.Assert (Map (Admin), "The admin role is not set in the map");
T.Assert (Map (Manager), "The manager role is not set in the map");
end Test_Set_Roles;
-- ------------------------------
-- Test Set_Roles on an invalid role name
-- ------------------------------
procedure Test_Set_Invalid_Roles (T : in out Test) is
use Security.Policies.Roles;
M : Security.Policies.Roles.Role_Policy;
Map : Role_Map := (others => False);
begin
M.Set_Roles ("manager,admin", Map);
T.Assert (False, "No exception was raised");
exception
when E : Security.Policies.Roles.Invalid_Name =>
null;
end Test_Set_Invalid_Roles;
-- ------------------------------
-- Test Has_Permission
-- ------------------------------
procedure Test_Has_Permission (T : in out Test) is
M : Security.Policies.Policy_Manager (1);
-- Perm : Permissions.Permission_Type;
User : Test_Principal;
begin
-- T.Assert (not M.Has_Permission (User, 1), "User has a non-existing permission");
null;
end Test_Has_Permission;
procedure Configure_Policy (Manager : in out Security.Policies.Policy_Manager;
Name : in String) is
Dir : constant String := "regtests/files/permissions/";
Path : constant String := Util.Tests.Get_Path (Dir);
R : Security.Policies.Roles.Role_Policy_Access := new Roles.Role_Policy;
U : Security.Policies.URLs.URL_Policy_Access := new URLs.URL_Policy;
begin
Manager.Add_Policy (R.all'Access);
Manager.Add_Policy (U.all'Access);
Manager.Read_Policy (Util.Files.Compose (Path, Name));
end Configure_Policy;
-- ------------------------------
-- Test the Get_Policy, Get_Role_Policy and Add_Policy operations.
-- ------------------------------
procedure Test_Get_Role_Policy (T : in out Test) is
use type Roles.Role_Policy_Access;
M : aliased Security.Policies.Policy_Manager (Max_Policies => 2);
P : Security.Policies.Policy_Access;
R : Security.Policies.Roles.Role_Policy_Access;
begin
P := M.Get_Policy (Security.Policies.Roles.NAME);
T.Assert (P = null, "Get_Policy succeeded");
R := Security.Policies.Roles.Get_Role_Policy (M);
T.Assert (R = null, "Get_Role_Policy succeeded");
R := new Roles.Role_Policy;
M.Add_Policy (R.all'Access);
P := M.Get_Policy (Security.Policies.Roles.NAME);
T.Assert (P /= null, "Role policy not found");
T.Assert (P.all in Roles.Role_Policy'Class, "Invalid role policy");
R := Security.Policies.Roles.Get_Role_Policy (M);
T.Assert (R /= null, "Get_Role_Policy should not return null");
end Test_Get_Role_Policy;
-- ------------------------------
-- Test reading an empty policy file
-- ------------------------------
procedure Test_Read_Empty_Policy (T : in out Test) is
M : aliased Security.Policies.Policy_Manager (Max_Policies => 2);
User : aliased Test_Principal;
Context : aliased Security.Contexts.Security_Context;
P : Security.Policies.Policy_Access;
R : Security.Policies.Roles.Role_Policy_Access;
begin
Configure_Policy (M, "empty.xml");
Context.Set_Context (Manager => M'Unchecked_Access,
Principal => User'Unchecked_Access);
R := Security.Policies.Roles.Get_Role_Policy (M);
declare
Admin : Policies.Roles.Role_Type;
begin
Admin := R.Find_Role ("admin");
T.Fail ("'admin' role was returned");
exception
when Security.Policies.Roles.Invalid_Name =>
null;
end;
T.Assert (not Contexts.Has_Permission (Permissions.Tests.P_Admin.Permission),
"Has_Permission (admin) failed for empty policy");
T.Assert (not Contexts.Has_Permission (Permissions.Tests.P_Create.Permission),
"Has_Permission (create) failed for empty policy");
T.Assert (not Contexts.Has_Permission (Permissions.Tests.P_Update.Permission),
"Has_Permission (update) failed for empty policy");
T.Assert (not Contexts.Has_Permission (Permissions.Tests.P_Delete.Permission),
"Has_Permission (delete) failed for empty policy");
end Test_Read_Empty_Policy;
-- ------------------------------
-- Test reading policy files
-- ------------------------------
procedure Test_Read_Policy (T : in out Test) is
use Security.Permissions.Tests;
M : aliased Security.Policies.Policy_Manager (Max_Policies => 2);
User : aliased Test_Principal;
Admin : Policies.Roles.Role_Type;
Manager_Perm : Policies.Roles.Role_Type;
Context : aliased Security.Contexts.Security_Context;
R : Security.Policies.Roles.Role_Policy_Access;
begin
Configure_Policy (M, "simple-policy.xml");
Context.Set_Context (Manager => M'Unchecked_Access,
Principal => User'Unchecked_Access);
R := Security.Policies.Roles.Get_Role_Policy (M);
Admin := R.Find_Role ("admin");
T.Assert (not Contexts.Has_Permission (Permission => P_Admin.Permission),
"Permission was granted but user has no role");
User.Roles (Admin) := True;
T.Assert (Contexts.Has_Permission (Permission => P_Admin.Permission),
"Permission was not granted and user has admin role");
declare
S : Util.Measures.Stamp;
Result : Boolean;
begin
for I in 1 .. 1_000 loop
Result := Contexts.Has_Permission (Permission => P_Admin.Permission);
end loop;
Util.Measures.Report (S, "Has_Permission role based (1000 calls)");
T.Assert (Result, "Permission not granted");
end;
declare
use Security.Permissions.Tests;
S : Util.Measures.Stamp;
begin
for I in 1 .. 1_000 loop
declare
URI : constant String := "/admin/home/list.html";
P : constant URLs.URI_Permission (URI'Length)
:= URLs.URI_Permission '(Len => URI'Length, URI => URI);
begin
T.Assert (Contexts.Has_Permission (Permission => P_Admin.Permission),
"Permission not granted");
end;
end loop;
Util.Measures.Report (S, "Has_Permission (1000 calls, cache hit)");
end;
end Test_Read_Policy;
-- ------------------------------
-- Read the policy file <b>File</b> and perform a test on the given URI
-- with a user having the given role.
-- ------------------------------
procedure Check_Policy (T : in out Test;
File : in String;
Role : in String;
URI : in String) is
M : aliased Security.Policies.Policy_Manager (2);
User : aliased Test_Principal;
Admin : Roles.Role_Type;
Context : aliased Security.Contexts.Security_Context;
P : Security.Policies.Policy_Access;
R : Security.Policies.Roles.Role_Policy_Access;
U : Security.Policies.URLs.URL_Policy_Access;
begin
Configure_Policy (M, File);
Context.Set_Context (Manager => M'Unchecked_Access,
Principal => User'Unchecked_Access);
R := Security.Policies.Roles.Get_Role_Policy (M);
U := Security.Policies.URLs.Get_URL_Policy (M);
Admin := R.Find_Role (Role);
declare
P : constant URLs.URI_Permission (URI'Length)
:= URLs.URI_Permission '(Len => URI'Length, URI => URI);
begin
-- A user without the role should not have the permission.
T.Assert (not U.Has_Permission (Context => Context'Unchecked_Access,
Permission => P),
"Permission was granted for user without role. URI=" & URI);
-- Set the role.
User.Roles (Admin) := True;
T.Assert (U.Has_Permission (Context => Context'Unchecked_Access,
Permission => P),
"Permission was not granted for user with role. URI=" & URI);
end;
end Check_Policy;
-- ------------------------------
-- Test reading policy files and using the <role-permission> controller
-- ------------------------------
procedure Test_Role_Policy (T : in out Test) is
begin
T.Check_Policy (File => "policy-with-role.xml",
Role => "developer",
URI => "/developer/user-should-have-developer-role");
T.Check_Policy (File => "policy-with-role.xml",
Role => "manager",
URI => "/developer/user-should-have-manager-role");
T.Check_Policy (File => "policy-with-role.xml",
Role => "manager",
URI => "/manager/user-should-have-manager-role");
T.Check_Policy (File => "policy-with-role.xml",
Role => "admin",
URI => "/manager/user-should-have-admin-role");
T.Check_Policy (File => "policy-with-role.xml",
Role => "admin",
URI => "/admin/user-should-have-admin-role");
end Test_Role_Policy;
end Security.Policies.Tests;
|
Fix memory leak in unit test
|
Fix memory leak in unit test
|
Ada
|
apache-2.0
|
stcarrez/ada-security
|
cbb1ffb70e1f1605a623b01caf670ca848543116
|
awa/src/awa-modules-lifecycles.ads
|
awa/src/awa-modules-lifecycles.ads
|
-----------------------------------------------------------------------
-- awa-modules-lifecycles -- Lifecycle listeners
-- Copyright (C) 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Listeners.Lifecycles;
generic
type Element_Type (<>) is limited private;
package AWA.Modules.Lifecycles is
package LF is new Util.Listeners.Lifecycles (Element_Type);
subtype Listener is LF.Listener;
-- Inform the the lifecycle listeners registered in `List` that the item passed in `Item`
-- has been created (calls `On_Create`).
procedure Notify_Create (Service : in AWA.Modules.Module_Manager'Class;
Item : in Element_Type);
pragma Inline (Notify_Create);
-- Inform the the lifecycle listeners registered in `List` that the item passed in `Item`
-- has been updated (calls `On_Update`).
procedure Notify_Update (Service : in AWA.Modules.Module_Manager'Class;
Item : in Element_Type);
pragma Inline (Notify_Update);
-- Inform the the lifecycle listeners registered in `List` that the item passed in `Item`
-- has been deleted (calls `On_Delete`).
procedure Notify_Delete (Service : in AWA.Modules.Module_Manager'Class;
Item : in Element_Type);
pragma Inline (Notify_Delete);
end AWA.Modules.Lifecycles;
|
-----------------------------------------------------------------------
-- awa-modules-lifecycles -- Lifecycle listeners
-- Copyright (C) 2012, 2013, 2014 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Listeners.Lifecycles;
generic
type Element_Type (<>) is limited private;
package AWA.Modules.Lifecycles is
package LF is new Util.Listeners.Lifecycles (Element_Type);
subtype Listener is LF.Listener;
-- Inform the the life cycle listeners registered in `List` that the item passed in `Item`
-- has been created (calls `On_Create`).
procedure Notify_Create (Service : in AWA.Modules.Module_Manager'Class;
Item : in Element_Type);
procedure Notify_Create (Service : in AWA.Modules.Module'Class;
Item : in Element_Type);
pragma Inline (Notify_Create);
-- Inform the the life cycle listeners registered in `List` that the item passed in `Item`
-- has been updated (calls `On_Update`).
procedure Notify_Update (Service : in AWA.Modules.Module_Manager'Class;
Item : in Element_Type);
procedure Notify_Update (Service : in AWA.Modules.Module'Class;
Item : in Element_Type);
pragma Inline (Notify_Update);
-- Inform the the life cycle listeners registered in `List` that the item passed in `Item`
-- has been deleted (calls `On_Delete`).
procedure Notify_Delete (Service : in AWA.Modules.Module_Manager'Class;
Item : in Element_Type);
procedure Notify_Delete (Service : in AWA.Modules.Module'Class;
Item : in Element_Type);
pragma Inline (Notify_Delete);
end AWA.Modules.Lifecycles;
|
Add Notify_Create, Notify_Update and Notify_Delete with the Module'Class instance
|
Add Notify_Create, Notify_Update and Notify_Delete with the Module'Class instance
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
f2791bba5ae3b7464acda36baab8ca78a10b8f7b
|
src/security-auth-oauth-github.adb
|
src/security-auth-oauth-github.adb
|
-----------------------------------------------------------------------
-- security-auth-oauth-github -- Github OAuth based authentication
-- Copyright (C) 2020 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Log.Loggers;
with Util.Http.Clients;
with Util.Properties.JSON;
package body Security.Auth.OAuth.Github is
use Util.Log;
Log : constant Loggers.Logger := Util.Log.Loggers.Create ("Security.Auth.OAuth.Github");
-- ------------------------------
-- Verify the OAuth access token and retrieve information about the user.
-- ------------------------------
overriding
procedure Verify_Access_Token (Realm : in Manager;
Assoc : in Association;
Request : in Parameters'Class;
Token : in Security.OAuth.Clients.Access_Token_Access;
Result : in out Authentication) is
pragma Unreferenced (Request);
URI : constant String := "https://api.github.com/user";
Http : Util.Http.Clients.Client;
Reply : Util.Http.Clients.Response;
Props : Util.Properties.Manager;
begin
Http.Add_Header ("Authorization", "token " & Token.Get_Name);
Http.Get (URI, Reply);
if Reply.Get_Status /= Util.Http.SC_OK then
Log.Warn ("Cannot retrieve Github user information");
Set_Result (Result, INVALID_SIGNATURE, "invalid access token");
return;
end if;
Util.Properties.JSON.Parse_JSON (Props, Reply.Get_Body);
Result.Identity := Realm.Issuer;
Append (Result.Identity, "/");
Append (Result.Identity, String '(Props.Get ("id")));
Result.Claimed_Id := Result.Identity;
Result.First_Name := To_Unbounded_String (Props.Get ("name"));
Result.Full_Name := To_Unbounded_String (Props.Get ("name"));
-- The email is optional and depends on the scope.
Result.Email := To_Unbounded_String (Props.Get ("email"));
Set_Result (Result, AUTHENTICATED, "authenticated");
end Verify_Access_Token;
end Security.Auth.OAuth.Github;
|
-----------------------------------------------------------------------
-- security-auth-oauth-github -- Github OAuth based authentication
-- Copyright (C) 2020, 2021 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Log.Loggers;
with Util.Http.Clients;
with Util.Properties.JSON;
package body Security.Auth.OAuth.Github is
use Util.Log;
Log : constant Loggers.Logger := Util.Log.Loggers.Create ("Security.Auth.OAuth.Github");
-- ------------------------------
-- Verify the OAuth access token and retrieve information about the user.
-- ------------------------------
overriding
procedure Verify_Access_Token (Realm : in Manager;
Assoc : in Association;
Request : in Parameters'Class;
Token : in Security.OAuth.Clients.Access_Token_Access;
Result : in out Authentication) is
pragma Unreferenced (Assoc, Request);
URI : constant String := "https://api.github.com/user";
Http : Util.Http.Clients.Client;
Reply : Util.Http.Clients.Response;
Props : Util.Properties.Manager;
begin
Http.Add_Header ("Authorization", "token " & Token.Get_Name);
Http.Get (URI, Reply);
if Reply.Get_Status /= Util.Http.SC_OK then
Log.Warn ("Cannot retrieve Github user information");
Set_Result (Result, INVALID_SIGNATURE, "invalid access token");
return;
end if;
Util.Properties.JSON.Parse_JSON (Props, Reply.Get_Body);
Result.Identity := Realm.Issuer;
Append (Result.Identity, "/");
Append (Result.Identity, String '(Props.Get ("id")));
Result.Claimed_Id := Result.Identity;
Result.First_Name := To_Unbounded_String (Props.Get ("name"));
Result.Full_Name := To_Unbounded_String (Props.Get ("name"));
-- The email is optional and depends on the scope.
Result.Email := To_Unbounded_String (Props.Get ("email"));
Set_Result (Result, AUTHENTICATED, "authenticated");
end Verify_Access_Token;
end Security.Auth.OAuth.Github;
|
Fix compilation warning
|
Fix compilation warning
|
Ada
|
apache-2.0
|
stcarrez/ada-security
|
5d056e3f470bf11e6e87b87841beb93ee068b370
|
src/util-beans-objects-readers.adb
|
src/util-beans-objects-readers.adb
|
-----------------------------------------------------------------------
-- util-beans-objects-readers -- Datasets
-- Copyright (C) 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
package body Util.Beans.Objects.Readers is
use type Maps.Map_Bean_Access;
use type Vectors.Vector_Bean_Access;
-- Start a document.
overriding
procedure Start_Document (Handler : in out Reader) is
begin
Object_Stack.Clear (Handler.Context);
end Start_Document;
-- -----------------------
-- Start a new object associated with the given name. This is called when
-- the '{' is reached. The reader must be updated so that the next
-- <b>Set_Member</b> procedure will associate the name/value pair on the
-- new object.
-- -----------------------
overriding
procedure Start_Object (Handler : in out Reader;
Name : in String;
Logger : in out Util.Log.Logging'Class) is
pragma Unreferenced (Logger);
Current : constant Object_Context_Access := Object_Stack.Current (Handler.Context);
Next : Object_Context_Access;
begin
Object_Stack.Push (Handler.Context);
Next := Object_Stack.Current (Handler.Context);
Next.Map := new Maps.Map_Bean;
if Current = null then
Handler.Root := To_Object (Next.Map, DYNAMIC);
elsif Current.Map /= null then
Current.Map.Include (Name, To_Object (Next.Map, DYNAMIC));
else
Current.List.Append (To_Object (Next.Map, DYNAMIC));
end if;
end Start_Object;
-- -----------------------
-- Finish an object associated with the given name. The reader must be
-- updated to be associated with the previous object.
-- -----------------------
overriding
procedure Finish_Object (Handler : in out Reader;
Name : in String;
Logger : in out Util.Log.Logging'Class) is
pragma Unreferenced (Name, Logger);
begin
Object_Stack.Pop (Handler.Context);
end Finish_Object;
overriding
procedure Start_Array (Handler : in out Reader;
Name : in String;
Logger : in out Util.Log.Logging'Class) is
pragma Unreferenced (Logger);
Current : constant Object_Context_Access := Object_Stack.Current (Handler.Context);
Next : Object_Context_Access;
begin
Object_Stack.Push (Handler.Context);
Next := Object_Stack.Current (Handler.Context);
Next.List := new Vectors.Vector_Bean;
if Current = null then
Handler.Root := To_Object (Next.List, DYNAMIC);
elsif Current.Map /= null then
Current.Map.Include (Name, To_Object (Next.List, DYNAMIC));
else
Current.List.Append (To_Object (Next.List, DYNAMIC));
end if;
end Start_Array;
overriding
procedure Finish_Array (Handler : in out Reader;
Name : in String;
Count : in Natural;
Logger : in out Util.Log.Logging'Class) is
pragma Unreferenced (Name, Count, Logger);
begin
Object_Stack.Pop (Handler.Context);
end Finish_Array;
-- -----------------------
-- Set the name/value pair on the current object. For each active mapping,
-- find whether a rule matches our name and execute it.
-- -----------------------
overriding
procedure Set_Member (Handler : in out Reader;
Name : in String;
Value : in Util.Beans.Objects.Object;
Logger : in out Util.Log.Logging'Class;
Attribute : in Boolean := False) is
pragma Unreferenced (Logger, Attribute);
Current : constant Object_Context_Access := Object_Stack.Current (Handler.Context);
begin
if Current.Map /= null then
Current.Map.Set_Value (Name, Value);
else
Current.List.Append (Value);
end if;
end Set_Member;
-- -----------------------
-- Get the root object.
-- -----------------------
function Get_Root (Handler : in Reader) return Object is
begin
return Handler.Root;
end Get_Root;
end Util.Beans.Objects.Readers;
|
-----------------------------------------------------------------------
-- util-beans-objects-readers -- Datasets
-- Copyright (C) 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
package body Util.Beans.Objects.Readers is
use type Maps.Map_Bean_Access;
use type Vectors.Vector_Bean_Access;
-- Start a document.
overriding
procedure Start_Document (Handler : in out Reader) is
begin
Object_Stack.Clear (Handler.Context);
end Start_Document;
-- -----------------------
-- Start a new object associated with the given name. This is called when
-- the '{' is reached. The reader must be updated so that the next
-- <b>Set_Member</b> procedure will associate the name/value pair on the
-- new object.
-- -----------------------
overriding
procedure Start_Object (Handler : in out Reader;
Name : in String;
Logger : in out Util.Log.Logging'Class) is
pragma Unreferenced (Logger);
Current : constant Object_Context_Access := Object_Stack.Current (Handler.Context);
Next : Object_Context_Access;
begin
Object_Stack.Push (Handler.Context);
Next := Object_Stack.Current (Handler.Context);
Next.Map := new Maps.Map_Bean;
Next.List := null;
if Current = null then
Handler.Root := To_Object (Next.Map, DYNAMIC);
elsif Current.Map /= null then
Current.Map.Include (Name, To_Object (Next.Map, DYNAMIC));
else
Current.List.Append (To_Object (Next.Map, DYNAMIC));
end if;
end Start_Object;
-- -----------------------
-- Finish an object associated with the given name. The reader must be
-- updated to be associated with the previous object.
-- -----------------------
overriding
procedure Finish_Object (Handler : in out Reader;
Name : in String;
Logger : in out Util.Log.Logging'Class) is
pragma Unreferenced (Name, Logger);
begin
Object_Stack.Pop (Handler.Context);
end Finish_Object;
overriding
procedure Start_Array (Handler : in out Reader;
Name : in String;
Logger : in out Util.Log.Logging'Class) is
pragma Unreferenced (Logger);
Current : constant Object_Context_Access := Object_Stack.Current (Handler.Context);
Next : Object_Context_Access;
begin
Object_Stack.Push (Handler.Context);
Next := Object_Stack.Current (Handler.Context);
Next.List := new Vectors.Vector_Bean;
Next.Map := null;
if Current = null then
Handler.Root := To_Object (Next.List, DYNAMIC);
elsif Current.Map /= null then
Current.Map.Include (Name, To_Object (Next.List, DYNAMIC));
else
Current.List.Append (To_Object (Next.List, DYNAMIC));
end if;
end Start_Array;
overriding
procedure Finish_Array (Handler : in out Reader;
Name : in String;
Count : in Natural;
Logger : in out Util.Log.Logging'Class) is
pragma Unreferenced (Name, Count, Logger);
begin
Object_Stack.Pop (Handler.Context);
end Finish_Array;
-- -----------------------
-- Set the name/value pair on the current object. For each active mapping,
-- find whether a rule matches our name and execute it.
-- -----------------------
overriding
procedure Set_Member (Handler : in out Reader;
Name : in String;
Value : in Util.Beans.Objects.Object;
Logger : in out Util.Log.Logging'Class;
Attribute : in Boolean := False) is
pragma Unreferenced (Logger, Attribute);
Current : constant Object_Context_Access := Object_Stack.Current (Handler.Context);
begin
if Current.Map /= null then
Current.Map.Set_Value (Name, Value);
else
Current.List.Append (Value);
end if;
end Set_Member;
-- -----------------------
-- Get the root object.
-- -----------------------
function Get_Root (Handler : in Reader) return Object is
begin
return Handler.Root;
end Get_Root;
end Util.Beans.Objects.Readers;
|
Fix initialization of the context object when starting a new array or object
|
Fix initialization of the context object when starting a new array or object
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
539ebf7a2666d900fe35c148880fbb1b232f161c
|
regtests/ado-statements-tests.ads
|
regtests/ado-statements-tests.ads
|
-----------------------------------------------------------------------
-- ado-statements-tests -- Test statements package
-- Copyright (C) 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Tests;
package ADO.Statements.Tests is
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite);
type Test is new Util.Tests.Test with null record;
-- Test creation of several rows in test_table with different column type.
procedure Test_Save (T : in out Test);
end ADO.Statements.Tests;
|
-----------------------------------------------------------------------
-- ado-statements-tests -- Test statements package
-- Copyright (C) 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.Tests;
package ADO.Statements.Tests is
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite);
type Test is new Util.Tests.Test with null record;
-- Test creation of several rows in test_table with different column type.
procedure Test_Save (T : in out Test);
-- Test queries using the $entity_type[] cache group.
procedure Test_Entity_Types (T : in out Test);
end ADO.Statements.Tests;
|
Declare the Test_Entity_Types procedure
|
Declare the Test_Entity_Types procedure
|
Ada
|
apache-2.0
|
stcarrez/ada-ado
|
b7e6d38b90dca1943e508567c051b5da2e1c955a
|
src/drivers/adabase-driver-base-postgresql.adb
|
src/drivers/adabase-driver-base-postgresql.adb
|
-- This file is covered by the Internet Software Consortium (ISC) License
-- Reference: ../../License.txt
package body AdaBase.Driver.Base.PostgreSQL is
-------------
-- query --
-------------
function query (driver : PostgreSQL_Driver; sql : String)
return SMT.PostgreSQL_statement is
begin
return driver.private_statement (sql => sql, prepared => False);
end query;
---------------
-- prepare --
---------------
function prepare (driver : PostgreSQL_Driver; sql : String)
return SMT.PostgreSQL_statement is
begin
return driver.private_statement (sql => sql, prepared => True);
end prepare;
----------------------
-- prepare_select --
----------------------
function prepare_select (driver : PostgreSQL_Driver;
distinct : Boolean := False;
tables : String;
columns : String;
conditions : String := blankstring;
groupby : String := blankstring;
having : String := blankstring;
order : String := blankstring;
null_sort : NullPriority := native;
limit : TraxID := 0;
offset : TraxID := 0)
return SMT.PostgreSQL_statement is
begin
return driver.private_statement
(prepared => True,
sql => sql_assemble (distinct => distinct,
tables => tables,
columns => columns,
conditions => conditions,
groupby => groupby,
having => having,
order => order,
null_sort => null_sort,
limit => limit,
offset => offset));
end prepare_select;
--------------------
-- query_select --
--------------------
function query_select (driver : PostgreSQL_Driver;
distinct : Boolean := False;
tables : String;
columns : String;
conditions : String := blankstring;
groupby : String := blankstring;
having : String := blankstring;
order : String := blankstring;
null_sort : NullPriority := native;
limit : TraxID := 0;
offset : TraxID := 0)
return SMT.PostgreSQL_statement is
begin
return driver.private_statement
(prepared => False,
sql => sql_assemble (distinct => distinct,
tables => tables,
columns => columns,
conditions => conditions,
groupby => groupby,
having => having,
order => order,
null_sort => null_sort,
limit => limit,
offset => offset));
end query_select;
--------------------
-- sql_assemble --
--------------------
function sql_assemble (distinct : Boolean := False;
tables : String;
columns : String;
conditions : String := blankstring;
groupby : String := blankstring;
having : String := blankstring;
order : String := blankstring;
null_sort : NullPriority := native;
limit : TraxID := 0;
offset : TraxID := 0) return String
is
rockyroad : CT.Text;
vanilla : String := assembly_common_select
(distinct, tables, columns, conditions, groupby, having, order);
begin
case null_sort is
when native => rockyroad := CT.SUS (vanilla);
when nulls_first => rockyroad := CT.SUS (vanilla & " NULLS FIRST");
when nulls_last => rockyroad := CT.SUS (vanilla & " NULLS LAST");
end case;
if limit > 0 then
if offset > 0 then
return CT.USS (rockyroad) & " LIMIT" & limit'Img &
" OFFSET" & offset'Img;
else
return CT.USS (rockyroad) & " LIMIT" & limit'Img;
end if;
end if;
return CT.USS (rockyroad);
end sql_assemble;
------------------
-- initialize --
------------------
overriding
procedure initialize (Object : in out PostgreSQL_Driver) is
begin
Object.connection := Object.local_connection'Unchecked_Access;
Object.dialect := driver_postgresql;
end initialize;
-----------------------
-- private_connect --
-----------------------
overriding
procedure private_connect (driver : out PostgreSQL_Driver;
database : String;
username : String;
password : String;
hostname : String := blankstring;
socket : String := blankstring;
port : PosixPort := portless)
is
err1 : constant CT.Text :=
CT.SUS ("ACK! Reconnection attempted on active connection");
nom : constant CT.Text :=
CT.SUS ("Connection to " & database & " database succeeded.");
begin
if driver.connection_active then
driver.log_problem (category => execution,
message => err1);
return;
end if;
driver.connection.connect (database => database,
username => username,
password => password,
socket => socket,
hostname => hostname,
port => port);
driver.connection_active := driver.connection.connected;
driver.log_nominal (category => connecting, message => nom);
exception
when Error : others =>
driver.log_problem
(category => connecting,
break => True,
message => CT.SUS (CON.EX.Exception_Message (X => Error)));
end private_connect;
---------------
-- execute --
---------------
overriding
function execute (driver : PostgreSQL_Driver; sql : String)
return AffectedRows
is
trsql : String := CT.trim_sql (sql);
nquery : Natural := CT.count_queries (trsql);
aborted : constant AffectedRows := 0;
err1 : constant CT.Text :=
CT.SUS ("ACK! Execution attempted on inactive connection");
err2 : constant String :=
"Driver is configured to allow only one query at " &
"time, but this SQL contains multiple queries: ";
begin
if not driver.connection_active then
-- Fatal attempt to query an unccnnected database
driver.log_problem (category => execution,
message => err1,
break => True);
return aborted;
end if;
if nquery > 1 and then not driver.trait_multiquery_enabled then
-- Fatal attempt to execute multiple queries when it's not permitted
driver.log_problem (category => execution,
message => CT.SUS (err2 & trsql),
break => True);
return aborted;
end if;
declare
result : AffectedRows;
begin
-- PostgreSQL execute supports multiquery in all cases, so it is not
-- necessary to loop through subqueries. We send the trimmed
-- compound query as it was received.
driver.connection.execute (trsql);
driver.log_nominal (execution, CT.SUS (trsql));
result := driver.connection.rows_affected_by_execution;
return result;
exception
when CON.QUERY_FAIL =>
driver.log_problem (category => execution,
message => CT.SUS (trsql),
pull_codes => True);
return aborted;
end;
end execute;
-------------------------
-- private_statement --
-------------------------
function private_statement (driver : PostgreSQL_Driver;
sql : String;
prepared : Boolean)
return SMT.PostgreSQL_statement
is
stype : AID.ASB.stmt_type := AID.ASB.direct_statement;
logcat : LogCategory := execution;
duplicate : aliased String := sql;
err1 : constant CT.Text :=
CT.SUS ("ACK! Query attempted on inactive connection");
begin
if prepared then
stype := AID.ASB.prepared_statement;
logcat := statement_preparation;
end if;
if driver.connection_active then
declare
statement : SMT.PostgreSQL_statement
(type_of_statement => AID.ASB.prepared_statement,
log_handler => logger'Access,
pgsql_conn => CON.PostgreSQL_Connection_Access
(driver.connection),
initial_sql => duplicate'Unchecked_Access,
con_error_mode => driver.trait_error_mode,
con_case_mode => driver.trait_column_case,
con_max_blob => driver.trait_max_blob_size,
con_buffered => True);
begin
if not prepared then
if statement.successful then
driver.log_nominal
(category => logcat,
message => CT.SUS ("query succeeded," &
statement.rows_returned'Img & " rows returned"));
else
driver.log_nominal (category => execution,
message => CT.SUS ("Query failed!"));
end if;
end if;
return statement;
exception
when RES : others =>
-- Fatal attempt to prepare a statement
-- Logged already by stmt initialization
-- Should be internally marked as unsuccessful
return statement;
end;
else
-- Fatal attempt to query an unconnected database
driver.log_problem (category => logcat,
message => err1,
break => True);
end if;
-- We never get here, the driver.log_problem throws exception first
raise CON.STMT_NOT_VALID
with "failed to return SQLite statement";
end private_statement;
end AdaBase.Driver.Base.PostgreSQL;
|
-- This file is covered by the Internet Software Consortium (ISC) License
-- Reference: ../../License.txt
package body AdaBase.Driver.Base.PostgreSQL is
-------------
-- query --
-------------
function query (driver : PostgreSQL_Driver; sql : String)
return SMT.PostgreSQL_statement is
begin
return driver.private_statement (sql => sql, prepared => False);
end query;
---------------
-- prepare --
---------------
function prepare (driver : PostgreSQL_Driver; sql : String)
return SMT.PostgreSQL_statement is
begin
return driver.private_statement (sql => sql, prepared => True);
end prepare;
----------------------
-- prepare_select --
----------------------
function prepare_select (driver : PostgreSQL_Driver;
distinct : Boolean := False;
tables : String;
columns : String;
conditions : String := blankstring;
groupby : String := blankstring;
having : String := blankstring;
order : String := blankstring;
null_sort : NullPriority := native;
limit : TraxID := 0;
offset : TraxID := 0)
return SMT.PostgreSQL_statement is
begin
return driver.private_statement
(prepared => True,
sql => sql_assemble (distinct => distinct,
tables => tables,
columns => columns,
conditions => conditions,
groupby => groupby,
having => having,
order => order,
null_sort => null_sort,
limit => limit,
offset => offset));
end prepare_select;
--------------------
-- query_select --
--------------------
function query_select (driver : PostgreSQL_Driver;
distinct : Boolean := False;
tables : String;
columns : String;
conditions : String := blankstring;
groupby : String := blankstring;
having : String := blankstring;
order : String := blankstring;
null_sort : NullPriority := native;
limit : TraxID := 0;
offset : TraxID := 0)
return SMT.PostgreSQL_statement is
begin
return driver.private_statement
(prepared => False,
sql => sql_assemble (distinct => distinct,
tables => tables,
columns => columns,
conditions => conditions,
groupby => groupby,
having => having,
order => order,
null_sort => null_sort,
limit => limit,
offset => offset));
end query_select;
--------------------
-- sql_assemble --
--------------------
function sql_assemble (distinct : Boolean := False;
tables : String;
columns : String;
conditions : String := blankstring;
groupby : String := blankstring;
having : String := blankstring;
order : String := blankstring;
null_sort : NullPriority := native;
limit : TraxID := 0;
offset : TraxID := 0) return String
is
rockyroad : CT.Text;
vanilla : String := assembly_common_select
(distinct, tables, columns, conditions, groupby, having, order);
begin
case null_sort is
when native => rockyroad := CT.SUS (vanilla);
when nulls_first => rockyroad := CT.SUS (vanilla & " NULLS FIRST");
when nulls_last => rockyroad := CT.SUS (vanilla & " NULLS LAST");
end case;
if limit > 0 then
if offset > 0 then
return CT.USS (rockyroad) & " LIMIT" & limit'Img &
" OFFSET" & offset'Img;
else
return CT.USS (rockyroad) & " LIMIT" & limit'Img;
end if;
end if;
return CT.USS (rockyroad);
end sql_assemble;
------------------
-- initialize --
------------------
overriding
procedure initialize (Object : in out PostgreSQL_Driver) is
begin
Object.connection := Object.local_connection'Unchecked_Access;
Object.dialect := driver_postgresql;
end initialize;
-----------------------
-- private_connect --
-----------------------
overriding
procedure private_connect (driver : out PostgreSQL_Driver;
database : String;
username : String;
password : String;
hostname : String := blankstring;
socket : String := blankstring;
port : PosixPort := portless)
is
err1 : constant CT.Text :=
CT.SUS ("ACK! Reconnection attempted on active connection");
nom : constant CT.Text :=
CT.SUS ("Connection to " & database & " database succeeded.");
begin
if driver.connection_active then
driver.log_problem (category => execution,
message => err1);
return;
end if;
driver.connection.connect (database => database,
username => username,
password => password,
socket => socket,
hostname => hostname,
port => port);
driver.connection_active := driver.connection.connected;
driver.log_nominal (category => connecting, message => nom);
exception
when Error : others =>
driver.log_problem
(category => connecting,
break => True,
message => CT.SUS (CON.EX.Exception_Message (X => Error)));
end private_connect;
---------------
-- execute --
---------------
overriding
function execute (driver : PostgreSQL_Driver; sql : String)
return AffectedRows
is
trsql : String := CT.trim_sql (sql);
nquery : Natural := CT.count_queries (trsql);
aborted : constant AffectedRows := 0;
err1 : constant CT.Text :=
CT.SUS ("ACK! Execution attempted on inactive connection");
err2 : constant String :=
"Driver is configured to allow only one query at " &
"time, but this SQL contains multiple queries: ";
begin
if not driver.connection_active then
-- Fatal attempt to query an unccnnected database
driver.log_problem (category => execution,
message => err1,
break => True);
return aborted;
end if;
if nquery > 1 and then not driver.trait_multiquery_enabled then
-- Fatal attempt to execute multiple queries when it's not permitted
driver.log_problem (category => execution,
message => CT.SUS (err2 & trsql),
break => True);
return aborted;
end if;
declare
result : AffectedRows;
begin
-- In order to support INSERT INTO .. RETURNING, we have to execute
-- multiqueries individually because we are scanning the first 7
-- characters to be "INSERT " after converting to upper case.
for query_index in Positive range 1 .. nquery loop
result := 0;
if nquery = 1 then
driver.connection.execute (trsql);
driver.log_nominal (execution, CT.SUS (trsql));
else
declare
SQ : constant String := CT.subquery (trsql, query_index);
begin
driver.connection.execute (SQ);
driver.log_nominal (execution, CT.SUS (SQ));
end;
end if;
end loop;
result := driver.connection.rows_affected_by_execution;
return result;
exception
when CON.QUERY_FAIL =>
driver.log_problem (category => execution,
message => CT.SUS (trsql),
pull_codes => True);
return aborted;
end;
end execute;
-------------------------
-- private_statement --
-------------------------
function private_statement (driver : PostgreSQL_Driver;
sql : String;
prepared : Boolean)
return SMT.PostgreSQL_statement
is
stype : AID.ASB.stmt_type := AID.ASB.direct_statement;
logcat : LogCategory := execution;
duplicate : aliased String := sql;
err1 : constant CT.Text :=
CT.SUS ("ACK! Query attempted on inactive connection");
begin
if prepared then
stype := AID.ASB.prepared_statement;
logcat := statement_preparation;
end if;
if driver.connection_active then
declare
statement : SMT.PostgreSQL_statement
(type_of_statement => AID.ASB.prepared_statement,
log_handler => logger'Access,
pgsql_conn => CON.PostgreSQL_Connection_Access
(driver.connection),
initial_sql => duplicate'Unchecked_Access,
con_error_mode => driver.trait_error_mode,
con_case_mode => driver.trait_column_case,
con_max_blob => driver.trait_max_blob_size,
con_buffered => True);
begin
if not prepared then
if statement.successful then
driver.log_nominal
(category => logcat,
message => CT.SUS ("query succeeded," &
statement.rows_returned'Img & " rows returned"));
else
driver.log_nominal (category => execution,
message => CT.SUS ("Query failed!"));
end if;
end if;
return statement;
exception
when RES : others =>
-- Fatal attempt to prepare a statement
-- Logged already by stmt initialization
-- Should be internally marked as unsuccessful
return statement;
end;
else
-- Fatal attempt to query an unconnected database
driver.log_problem (category => logcat,
message => err1,
break => True);
end if;
-- We never get here, the driver.log_problem throws exception first
raise CON.STMT_NOT_VALID
with "failed to return SQLite statement";
end private_statement;
end AdaBase.Driver.Base.PostgreSQL;
|
Return to executing multiquery statements indvidually
|
Return to executing multiquery statements indvidually
In order to properly use INSERT INTO .. RETURNING, we have to process
the multiquery statements individually.
|
Ada
|
isc
|
jrmarino/AdaBase
|
223349a7d33795126232038d80327c73ebf2aa7f
|
src/asf-views-facelets.ads
|
src/asf-views-facelets.ads
|
-----------------------------------------------------------------------
-- asf-views-facelets -- Facelets representation and management
-- Copyright (C) 2009, 2010, 2011, 2014 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Calendar;
with Ada.Strings.Unbounded;
with Ada.Containers.Hashed_Maps;
with Ada.Strings.Unbounded.Hash;
with ASF.Views.Nodes;
with ASF.Contexts.Facelets;
with ASF.Factory;
with ASF.Components.Base;
with Util.Strings.Maps;
with Ada.Finalization;
-- The <b>ASF.Views.Facelets</b> package contains the facelet factory
-- responsible for getting the facelet tree from a facelet name.
-- The facelets (or *.xhtml) files are loaded by the reader to form
-- a tag node tree which is cached by the factory. The facelet factory
-- is shared by multiple requests and threads.
package ASF.Views.Facelets is
type Facelet is private;
type Facelet_Access is access all Facelet;
-- Returns True if the facelet is null/empty.
function Is_Null (F : Facelet) return Boolean;
-- ------------------------------
-- Facelet factory
-- ------------------------------
-- The facelet factory allows to retrieve the node tree to build the
-- component tree. The node tree can be shared by several component trees.
-- The node tree is initialized from the <b>XHTML</b> view file. It is put
-- in a cache to avoid loading and parsing the file several times.
type Facelet_Factory is limited private;
-- Get the facelet identified by the given name. If the facelet is already
-- loaded, the cached value is returned. The facelet file is searched in
-- a set of directories configured in the facelet factory.
procedure Find_Facelet (Factory : in out Facelet_Factory;
Name : in String;
Context : in ASF.Contexts.Facelets.Facelet_Context'Class;
Result : out Facelet);
-- Create the component tree from the facelet view.
procedure Build_View (View : in Facelet;
Context : in out ASF.Contexts.Facelets.Facelet_Context'Class;
Root : in ASF.Components.Base.UIComponent_Access);
-- Initialize the facelet factory.
-- Set the search directories for facelet files.
-- Set the ignore white space configuration when reading XHTML files.
-- Set the ignore empty lines configuration when reading XHTML files.
-- Set the escape unknown tags configuration when reading XHTML files.
procedure Initialize (Factory : in out Facelet_Factory;
Components : access ASF.Factory.Component_Factory;
Paths : in String;
Ignore_White_Spaces : in Boolean;
Ignore_Empty_Lines : in Boolean;
Escape_Unknown_Tags : in Boolean);
-- Find the facelet file in one of the facelet directories.
-- Returns the path to be used for reading the facelet file.
function Find_Facelet_Path (Factory : in Facelet_Factory;
Name : in String) return String;
-- Clear the facelet cache
procedure Clear_Cache (Factory : in out Facelet_Factory);
private
use Ada.Strings.Unbounded;
type Facelet is record
Root : ASF.Views.Nodes.Tag_Node_Access;
File : ASF.Views.File_Info_Access;
Modify_Time : Ada.Calendar.Time;
end record;
-- Tag library map indexed on the library namespace.
package Facelet_Maps is new
Ada.Containers.Hashed_Maps (Key_Type => Unbounded_String,
Element_Type => Facelet,
Hash => Ada.Strings.Unbounded.Hash,
Equivalent_Keys => "=");
use Facelet_Maps;
protected type Facelet_Cache is
-- Find the facelet entry associated with the given name.
function Find (Name : in Unbounded_String) return Facelet;
-- Insert or replace the facelet entry associated with the given name.
procedure Insert (Name : in Unbounded_String;
Item : in Facelet);
-- Clear the cache.
procedure Clear;
private
Map : Facelet_Maps.Map;
end Facelet_Cache;
type Facelet_Factory is new Ada.Finalization.Limited_Controlled with record
Paths : Unbounded_String := To_Unbounded_String ("");
-- The facelet cache.
Map : Facelet_Cache;
-- The component factory
Factory : access ASF.Factory.Component_Factory;
-- Whether the unknown tags are escaped using XML escape rules.
Escape_Unknown_Tags : Boolean := True;
-- Whether white spaces can be ignored.
Ignore_White_Spaces : Boolean := True;
-- Whether empty lines should be ignored (when white spaces are kept).
Ignore_Empty_Lines : Boolean := True;
end record;
-- Free the storage held by the factory cache.
overriding
procedure Finalize (Factory : in out Facelet_Factory);
end ASF.Views.Facelets;
|
-----------------------------------------------------------------------
-- asf-views-facelets -- Facelets representation and management
-- Copyright (C) 2009, 2010, 2011, 2014, 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Calendar;
with Ada.Strings.Unbounded;
with Ada.Containers.Hashed_Maps;
with Ada.Strings.Unbounded.Hash;
with ASF.Views.Nodes;
with ASF.Contexts.Facelets;
with ASF.Factory;
with ASF.Components.Base;
with Ada.Finalization;
-- The <b>ASF.Views.Facelets</b> package contains the facelet factory
-- responsible for getting the facelet tree from a facelet name.
-- The facelets (or *.xhtml) files are loaded by the reader to form
-- a tag node tree which is cached by the factory. The facelet factory
-- is shared by multiple requests and threads.
package ASF.Views.Facelets is
type Facelet is private;
type Facelet_Access is access all Facelet;
-- Returns True if the facelet is null/empty.
function Is_Null (F : Facelet) return Boolean;
-- ------------------------------
-- Facelet factory
-- ------------------------------
-- The facelet factory allows to retrieve the node tree to build the
-- component tree. The node tree can be shared by several component trees.
-- The node tree is initialized from the <b>XHTML</b> view file. It is put
-- in a cache to avoid loading and parsing the file several times.
type Facelet_Factory is limited private;
-- Get the facelet identified by the given name. If the facelet is already
-- loaded, the cached value is returned. The facelet file is searched in
-- a set of directories configured in the facelet factory.
procedure Find_Facelet (Factory : in out Facelet_Factory;
Name : in String;
Context : in ASF.Contexts.Facelets.Facelet_Context'Class;
Result : out Facelet);
-- Create the component tree from the facelet view.
procedure Build_View (View : in Facelet;
Context : in out ASF.Contexts.Facelets.Facelet_Context'Class;
Root : in ASF.Components.Base.UIComponent_Access);
-- Initialize the facelet factory.
-- Set the search directories for facelet files.
-- Set the ignore white space configuration when reading XHTML files.
-- Set the ignore empty lines configuration when reading XHTML files.
-- Set the escape unknown tags configuration when reading XHTML files.
procedure Initialize (Factory : in out Facelet_Factory;
Components : access ASF.Factory.Component_Factory;
Paths : in String;
Ignore_White_Spaces : in Boolean;
Ignore_Empty_Lines : in Boolean;
Escape_Unknown_Tags : in Boolean);
-- Find the facelet file in one of the facelet directories.
-- Returns the path to be used for reading the facelet file.
function Find_Facelet_Path (Factory : in Facelet_Factory;
Name : in String) return String;
-- Clear the facelet cache
procedure Clear_Cache (Factory : in out Facelet_Factory);
private
use Ada.Strings.Unbounded;
type Facelet is record
Root : ASF.Views.Nodes.Tag_Node_Access;
File : ASF.Views.File_Info_Access;
Modify_Time : Ada.Calendar.Time;
end record;
-- Tag library map indexed on the library namespace.
package Facelet_Maps is new
Ada.Containers.Hashed_Maps (Key_Type => Unbounded_String,
Element_Type => Facelet,
Hash => Ada.Strings.Unbounded.Hash,
Equivalent_Keys => "=");
use Facelet_Maps;
protected type Facelet_Cache is
-- Find the facelet entry associated with the given name.
function Find (Name : in Unbounded_String) return Facelet;
-- Insert or replace the facelet entry associated with the given name.
procedure Insert (Name : in Unbounded_String;
Item : in Facelet);
-- Clear the cache.
procedure Clear;
private
Map : Facelet_Maps.Map;
end Facelet_Cache;
type Facelet_Factory is new Ada.Finalization.Limited_Controlled with record
Paths : Unbounded_String := To_Unbounded_String ("");
-- The facelet cache.
Map : Facelet_Cache;
-- The component factory
Factory : access ASF.Factory.Component_Factory;
-- Whether the unknown tags are escaped using XML escape rules.
Escape_Unknown_Tags : Boolean := True;
-- Whether white spaces can be ignored.
Ignore_White_Spaces : Boolean := True;
-- Whether empty lines should be ignored (when white spaces are kept).
Ignore_Empty_Lines : Boolean := True;
end record;
-- Free the storage held by the factory cache.
overriding
procedure Finalize (Factory : in out Facelet_Factory);
end ASF.Views.Facelets;
|
Fix compilation warning
|
Fix compilation warning
|
Ada
|
apache-2.0
|
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
|
8fe95f8a1fd7c31ad045677d5606537ec85c4704
|
orka_transforms/src/orka-transforms-simd_vectors.ads
|
orka_transforms/src/orka-transforms-simd_vectors.ads
|
-- SPDX-License-Identifier: Apache-2.0
--
-- Copyright (c) 2017 onox <[email protected]>
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
with Ada.Numerics;
generic
type Element_Type is digits <>;
type Vector_Type is array (Index_Homogeneous) of Element_Type;
with function Multiply_Vectors (Left, Right : Vector_Type) return Vector_Type;
with function Add_Vectors (Left, Right : Vector_Type) return Vector_Type;
with function Subtract_Vectors (Left, Right : Vector_Type) return Vector_Type;
with function Minus_Vector (Elements : Vector_Type) return Vector_Type;
with function Absolute_Vector (Elements : Vector_Type) return Vector_Type;
with function Sum (Elements : Vector_Type) return Element_Type;
with function Divide_Or_Zero (Left, Right : Vector_Type) return Vector_Type;
with function Cross_Product (Left, Right : Vector_Type) return Vector_Type;
package Orka.Transforms.SIMD_Vectors is
pragma Pure;
subtype Vector4 is Vector_Type;
type Direction is new Vector4
with Dynamic_Predicate => Direction (W) = 0.0;
type Point is new Vector4
with Dynamic_Predicate => Point (W) = 1.0;
function Zero return Vector4 is
((0.0, 0.0, 0.0, 0.0))
with Inline;
function Zero_Direction return Direction is
((0.0, 0.0, 0.0, 0.0))
with Inline;
function Zero_Point return Point is
((0.0, 0.0, 0.0, 1.0))
with Inline;
function To_Radians (Angle : Element_Type) return Element_Type is
(Angle / 180.0 * Ada.Numerics.Pi);
function To_Degrees (Angle : Element_Type) return Element_Type is
(Angle / Ada.Numerics.Pi * 180.0);
function "=" (Left, Right : Vector_Type) return Boolean;
function "+" (Left, Right : Vector_Type) return Vector_Type renames Add_Vectors;
function "-" (Left, Right : Vector_Type) return Vector_Type renames Subtract_Vectors;
function "-" (Elements : Vector_Type) return Vector_Type renames Minus_Vector;
function "abs" (Elements : Vector_Type) return Vector_Type renames Absolute_Vector;
function "*" (Left, Right : Vector_Type) return Vector_Type renames Multiply_Vectors;
function "*" (Factor : Element_Type; Elements : Vector_Type) return Vector_Type;
function "*" (Elements : Vector_Type; Factor : Element_Type) return Vector_Type;
----------------------------------------------------------------------------
function "*" (Factor : Element_Type; Elements : Direction) return Direction;
function "*" (Elements : Direction; Factor : Element_Type) return Direction;
function "-" (Elements : Point) return Point;
function "+" (Left, Right : Direction) return Direction;
function "+" (Left : Point; Right : Direction) return Point;
function "+" (Left : Direction; Right : Point) return Point;
function "-" (Left, Right : Point) return Direction;
----------------------------------------------------------------------------
function Magnitude2 (Elements : Vector_Type) return Element_Type
with Inline;
function Magnitude (Elements : Vector_Type) return Element_Type;
-- Return the magnitude or length of the vector
function Length (Elements : Vector_Type) return Element_Type renames Magnitude;
-- Return the magnitude or length of the vector
function Normalize (Elements : Vector_Type) return Vector_Type;
-- Return the unit vector of the given vector
function Normalized (Elements : Vector_Type) return Boolean;
-- Return True if the vector is normalized, False otherwise
function Distance (Left, Right : Point) return Element_Type;
-- Return the distance between two points
function Projection (Elements, Direction : Vector_Type) return Vector_Type;
-- Return the projection of a vector in some direction
function Perpendicular (Elements, Direction : Vector_Type) return Vector_Type;
-- Return a vector perpendicular to the projection of the vector in
-- the given direction
function Angle (Left, Right : Vector_Type) return Element_Type;
-- Return the angle in radians between two vectors
function Dot (Left, Right : Vector_Type) return Element_Type;
function Cross (Left, Right : Vector_Type) return Vector_Type renames Cross_Product;
function Slerp
(Left, Right : Vector_Type;
Weight : Element_Type) return Vector_Type
with Pre => Weight in 0.0 .. 1.0,
Post => Normalized (Slerp'Result);
-- Return the interpolated unit vector on the shortest arc
-- between the Left and Right vectors
end Orka.Transforms.SIMD_Vectors;
|
-- SPDX-License-Identifier: Apache-2.0
--
-- Copyright (c) 2017 onox <[email protected]>
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
with Ada.Numerics;
generic
type Element_Type is digits <>;
type Vector_Type is array (Index_Homogeneous) of Element_Type;
with function Multiply_Vectors (Left, Right : Vector_Type) return Vector_Type;
with function Add_Vectors (Left, Right : Vector_Type) return Vector_Type;
with function Subtract_Vectors (Left, Right : Vector_Type) return Vector_Type;
with function Minus_Vector (Elements : Vector_Type) return Vector_Type;
with function Absolute_Vector (Elements : Vector_Type) return Vector_Type;
with function Sum (Elements : Vector_Type) return Element_Type;
with function Divide_Or_Zero (Left, Right : Vector_Type) return Vector_Type;
with function Cross_Product (Left, Right : Vector_Type) return Vector_Type;
package Orka.Transforms.SIMD_Vectors is
pragma Pure;
subtype Vector4 is Vector_Type;
type Direction is new Vector4
with Dynamic_Predicate => Vector4 (Direction) (W) = 0.0;
type Point is new Vector4
with Dynamic_Predicate => Vector4 (Point) (W) = 1.0;
function Zero return Vector4 is
((0.0, 0.0, 0.0, 0.0))
with Inline;
function Zero_Direction return Direction is
((0.0, 0.0, 0.0, 0.0))
with Inline;
function Zero_Point return Point is
((0.0, 0.0, 0.0, 1.0))
with Inline;
function To_Radians (Angle : Element_Type) return Element_Type is
(Angle / 180.0 * Ada.Numerics.Pi);
function To_Degrees (Angle : Element_Type) return Element_Type is
(Angle / Ada.Numerics.Pi * 180.0);
function "=" (Left, Right : Vector_Type) return Boolean;
function "+" (Left, Right : Vector_Type) return Vector_Type renames Add_Vectors;
function "-" (Left, Right : Vector_Type) return Vector_Type renames Subtract_Vectors;
function "-" (Elements : Vector_Type) return Vector_Type renames Minus_Vector;
function "abs" (Elements : Vector_Type) return Vector_Type renames Absolute_Vector;
function "*" (Left, Right : Vector_Type) return Vector_Type renames Multiply_Vectors;
function "*" (Factor : Element_Type; Elements : Vector_Type) return Vector_Type;
function "*" (Elements : Vector_Type; Factor : Element_Type) return Vector_Type;
----------------------------------------------------------------------------
function "*" (Factor : Element_Type; Elements : Direction) return Direction;
function "*" (Elements : Direction; Factor : Element_Type) return Direction;
function "-" (Elements : Point) return Point;
function "+" (Left, Right : Direction) return Direction;
function "+" (Left : Point; Right : Direction) return Point;
function "+" (Left : Direction; Right : Point) return Point;
function "-" (Left, Right : Point) return Direction;
----------------------------------------------------------------------------
function Magnitude2 (Elements : Vector_Type) return Element_Type
with Inline;
function Magnitude (Elements : Vector_Type) return Element_Type;
-- Return the magnitude or length of the vector
function Length (Elements : Vector_Type) return Element_Type renames Magnitude;
-- Return the magnitude or length of the vector
function Normalize (Elements : Vector_Type) return Vector_Type;
-- Return the unit vector of the given vector
function Normalized (Elements : Vector_Type) return Boolean;
-- Return True if the vector is normalized, False otherwise
function Distance (Left, Right : Point) return Element_Type;
-- Return the distance between two points
function Projection (Elements, Direction : Vector_Type) return Vector_Type;
-- Return the projection of a vector in some direction
function Perpendicular (Elements, Direction : Vector_Type) return Vector_Type;
-- Return a vector perpendicular to the projection of the vector in
-- the given direction
function Angle (Left, Right : Vector_Type) return Element_Type;
-- Return the angle in radians between two vectors
function Dot (Left, Right : Vector_Type) return Element_Type;
function Cross (Left, Right : Vector_Type) return Vector_Type renames Cross_Product;
function Slerp
(Left, Right : Vector_Type;
Weight : Element_Type) return Vector_Type
with Pre => Weight in 0.0 .. 1.0,
Post => Normalized (Slerp'Result);
-- Return the interpolated unit vector on the shortest arc
-- between the Left and Right vectors
end Orka.Transforms.SIMD_Vectors;
|
Fix compile error in predicates of types Direction and Point
|
transforms: Fix compile error in predicates of types Direction and Point
Signed-off-by: onox <[email protected]>
|
Ada
|
apache-2.0
|
onox/orka
|
8907659b8a9bebd6ba12ba430ac688877efd4de6
|
src/util-dates-formats.ads
|
src/util-dates-formats.ads
|
-----------------------------------------------------------------------
-- util-dates-formats -- Date Format ala strftime
-- 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.Properties;
-- The <b>Util.Dates.Formats</b> provides a date formatting operation similar to the
-- Unix <b>strftime</b> or the <b>GNAT.Calendar.Time_IO</b>. The localization of month
-- and day labels is however handled through <b>Util.Properties.Bundle</b> (similar to
-- the Java world). Unlike <b>strftime</b>, this allows to have a multi-threaded application
-- that reports dates in several languages. The <b>GNAT.Calendar.Time_IO</b> only supports
-- English and this is the reason why it is not used here.
--
-- The date pattern recognizes the following formats:
--
-- %a The abbreviated weekday name according to the current locale.
-- %A The full weekday name according to the current locale.
-- %b The abbreviated month name according to the current locale.
-- %h Equivalent to %b. (SU)
-- %B The full month name according to the current locale.
-- %c The preferred date and time representation for the current locale.
-- %C The century number (year/100) as a 2-digit integer. (SU)
-- %d The day of the month as a decimal number (range 01 to 31).
-- %D Equivalent to %m/%d/%y
-- %e Like %d, the day of the month as a decimal number,
-- but a leading zero is replaced by a space. (SU)
-- %F Equivalent to %Y-%m-%d (the ISO 8601 date format). (C99)
-- %G The ISO 8601 week-based year
-- %g Like %G, but without century, that is, with a 2-digit year (00-99). (TZ)
-- %H The hour as a decimal number using a 24-hour clock (range 00 to 23).
-- %I The hour as a decimal number using a 12-hour clock (range 01 to 12).
-- %j The day of the year as a decimal number (range 001 to 366).
-- %k The hour (24-hour clock) as a decimal number (range 0 to 23);
-- %l The hour (12-hour clock) as a decimal number (range 1 to 12);
-- %m The month as a decimal number (range 01 to 12).
-- %M The minute as a decimal number (range 00 to 59).
-- %n A newline character. (SU)
-- %p Either "AM" or "PM"
-- %P Like %p but in lowercase: "am" or "pm"
-- %r The time in a.m. or p.m. notation.
-- In the POSIX locale this is equivalent to %I:%M:%S %p. (SU)
-- %R The time in 24-hour notation (%H:%M).
-- %s The number of seconds since the Epoch, that is,
-- since 1970-01-01 00:00:00 UTC. (TZ)
-- %S The second as a decimal number (range 00 to 60).
-- %t A tab character. (SU)
-- %T The time in 24-hour notation (%H:%M:%S). (SU)
-- %u The day of the week as a decimal, range 1 to 7, Monday being 1. See also %w. (SU)
-- %U The week number of the current year as a decimal number, range 00 to 53
-- %V The ISO 8601 week number
-- %w The day of the week as a decimal, range 0 to 6, Sunday being 0. See also %u.
-- %W The week number of the current year as a decimal number, range 00 to 53
-- %x The preferred date representation for the current locale without the time.
-- %X The preferred time representation for the current locale without the date.
-- %y The year as a decimal number without a century (range 00 to 99).
-- %Y The year as a decimal number including the century.
-- %z The time-zone as hour offset from GMT.
-- %Z The timezone or name or abbreviation.
--
-- The following strftime flags are ignored:
--
-- %E Modifier: use alternative format, see below. (SU)
-- %O Modifier: use alternative format, see below. (SU)
--
-- SU: Single Unix Specification
-- C99: C99 standard, POSIX.1-2001
--
-- See strftime (3) manual page
package Util.Dates.Formats is
-- Month labels.
MONTH_NAME_PREFIX : constant String := "util.month";
-- Day labels.
DAY_NAME_PREFIX : constant String := "util.day";
-- Short month/day suffix.
SHORT_SUFFIX : constant String := ".short";
-- Long month/day suffix.
LONG_SUFFIX : constant String := ".long";
-- The date time pattern name to be used for the %x representation.
-- This property name is searched in the bundle to find the localized date time pattern.
DATE_TIME_LOCALE_NAME : constant String := "util.datetime.pattern";
-- The default date pattern for %c (English).
DATE_TIME_DEFAULT_PATTERN : constant String := "%a %b %_d %T %Y";
-- The date pattern to be used for the %x representation.
-- This property name is searched in the bundle to find the localized date pattern.
DATE_LOCALE_NAME : constant String := "util.date.pattern";
-- The default date pattern for %x (English).
DATE_DEFAULT_PATTERN : constant String := "%m/%d/%y";
-- The time pattern to be used for the %X representation.
-- This property name is searched in the bundle to find the localized time pattern.
TIME_LOCALE_NAME : constant String := "util.time.pattern";
-- The default time pattern for %X (English).
TIME_DEFAULT_PATTERN : constant String := "%T %Y";
AM_NAME : constant String := "util.date.am";
PM_NAME : constant String := "util.date.pm";
AM_DEFAULT : constant String := "AM";
PM_DEFAULT : constant String := "PM";
-- Format the date passed in <b>Date</b> using the date pattern specified in <b>Pattern</b>.
-- The date pattern is similar to the Unix <b>strftime</b> operation.
--
-- For month and day of week strings, use the resource bundle passed in <b>Bundle</b>.
-- Append the formatted date in the <b>Into</b> string.
procedure Format (Into : in out Ada.Strings.Unbounded.Unbounded_String;
Pattern : in String;
Date : in Date_Record;
Bundle : in Util.Properties.Manager'Class);
-- Format the date passed in <b>Date</b> using the date pattern specified in <b>Pattern</b>.
-- For month and day of week strings, use the resource bundle passed in <b>Bundle</b>.
-- Append the formatted date in the <b>Into</b> string.
procedure Format (Into : in out Ada.Strings.Unbounded.Unbounded_String;
Pattern : in String;
Date : in Ada.Calendar.Time;
Bundle : in Util.Properties.Manager'Class);
function Format (Pattern : in String;
Date : in Ada.Calendar.Time;
Bundle : in Util.Properties.Manager'Class) return String;
-- Append the localized month string in the <b>Into</b> string.
-- The month string is found in the resource bundle under the name:
-- util.month<month number>.short
-- util.month<month number>.long
-- If the month string is not found, the month is displayed as a number.
procedure Append_Month (Into : in out Ada.Strings.Unbounded.Unbounded_String;
Month : in Ada.Calendar.Month_Number;
Bundle : in Util.Properties.Manager'Class;
Short : in Boolean := True);
-- Append the localized month string in the <b>Into</b> string.
-- The month string is found in the resource bundle under the name:
-- util.month<month number>.short
-- util.month<month number>.long
-- If the month string is not found, the month is displayed as a number.
procedure Append_Day (Into : in out Ada.Strings.Unbounded.Unbounded_String;
Day : in Ada.Calendar.Formatting.Day_Name;
Bundle : in Util.Properties.Manager'Class;
Short : in Boolean := True);
-- Append a number with padding if necessary
procedure Append_Number (Into : in out Ada.Strings.Unbounded.Unbounded_String;
Value : in Natural;
Padding : in Character;
Length : in Natural := 2);
-- Append the timezone offset
procedure Append_Time_Offset (Into : in out Ada.Strings.Unbounded.Unbounded_String;
Offset : in Ada.Calendar.Time_Zones.Time_Offset);
end Util.Dates.Formats;
|
-----------------------------------------------------------------------
-- util-dates-formats -- Date Format ala strftime
-- 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 Ada.Strings.Unbounded;
with Util.Properties;
-- == Localized date formatting ==
-- The `Util.Dates.Formats` provides a date formatting operation similar to the
-- Unix `strftime` or the `GNAT.Calendar.Time_IO`. The localization of month
-- and day labels is however handled through `Util.Properties.Bundle` (similar to
-- the Java world). Unlike `strftime`, this allows to have a multi-threaded application
-- that reports dates in several languages. The `GNAT.Calendar.Time_IO` only supports
-- English and this is the reason why it is not used here.
--
-- The date pattern recognizes the following formats:
--
-- | Format | Description |
-- | --- | ---------- |
-- | %a | The abbreviated weekday name according to the current locale.
-- | %A | The full weekday name according to the current locale.
-- | %b | The abbreviated month name according to the current locale.
-- | %h | Equivalent to %b. (SU)
-- | %B | The full month name according to the current locale.
-- | %c | The preferred date and time representation for the current locale.
-- | %C | The century number (year/100) as a 2-digit integer. (SU)
-- | %d | The day of the month as a decimal number (range 01 to 31).
-- | %D | Equivalent to %m/%d/%y
-- | %e | Like %d, the day of the month as a decimal number,
-- | | but a leading zero is replaced by a space. (SU)
-- | %F | Equivalent to %Y\-%m\-%d (the ISO 8601 date format). (C99)
-- | %G | The ISO 8601 week-based year
-- | %H | The hour as a decimal number using a 24-hour clock (range 00 to 23).
-- | %I | The hour as a decimal number using a 12-hour clock (range 01 to 12).
-- | %j | The day of the year as a decimal number (range 001 to 366).
-- | %k | The hour (24 hour clock) as a decimal number (range 0 to 23);
-- | %l | The hour (12 hour clock) as a decimal number (range 1 to 12);
-- | %m | The month as a decimal number (range 01 to 12).
-- | %M | The minute as a decimal number (range 00 to 59).
-- | %n | A newline character. (SU)
-- | %p | Either "AM" or "PM"
-- | %P | Like %p but in lowercase: "am" or "pm"
-- | %r | The time in a.m. or p.m. notation.
-- | | In the POSIX locale this is equivalent to %I:%M:%S %p. (SU)
-- | %R | The time in 24 hour notation (%H:%M).
-- | %s | The number of seconds since the Epoch, that is,
-- | | since 1970\-01\-01 00:00:00 UTC. (TZ)
-- | %S | The second as a decimal number (range 00 to 60).
-- | %t | A tab character. (SU)
-- | %T | The time in 24 hour notation (%H:%M:%S). (SU)
-- | %u | The day of the week as a decimal, range 1 to 7,
-- | | Monday being 1. See also %w. (SU)
-- | %U | The week number of the current year as a decimal
-- | | number, range 00 to 53
-- | %V | The ISO 8601 week number
-- | %w | The day of the week as a decimal, range 0 to 6,
-- | | Sunday being 0. See also %u.
-- | %W | The week number of the current year as a decimal number,
-- | | range 00 to 53
-- | %x | The preferred date representation for the current locale
-- | | without the time.
-- | %X | The preferred time representation for the current locale
-- | | without the date.
-- | %y | The year as a decimal number without a century (range 00 to 99).
-- | %Y | The year as a decimal number including the century.
-- | %z | The timezone as hour offset from GMT.
-- | %Z | The timezone or name or abbreviation.
--
-- The following strftime flags are ignored:
--
-- %E Modifier: use alternative format, see below. (SU)
-- %O Modifier: use alternative format, see below. (SU)
--
-- SU: Single Unix Specification
-- C99: C99 standard, POSIX.1-2001
--
-- See strftime (3) manual page
package Util.Dates.Formats is
-- Month labels.
MONTH_NAME_PREFIX : constant String := "util.month";
-- Day labels.
DAY_NAME_PREFIX : constant String := "util.day";
-- Short month/day suffix.
SHORT_SUFFIX : constant String := ".short";
-- Long month/day suffix.
LONG_SUFFIX : constant String := ".long";
-- The date time pattern name to be used for the %x representation.
-- This property name is searched in the bundle to find the localized date time pattern.
DATE_TIME_LOCALE_NAME : constant String := "util.datetime.pattern";
-- The default date pattern for %c (English).
DATE_TIME_DEFAULT_PATTERN : constant String := "%a %b %_d %T %Y";
-- The date pattern to be used for the %x representation.
-- This property name is searched in the bundle to find the localized date pattern.
DATE_LOCALE_NAME : constant String := "util.date.pattern";
-- The default date pattern for %x (English).
DATE_DEFAULT_PATTERN : constant String := "%m/%d/%y";
-- The time pattern to be used for the %X representation.
-- This property name is searched in the bundle to find the localized time pattern.
TIME_LOCALE_NAME : constant String := "util.time.pattern";
-- The default time pattern for %X (English).
TIME_DEFAULT_PATTERN : constant String := "%T %Y";
AM_NAME : constant String := "util.date.am";
PM_NAME : constant String := "util.date.pm";
AM_DEFAULT : constant String := "AM";
PM_DEFAULT : constant String := "PM";
-- Format the date passed in <b>Date</b> using the date pattern specified in <b>Pattern</b>.
-- The date pattern is similar to the Unix <b>strftime</b> operation.
--
-- For month and day of week strings, use the resource bundle passed in <b>Bundle</b>.
-- Append the formatted date in the <b>Into</b> string.
procedure Format (Into : in out Ada.Strings.Unbounded.Unbounded_String;
Pattern : in String;
Date : in Date_Record;
Bundle : in Util.Properties.Manager'Class);
-- Format the date passed in <b>Date</b> using the date pattern specified in <b>Pattern</b>.
-- For month and day of week strings, use the resource bundle passed in <b>Bundle</b>.
-- Append the formatted date in the <b>Into</b> string.
procedure Format (Into : in out Ada.Strings.Unbounded.Unbounded_String;
Pattern : in String;
Date : in Ada.Calendar.Time;
Bundle : in Util.Properties.Manager'Class);
function Format (Pattern : in String;
Date : in Ada.Calendar.Time;
Bundle : in Util.Properties.Manager'Class) return String;
-- Append the localized month string in the <b>Into</b> string.
-- The month string is found in the resource bundle under the name:
-- util.month<month number>.short
-- util.month<month number>.long
-- If the month string is not found, the month is displayed as a number.
procedure Append_Month (Into : in out Ada.Strings.Unbounded.Unbounded_String;
Month : in Ada.Calendar.Month_Number;
Bundle : in Util.Properties.Manager'Class;
Short : in Boolean := True);
-- Append the localized month string in the <b>Into</b> string.
-- The month string is found in the resource bundle under the name:
-- util.month<month number>.short
-- util.month<month number>.long
-- If the month string is not found, the month is displayed as a number.
procedure Append_Day (Into : in out Ada.Strings.Unbounded.Unbounded_String;
Day : in Ada.Calendar.Formatting.Day_Name;
Bundle : in Util.Properties.Manager'Class;
Short : in Boolean := True);
-- Append a number with padding if necessary
procedure Append_Number (Into : in out Ada.Strings.Unbounded.Unbounded_String;
Value : in Natural;
Padding : in Character;
Length : in Natural := 2);
-- Append the timezone offset
procedure Append_Time_Offset (Into : in out Ada.Strings.Unbounded.Unbounded_String;
Offset : in Ada.Calendar.Time_Zones.Time_Offset);
end Util.Dates.Formats;
|
Add and update the documentation
|
Add and update the documentation
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
2e0fa20c3ab5fc7f7312ac917e3a997f42e154ef
|
mat/src/mat-readers-marshaller.adb
|
mat/src/mat-readers-marshaller.adb
|
-----------------------------------------------------------------------
-- Ipc -- Ipc channel between profiler tool and application --
-- 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;
with System; use System;
with System.Address_To_Access_Conversions;
with System.Storage_Elements;
with Util.Log.Loggers;
with Interfaces; use Interfaces;
package body MAT.Readers.Marshaller is
use System.Storage_Elements;
-- The logger
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("MAT.Readers.Marshaller");
package Uint8_Access is new System.Address_To_Access_Conversions (MAT.Types.Uint8);
package Uint32_Access is new System.Address_To_Access_Conversions (MAT.Types.Uint32);
function Get_Raw_Uint32 (Buf : System.Address) return MAT.Types.Uint32 is
use Uint32_Access;
P : constant Object_Pointer := To_Pointer (Buf);
begin
return P.all;
end Get_Raw_Uint32;
-- ------------------------------
-- Get an 8-bit value from the buffer.
-- ------------------------------
function Get_Uint8 (Buffer : in Buffer_Ptr) return MAT.Types.Uint8 is
use Uint8_Access;
P : constant Object_Pointer := To_Pointer (Buffer.Current);
begin
if Buffer.Size = 0 then
Log.Error ("Not enough data to get a uint8");
raise Buffer_Underflow_Error;
end if;
Buffer.Size := Buffer.Size - 1;
Buffer.Current := Buffer.Current + Storage_Offset (1);
return P.all;
end Get_Uint8;
-- ------------------------------
-- Get a 16-bit value either from big-endian or little endian.
-- ------------------------------
function Get_Uint16 (Buffer : in Buffer_Ptr) return MAT.Types.Uint16 is
use Uint8_Access;
High : Object_Pointer;
Low : Object_Pointer;
begin
if Buffer.Size <= 1 then
Log.Error ("Not enough data to get a uint16");
raise Buffer_Underflow_Error;
end if;
if Buffer.Endian = LITTLE_ENDIAN then
Low := To_Pointer (Buffer.Current);
High := To_Pointer (Buffer.Current + Storage_Offset (1));
else
High := To_Pointer (Buffer.Current);
Low := To_Pointer (Buffer.Current + Storage_Offset (1));
end if;
Buffer.Size := Buffer.Size - 2;
Buffer.Current := Buffer.Current + Storage_Offset (2);
return MAT.Types.Uint16 (High.all) * 256 + MAT.Types.Uint16 (Low.all);
end Get_Uint16;
function Get_Uint32 (Buffer : in Buffer_Ptr) return MAT.Types.Uint32 is
use Uint32_Access;
Low, High : MAT.Types.Uint16;
begin
if Buffer.Size < 4 then
Log.Error ("Not enough data to get a uint32");
raise Buffer_Underflow_Error;
end if;
if Buffer.Endian = LITTLE_ENDIAN then
Low := Get_Uint16 (Buffer);
High := Get_Uint16 (Buffer);
else
High := Get_Uint16 (Buffer);
Low := Get_Uint16 (Buffer);
end if;
return Interfaces.Shift_Left (MAT.Types.Uint32 (High), 16) + MAT.Types.Uint32 (Low);
end Get_Uint32;
function Get_Uint64 (Buffer : in Buffer_Ptr) return MAT.Types.Uint64 is
Val : constant MAT.Types.Uint64 := MAT.Types.Uint64 (Get_Uint32 (Buffer));
begin
return Val + MAT.Types.Uint64 (Get_Uint32 (Buffer)) * 2**32;
end Get_Uint64;
function Get_Target_Value (Msg : in Buffer_Ptr;
Kind : in MAT.Events.Attribute_Type) return Target_Type is
begin
case Kind is
when MAT.Events.T_UINT8 =>
return Target_Type (Get_Uint8 (Msg));
when MAT.Events.T_UINT16 =>
return Target_Type (Get_Uint16 (Msg));
when MAT.Events.T_UINT32 =>
return Target_Type (Get_Uint32 (Msg));
when MAT.Events.T_UINT64 =>
return Target_Type (Get_Uint64 (Msg));
when others =>
Log.Error ("Invalid attribute type {0}",
MAT.Events.Attribute_Type'Image (Kind));
return 0;
end case;
end Get_Target_Value;
-- ------------------------------
-- Extract a string from the buffer. The string starts with a byte that
-- indicates the string length.
-- ------------------------------
function Get_String (Buffer : in Buffer_Ptr) return String is
Len : constant MAT.Types.Uint8 := Get_Uint8 (Buffer);
Result : String (1 .. Natural (Len));
begin
for I in Result'Range loop
Result (I) := Character'Val (Get_Uint8 (Buffer));
end loop;
return Result;
end Get_String;
-- ------------------------------
-- Extract a string from the buffer. The string starts with a byte that
-- indicates the string length.
-- ------------------------------
function Get_String (Msg : in Buffer_Ptr) return Ada.Strings.Unbounded.Unbounded_String is
begin
return Ada.Strings.Unbounded.To_Unbounded_String (Get_String (Msg));
end Get_String;
-- ------------------------------
-- Skip the given number of bytes from the message.
-- ------------------------------
procedure Skip (Buffer : in Buffer_Ptr;
Size : in Natural) is
begin
Buffer.Size := Buffer.Size - Size;
Buffer.Current := Buffer.Current + Storage_Offset (Size);
end Skip;
function Get_Target_Size (Msg : in Buffer_Ptr;
Kind : in MAT.Events.Attribute_Type) return MAT.Types.Target_Size is
function Get_Value is new Get_Target_Value (MAT.Types.Target_Size);
begin
return Get_Value (Msg, Kind);
end Get_Target_Size;
function Get_Target_Addr (Msg : in Buffer_Ptr;
Kind : in MAT.Events.Attribute_Type) return MAT.Types.Target_Addr is
function Get_Value is new Get_Target_Value (MAT.Types.Target_Addr);
begin
return Get_Value (Msg, Kind);
end Get_Target_Addr;
function Get_Target_Uint32 (Msg : in Buffer_Ptr;
Kind : in MAT.Events.Attribute_Type) return MAT.Types.Uint32 is
function Get_Value is new Get_Target_Value (MAT.Types.Target_Addr);
begin
return Get_Value (Msg, Kind);
end Get_Target_Uint32;
end MAT.Readers.Marshaller;
|
-----------------------------------------------------------------------
-- Ipc -- Ipc channel between profiler tool and application --
-- 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;
with System; use System;
with System.Address_To_Access_Conversions;
with System.Storage_Elements;
with Util.Log.Loggers;
with Interfaces; use Interfaces;
package body MAT.Readers.Marshaller is
use System.Storage_Elements;
-- The logger
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("MAT.Readers.Marshaller");
package Uint8_Access is new System.Address_To_Access_Conversions (MAT.Types.Uint8);
package Uint32_Access is new System.Address_To_Access_Conversions (MAT.Types.Uint32);
function Get_Raw_Uint32 (Buf : System.Address) return MAT.Types.Uint32 is
use Uint32_Access;
P : constant Object_Pointer := To_Pointer (Buf);
begin
return P.all;
end Get_Raw_Uint32;
-- ------------------------------
-- Get an 8-bit value from the buffer.
-- ------------------------------
function Get_Uint8 (Buffer : in Buffer_Ptr) return MAT.Types.Uint8 is
use Uint8_Access;
P : constant Object_Pointer := To_Pointer (Buffer.Current);
begin
if Buffer.Size = 0 then
Log.Error ("Not enough data to get a uint8");
raise Buffer_Underflow_Error;
end if;
Buffer.Size := Buffer.Size - 1;
Buffer.Current := Buffer.Current + Storage_Offset (1);
return P.all;
end Get_Uint8;
-- ------------------------------
-- Get a 16-bit value either from big-endian or little endian.
-- ------------------------------
function Get_Uint16 (Buffer : in Buffer_Ptr) return MAT.Types.Uint16 is
use Uint8_Access;
High : Object_Pointer;
Low : Object_Pointer;
begin
if Buffer.Size <= 1 then
Log.Error ("Not enough data to get a uint16");
raise Buffer_Underflow_Error;
end if;
if Buffer.Endian = LITTLE_ENDIAN then
Low := To_Pointer (Buffer.Current);
High := To_Pointer (Buffer.Current + Storage_Offset (1));
else
High := To_Pointer (Buffer.Current);
Low := To_Pointer (Buffer.Current + Storage_Offset (1));
end if;
Buffer.Size := Buffer.Size - 2;
Buffer.Current := Buffer.Current + Storage_Offset (2);
return MAT.Types.Uint16 (High.all) * 256 + MAT.Types.Uint16 (Low.all);
end Get_Uint16;
-- ------------------------------
-- Get a 32-bit value either from big-endian or little endian.
-- ------------------------------
function Get_Uint32 (Buffer : in Buffer_Ptr) return MAT.Types.Uint32 is
use Uint32_Access;
Low, High : MAT.Types.Uint16;
begin
if Buffer.Size < 4 then
Log.Error ("Not enough data to get a uint32");
raise Buffer_Underflow_Error;
end if;
if Buffer.Endian = LITTLE_ENDIAN then
Low := Get_Uint16 (Buffer);
High := Get_Uint16 (Buffer);
else
High := Get_Uint16 (Buffer);
Low := Get_Uint16 (Buffer);
end if;
return Interfaces.Shift_Left (MAT.Types.Uint32 (High), 16) + MAT.Types.Uint32 (Low);
end Get_Uint32;
function Get_Uint64 (Buffer : in Buffer_Ptr) return MAT.Types.Uint64 is
Val : constant MAT.Types.Uint64 := MAT.Types.Uint64 (Get_Uint32 (Buffer));
begin
return Val + MAT.Types.Uint64 (Get_Uint32 (Buffer)) * 2**32;
end Get_Uint64;
function Get_Target_Value (Msg : in Buffer_Ptr;
Kind : in MAT.Events.Attribute_Type) return Target_Type is
begin
case Kind is
when MAT.Events.T_UINT8 =>
return Target_Type (Get_Uint8 (Msg));
when MAT.Events.T_UINT16 =>
return Target_Type (Get_Uint16 (Msg));
when MAT.Events.T_UINT32 =>
return Target_Type (Get_Uint32 (Msg));
when MAT.Events.T_UINT64 =>
return Target_Type (Get_Uint64 (Msg));
when others =>
Log.Error ("Invalid attribute type {0}",
MAT.Events.Attribute_Type'Image (Kind));
return 0;
end case;
end Get_Target_Value;
-- ------------------------------
-- Extract a string from the buffer. The string starts with a byte that
-- indicates the string length.
-- ------------------------------
function Get_String (Buffer : in Buffer_Ptr) return String is
Len : constant MAT.Types.Uint8 := Get_Uint8 (Buffer);
Result : String (1 .. Natural (Len));
begin
for I in Result'Range loop
Result (I) := Character'Val (Get_Uint8 (Buffer));
end loop;
return Result;
end Get_String;
-- ------------------------------
-- Extract a string from the buffer. The string starts with a byte that
-- indicates the string length.
-- ------------------------------
function Get_String (Msg : in Buffer_Ptr) return Ada.Strings.Unbounded.Unbounded_String is
begin
return Ada.Strings.Unbounded.To_Unbounded_String (Get_String (Msg));
end Get_String;
-- ------------------------------
-- Skip the given number of bytes from the message.
-- ------------------------------
procedure Skip (Buffer : in Buffer_Ptr;
Size : in Natural) is
begin
Buffer.Size := Buffer.Size - Size;
Buffer.Current := Buffer.Current + Storage_Offset (Size);
end Skip;
function Get_Target_Size (Msg : in Buffer_Ptr;
Kind : in MAT.Events.Attribute_Type) return MAT.Types.Target_Size is
function Get_Value is new Get_Target_Value (MAT.Types.Target_Size);
begin
return Get_Value (Msg, Kind);
end Get_Target_Size;
function Get_Target_Addr (Msg : in Buffer_Ptr;
Kind : in MAT.Events.Attribute_Type) return MAT.Types.Target_Addr is
function Get_Value is new Get_Target_Value (MAT.Types.Target_Addr);
begin
return Get_Value (Msg, Kind);
end Get_Target_Addr;
function Get_Target_Uint32 (Msg : in Buffer_Ptr;
Kind : in MAT.Events.Attribute_Type) return MAT.Types.Uint32 is
function Get_Value is new Get_Target_Value (MAT.Types.Target_Addr);
begin
return Get_Value (Msg, Kind);
end Get_Target_Uint32;
end MAT.Readers.Marshaller;
|
Document Get_Uint32
|
Document Get_Uint32
|
Ada
|
apache-2.0
|
stcarrez/mat,stcarrez/mat,stcarrez/mat
|
5c66889ba7f990d2c18ef46309519e41129c9622
|
src/ado-drivers-connections.adb
|
src/ado-drivers-connections.adb
|
-----------------------------------------------------------------------
-- ADO Drivers -- Database Drivers
-- Copyright (C) 2010, 2011, 2012, 2013, 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 Util.Log.Loggers;
with Util.Systems.DLLs;
with System;
with Ada.Containers.Doubly_Linked_Lists;
with Ada.Exceptions;
package body ADO.Drivers.Connections is
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("ADO.Drivers.Connections");
-- Load the database driver.
procedure Load_Driver (Name : in String);
-- ------------------------------
-- Get the driver index that corresponds to the driver for this database connection string.
-- ------------------------------
function Get_Driver (Config : in Configuration) return Driver_Index is
Driver : constant Driver_Access := Get_Driver (Config.Get_Driver);
begin
if Driver = null then
return Driver_Index'First;
else
return Driver.Get_Driver_Index;
end if;
end Get_Driver;
-- ------------------------------
-- Create a new connection using the configuration parameters.
-- ------------------------------
procedure Create_Connection (Config : in Configuration'Class;
Result : in out Ref.Ref'Class) is
Driver : Driver_Access;
Log_URI : constant String := Config.Get_Log_URI;
begin
Driver := Get_Driver (Config.Get_Driver);
if Driver = null then
Log.Error ("No driver found for connection {0}", Log_URI);
raise ADO.Configs.Connection_Error with
"Data source is not initialized: driver '" & Config.Get_Driver & "' not found";
end if;
Driver.Create_Connection (Config, Result);
if Result.Is_Null then
Log.Error ("Driver {0} failed to create connection {0}",
Driver.Name.all, Log_URI);
raise ADO.Configs.Connection_Error with
"Data source is not initialized: driver error";
end if;
Log.Info ("Created connection to '{0}' -> {1}", Log_URI, Result.Value.Ident);
exception
when others =>
Log.Info ("Failed to create connection to '{0}'", Log_URI);
raise;
end Create_Connection;
-- Get the database driver index.
function Get_Driver_Index (Database : in Database_Connection) return Driver_Index is
Driver : constant ADO.Drivers.Connections.Driver_Access
:= Database_Connection'Class (Database).Get_Driver;
begin
return Driver.Get_Driver_Index;
end Get_Driver_Index;
package Driver_List is
new Ada.Containers.Doubly_Linked_Lists (Element_Type => Driver_Access);
Next_Index : Driver_Index := 1;
Drivers : Driver_List.List;
-- ------------------------------
-- Get the driver unique index.
-- ------------------------------
function Get_Driver_Index (D : in Driver) return Driver_Index is
begin
return D.Index;
end Get_Driver_Index;
-- ------------------------------
-- Get the driver name.
-- ------------------------------
function Get_Driver_Name (D : in Driver) return String is
begin
return D.Name.all;
end Get_Driver_Name;
-- ------------------------------
-- Register a database driver.
-- ------------------------------
procedure Register (Driver : in Driver_Access) is
begin
Log.Info ("Register driver {0}", Driver.Name.all);
Driver_List.Prepend (Container => Drivers, New_Item => Driver);
Driver.Index := Next_Index;
Next_Index := Next_Index + 1;
end Register;
-- ------------------------------
-- Load the database driver.
-- ------------------------------
procedure Load_Driver (Name : in String) is
Lib : constant String := "libada_ado_" & Name & Util.Systems.DLLs.Extension;
Symbol : constant String := "ado__drivers__connections__" & Name & "__initialize";
Handle : Util.Systems.DLLs.Handle;
Addr : System.Address;
begin
Log.Info ("Loading driver {0}", Lib);
Handle := Util.Systems.DLLs.Load (Lib);
Addr := Util.Systems.DLLs.Get_Symbol (Handle, Symbol);
declare
procedure Init;
pragma Import (C, Init);
for Init'Address use Addr;
begin
Init;
end;
exception
when Util.Systems.DLLs.Not_Found =>
Log.Error ("Driver for {0} was loaded but does not define the initialization symbol",
Name);
when E : Util.Systems.DLLs.Load_Error =>
Log.Error ("Driver for {0} was not found: {1}",
Name, Ada.Exceptions.Exception_Message (E));
end Load_Driver;
-- ------------------------------
-- Get a database driver given its name.
-- ------------------------------
function Get_Driver (Name : in String) return Driver_Access is
begin
Log.Info ("Get driver {0}", Name);
for Retry in 0 .. 2 loop
if Retry = 1 then
ADO.Drivers.Initialize;
elsif Retry = 2 then
Load_Driver (Name);
end if;
declare
Iter : Driver_List.Cursor := Driver_List.First (Drivers);
begin
while Driver_List.Has_Element (Iter) loop
declare
D : constant Driver_Access := Driver_List.Element (Iter);
begin
if Name = D.Name.all then
return D;
end if;
end;
Driver_List.Next (Iter);
end loop;
end;
end loop;
return null;
end Get_Driver;
end ADO.Drivers.Connections;
|
-----------------------------------------------------------------------
-- ADO Drivers -- Database Drivers
-- Copyright (C) 2010, 2011, 2012, 2013, 2015, 2016, 2017, 2018 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Log.Loggers;
with Util.Systems.DLLs;
with System;
with Ada.Containers.Doubly_Linked_Lists;
with Ada.Exceptions;
package body ADO.Drivers.Connections is
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("ADO.Drivers.Connections");
-- Load the database driver.
procedure Load_Driver (Name : in String);
-- ------------------------------
-- Get the driver index that corresponds to the driver for this database connection string.
-- ------------------------------
function Get_Driver (Config : in Configuration) return Driver_Index is
Driver : constant Driver_Access := Get_Driver (Config.Get_Driver);
begin
if Driver = null then
return Driver_Index'First;
else
return Driver.Get_Driver_Index;
end if;
end Get_Driver;
-- ------------------------------
-- Create a new connection using the configuration parameters.
-- ------------------------------
procedure Create_Connection (Config : in Configuration'Class;
Result : in out Ref.Ref'Class) is
Driver : Driver_Access;
Log_URI : constant String := Config.Get_Log_URI;
begin
Driver := Get_Driver (Config.Get_Driver);
if Driver = null then
Log.Error ("No driver found for connection {0}", Log_URI);
raise ADO.Configs.Connection_Error with
"Data source is not initialized: driver '" & Config.Get_Driver & "' not found";
end if;
Driver.Create_Connection (Config, Result);
if Result.Is_Null then
Log.Error ("Driver {0} failed to create connection {0}",
Driver.Name.all, Log_URI);
raise ADO.Configs.Connection_Error with
"Data source is not initialized: driver error";
end if;
Log.Info ("Created connection to '{0}' -> {1}", Log_URI, Result.Value.Ident);
exception
when others =>
Log.Info ("Failed to create connection to '{0}'", Log_URI);
raise;
end Create_Connection;
-- Get the database driver index.
function Get_Driver_Index (Database : in Database_Connection) return Driver_Index is
Driver : constant ADO.Drivers.Connections.Driver_Access
:= Database_Connection'Class (Database).Get_Driver;
begin
return Driver.Get_Driver_Index;
end Get_Driver_Index;
package Driver_List is
new Ada.Containers.Doubly_Linked_Lists (Element_Type => Driver_Access);
Next_Index : Driver_Index := 1;
Drivers : Driver_List.List;
-- ------------------------------
-- Get the driver unique index.
-- ------------------------------
function Get_Driver_Index (D : in Driver) return Driver_Index is
begin
return D.Index;
end Get_Driver_Index;
-- ------------------------------
-- Get the driver name.
-- ------------------------------
function Get_Driver_Name (D : in Driver) return String is
begin
return D.Name.all;
end Get_Driver_Name;
-- ------------------------------
-- Register a database driver.
-- ------------------------------
procedure Register (Driver : in Driver_Access) is
begin
Log.Info ("Register driver {0}", Driver.Name.all);
Driver_List.Prepend (Container => Drivers, New_Item => Driver);
Driver.Index := Next_Index;
Next_Index := Next_Index + 1;
end Register;
-- ------------------------------
-- Load the database driver.
-- ------------------------------
procedure Load_Driver (Name : in String) is
Lib : constant String := "libada_ado_" & Name & Util.Systems.DLLs.Extension;
Symbol : constant String := "ado__drivers__connections__" & Name & "__initialize";
Handle : Util.Systems.DLLs.Handle;
Addr : System.Address;
begin
Log.Debug ("Loading driver {0}", Lib);
Handle := Util.Systems.DLLs.Load (Lib);
Addr := Util.Systems.DLLs.Get_Symbol (Handle, Symbol);
declare
procedure Init;
pragma Import (C, Init);
for Init'Address use Addr;
begin
Log.Info ("Initialising driver {0}", Lib);
Init;
end;
exception
when Util.Systems.DLLs.Not_Found =>
Log.Error ("Driver for {0} was loaded but does not define the initialization symbol",
Name);
when E : Util.Systems.DLLs.Load_Error =>
Log.Error ("Driver for {0} was not found: {1}",
Name, Ada.Exceptions.Exception_Message (E));
end Load_Driver;
-- ------------------------------
-- Get a database driver given its name.
-- ------------------------------
function Get_Driver (Name : in String) return Driver_Access is
begin
Log.Debug ("Get driver {0}", Name);
if Name'Length = 0 then
return null;
end if;
for Retry in 0 .. 2 loop
if Retry = 1 then
ADO.Drivers.Initialize;
elsif Retry = 2 then
Load_Driver (Name);
end if;
declare
Iter : Driver_List.Cursor := Driver_List.First (Drivers);
begin
while Driver_List.Has_Element (Iter) loop
declare
D : constant Driver_Access := Driver_List.Element (Iter);
begin
if Name = D.Name.all then
return D;
end if;
end;
Driver_List.Next (Iter);
end loop;
end;
end loop;
return null;
end Get_Driver;
end ADO.Drivers.Connections;
|
Update the logs for better trouble shotting
|
Update the logs for better trouble shotting
|
Ada
|
apache-2.0
|
stcarrez/ada-ado
|
b85aa6d2bc1ebc3ba53e406fe02da6a882d8e1e1
|
src/natools-s_expressions-printers.adb
|
src/natools-s_expressions-printers.adb
|
------------------------------------------------------------------------------
-- Copyright (c) 2013-2014, Natacha Porté --
-- --
-- Permission to use, copy, modify, and distribute this software for any --
-- purpose with or without fee is hereby granted, provided that the above --
-- copyright notice and this permission notice appear in all copies. --
-- --
-- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES --
-- WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF --
-- MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR --
-- ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES --
-- WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN --
-- ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF --
-- OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. --
------------------------------------------------------------------------------
with Natools.S_Expressions.Encodings;
package body Natools.S_Expressions.Printers is
overriding procedure Open_List (Output : in out Canonical) is
begin
Output.Stream.Write ((0 => Encodings.List_Begin));
end Open_List;
overriding procedure Append_Atom (Output : in out Canonical;
Data : in Atom)
is
Length_Image : constant String := Count'Image (Data'Length);
Length_Data : Atom (0 .. Length_Image'Length);
begin
Length_Data (0 .. Length_Image'Length - 1) := To_Atom (Length_Image);
Length_Data (Length_Data'Last) := Encodings.Verbatim_Begin;
Output.Stream.Write (Length_Data (1 .. Length_Data'Last));
Output.Stream.Write (Data);
end Append_Atom;
overriding procedure Close_List (Output : in out Canonical) is
begin
Output.Stream.Write ((0 => Encodings.List_End));
end Close_List;
procedure Transfer
(Source : in out Descriptor'Class;
Target : in out Printer'Class;
Check_Level : in Boolean := False)
is
procedure Print_Atom (Data : in Atom);
procedure Print_Atom (Data : in Atom) is
begin
Target.Append_Atom (Data);
end Print_Atom;
Event : Events.Event := Source.Current_Event;
Starting_Level : constant Natural := Source.Current_Level;
begin
loop
case Event is
when Events.Error | Events.End_Of_Input =>
exit;
when Events.Open_List =>
Target.Open_List;
when Events.Close_List =>
exit when Check_Level
and then Source.Current_Level < Starting_Level;
Target.Close_List;
when Events.Add_Atom =>
Source.Query_Atom (Print_Atom'Access);
end case;
Source.Next (Event);
end loop;
end Transfer;
end Natools.S_Expressions.Printers;
|
------------------------------------------------------------------------------
-- Copyright (c) 2013-2014, Natacha Porté --
-- --
-- Permission to use, copy, modify, and distribute this software for any --
-- purpose with or without fee is hereby granted, provided that the above --
-- copyright notice and this permission notice appear in all copies. --
-- --
-- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES --
-- WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF --
-- MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR --
-- ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES --
-- WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN --
-- ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF --
-- OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. --
------------------------------------------------------------------------------
with Natools.S_Expressions.Encodings;
package body Natools.S_Expressions.Printers is
overriding procedure Open_List (Output : in out Canonical) is
begin
Output.Stream.Write ((0 => Encodings.List_Begin));
end Open_List;
overriding procedure Append_Atom (Output : in out Canonical;
Data : in Atom)
is
Length_Image : constant String := Count'Image (Data'Length);
Length_Data : Atom (0 .. Length_Image'Length);
begin
Length_Data (0 .. Length_Image'Length - 1) := To_Atom (Length_Image);
Length_Data (Length_Data'Last) := Encodings.Verbatim_Begin;
Output.Stream.Write (Length_Data (1 .. Length_Data'Last));
Output.Stream.Write (Data);
end Append_Atom;
overriding procedure Close_List (Output : in out Canonical) is
begin
Output.Stream.Write ((0 => Encodings.List_End));
end Close_List;
procedure Transfer
(Source : in out Descriptor'Class;
Target : in out Printer'Class;
Check_Level : in Boolean := False)
is
procedure Print_Atom (Data : in Atom);
procedure Print_Atom (Data : in Atom) is
begin
Target.Append_Atom (Data);
end Print_Atom;
Event : Events.Event := Source.Current_Event;
Starting_Level : Natural := Source.Current_Level;
begin
if Events."=" (Event, Events.Open_List) then
Starting_Level := Starting_Level - 1;
end if;
loop
case Event is
when Events.Error | Events.End_Of_Input =>
exit;
when Events.Open_List =>
Target.Open_List;
when Events.Close_List =>
exit when Check_Level
and then Source.Current_Level < Starting_Level;
Target.Close_List;
when Events.Add_Atom =>
Source.Query_Atom (Print_Atom'Access);
end case;
Source.Next (Event);
end loop;
end Transfer;
end Natools.S_Expressions.Printers;
|
make level-checked Transfer go beyond the first list
|
s_expressions-printers: make level-checked Transfer go beyond the first list
|
Ada
|
isc
|
faelys/natools
|
b0d3546a11e8d279bd322eb46ea325bf4952b645
|
awa/plugins/awa-blogs/src/awa-blogs-beans.ads
|
awa/plugins/awa-blogs/src/awa-blogs-beans.ads
|
-----------------------------------------------------------------------
-- awa-blogs-beans -- Beans for blog module
-- Copyright (C) 2011, 2012, 2013 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Util.Beans.Basic;
with Util.Beans.Objects;
with ADO;
with AWA.Blogs.Modules;
with AWA.Blogs.Models;
with AWA.Tags.Beans;
package AWA.Blogs.Beans is
-- Attributes exposed by <b>Post_Bean</b>
BLOG_ID_ATTR : constant String := "blogId";
POST_ID_ATTR : constant String := "id";
POST_TITLE_ATTR : constant String := "title";
POST_TEXT_ATTR : constant String := "text";
POST_URI_ATTR : constant String := "uri";
POST_STATUS_ATTR : constant String := "status";
POST_USERNAME_ATTR : constant String := "username";
POST_TAG_ATTR : constant String := "tags";
-- ------------------------------
-- Blog Bean
-- ------------------------------
-- The <b>Blog_Bean</b> holds the information about the current blog.
-- It allows to create the blog as well as update its primary title.
type Blog_Bean is new AWA.Blogs.Models.Blog_Bean with record
Module : AWA.Blogs.Modules.Blog_Module_Access := null;
end record;
type Blog_Bean_Access is access all Blog_Bean'Class;
-- Get the value identified by the name.
overriding
function Get_Value (From : in Blog_Bean;
Name : in String) return Util.Beans.Objects.Object;
-- Set the value identified by the name.
overriding
procedure Set_Value (From : in out Blog_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object);
-- Create a new blog.
overriding
procedure Create (Bean : in out Blog_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String);
type Post_Bean is new AWA.Blogs.Models.Post_Bean with record
Module : AWA.Blogs.Modules.Blog_Module_Access := null;
Blog_Id : ADO.Identifier;
-- List of tags associated with the post.
Tags : aliased AWA.Tags.Beans.Tag_List_Bean;
Tags_Bean : Util.Beans.Basic.Readonly_Bean_Access;
end record;
type Post_Bean_Access is access all Post_Bean'Class;
-- Get the value identified by the name.
overriding
function Get_Value (From : in Post_Bean;
Name : in String) return Util.Beans.Objects.Object;
-- Set the value identified by the name.
overriding
procedure Set_Value (From : in out Post_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object);
-- Load the post.
procedure Load_Post (Post : in out Post_Bean;
Id : in ADO.Identifier);
-- Create or save the post.
overriding
procedure Save (Bean : in out Post_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String);
-- Delete a post.
overriding
procedure Delete (Bean : in out Post_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String);
-- Load the post.
overriding
procedure Load (Bean : in out Post_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String);
-- Create the Blog_Bean bean instance.
function Create_Blog_Bean (Module : in AWA.Blogs.Modules.Blog_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access;
-- Create the Post_Bean bean instance.
function Create_Post_Bean (Module : in AWA.Blogs.Modules.Blog_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access;
-- List of posts visible to anybody.
type Post_List_Bean is limited new Util.Beans.Basic.Bean with record
Posts : aliased AWA.Blogs.Models.Post_Info_List_Bean;
Service : Modules.Blog_Module_Access := null;
Tag : Ada.Strings.Unbounded.Unbounded_String;
Tags : AWA.Tags.Beans.Entity_Tag_Map;
Posts_Bean : AWA.Blogs.Models.Post_Info_List_Bean_Access;
end record;
type Post_List_Bean_Access is access all Post_List_Bean'Class;
-- Get the value identified by the name.
overriding
function Get_Value (From : in Post_List_Bean;
Name : in String) return Util.Beans.Objects.Object;
-- Set the value identified by the name.
overriding
procedure Set_Value (From : in out Post_List_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object);
-- Load the list of posts. If a tag was set, filter the list of posts with the tag.
procedure Load_List (Into : in out Post_List_Bean);
-- Create the Post_List_Bean bean instance.
function Create_Post_List_Bean (Module : in AWA.Blogs.Modules.Blog_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access;
-- Create the Blog_Admin_Bean bean instance.
function Create_Blog_Admin_Bean (Module : in AWA.Blogs.Modules.Blog_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access;
-- Get a select item list which contains a list of post status.
function Create_Status_List (Module : in AWA.Blogs.Modules.Blog_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access;
type Init_Flag is (INIT_BLOG_LIST, INIT_POST_LIST);
type Init_Map is array (Init_Flag) of Boolean;
type Blog_Admin_Bean is new Util.Beans.Basic.Bean with record
Module : AWA.Blogs.Modules.Blog_Module_Access := null;
-- The blog identifier.
Blog_Id : ADO.Identifier := ADO.NO_IDENTIFIER;
-- List of blogs.
Blog_List : aliased AWA.Blogs.Models.Blog_Info_List_Bean;
Blog_List_Bean : AWA.Blogs.Models.Blog_Info_List_Bean_Access;
-- List of posts.
Post_List : aliased AWA.Blogs.Models.Admin_Post_Info_List_Bean;
Post_List_Bean : AWA.Blogs.Models.Admin_Post_Info_List_Bean_Access;
-- Initialization flags.
Init_Flags : aliased Init_Map := (others => False);
Flags : access Init_Map;
end record;
type Blog_Admin_Bean_Access is access all Blog_Admin_Bean;
-- Get the blog identifier.
function Get_Blog_Id (List : in Blog_Admin_Bean) return ADO.Identifier;
-- Load the posts associated with the current blog.
procedure Load_Posts (List : in Blog_Admin_Bean);
overriding
function Get_Value (List : in Blog_Admin_Bean;
Name : in String) return Util.Beans.Objects.Object;
-- Set the value identified by the name.
overriding
procedure Set_Value (From : in out Blog_Admin_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object);
-- Load the list of blogs.
procedure Load_Blogs (List : in Blog_Admin_Bean);
end AWA.Blogs.Beans;
|
-----------------------------------------------------------------------
-- awa-blogs-beans -- Beans for blog module
-- Copyright (C) 2011, 2012, 2013, 2014 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Util.Beans.Basic;
with Util.Beans.Objects;
with ADO;
with AWA.Blogs.Modules;
with AWA.Blogs.Models;
with AWA.Tags.Beans;
package AWA.Blogs.Beans is
-- Attributes exposed by <b>Post_Bean</b>
BLOG_ID_ATTR : constant String := "blogId";
POST_ID_ATTR : constant String := "id";
POST_TITLE_ATTR : constant String := "title";
POST_TEXT_ATTR : constant String := "text";
POST_URI_ATTR : constant String := "uri";
POST_STATUS_ATTR : constant String := "status";
POST_USERNAME_ATTR : constant String := "username";
POST_TAG_ATTR : constant String := "tags";
-- ------------------------------
-- Blog Bean
-- ------------------------------
-- The <b>Blog_Bean</b> holds the information about the current blog.
-- It allows to create the blog as well as update its primary title.
type Blog_Bean is new AWA.Blogs.Models.Blog_Bean with record
Module : AWA.Blogs.Modules.Blog_Module_Access := null;
end record;
type Blog_Bean_Access is access all Blog_Bean'Class;
-- Get the value identified by the name.
overriding
function Get_Value (From : in Blog_Bean;
Name : in String) return Util.Beans.Objects.Object;
-- Set the value identified by the name.
overriding
procedure Set_Value (From : in out Blog_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object);
-- Create a new blog.
overriding
procedure Create (Bean : in out Blog_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String);
type Post_Bean is new AWA.Blogs.Models.Post_Bean with record
Module : AWA.Blogs.Modules.Blog_Module_Access := null;
Blog_Id : ADO.Identifier;
-- List of tags associated with the post.
Tags : aliased AWA.Tags.Beans.Tag_List_Bean;
Tags_Bean : Util.Beans.Basic.Readonly_Bean_Access;
end record;
type Post_Bean_Access is access all Post_Bean'Class;
-- Get the value identified by the name.
overriding
function Get_Value (From : in Post_Bean;
Name : in String) return Util.Beans.Objects.Object;
-- Set the value identified by the name.
overriding
procedure Set_Value (From : in out Post_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object);
-- Load the post.
procedure Load_Post (Post : in out Post_Bean;
Id : in ADO.Identifier);
-- Create or save the post.
overriding
procedure Save (Bean : in out Post_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String);
-- Delete a post.
overriding
procedure Delete (Bean : in out Post_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String);
-- Load the post.
overriding
procedure Load (Bean : in out Post_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String);
-- Create the Blog_Bean bean instance.
function Create_Blog_Bean (Module : in AWA.Blogs.Modules.Blog_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access;
-- Create the Post_Bean bean instance.
function Create_Post_Bean (Module : in AWA.Blogs.Modules.Blog_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access;
-- List of posts visible to anybody.
type Post_List_Bean is limited new Util.Beans.Basic.Bean with record
Posts : aliased AWA.Blogs.Models.Post_Info_List_Bean;
Service : Modules.Blog_Module_Access := null;
Tag : Ada.Strings.Unbounded.Unbounded_String;
Tags : AWA.Tags.Beans.Entity_Tag_Map;
Posts_Bean : AWA.Blogs.Models.Post_Info_List_Bean_Access;
end record;
type Post_List_Bean_Access is access all Post_List_Bean'Class;
-- Get the value identified by the name.
overriding
function Get_Value (From : in Post_List_Bean;
Name : in String) return Util.Beans.Objects.Object;
-- Set the value identified by the name.
overriding
procedure Set_Value (From : in out Post_List_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object);
-- Load the list of posts. If a tag was set, filter the list of posts with the tag.
procedure Load_List (Into : in out Post_List_Bean);
-- Create the Post_List_Bean bean instance.
function Create_Post_List_Bean (Module : in AWA.Blogs.Modules.Blog_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access;
-- Create the Blog_Admin_Bean bean instance.
function Create_Blog_Admin_Bean (Module : in AWA.Blogs.Modules.Blog_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access;
-- Get a select item list which contains a list of post status.
function Create_Status_List (Module : in AWA.Blogs.Modules.Blog_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access;
type Init_Flag is (INIT_BLOG_LIST, INIT_POST_LIST, INIT_COMMENT_LIST);
type Init_Map is array (Init_Flag) of Boolean;
type Blog_Admin_Bean is new Util.Beans.Basic.Bean with record
Module : AWA.Blogs.Modules.Blog_Module_Access := null;
-- The blog identifier.
Blog_Id : ADO.Identifier := ADO.NO_IDENTIFIER;
-- List of blogs.
Blog_List : aliased AWA.Blogs.Models.Blog_Info_List_Bean;
Blog_List_Bean : AWA.Blogs.Models.Blog_Info_List_Bean_Access;
-- List of posts.
Post_List : aliased AWA.Blogs.Models.Admin_Post_Info_List_Bean;
Post_List_Bean : AWA.Blogs.Models.Admin_Post_Info_List_Bean_Access;
-- List of comments.
Comment_List : aliased AWA.Blogs.Models.Comment_Info_List_Bean;
Comment_List_Bean : AWA.Blogs.Models.Comment_Info_List_Bean_Access;
-- Initialization flags.
Init_Flags : aliased Init_Map := (others => False);
Flags : access Init_Map;
end record;
type Blog_Admin_Bean_Access is access all Blog_Admin_Bean;
-- Get the blog identifier.
function Get_Blog_Id (List : in Blog_Admin_Bean) return ADO.Identifier;
-- Load the posts associated with the current blog.
procedure Load_Posts (List : in Blog_Admin_Bean);
-- Load the comments associated with the current blog.
procedure Load_Comments (List : in Blog_Admin_Bean);
overriding
function Get_Value (List : in Blog_Admin_Bean;
Name : in String) return Util.Beans.Objects.Object;
-- Set the value identified by the name.
overriding
procedure Set_Value (From : in out Blog_Admin_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object);
-- Load the list of blogs.
procedure Load_Blogs (List : in Blog_Admin_Bean);
end AWA.Blogs.Beans;
|
Add a list of comments in the blog admin bean
|
Add a list of comments in the blog admin bean
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
1069f1b0c18aeb22cee013dcb951a477b7de3691
|
awa/plugins/awa-wikis/src/awa-wikis-beans.ads
|
awa/plugins/awa-wikis/src/awa-wikis-beans.ads
|
-----------------------------------------------------------------------
-- awa-wikis-beans -- Beans for module wikis
-- Copyright (C) 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Util.Beans.Basic;
with Util.Beans.Objects;
with ADO;
with AWA.Wikis.Modules;
with AWA.Wikis.Models;
with AWA.Tags.Beans;
package AWA.Wikis.Beans is
type Wiki_Space_Bean is new AWA.Wikis.Models.Wiki_Space_Bean with record
Service : Modules.Wiki_Module_Access := null;
-- List of tags associated with the question.
Tags : aliased AWA.Tags.Beans.Tag_List_Bean;
Tags_Bean : Util.Beans.Basic.Readonly_Bean_Access;
end record;
type Wiki_Space_Bean_Access is access all Wiki_Space_Bean'Class;
-- Get the value identified by the name.
overriding
function Get_Value (From : in Wiki_Space_Bean;
Name : in String) return Util.Beans.Objects.Object;
-- Set the value identified by the name.
overriding
procedure Set_Value (From : in out Wiki_Space_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object);
-- Create or save the wiki space.
overriding
procedure Save (Bean : in out Wiki_Space_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String);
-- Delete the wiki space.
procedure Delete (Bean : in out Wiki_Space_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String);
-- Create the Wiki_Space_Bean bean instance.
function Create_Wiki_Space_Bean (Module : in AWA.Wikis.Modules.Wiki_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access;
type Wiki_Page_Bean is new AWA.Wikis.Models.Wiki_Page_Bean with record
Service : Modules.Wiki_Module_Access := null;
-- The page content.
Content : Models.Wiki_Content_Ref;
Has_Content : Boolean := False;
Wiki_Space : Wiki_Space_Bean;
-- List of tags associated with the question.
Tags : aliased AWA.Tags.Beans.Tag_List_Bean;
Tags_Bean : Util.Beans.Basic.Readonly_Bean_Access;
end record;
type Wiki_Page_Bean_Access is access all Wiki_Page_Bean'Class;
-- Get the value identified by the name.
overriding
function Get_Value (From : in Wiki_Page_Bean;
Name : in String) return Util.Beans.Objects.Object;
-- Set the value identified by the name.
overriding
procedure Set_Value (From : in out Wiki_Page_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object);
-- Create or save the wiki page.
overriding
procedure Save (Bean : in out Wiki_Page_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String);
-- Load the wiki page.
overriding
procedure Load (Bean : in out Wiki_Page_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String);
-- Delete the wiki page.
overriding
procedure Delete (Bean : in out Wiki_Page_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String);
-- Create the Wiki_Page_Bean bean instance.
function Create_Wiki_Page_Bean (Module : in AWA.Wikis.Modules.Wiki_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access;
type Init_Flag is (INIT_WIKI_LIST);
type Init_Map is array (Init_Flag) of Boolean;
-- ------------------------------
-- Admin List Bean
-- ------------------------------
-- The <b>Wiki_Admin_Bean</b> is used for the administration of a wiki. It gives the
-- list of wikis and pages that are created, published or not.
type Wiki_Admin_Bean is new Util.Beans.Basic.Bean with record
Module : AWA.Wikis.Modules.Wiki_Module_Access := null;
-- The wiki space identifier.
Wiki_Id : ADO.Identifier := ADO.NO_IDENTIFIER;
-- List of blogs.
Wiki_List : aliased AWA.Wikis.Models.Wiki_Info_List_Bean;
Wiki_List_Bean : AWA.Wikis.Models.Wiki_Info_List_Bean_Access;
-- Initialization flags.
Init_Flags : aliased Init_Map := (others => False);
Flags : access Init_Map;
end record;
type Wiki_Admin_Bean_Access is access all Wiki_Admin_Bean;
-- Get the wiki space identifier.
function Get_Wiki_Id (List : in Wiki_Admin_Bean) return ADO.Identifier;
overriding
function Get_Value (List : in Wiki_Admin_Bean;
Name : in String) return Util.Beans.Objects.Object;
-- Set the value identified by the name.
overriding
procedure Set_Value (From : in out Wiki_Admin_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object);
-- Load the list of wikis.
procedure Load_Wikis (List : in Wiki_Admin_Bean);
-- Create the Wiki_Admin_Bean bean instance.
function Create_Wiki_Admin_Bean (Module : in AWA.Wikis.Modules.Wiki_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access;
end AWA.Wikis.Beans;
|
-----------------------------------------------------------------------
-- awa-wikis-beans -- Beans for module wikis
-- Copyright (C) 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Util.Beans.Basic;
with Util.Beans.Objects;
with Util.Beans.Objects.Time;
with ADO;
with AWA.Wikis.Modules;
with AWA.Wikis.Models;
with AWA.Tags.Beans;
package AWA.Wikis.Beans is
type Wiki_Space_Bean is new AWA.Wikis.Models.Wiki_Space_Bean with record
Service : Modules.Wiki_Module_Access := null;
-- List of tags associated with the question.
Tags : aliased AWA.Tags.Beans.Tag_List_Bean;
Tags_Bean : Util.Beans.Basic.Readonly_Bean_Access;
end record;
type Wiki_Space_Bean_Access is access all Wiki_Space_Bean'Class;
-- Get the value identified by the name.
overriding
function Get_Value (From : in Wiki_Space_Bean;
Name : in String) return Util.Beans.Objects.Object;
-- Set the value identified by the name.
overriding
procedure Set_Value (From : in out Wiki_Space_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object);
-- Create or save the wiki space.
overriding
procedure Save (Bean : in out Wiki_Space_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String);
-- Delete the wiki space.
procedure Delete (Bean : in out Wiki_Space_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String);
-- Create the Wiki_Space_Bean bean instance.
function Create_Wiki_Space_Bean (Module : in AWA.Wikis.Modules.Wiki_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access;
type Wiki_Page_Bean is new AWA.Wikis.Models.Wiki_Page_Bean with record
Service : Modules.Wiki_Module_Access := null;
-- The page content.
Content : Models.Wiki_Content_Ref;
Has_Content : Boolean := False;
Wiki_Space : Wiki_Space_Bean;
-- List of tags associated with the question.
Tags : aliased AWA.Tags.Beans.Tag_List_Bean;
Tags_Bean : Util.Beans.Basic.Readonly_Bean_Access;
end record;
type Wiki_Page_Bean_Access is access all Wiki_Page_Bean'Class;
-- Get the value identified by the name.
overriding
function Get_Value (From : in Wiki_Page_Bean;
Name : in String) return Util.Beans.Objects.Object;
-- Set the value identified by the name.
overriding
procedure Set_Value (From : in out Wiki_Page_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object);
-- Create or save the wiki page.
overriding
procedure Save (Bean : in out Wiki_Page_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String);
-- Load the wiki page.
overriding
procedure Load (Bean : in out Wiki_Page_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String);
-- Delete the wiki page.
overriding
procedure Delete (Bean : in out Wiki_Page_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String);
-- Create the Wiki_Page_Bean bean instance.
function Create_Wiki_Page_Bean (Module : in AWA.Wikis.Modules.Wiki_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access;
-- ------------------------------
-- Wiki List Bean
-- ------------------------------
-- The <b>Wiki_List_Bean</b> gives a list of visible wikis to be displayed to users.
-- The list can be filtered by a given tag. The list pagination is supported.
type Wiki_List_Bean is new AWA.Wikis.Models.Wiki_Page_List_Bean with record
Pages : aliased AWA.Wikis.Models.Wiki_Page_Info_List_Bean;
Service : Modules.Wiki_Module_Access := null;
Tags : AWA.Tags.Beans.Entity_Tag_Map;
Pages_Bean : AWA.Wikis.Models.Wiki_Page_Info_List_Bean_Access;
end record;
type Wiki_List_Bean_Access is access all Wiki_List_Bean'Class;
-- Get the value identified by the name.
overriding
function Get_Value (From : in Wiki_List_Bean;
Name : in String) return Util.Beans.Objects.Object;
-- Set the value identified by the name.
overriding
procedure Set_Value (From : in out Wiki_List_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object);
overriding
procedure Load (From : in out Wiki_List_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String);
-- Load the list of pages. If a tag was set, filter the list of pages with the tag.
procedure Load_List (Into : in out Wiki_List_Bean);
-- Create the Post_List_Bean bean instance.
function Create_Wiki_List_Bean (Module : in AWA.Wikis.Modules.Wiki_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access;
type Init_Flag is (INIT_WIKI_LIST);
type Init_Map is array (Init_Flag) of Boolean;
-- ------------------------------
-- Admin List Bean
-- ------------------------------
-- The <b>Wiki_Admin_Bean</b> is used for the administration of a wiki. It gives the
-- list of wikis and pages that are created, published or not.
type Wiki_Admin_Bean is new Util.Beans.Basic.Bean with record
Module : AWA.Wikis.Modules.Wiki_Module_Access := null;
-- The wiki space identifier.
Wiki_Id : ADO.Identifier := ADO.NO_IDENTIFIER;
-- List of blogs.
Wiki_List : aliased AWA.Wikis.Models.Wiki_Info_List_Bean;
Wiki_List_Bean : AWA.Wikis.Models.Wiki_Info_List_Bean_Access;
-- Initialization flags.
Init_Flags : aliased Init_Map := (others => False);
Flags : access Init_Map;
end record;
type Wiki_Admin_Bean_Access is access all Wiki_Admin_Bean;
-- Get the wiki space identifier.
function Get_Wiki_Id (List : in Wiki_Admin_Bean) return ADO.Identifier;
overriding
function Get_Value (List : in Wiki_Admin_Bean;
Name : in String) return Util.Beans.Objects.Object;
-- Set the value identified by the name.
overriding
procedure Set_Value (From : in out Wiki_Admin_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object);
-- Load the list of wikis.
procedure Load_Wikis (List : in Wiki_Admin_Bean);
-- Create the Wiki_Admin_Bean bean instance.
function Create_Wiki_Admin_Bean (Module : in AWA.Wikis.Modules.Wiki_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access;
end AWA.Wikis.Beans;
|
Declare the Wiki_List_Bean type with its operations
|
Declare the Wiki_List_Bean type with its operations
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
bdad1a5139be5c15c3405e09689fcea981dceaed
|
src/wiki-filters.adb
|
src/wiki-filters.adb
|
-----------------------------------------------------------------------
-- wiki-filters -- Wiki filters
-- Copyright (C) 2015, 2016 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
package body Wiki.Filters is
-- ------------------------------
-- 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) is
begin
if Filter.Next /= null then
Filter.Next.Add_Node (Document, Kind);
else
Document.Append (Kind);
end if;
end Add_Node;
-- ------------------------------
-- 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) is
begin
if Filter.Next /= null then
Filter.Next.Add_Text (Document, Text, Format);
else
Wiki.Documents.Append (Document, Text, Format);
end if;
end Add_Text;
-- ------------------------------
-- 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) is
begin
if Filter.Next /= null then
Filter.Next.Add_Header (Document, Header, Level);
else
Wiki.Documents.Append (Document, Header, Level);
end if;
end Add_Header;
-- ------------------------------
-- 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) is
begin
if Filter.Next /= null then
Filter.Next.Push_Node (Document, Tag, Attributes);
else
Document.Push_Node (Tag, Attributes);
end if;
end Push_Node;
-- ------------------------------
-- 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) is
begin
if Filter.Next /= null then
Filter.Next.Pop_Node (Document, Tag);
else
Document.Pop_Node (Tag);
end if;
end Pop_Node;
-- ------------------------------
-- 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) is
begin
if Filter.Next /= null then
Filter.Next.Add_Blockquote (Document, Level);
else
Document.Add_Blockquote (Level);
end if;
end Add_Blockquote;
-- ------------------------------
-- Add a list item (<li>). Close the previous paragraph and list item if any.
-- The list item will be closed at the next list item, next paragraph or next header.
-- ------------------------------
procedure Add_List_Item (Filter : in out Filter_Type;
Document : in out Wiki.Documents.Document;
Level : in Positive;
Ordered : in Boolean) is
begin
if Filter.Next /= null then
Filter.Next.Add_List_Item (Document, Level, Ordered);
else
Document.Add_List_Item (Level, Ordered);
end if;
end Add_List_Item;
-- ------------------------------
-- 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) is
begin
if Filter.Next /= null then
Filter.Next.Add_Link (Document, Name, Attributes);
else
Document.Add_Link (Name, Attributes);
end if;
end Add_Link;
-- ------------------------------
-- 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) is
begin
if Filter.Next /= null then
Filter.Next.Add_Image (Document, Name, Attributes);
else
Document.Add_Image (Name, Attributes);
end if;
end Add_Image;
-- ------------------------------
-- 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) is
begin
if Filter.Next /= null then
Filter.Next.Add_Quote (Document, Name, Attributes);
else
Document.Add_Quote (Name, Attributes);
end if;
end Add_Quote;
-- ------------------------------
-- 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 Unbounded_Wide_Wide_String) is
begin
if Filter.Next /= null then
Filter.Next.Add_Preformatted (Document, Text, Format);
else
Document.Add_Preformatted (Text, To_Wide_Wide_String (Format));
end if;
end Add_Preformatted;
-- ------------------------------
-- Finish the document after complete wiki text has been parsed.
-- ------------------------------
procedure Finish (Filter : in out Filter_Type;
Document : in out Wiki.Documents.Document) is
begin
if Filter.Next /= null then
Filter.Next.Finish (Document);
end if;
end Finish;
-- ------------------------------
-- Add the filter at beginning of the filter chain.
-- ------------------------------
procedure Add_Filter (Chain : in out Filter_Chain;
Filter : in Filter_Type_Access) is
begin
Filter.Next := Chain.Next;
Chain.Next := Filter;
end Add_Filter;
end Wiki.Filters;
|
-----------------------------------------------------------------------
-- wiki-filters -- Wiki filters
-- Copyright (C) 2015, 2016 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
package body Wiki.Filters is
-- ------------------------------
-- 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) is
begin
if Filter.Next /= null then
Filter.Next.Add_Node (Document, Kind);
else
Document.Append (Kind);
end if;
end Add_Node;
-- ------------------------------
-- 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) is
begin
if Filter.Next /= null then
Filter.Next.Add_Text (Document, Text, Format);
else
Wiki.Documents.Append (Document, Text, Format);
end if;
end Add_Text;
-- ------------------------------
-- 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) is
begin
if Filter.Next /= null then
Filter.Next.Add_Header (Document, Header, Level);
else
Wiki.Documents.Append (Document, Header, Level);
end if;
end Add_Header;
-- ------------------------------
-- 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) is
begin
if Filter.Next /= null then
Filter.Next.Push_Node (Document, Tag, Attributes);
else
Document.Push_Node (Tag, Attributes);
end if;
end Push_Node;
-- ------------------------------
-- 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) is
begin
if Filter.Next /= null then
Filter.Next.Pop_Node (Document, Tag);
else
Document.Pop_Node (Tag);
end if;
end Pop_Node;
-- ------------------------------
-- 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) is
begin
if Filter.Next /= null then
Filter.Next.Add_Blockquote (Document, Level);
else
Document.Add_Blockquote (Level);
end if;
end Add_Blockquote;
-- ------------------------------
-- Add a list item (<li>). Close the previous paragraph and list item if any.
-- The list item will be closed at the next list item, next paragraph or next header.
-- ------------------------------
procedure Add_List_Item (Filter : in out Filter_Type;
Document : in out Wiki.Documents.Document;
Level : in Positive;
Ordered : in Boolean) is
begin
if Filter.Next /= null then
Filter.Next.Add_List_Item (Document, Level, Ordered);
else
Document.Add_List_Item (Level, Ordered);
end if;
end Add_List_Item;
-- ------------------------------
-- 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) is
begin
if Filter.Next /= null then
Filter.Next.Add_Link (Document, Name, Attributes);
else
Document.Add_Link (Name, Attributes);
end if;
end Add_Link;
-- ------------------------------
-- 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) is
begin
if Filter.Next /= null then
Filter.Next.Add_Image (Document, Name, Attributes);
else
Document.Add_Image (Name, Attributes);
end if;
end Add_Image;
-- ------------------------------
-- 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) is
begin
if Filter.Next /= null then
Filter.Next.Add_Quote (Document, Name, Attributes);
else
Document.Add_Quote (Name, Attributes);
end if;
end Add_Quote;
-- ------------------------------
-- 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) is
begin
if Filter.Next /= null then
Filter.Next.Add_Preformatted (Document, Text, Format);
else
Document.Add_Preformatted (Text, Format);
end if;
end Add_Preformatted;
-- ------------------------------
-- Finish the document after complete wiki text has been parsed.
-- ------------------------------
procedure Finish (Filter : in out Filter_Type;
Document : in out Wiki.Documents.Document) is
begin
if Filter.Next /= null then
Filter.Next.Finish (Document);
end if;
end Finish;
-- ------------------------------
-- Add the filter at beginning of the filter chain.
-- ------------------------------
procedure Add_Filter (Chain : in out Filter_Chain;
Filter : in Filter_Type_Access) is
begin
Filter.Next := Chain.Next;
Chain.Next := Filter;
end Add_Filter;
end Wiki.Filters;
|
Use a Wiki.Strings.WString for the format parameter of Add_Preformatted
|
Use a Wiki.Strings.WString for the format parameter of Add_Preformatted
|
Ada
|
apache-2.0
|
stcarrez/ada-wiki,stcarrez/ada-wiki
|
9d7344c94a2b5723676cc985aefc8f8d02541737
|
src/wiki-helpers.ads
|
src/wiki-helpers.ads
|
-----------------------------------------------------------------------
-- wiki-helpers -- Helper operations for wiki parsers and renderer
-- Copyright (C) 2016 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Wiki.Strings;
package Wiki.Helpers is
pragma Preelaborate;
LF : constant Wiki.Strings.WChar := Wiki.Strings.WChar'Val (16#0A#);
CR : constant Wiki.Strings.WChar := Wiki.Strings.WChar'Val (16#0D#);
HT : constant Wiki.Strings.WChar := Wiki.Strings.WChar'Val (16#09#);
-- Returns True if the character is a space or tab.
function Is_Space (C : in Wiki.Strings.WChar) return Boolean;
-- Returns True if the character is a space, tab or a newline.
function Is_Space_Or_Newline (C : in Wiki.Strings.WChar) return Boolean;
-- Returns True if the character is a line terminator.
function Is_Newline (C : in Wiki.Strings.WChar) return Boolean;
-- Returns True if the text is a valid URL
function Is_Url (Text : in Wiki.Strings.WString) return Boolean;
-- Returns True if the extension part correspond to an image.
-- Recognized extension are: .png, .gif, .jpg, .jpeg.
-- The extension case is ignored.
function Is_Image_Extension (Ext : in Wiki.Strings.WString) return Boolean;
-- Given the current tag on the top of the stack and the new tag that will be pushed,
-- decide whether the current tag must be closed or not.
-- Returns True if the current tag must be closed.
function Need_Close (Tag : in Html_Tag;
Current_Tag : in Html_Tag) return Boolean;
-- Get the dimension represented by the string. The string has one of the following
-- formats:
-- original -> Width, Height := Natural'Last
-- default -> Width := 800, Height := 0
-- upright -> Width := 800, Height := 0
-- <width>px -> Width := <width>, Height := 0
-- x<height>px -> Width := 0, Height := <height>
-- <width>x<height>px -> Width := <width>, Height := <height>
procedure Get_Sizes (Dimension : in Wiki.Strings.WString;
Width : out Natural;
Height : out Natural);
end Wiki.Helpers;
|
-----------------------------------------------------------------------
-- wiki-helpers -- Helper operations for wiki parsers and renderer
-- Copyright (C) 2016, 2020 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Wiki.Strings;
package Wiki.Helpers is
pragma Preelaborate;
LF : constant Wiki.Strings.WChar := Wiki.Strings.WChar'Val (16#0A#);
CR : constant Wiki.Strings.WChar := Wiki.Strings.WChar'Val (16#0D#);
HT : constant Wiki.Strings.WChar := Wiki.Strings.WChar'Val (16#09#);
NBSP : constant Wiki.Strings.WChar := Wiki.Strings.WChar'Val (16#A0#);
-- Returns True if the character is a space or tab.
function Is_Space (C : in Wiki.Strings.WChar) return Boolean;
-- Returns True if the character is a space, tab or a newline.
function Is_Space_Or_Newline (C : in Wiki.Strings.WChar) return Boolean;
-- Returns True if the character is a line terminator.
function Is_Newline (C : in Wiki.Strings.WChar) return Boolean;
-- Returns True if the text is a valid URL
function Is_Url (Text : in Wiki.Strings.WString) return Boolean;
-- Returns True if the extension part correspond to an image.
-- Recognized extension are: .png, .gif, .jpg, .jpeg.
-- The extension case is ignored.
function Is_Image_Extension (Ext : in Wiki.Strings.WString) return Boolean;
-- Given the current tag on the top of the stack and the new tag that will be pushed,
-- decide whether the current tag must be closed or not.
-- Returns True if the current tag must be closed.
function Need_Close (Tag : in Html_Tag;
Current_Tag : in Html_Tag) return Boolean;
-- Get the dimension represented by the string. The string has one of the following
-- formats:
-- original -> Width, Height := Natural'Last
-- default -> Width := 800, Height := 0
-- upright -> Width := 800, Height := 0
-- <width>px -> Width := <width>, Height := 0
-- x<height>px -> Width := 0, Height := <height>
-- <width>x<height>px -> Width := <width>, Height := <height>
procedure Get_Sizes (Dimension : in Wiki.Strings.WString;
Width : out Natural;
Height : out Natural);
end Wiki.Helpers;
|
Declare the NBSP constant
|
Declare the NBSP constant
|
Ada
|
apache-2.0
|
stcarrez/ada-wiki,stcarrez/ada-wiki
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.