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
|
---|---|---|---|---|---|---|---|---|---|
afe44f4e9bc23f490a33439da8f30bbf07050076
|
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
|
stcarrez/ada-ado
|
559569eb4e851d1c4b0d8e6796c3ff3eda52929e
|
mat/src/events/mat-events-targets.adb
|
mat/src/events/mat-events-targets.adb
|
-----------------------------------------------------------------------
-- mat-events-targets - Events received and collected from a target
-- Copyright (C) 2014 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
package body MAT.Events.Targets is
-- ------------------------------
-- Add the event in the list of events and increment the event counter.
-- ------------------------------
procedure Insert (Target : in out Target_Events;
Event : in Probe_Event_Type) is
begin
Target.Events.Insert (Event);
Util.Concurrent.Counters.Increment (Target.Event_Count);
end Insert;
procedure Get_Events (Target : in out Target_Events;
Start : in MAT.Types.Target_Time;
Finish : in MAT.Types.Target_Time;
Into : in out Target_Event_Vector) is
begin
Target.Events.Get_Events (Start, Finish, Into);
end Get_Events;
-- ------------------------------
-- Get the start and finish time for the events that have been received.
-- ------------------------------
procedure Get_Time_Range (Target : in out Target_Events;
Start : out MAT.Types.Target_Time;
Finish : out MAT.Types.Target_Time) is
begin
Target.Events.Get_Time_Range (Start, Finish);
end Get_Time_Range;
-- ------------------------------
-- Get the current event counter.
-- ------------------------------
function Get_Event_Counter (Target : in Target_Events) return Integer is
begin
return Util.Concurrent.Counters.Value (Target.Event_Count);
end Get_Event_Counter;
protected body Event_Collector is
-- ------------------------------
-- Add the event in the list of events.
-- ------------------------------
procedure Insert (Event : in Probe_Event_Type) is
Info : Target_Event;
begin
if Current = null then
Current := new Event_Block;
Current.Start := Event.Time;
Events.Insert (Event.Time, Current);
end if;
Current.Count := Current.Count + 1;
Current.Events (Current.Count) := Event;
Current.Events (Current.Count).Id := Last_Id;
Last_Id := Last_Id + 1;
Current.Finish := Event.Time;
if Current.Count = Current.Events'Last then
Current := null;
end if;
end Insert;
procedure Get_Events (Start : in MAT.Types.Target_Time;
Finish : in MAT.Types.Target_Time;
Into : in out Target_Event_Vector) is
Iter : Event_Cursor := Events.Floor (Start);
Block : Event_Block_Access;
begin
while Event_Maps.Has_Element (Iter) loop
Block := Event_Maps.Element (Iter);
exit when Block.Start > Finish;
for I in Block.Events'First .. Block.Count loop
exit when Block.Events (I).Time > Finish;
if Block.Events (I).Time >= Start then
Into.Append (Block.Events (I));
end if;
end loop;
Event_Maps.Next (Iter);
end loop;
end Get_Events;
-- ------------------------------
-- Get the start and finish time for the events that have been received.
-- ------------------------------
procedure Get_Time_Range (Start : out MAT.Types.Target_Time;
Finish : out MAT.Types.Target_Time) is
First : constant Event_Block_Access := Events.First_Element;
Last : constant Event_Block_Access := Events.Last_Element;
begin
Start := First.Events (First.Events'First).Time;
Finish := Last.Events (Last.Count).Time;
end Get_Time_Range;
end Event_Collector;
end MAT.Events.Targets;
|
-----------------------------------------------------------------------
-- mat-events-targets - Events received and collected from a target
-- Copyright (C) 2014 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
package body MAT.Events.Targets is
-- ------------------------------
-- Add the event in the list of events and increment the event counter.
-- ------------------------------
procedure Insert (Target : in out Target_Events;
Event : in Probe_Event_Type) is
begin
Target.Events.Insert (Event);
Util.Concurrent.Counters.Increment (Target.Event_Count);
end Insert;
procedure Get_Events (Target : in out Target_Events;
Start : in MAT.Types.Target_Time;
Finish : in MAT.Types.Target_Time;
Into : in out Target_Event_Vector) is
begin
Target.Events.Get_Events (Start, Finish, Into);
end Get_Events;
-- ------------------------------
-- Get the start and finish time for the events that have been received.
-- ------------------------------
procedure Get_Time_Range (Target : in out Target_Events;
Start : out MAT.Types.Target_Time;
Finish : out MAT.Types.Target_Time) is
begin
Target.Events.Get_Time_Range (Start, Finish);
end Get_Time_Range;
-- ------------------------------
-- Get the current event counter.
-- ------------------------------
function Get_Event_Counter (Target : in Target_Events) return Integer is
begin
return Util.Concurrent.Counters.Value (Target.Event_Count);
end Get_Event_Counter;
protected body Event_Collector is
-- ------------------------------
-- Add the event in the list of events.
-- ------------------------------
procedure Insert (Event : in Probe_Event_Type) is
Info : Target_Event;
begin
if Current = null then
Current := new Event_Block;
Current.Start := Event.Time;
Events.Insert (Event.Time, Current);
Ids.Insert (Last_Id + 1, Current);
end if;
Current.Count := Current.Count + 1;
Current.Events (Current.Count) := Event;
Current.Events (Current.Count).Id := Last_Id;
Last_Id := Last_Id + 1;
Current.Finish := Event.Time;
if Current.Count = Current.Events'Last then
Current := null;
end if;
end Insert;
procedure Get_Events (Start : in MAT.Types.Target_Time;
Finish : in MAT.Types.Target_Time;
Into : in out Target_Event_Vector) is
Iter : Event_Cursor := Events.Floor (Start);
Block : Event_Block_Access;
begin
while Event_Maps.Has_Element (Iter) loop
Block := Event_Maps.Element (Iter);
exit when Block.Start > Finish;
for I in Block.Events'First .. Block.Count loop
exit when Block.Events (I).Time > Finish;
if Block.Events (I).Time >= Start then
Into.Append (Block.Events (I));
end if;
end loop;
Event_Maps.Next (Iter);
end loop;
end Get_Events;
-- ------------------------------
-- Get the start and finish time for the events that have been received.
-- ------------------------------
procedure Get_Time_Range (Start : out MAT.Types.Target_Time;
Finish : out MAT.Types.Target_Time) is
First : constant Event_Block_Access := Events.First_Element;
Last : constant Event_Block_Access := Events.Last_Element;
begin
Start := First.Events (First.Events'First).Time;
Finish := Last.Events (Last.Count).Time;
end Get_Time_Range;
-- ------------------------------
-- Get the probe event with the given allocated unique id.
-- ------------------------------
function Get_Event (Id : in Event_Id_Type) return Probe_Event_Type is
Iter : Event_Id_Cursor := Ids.Floor (Id);
Block : Event_Block_Access;
Pos : Event_Id_Type;
begin
while not Event_Id_Maps.Has_Element (Iter) loop
Block := Event_Id_Maps.Element (Iter);
exit when Id < Block.Events (Block.Events'First).Id;
Pos := Id - Block.Events (Block.Events'First).Id;
if Pos < Block.Count then
return Block.Events (Pos);
end if;
Event_Id_Maps.Next (Iter);
end loop;
raise Not_Found;
end Get_Event;
end Event_Collector;
end MAT.Events.Targets;
|
Implement the Get_Event protected operation
|
Implement the Get_Event protected operation
|
Ada
|
apache-2.0
|
stcarrez/mat,stcarrez/mat,stcarrez/mat
|
490e6e2cbb79b2815939dc94a99a11cb51456d46
|
awa/plugins/awa-storages/regtests/awa-storages-services-tests.adb
|
awa/plugins/awa-storages/regtests/awa-storages-services-tests.adb
|
-----------------------------------------------------------------------
-- awa-storages-services-tests -- Unit tests for 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.Streams;
with Ada.Strings.Unbounded;
with Util.Test_Caller;
with ADO;
with ADO.Objects;
with Security.Contexts;
with AWA.Services.Contexts;
with AWA.Storages.Modules;
with AWA.Storages.Beans.Factories;
with AWA.Tests.Helpers.Users;
package body AWA.Storages.Services.Tests is
use ADO;
package Caller is new Util.Test_Caller (Test, "Storages.Services");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test AWA.Storages.Services.Save (DATABASE)",
Test_Create_Storage'Access);
Caller.Add_Test (Suite, "Test AWA.Storages.Services.Save (FILE)",
Test_File_Create_Storage'Access);
Caller.Add_Test (Suite, "Test AWA.Storages.Services.Delete",
Test_Delete_Storage'Access);
Caller.Add_Test (Suite, "Test AWA.Storages.Services.Save_Folder, Folder_Bean",
Test_Create_Folder'Access);
Caller.Add_Test (Suite, "Test AWA.Storages.Services.Get_Local_File",
Test_Get_Local_File'Access);
end Add_Tests;
-- ------------------------------
-- Save something in a storage element and keep track of the store id in the test <b>Id</b>.
-- ------------------------------
procedure Save (T : in out Test) is
Store : AWA.Storages.Models.Storage_Ref;
begin
T.Manager := AWA.Storages.Modules.Get_Storage_Manager;
T.Assert (T.Manager /= null, "Null storage manager");
Store.Set_Mime_Type ("text/plain");
Store.Set_Name ("Makefile");
Store.Set_File_Size (1000);
T.Manager.Save (Into => Store,
Path => "Makefile",
Storage => T.Kind);
T.Assert (not Store.Is_Null, "Storage object should not be null");
T.Id := Store.Get_Id;
T.Assert (T.Id > 0, "Invalid storage identifier");
end Save;
-- ------------------------------
-- Load the storage element refered to by the test <b>Id</b>.
-- ------------------------------
procedure Load (T : in out Test) is
use type Ada.Streams.Stream_Element_Offset;
Name : Ada.Strings.Unbounded.Unbounded_String;
Mime : Ada.Strings.Unbounded.Unbounded_String;
Date : Ada.Calendar.Time;
Data : ADO.Blob_Ref;
begin
T.Manager := AWA.Storages.Modules.Get_Storage_Manager;
T.Assert (T.Manager /= null, "Null storage manager");
T.Manager.Load (From => T.Id, Name => Name, Mime => Mime, Date => Date, Into => Data);
T.Assert (not Data.Is_Null, "Null blob returned by load");
T.Assert (Data.Value.Len > 100, "Invalid length for the blob data");
end Load;
-- ------------------------------
-- Test creation of a storage object
-- ------------------------------
procedure Test_Create_Storage (T : in out Test) is
Sec_Ctx : Security.Contexts.Security_Context;
Context : AWA.Services.Contexts.Service_Context;
begin
AWA.Tests.Helpers.Users.Login (Context, Sec_Ctx, "[email protected]");
T.Save;
T.Load;
end Test_Create_Storage;
procedure Test_File_Create_Storage (T : in out Test) is
begin
T.Kind := AWA.Storages.Models.FILE;
T.Test_Create_Storage;
end Test_File_Create_Storage;
-- ------------------------------
-- Test creation of a storage object and local file access after its creation.
-- ------------------------------
procedure Test_Get_Local_File (T : in out Test) is
Sec_Ctx : Security.Contexts.Security_Context;
Context : AWA.Services.Contexts.Service_Context;
begin
AWA.Tests.Helpers.Users.Login (Context, Sec_Ctx, "[email protected]");
T.Save;
declare
File : AWA.Storages.Storage_File (AWA.Storages.TMP);
begin
T.Manager.Get_Local_File (From => T.Id, Into => File);
T.Assert (AWA.Storages.Get_Path (File)'Length > 0, "Invalid local file path");
end;
end Test_Get_Local_File;
-- ------------------------------
-- Test deletion of a storage object
-- ------------------------------
procedure Test_Delete_Storage (T : in out Test) is
Sec_Ctx : Security.Contexts.Security_Context;
Context : AWA.Services.Contexts.Service_Context;
Data : ADO.Blob_Ref;
Name : Ada.Strings.Unbounded.Unbounded_String;
Mime : Ada.Strings.Unbounded.Unbounded_String;
Date : Ada.Calendar.Time;
begin
AWA.Tests.Helpers.Users.Login (Context, Sec_Ctx, "[email protected]");
T.Save;
T.Manager.Delete (T.Id);
begin
T.Manager.Load (From => T.Id, Name => Name, Mime => Mime, Date => Date, Into => Data);
T.Assert (False, "No exception raised");
exception
when ADO.Objects.NOT_FOUND =>
null;
end;
end Test_Delete_Storage;
-- ------------------------------
-- Test creation of a storage folder
-- ------------------------------
procedure Test_Create_Folder (T : in out Test) is
Sec_Ctx : Security.Contexts.Security_Context;
Context : AWA.Services.Contexts.Service_Context;
Folder : AWA.Storages.Beans.Factories.Folder_Bean;
Outcome : Ada.Strings.Unbounded.Unbounded_String;
Upload : AWA.Storages.Beans.Factories.Upload_Bean;
begin
AWA.Tests.Helpers.Users.Login (Context, Sec_Ctx, "[email protected]");
Folder.Module := AWA.Storages.Modules.Get_Storage_Module;
Upload.Module := AWA.Storages.Modules.Get_Storage_Module;
Folder.Set_Name ("Test folder name");
Folder.Save (Outcome);
Util.Tests.Assert_Equals (T, "success", Outcome, "Invalid outcome returned by Save action");
Upload.Set_Value ("folderId", ADO.Objects.To_Object (Folder.Get_Key));
Util.Tests.Assert_Equals (T, "Test folder name", String '(Upload.Get_Folder.Get_Name),
"Invalid folder name");
end Test_Create_Folder;
end AWA.Storages.Services.Tests;
|
-----------------------------------------------------------------------
-- awa-storages-services-tests -- Unit tests for storage service
-- Copyright (C) 2012, 2016, 2019, 2020 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Streams;
with Ada.Strings.Unbounded;
with Util.Test_Caller;
with ADO;
with ADO.Objects;
with Security.Contexts;
with AWA.Services.Contexts;
with AWA.Storages.Modules;
with AWA.Storages.Beans;
with AWA.Tests.Helpers.Users;
package body AWA.Storages.Services.Tests is
use ADO;
package Caller is new Util.Test_Caller (Test, "Storages.Services");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test AWA.Storages.Services.Save (DATABASE)",
Test_Create_Storage'Access);
Caller.Add_Test (Suite, "Test AWA.Storages.Services.Save (FILE)",
Test_File_Create_Storage'Access);
Caller.Add_Test (Suite, "Test AWA.Storages.Services.Delete",
Test_Delete_Storage'Access);
Caller.Add_Test (Suite, "Test AWA.Storages.Services.Save_Folder, Folder_Bean",
Test_Create_Folder'Access);
Caller.Add_Test (Suite, "Test AWA.Storages.Services.Get_Local_File",
Test_Get_Local_File'Access);
end Add_Tests;
-- ------------------------------
-- Save something in a storage element and keep track of the store id in the test <b>Id</b>.
-- ------------------------------
procedure Save (T : in out Test) is
Store : AWA.Storages.Models.Storage_Ref;
begin
T.Manager := AWA.Storages.Modules.Get_Storage_Manager;
T.Assert (T.Manager /= null, "Null storage manager");
Store.Set_Mime_Type ("text/plain");
Store.Set_Name ("Makefile");
Store.Set_File_Size (1000);
T.Manager.Save (Into => Store,
Path => "Makefile",
Storage => T.Kind);
T.Assert (not Store.Is_Null, "Storage object should not be null");
T.Id := Store.Get_Id;
T.Assert (T.Id > 0, "Invalid storage identifier");
end Save;
-- ------------------------------
-- Load the storage element refered to by the test <b>Id</b>.
-- ------------------------------
procedure Load (T : in out Test) is
use type Ada.Streams.Stream_Element_Offset;
Name : Ada.Strings.Unbounded.Unbounded_String;
Mime : Ada.Strings.Unbounded.Unbounded_String;
Date : Ada.Calendar.Time;
Data : ADO.Blob_Ref;
begin
T.Manager := AWA.Storages.Modules.Get_Storage_Manager;
T.Assert (T.Manager /= null, "Null storage manager");
T.Manager.Load (From => T.Id, Name => Name, Mime => Mime, Date => Date, Into => Data);
T.Assert (not Data.Is_Null, "Null blob returned by load");
T.Assert (Data.Value.Len > 100, "Invalid length for the blob data");
end Load;
-- ------------------------------
-- Test creation of a storage object
-- ------------------------------
procedure Test_Create_Storage (T : in out Test) is
Sec_Ctx : Security.Contexts.Security_Context;
Context : AWA.Services.Contexts.Service_Context;
begin
AWA.Tests.Helpers.Users.Login (Context, Sec_Ctx, "[email protected]");
T.Save;
T.Load;
end Test_Create_Storage;
procedure Test_File_Create_Storage (T : in out Test) is
begin
T.Kind := AWA.Storages.Models.FILE;
T.Test_Create_Storage;
end Test_File_Create_Storage;
-- ------------------------------
-- Test creation of a storage object and local file access after its creation.
-- ------------------------------
procedure Test_Get_Local_File (T : in out Test) is
Sec_Ctx : Security.Contexts.Security_Context;
Context : AWA.Services.Contexts.Service_Context;
begin
AWA.Tests.Helpers.Users.Login (Context, Sec_Ctx, "[email protected]");
T.Save;
declare
File : AWA.Storages.Storage_File (AWA.Storages.TMP);
begin
T.Manager.Get_Local_File (From => T.Id, Into => File);
T.Assert (AWA.Storages.Get_Path (File)'Length > 0, "Invalid local file path");
end;
end Test_Get_Local_File;
-- ------------------------------
-- Test deletion of a storage object
-- ------------------------------
procedure Test_Delete_Storage (T : in out Test) is
Sec_Ctx : Security.Contexts.Security_Context;
Context : AWA.Services.Contexts.Service_Context;
Data : ADO.Blob_Ref;
Name : Ada.Strings.Unbounded.Unbounded_String;
Mime : Ada.Strings.Unbounded.Unbounded_String;
Date : Ada.Calendar.Time;
begin
AWA.Tests.Helpers.Users.Login (Context, Sec_Ctx, "[email protected]");
T.Save;
T.Manager.Delete (T.Id);
begin
T.Manager.Load (From => T.Id, Name => Name, Mime => Mime, Date => Date, Into => Data);
T.Assert (False, "No exception raised");
exception
when ADO.Objects.NOT_FOUND =>
null;
end;
end Test_Delete_Storage;
-- ------------------------------
-- Test creation of a storage folder
-- ------------------------------
procedure Test_Create_Folder (T : in out Test) is
Sec_Ctx : Security.Contexts.Security_Context;
Context : AWA.Services.Contexts.Service_Context;
Folder : AWA.Storages.Beans.Folder_Bean;
Outcome : Ada.Strings.Unbounded.Unbounded_String;
Upload : AWA.Storages.Beans.Upload_Bean;
begin
AWA.Tests.Helpers.Users.Login (Context, Sec_Ctx, "[email protected]");
Folder.Module := AWA.Storages.Modules.Get_Storage_Module;
Upload.Module := AWA.Storages.Modules.Get_Storage_Module;
Folder.Set_Name ("Test folder name");
Folder.Save (Outcome);
Util.Tests.Assert_Equals (T, "success", Outcome, "Invalid outcome returned by Save action");
Upload.Set_Value ("folderId", ADO.Objects.To_Object (Folder.Get_Key));
Util.Tests.Assert_Equals (T, "Test folder name", String '(Upload.Get_Folder.Get_Name),
"Invalid folder name");
end Test_Create_Folder;
end AWA.Storages.Services.Tests;
|
Update the test to avoir using the Beans.Factories package
|
Update the test to avoir using the Beans.Factories package
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
61a67f03030ff16e73ab0c248507653a94c18807
|
regtests/util-streams-texts-tests.adb
|
regtests/util-streams-texts-tests.adb
|
-----------------------------------------------------------------------
-- streams.files.tests -- Unit tests for buffered streams
-- Copyright (C) 2012, 2018, 2019, 2021 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Ada.Streams.Stream_IO;
with Util.Test_Caller;
with Util.Streams.Files;
with Util.Streams.Texts;
package body Util.Streams.Texts.Tests is
use Ada.Streams.Stream_IO;
use Util.Tests;
package Caller is new Util.Test_Caller (Test, "Streams.Texts");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test Util.Streams.Texts.Open, Read_Line, Close",
Test_Read_Line'Access);
Caller.Add_Test (Suite, "Test Util.Streams.Texts.Write (Integer)",
Test_Write_Integer'Access);
Caller.Add_Test (Suite, "Test Util.Streams.Texts.Write (Long_Long_Integer)",
Test_Write_Long_Integer'Access);
Caller.Add_Test (Suite, "Test Util.Streams.Texts.Write (Unbounded_String)",
Test_Write'Access);
end Add_Tests;
-- ------------------------------
-- Test reading a text stream.
-- ------------------------------
procedure Test_Read_Line (T : in out Test) is
Stream : aliased Files.File_Stream;
Reader : Util.Streams.Texts.Reader_Stream;
Count : Natural := 0;
begin
Stream.Open (Name => "Makefile", Mode => In_File);
Reader.Initialize (From => Stream'Access);
while not Reader.Is_Eof loop
declare
Line : Ada.Strings.Unbounded.Unbounded_String;
begin
Reader.Read_Line (Line);
Count := Count + 1;
end;
end loop;
Stream.Close;
T.Assert (Count > 100, "Too few lines read");
end Test_Read_Line;
-- ------------------------------
-- Write on a text stream converting an integer and writing it.
-- ------------------------------
procedure Test_Write_Integer (T : in out Test) is
Stream : Print_Stream;
Buf : Ada.Strings.Unbounded.Unbounded_String;
begin
Stream.Initialize (Size => 4);
-- Write '0' (we don't want the Ada spurious space).
Stream.Write (Integer (0));
Assert_Equals (T, 1, Integer (Stream.Get_Size), "Invalid size for stream");
Stream.Flush (Buf);
Assert_Equals (T, 1, Ada.Strings.Unbounded.Length (Buf), "Invalid size for string");
Assert_Equals (T, "0", Ada.Strings.Unbounded.To_String (Buf), "Invalid stream content");
Assert_Equals (T, 0, Integer (Stream.Get_Size), "Invalid size for stream after Flush");
-- Write '1234'
Stream.Write (Integer (1234));
Assert_Equals (T, 4, Integer (Stream.Get_Size), "Invalid size for stream");
Stream.Flush (Buf);
Assert_Equals (T, 4, Ada.Strings.Unbounded.Length (Buf), "Invalid size for string");
Assert_Equals (T, "1234", Ada.Strings.Unbounded.To_String (Buf), "Invalid stream content");
Assert_Equals (T, 0, Integer (Stream.Get_Size), "Invalid size for stream after Flush");
-- Write '-234'
Stream.Write (Integer (-234));
Assert_Equals (T, 4, Integer (Stream.Get_Size), "Invalid size for stream");
Stream.Flush (Buf);
Assert_Equals (T, 4, Ada.Strings.Unbounded.Length (Buf), "Invalid size for string");
Assert_Equals (T, "-234", Ada.Strings.Unbounded.To_String (Buf), "Invalid stream content");
Assert_Equals (T, 0, Integer (Stream.Get_Size), "Invalid size for stream after Flush");
end Test_Write_Integer;
-- ------------------------------
-- Write on a text stream converting an integer and writing it.
-- ------------------------------
procedure Test_Write_Long_Integer (T : in out Test) is
Stream : Print_Stream;
Buf : Ada.Strings.Unbounded.Unbounded_String;
begin
Stream.Initialize (Size => 64);
-- Write '0' (we don't want the Ada spurious space).
Stream.Write (Long_Long_Integer (0));
Assert_Equals (T, 1, Integer (Stream.Get_Size), "Invalid size for stream");
Stream.Flush (Buf);
Assert_Equals (T, 1, Ada.Strings.Unbounded.Length (Buf), "Invalid size for string");
Assert_Equals (T, "0", Ada.Strings.Unbounded.To_String (Buf), "Invalid stream content");
Assert_Equals (T, 0, Integer (Stream.Get_Size), "Invalid size for stream after Flush");
-- Write '1234'
Stream.Write (Long_Long_Integer (123456789012345));
Assert_Equals (T, 15, Integer (Stream.Get_Size), "Invalid size for stream");
Stream.Flush (Buf);
Assert_Equals (T, 15, Ada.Strings.Unbounded.Length (Buf), "Invalid size for string");
Assert_Equals (T, "123456789012345", Ada.Strings.Unbounded.To_String (Buf),
"Invalid stream content");
Assert_Equals (T, 0, Integer (Stream.Get_Size), "Invalid size for stream after Flush");
-- Write '-2345678901234'
Stream.Write (Long_Long_Integer (-2345678901234));
Assert_Equals (T, 14, Integer (Stream.Get_Size), "Invalid size for stream");
Stream.Flush (Buf);
Assert_Equals (T, 14, Ada.Strings.Unbounded.Length (Buf), "Invalid size for string");
Assert_Equals (T, "-2345678901234", Ada.Strings.Unbounded.To_String (Buf),
"Invalid stream content");
Assert_Equals (T, 0, Integer (Stream.Get_Size), "Invalid size for stream after Flush");
end Test_Write_Long_Integer;
-- ------------------------------
-- Write on a text stream converting an integer and writing it.
-- ------------------------------
procedure Test_Write (T : in out Test) is
use Ada.Strings.Unbounded;
Stream : Print_Stream;
Buf : Ada.Strings.Unbounded.Unbounded_String;
begin
Stream.Initialize (Size => 10);
Stream.Write (Ada.Strings.Unbounded.To_Unbounded_String ("hello"));
Assert_Equals (T, 5, Integer (Stream.Get_Size), "Invalid size for stream");
Stream.Flush (Buf);
Assert_Equals (T, 5, Ada.Strings.Unbounded.Length (Buf), "Invalid size for string");
Assert_Equals (T, "hello", Ada.Strings.Unbounded.To_String (Buf), "Invalid stream content");
Assert_Equals (T, 0, Integer (Stream.Get_Size), "Invalid size for stream after Flush");
-- Wide string
Stream.Write (Ada.Strings.Wide_Wide_Unbounded.To_Unbounded_Wide_Wide_String ("hello"));
Assert_Equals (T, 5, Integer (Stream.Get_Size), "Invalid size for stream");
Stream.Flush (Buf);
Assert_Equals (T, 5, Ada.Strings.Unbounded.Length (Buf), "Invalid size for string");
Assert_Equals (T, "hello", Ada.Strings.Unbounded.To_String (Buf), "Invalid stream content");
Assert_Equals (T, 0, Integer (Stream.Get_Size), "Invalid size for stream after Flush");
end Test_Write;
end Util.Streams.Texts.Tests;
|
-----------------------------------------------------------------------
-- streams.files.tests -- Unit tests for buffered streams
-- Copyright (C) 2012, 2018, 2019, 2021 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Ada.Streams.Stream_IO;
with Ada.Strings.UTF_Encoding.Wide_Wide_Strings;
with Util.Test_Caller;
with Util.Streams.Files;
with Util.Streams.Texts;
package body Util.Streams.Texts.Tests is
pragma Wide_Character_Encoding (UTF8);
use Ada.Streams.Stream_IO;
use Util.Tests;
package Caller is new Util.Test_Caller (Test, "Streams.Texts");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test Util.Streams.Texts.Open, Read_Line, Close",
Test_Read_Line'Access);
Caller.Add_Test (Suite, "Test Util.Streams.Texts.Write (Integer)",
Test_Write_Integer'Access);
Caller.Add_Test (Suite, "Test Util.Streams.Texts.Write (Long_Long_Integer)",
Test_Write_Long_Integer'Access);
Caller.Add_Test (Suite, "Test Util.Streams.Texts.Write (Unbounded_String)",
Test_Write'Access);
end Add_Tests;
-- ------------------------------
-- Test reading a text stream.
-- ------------------------------
procedure Test_Read_Line (T : in out Test) is
Stream : aliased Files.File_Stream;
Reader : Util.Streams.Texts.Reader_Stream;
Count : Natural := 0;
begin
Stream.Open (Name => "Makefile", Mode => In_File);
Reader.Initialize (From => Stream'Access);
while not Reader.Is_Eof loop
declare
Line : Ada.Strings.Unbounded.Unbounded_String;
begin
Reader.Read_Line (Line);
Count := Count + 1;
end;
end loop;
Stream.Close;
T.Assert (Count > 100, "Too few lines read");
end Test_Read_Line;
-- ------------------------------
-- Write on a text stream converting an integer and writing it.
-- ------------------------------
procedure Test_Write_Integer (T : in out Test) is
Stream : Print_Stream;
Buf : Ada.Strings.Unbounded.Unbounded_String;
begin
Stream.Initialize (Size => 4);
-- Write '0' (we don't want the Ada spurious space).
Stream.Write (Integer (0));
Assert_Equals (T, 1, Integer (Stream.Get_Size), "Invalid size for stream");
Stream.Flush (Buf);
Assert_Equals (T, 1, Ada.Strings.Unbounded.Length (Buf), "Invalid size for string");
Assert_Equals (T, "0", Ada.Strings.Unbounded.To_String (Buf), "Invalid stream content");
Assert_Equals (T, 0, Integer (Stream.Get_Size), "Invalid size for stream after Flush");
-- Write '1234'
Stream.Write (Integer (1234));
Assert_Equals (T, 4, Integer (Stream.Get_Size), "Invalid size for stream");
Stream.Flush (Buf);
Assert_Equals (T, 4, Ada.Strings.Unbounded.Length (Buf), "Invalid size for string");
Assert_Equals (T, "1234", Ada.Strings.Unbounded.To_String (Buf), "Invalid stream content");
Assert_Equals (T, 0, Integer (Stream.Get_Size), "Invalid size for stream after Flush");
-- Write '-234'
Stream.Write (Integer (-234));
Assert_Equals (T, 4, Integer (Stream.Get_Size), "Invalid size for stream");
Stream.Flush (Buf);
Assert_Equals (T, 4, Ada.Strings.Unbounded.Length (Buf), "Invalid size for string");
Assert_Equals (T, "-234", Ada.Strings.Unbounded.To_String (Buf), "Invalid stream content");
Assert_Equals (T, 0, Integer (Stream.Get_Size), "Invalid size for stream after Flush");
end Test_Write_Integer;
-- ------------------------------
-- Write on a text stream converting an integer and writing it.
-- ------------------------------
procedure Test_Write_Long_Integer (T : in out Test) is
Stream : Print_Stream;
Buf : Ada.Strings.Unbounded.Unbounded_String;
begin
Stream.Initialize (Size => 64);
-- Write '0' (we don't want the Ada spurious space).
Stream.Write (Long_Long_Integer (0));
Assert_Equals (T, 1, Integer (Stream.Get_Size), "Invalid size for stream");
Stream.Flush (Buf);
Assert_Equals (T, 1, Ada.Strings.Unbounded.Length (Buf), "Invalid size for string");
Assert_Equals (T, "0", Ada.Strings.Unbounded.To_String (Buf), "Invalid stream content");
Assert_Equals (T, 0, Integer (Stream.Get_Size), "Invalid size for stream after Flush");
-- Write '1234'
Stream.Write (Long_Long_Integer (123456789012345));
Assert_Equals (T, 15, Integer (Stream.Get_Size), "Invalid size for stream");
Stream.Flush (Buf);
Assert_Equals (T, 15, Ada.Strings.Unbounded.Length (Buf), "Invalid size for string");
Assert_Equals (T, "123456789012345", Ada.Strings.Unbounded.To_String (Buf),
"Invalid stream content");
Assert_Equals (T, 0, Integer (Stream.Get_Size), "Invalid size for stream after Flush");
-- Write '-2345678901234'
Stream.Write (Long_Long_Integer (-2345678901234));
Assert_Equals (T, 14, Integer (Stream.Get_Size), "Invalid size for stream");
Stream.Flush (Buf);
Assert_Equals (T, 14, Ada.Strings.Unbounded.Length (Buf), "Invalid size for string");
Assert_Equals (T, "-2345678901234", Ada.Strings.Unbounded.To_String (Buf),
"Invalid stream content");
Assert_Equals (T, 0, Integer (Stream.Get_Size), "Invalid size for stream after Flush");
end Test_Write_Long_Integer;
-- ------------------------------
-- Write on a text stream converting an integer and writing it.
-- ------------------------------
procedure Test_Write (T : in out Test) is
use Ada.Strings.UTF_Encoding.Wide_Wide_Strings;
Stream : Print_Stream;
Buf : Ada.Strings.Unbounded.Unbounded_String;
Expect : constant Wide_Wide_String := "àéúíòࠀ€ಜ࠴𝄞" & Wide_Wide_Character'Val (16#0A#);
begin
Stream.Initialize (Size => 60);
Stream.Write (Ada.Strings.Unbounded.To_Unbounded_String ("hello"));
Assert_Equals (T, 5, Integer (Stream.Get_Size), "Invalid size for stream");
Stream.Flush (Buf);
Assert_Equals (T, 5, Ada.Strings.Unbounded.Length (Buf), "Invalid size for string");
Assert_Equals (T, "hello", Ada.Strings.Unbounded.To_String (Buf), "Invalid stream content");
Assert_Equals (T, 0, Integer (Stream.Get_Size), "Invalid size for stream after Flush");
-- Wide string
Stream.Write (Ada.Strings.Wide_Wide_Unbounded.To_Unbounded_Wide_Wide_String ("hello"));
Assert_Equals (T, 5, Integer (Stream.Get_Size), "Invalid size for stream");
Stream.Flush (Buf);
Assert_Equals (T, 5, Ada.Strings.Unbounded.Length (Buf), "Invalid size for string");
Assert_Equals (T, "hello", Ada.Strings.Unbounded.To_String (Buf), "Invalid stream content");
Assert_Equals (T, 0, Integer (Stream.Get_Size), "Invalid size for stream after Flush");
-- Wide string
Stream.Write_Wide (Expect);
Assert_Equals (T, 27, Integer (Stream.Get_Size), "Invalid size for stream");
Stream.Flush (Buf);
Assert_Equals (T, 27, Ada.Strings.Unbounded.Length (Buf), "Invalid size for string");
Assert_Equals (T, Encode (Expect),
Ada.Strings.Unbounded.To_String (Buf),
"Invalid stream content");
Assert_Equals (T, 0, Integer (Stream.Get_Size), "Invalid size for stream after Flush");
end Test_Write;
end Util.Streams.Texts.Tests;
|
Add test for Write_Wide procedure
|
Add test for Write_Wide procedure
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
ccb66b4eca8d15273120ec6550911bed689be335
|
src/gen-artifacts-xmi.ads
|
src/gen-artifacts-xmi.ads
|
-----------------------------------------------------------------------
-- gen-artifacts-xmi -- UML-XMI artifact for Code Generator
-- Copyright (C) 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with DOM.Core;
with Gen.Model.Packages;
with Gen.Model.XMI;
-- The <b>Gen.Artifacts.XMI</b> package is an artifact for the generation of Ada code
-- from an UML XMI description.
package Gen.Artifacts.XMI is
-- ------------------------------
-- UML XMI artifact
-- ------------------------------
type Artifact is new Gen.Artifacts.Artifact with private;
-- After the configuration file is read, processes the node whose root
-- is passed in <b>Node</b> and initializes the <b>Model</b> with the information.
overriding
procedure Initialize (Handler : in out Artifact;
Path : in String;
Node : in DOM.Core.Node;
Model : in out Gen.Model.Packages.Model_Definition'Class;
Context : in out Generator'Class);
-- Prepare the model after all the configuration files have been read and before
-- actually invoking the generation.
overriding
procedure Prepare (Handler : in out Artifact;
Model : in out Gen.Model.Packages.Model_Definition'Class;
Context : in out Generator'Class);
-- Read the UML/XMI model file.
procedure Read_Model (Handler : in out Artifact;
File : in String;
Context : in out Generator'Class);
-- Read the UML configuration files that define the pre-defined types, stereotypes
-- and other components used by a model. These files are XMI files as well.
-- All the XMI files in the UML config directory are read.
procedure Read_UML_Configuration (Handler : in out Artifact;
Context : in out Generator'Class);
private
type Artifact is new Gen.Artifacts.Artifact with record
Nodes : aliased Gen.Model.XMI.UML_Model;
Has_Config : Boolean := False;
-- Stereotype which triggers the generation of database table.
Table_Stereotype : Gen.Model.XMI.Stereotype_Element_Access;
PK_Stereotype : Gen.Model.XMI.Stereotype_Element_Access;
FK_Stereotype : Gen.Model.XMI.Stereotype_Element_Access;
Data_Model_Stereotype : Gen.Model.XMI.Stereotype_Element_Access;
Nullable_Stereotype : Gen.Model.XMI.Stereotype_Element_Access;
Not_Null_Stereotype : Gen.Model.XMI.Stereotype_Element_Access;
-- Tag definitions which control the generation.
Has_List_Tag : Gen.Model.XMI.Tag_Definition_Element_Access;
Table_Name_Tag : Gen.Model.XMI.Tag_Definition_Element_Access;
-- Stereotype which triggers the generation of AWA bean types.
Bean_Stereotype : Gen.Model.XMI.Stereotype_Element_Access;
end record;
end Gen.Artifacts.XMI;
|
-----------------------------------------------------------------------
-- gen-artifacts-xmi -- UML-XMI artifact for Code Generator
-- Copyright (C) 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with DOM.Core;
with Gen.Model.Packages;
with Gen.Model.XMI;
-- The <b>Gen.Artifacts.XMI</b> package is an artifact for the generation of Ada code
-- from an UML XMI description.
package Gen.Artifacts.XMI is
-- ------------------------------
-- UML XMI artifact
-- ------------------------------
type Artifact is new Gen.Artifacts.Artifact with private;
-- After the configuration file is read, processes the node whose root
-- is passed in <b>Node</b> and initializes the <b>Model</b> with the information.
overriding
procedure Initialize (Handler : in out Artifact;
Path : in String;
Node : in DOM.Core.Node;
Model : in out Gen.Model.Packages.Model_Definition'Class;
Context : in out Generator'Class);
-- Prepare the model after all the configuration files have been read and before
-- actually invoking the generation.
overriding
procedure Prepare (Handler : in out Artifact;
Model : in out Gen.Model.Packages.Model_Definition'Class;
Context : in out Generator'Class);
-- Read the UML/XMI model file.
procedure Read_Model (Handler : in out Artifact;
File : in String;
Context : in out Generator'Class);
-- Read the UML configuration files that define the pre-defined types, stereotypes
-- and other components used by a model. These files are XMI files as well.
-- All the XMI files in the UML config directory are read.
procedure Read_UML_Configuration (Handler : in out Artifact;
Context : in out Generator'Class);
private
type Artifact is new Gen.Artifacts.Artifact with record
Nodes : aliased Gen.Model.XMI.UML_Model;
Has_Config : Boolean := False;
-- Stereotype which triggers the generation of database table.
Table_Stereotype : Gen.Model.XMI.Stereotype_Element_Access;
PK_Stereotype : Gen.Model.XMI.Stereotype_Element_Access;
FK_Stereotype : Gen.Model.XMI.Stereotype_Element_Access;
Data_Model_Stereotype : Gen.Model.XMI.Stereotype_Element_Access;
Nullable_Stereotype : Gen.Model.XMI.Stereotype_Element_Access;
Not_Null_Stereotype : Gen.Model.XMI.Stereotype_Element_Access;
Use_FK_Stereotype : Gen.Model.XMI.Stereotype_Element_Access;
-- Tag definitions which control the generation.
Has_List_Tag : Gen.Model.XMI.Tag_Definition_Element_Access;
Table_Name_Tag : Gen.Model.XMI.Tag_Definition_Element_Access;
-- Stereotype which triggers the generation of AWA bean types.
Bean_Stereotype : Gen.Model.XMI.Stereotype_Element_Access;
end record;
end Gen.Artifacts.XMI;
|
Add the use foreign key stereotype
|
Add the use foreign key stereotype
|
Ada
|
apache-2.0
|
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
|
d07926e61979300d219ec23d41a9d491f1447065
|
src/gen-commands-docs.adb
|
src/gen-commands-docs.adb
|
-----------------------------------------------------------------------
-- gen-commands-docs -- Extract and generate documentation for the project
-- Copyright (C) 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with GNAT.Command_Line;
with Ada.Text_IO;
with Gen.Artifacts.Docs;
with Gen.Model.Packages;
package body Gen.Commands.Docs is
use GNAT.Command_Line;
-- ------------------------------
-- Execute the command with the arguments.
-- ------------------------------
procedure Execute (Cmd : in Command;
Generator : in out Gen.Generator.Handler) is
pragma Unreferenced (Cmd);
Doc : Gen.Artifacts.Docs.Artifact;
M : Gen.Model.Packages.Model_Definition;
begin
Generator.Read_Project ("dynamo.xml", False);
-- Setup the target directory where the distribution is created.
declare
Target_Dir : constant String := Get_Argument;
begin
if Target_Dir'Length = 0 then
Generator.Error ("Missing target directory");
return;
end if;
Generator.Set_Result_Directory (Target_Dir);
end;
--
-- -- Read the package description.
-- declare
-- Package_File : constant String := Get_Argument;
-- begin
-- if Package_File'Length > 0 then
-- Gen.Generator.Read_Package (Generator, Package_File);
-- else
-- Gen.Generator.Read_Package (Generator, "package.xml");
-- end if;
-- end;
Doc.Prepare (M, Generator);
-- -- Run the generation.
-- Gen.Generator.Prepare (Generator);
-- Gen.Generator.Generate_All (Generator);
-- Gen.Generator.Finish (Generator);
end Execute;
-- ------------------------------
-- Write the help associated with the command.
-- ------------------------------
procedure Help (Cmd : in Command;
Generator : in out Gen.Generator.Handler) is
pragma Unreferenced (Cmd, Generator);
use Ada.Text_IO;
begin
Put_Line ("build-doc: Extract and generate the project documentation");
Put_Line ("Usage: build-doc");
New_Line;
Put_Line (" Extract the documentation from the project source files and generate the");
Put_Line (" project documentation. The following files are scanned:");
Put_Line (" - Ada specifications (src/*.ads)");
Put_Line (" - XML configuration files (config/*.xml)");
Put_Line (" - XML database model files (db/*.xml)");
end Help;
end Gen.Commands.Docs;
|
-----------------------------------------------------------------------
-- gen-commands-docs -- Extract and generate documentation for the project
-- Copyright (C) 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with GNAT.Command_Line;
with Ada.Text_IO;
with Gen.Artifacts.Docs;
with Gen.Model.Packages;
package body Gen.Commands.Docs is
use GNAT.Command_Line;
-- ------------------------------
-- Execute the command with the arguments.
-- ------------------------------
procedure Execute (Cmd : in Command;
Generator : in out Gen.Generator.Handler) is
pragma Unreferenced (Cmd);
Doc : Gen.Artifacts.Docs.Artifact;
M : Gen.Model.Packages.Model_Definition;
begin
Generator.Read_Project ("dynamo.xml", False);
-- Setup the target directory where the distribution is created.
declare
Target_Dir : constant String := Get_Argument;
begin
if Target_Dir'Length = 0 then
Generator.Error ("Missing target directory");
return;
end if;
Generator.Set_Result_Directory (Target_Dir);
end;
Doc.Prepare (M, Generator);
end Execute;
-- ------------------------------
-- Write the help associated with the command.
-- ------------------------------
procedure Help (Cmd : in Command;
Generator : in out Gen.Generator.Handler) is
pragma Unreferenced (Cmd, Generator);
use Ada.Text_IO;
begin
Put_Line ("build-doc: Extract and generate the project documentation");
Put_Line ("Usage: build-doc");
New_Line;
Put_Line (" Extract the documentation from the project source files and generate the");
Put_Line (" project documentation. The following files are scanned:");
Put_Line (" - Ada specifications (src/*.ads)");
Put_Line (" - XML configuration files (config/*.xml)");
Put_Line (" - XML database model files (db/*.xml)");
end Help;
end Gen.Commands.Docs;
|
Remove unused commented code
|
Remove unused commented code
|
Ada
|
apache-2.0
|
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
|
807b9b65c668ed21f63bf6bbfaed0813586d0dba
|
src/gen-commands-page.adb
|
src/gen-commands-page.adb
|
-----------------------------------------------------------------------
-- gen-commands-page -- Page creation command for dynamo
-- Copyright (C) 2011, 2012, 2013, 2014 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Directories;
with Ada.Text_IO;
with Gen.Artifacts;
with GNAT.Command_Line;
with Util.Strings;
package body Gen.Commands.Page is
-- ------------------------------
-- Execute the command with the arguments.
-- ------------------------------
procedure Execute (Cmd : in Command;
Generator : in out Gen.Generator.Handler) is
pragma Unreferenced (Cmd);
use GNAT.Command_Line;
use Ada.Strings.Unbounded;
function Get_Layout return String;
function Get_Name return String;
Dir : constant String := Generator.Get_Result_Directory & "web/";
function Get_Name return String is
Name : constant String := Get_Argument;
Pos : constant Natural := Util.Strings.Rindex (Name, '.');
begin
if Pos = 0 then
return Name;
elsif Name (Pos .. Name'Last) = ".xhtml" then
return Name (Name'First .. Pos - 1);
elsif Name (Pos .. Name'Last) = ".html" then
return Name (Name'First .. Pos - 1);
else
return Name;
end if;
end Get_Name;
function Get_Layout return String is
Layout : constant String := Get_Argument;
begin
if Layout'Length = 0 then
return "layout";
end if;
if Ada.Directories.Exists (Dir & "WEB-INF/layouts/" & Layout & ".xhtml") then
return Layout;
end if;
Generator.Error ("Layout file {0} not found. Using 'layout' instead.", Layout);
return "layout";
end Get_Layout;
Name : constant String := Get_Name;
Layout : constant String := Get_Layout;
begin
if Name'Length = 0 then
Gen.Commands.Usage;
return;
end if;
Generator.Set_Force_Save (False);
Generator.Set_Result_Directory (Dir);
Generator.Set_Global ("pageName", Name);
Generator.Set_Global ("layout", Layout);
Gen.Generator.Generate_All (Generator, Gen.Artifacts.ITERATION_TABLE, "page");
end Execute;
-- ------------------------------
-- Write the help associated with the command.
-- ------------------------------
procedure Help (Cmd : in Command;
Generator : in out Gen.Generator.Handler) is
pragma Unreferenced (Cmd);
use Ada.Text_IO;
use Ada.Directories;
Path : constant String := Generator.Get_Result_Directory & "web/WEB-INF/layouts";
Filter : constant Filter_Type := (Ordinary_File => True, others => False);
Search : Search_Type;
Ent : Directory_Entry_Type;
begin
Put_Line ("add-page: Add a new web page to the application");
Put_Line ("Usage: add-page NAME [LAYOUT]");
New_Line;
Put_Line (" The web page is an XHTML file created under the 'web' directory.");
Put_Line (" The NAME can contain a directory that will be created if necessary.");
Put_Line (" The new web page can be configured to use the given layout.");
Put_Line (" The layout file must exist to be used. The default layout is 'layout'.");
Put_Line (" You can create a new layout with 'add-layout' command.");
Put_Line (" You can also write your layout by adding an XHTML file in the directory:");
Put_Line (" " & Path);
if Exists (Path) then
New_Line;
Put_Line (" Available layouts:");
Start_Search (Search, Directory => Path, Pattern => "*.xhtml", Filter => Filter);
while More_Entries (Search) loop
Get_Next_Entry (Search, Ent);
declare
Name : constant String := Simple_Name (Ent);
Layout : constant String := Base_Name (Name);
begin
Put_Line (" " & Layout);
end;
end loop;
end if;
New_Line;
Put_Line (" The following files are generated:");
Put_Line (" web/<name>.xhtml");
end Help;
end Gen.Commands.Page;
|
-----------------------------------------------------------------------
-- gen-commands-page -- Page creation command for dynamo
-- Copyright (C) 2011, 2012, 2013, 2014 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Directories;
with Ada.Text_IO;
with Gen.Artifacts;
with GNAT.Command_Line;
with Util.Strings;
package body Gen.Commands.Page is
-- ------------------------------
-- Execute the command with the arguments.
-- ------------------------------
procedure Execute (Cmd : in Command;
Generator : in out Gen.Generator.Handler) is
pragma Unreferenced (Cmd);
use GNAT.Command_Line;
use Ada.Strings.Unbounded;
function Get_Layout return String;
function Get_Name return String;
Dir : constant String := Generator.Get_Result_Directory & "web/";
function Get_Name return String is
Name : constant String := Get_Argument;
Pos : constant Natural := Util.Strings.Rindex (Name, '.');
begin
if Pos = 0 then
return Name;
elsif Name (Pos .. Name'Last) = ".xhtml" then
return Name (Name'First .. Pos - 1);
elsif Name (Pos .. Name'Last) = ".html" then
return Name (Name'First .. Pos - 1);
else
return Name;
end if;
end Get_Name;
function Get_Layout return String is
Layout : constant String := Get_Argument;
begin
if Layout'Length = 0 then
return "layout";
end if;
if Ada.Directories.Exists (Dir & "WEB-INF/layouts/" & Layout & ".xhtml") then
return Layout;
end if;
Generator.Info ("Layout file {0} not found.", Layout);
return Layout;
end Get_Layout;
Name : constant String := Get_Name;
Layout : constant String := Get_Layout;
begin
if Name'Length = 0 then
Gen.Commands.Usage;
return;
end if;
Generator.Set_Force_Save (False);
Generator.Set_Result_Directory (Dir);
Generator.Set_Global ("pageName", Name);
Generator.Set_Global ("layout", Layout);
Gen.Generator.Generate_All (Generator, Gen.Artifacts.ITERATION_TABLE, "page");
end Execute;
-- ------------------------------
-- Write the help associated with the command.
-- ------------------------------
procedure Help (Cmd : in Command;
Generator : in out Gen.Generator.Handler) is
pragma Unreferenced (Cmd);
use Ada.Text_IO;
use Ada.Directories;
Path : constant String := Generator.Get_Result_Directory & "web/WEB-INF/layouts";
Filter : constant Filter_Type := (Ordinary_File => True, others => False);
Search : Search_Type;
Ent : Directory_Entry_Type;
begin
Put_Line ("add-page: Add a new web page to the application");
Put_Line ("Usage: add-page NAME [LAYOUT]");
New_Line;
Put_Line (" The web page is an XHTML file created under the 'web' directory.");
Put_Line (" The NAME can contain a directory that will be created if necessary.");
Put_Line (" The new web page can be configured to use the given layout.");
Put_Line (" The layout file must exist to be used. The default layout is 'layout'.");
Put_Line (" You can create a new layout with 'add-layout' command.");
Put_Line (" You can also write your layout by adding an XHTML file in the directory:");
Put_Line (" " & Path);
if Exists (Path) then
New_Line;
Put_Line (" Available layouts:");
Start_Search (Search, Directory => Path, Pattern => "*.xhtml", Filter => Filter);
while More_Entries (Search) loop
Get_Next_Entry (Search, Ent);
declare
Name : constant String := Simple_Name (Ent);
Layout : constant String := Base_Name (Name);
begin
Put_Line (" " & Layout);
end;
end loop;
end if;
New_Line;
Put_Line (" The following files are generated:");
Put_Line (" web/<name>.xhtml");
end Help;
end Gen.Commands.Page;
|
Allow to use a layout that is located outside of the user WEB-INF directory
|
Allow to use a layout that is located outside of the user WEB-INF directory
|
Ada
|
apache-2.0
|
Letractively/ada-gen,Letractively/ada-gen,Letractively/ada-gen,Letractively/ada-gen
|
65bd03242d1c166c92a3724584bc9fba5536d508
|
src/babel-strategies.ads
|
src/babel-strategies.ads
|
-----------------------------------------------------------------------
-- babel-strategies -- Strategies to backup files
-- Copyright (C) 2014 Stephane.Carrez
-- Written by Stephane.Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
pragma Ada_2012;
with Babel.Files;
with Babel.Files.Buffers;
with Babel.Stores;
with Babel.Filters;
package Babel.Strategies is
type Strategy_Type is abstract limited new Babel.Files.File_Container with private;
type Strategy_Type_Access is access all Strategy_Type'Class;
-- Allocate a buffer to read the file content.
function Allocate_Buffer (Strategy : in Strategy_Type) return Babel.Files.Buffers.Buffer_Access;
-- Release the buffer that was allocated by Allocate_Buffer.
procedure Release_Buffer (Strategy : in Strategy_Type;
Buffer : in out Babel.Files.Buffers.Buffer_Access);
-- Returns true if there is a directory that must be processed by the current strategy.
function Has_Directory (Strategy : in Strategy_Type) return Boolean is abstract;
-- Get the next directory that must be processed by the strategy.
function Peek_Directory (Strategy : in out Strategy_Type) return String is abstract;
procedure Scan (Strategy : in out Strategy_Type;
Path : in String);
-- Read the file from the read store into the local buffer.
procedure Read_File (Strategy : in Strategy_Type;
File : in Babel.Files.File_Type;
Into : in Babel.Files.Buffers.Buffer_Access);
-- Write the file from the local buffer into the write store.
procedure Write_File (Strategy : in Strategy_Type;
File : in Babel.Files.File_Type;
Content : in Babel.Files.Buffers.Buffer_Access);
-- Backup the file from the local buffer into the write store.
procedure Backup_File (Strategy : in Strategy_Type;
File : in Babel.Files.File_Type;
Content : in out Babel.Files.Buffers.Buffer_Access);
procedure Execute (Strategy : in out Strategy_Type) is abstract;
-- Set the file filters that will be used when scanning the read store.
procedure Set_Filters (Strategy : in out Strategy_Type;
Filters : in Babel.Filters.Filter_Type_Access);
-- Set the read and write stores that the strategy will use.
procedure Set_Stores (Strategy : in out Strategy_Type;
Read : in Babel.Stores.Store_Type_Access;
Write : in Babel.Stores.Store_Type_Access);
-- Set the buffer pool to be used by Allocate_Buffer.
procedure Set_Buffers (Strategy : in out Strategy_Type;
Buffers : in Babel.Files.Buffers.Buffer_Pool_Access);
private
type Strategy_Type is abstract limited new Babel.Files.File_Container with record
Read_Store : Babel.Stores.Store_Type_Access;
Write_Store : Babel.Stores.Store_Type_Access;
Filters : Babel.Filters.Filter_Type_Access;
Buffers : Babel.Files.Buffers.Buffer_Pool_Access;
end record;
end Babel.Strategies;
|
-----------------------------------------------------------------------
-- babel-strategies -- Strategies to backup files
-- Copyright (C) 2014 Stephane.Carrez
-- Written by Stephane.Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
pragma Ada_2012;
with Babel.Files;
with Babel.Files.Buffers;
with Babel.Stores;
with Babel.Filters;
package Babel.Strategies is
type Strategy_Type is abstract limited new Babel.Files.File_Container with private;
type Strategy_Type_Access is access all Strategy_Type'Class;
-- Allocate a buffer to read the file content.
function Allocate_Buffer (Strategy : in Strategy_Type) return Babel.Files.Buffers.Buffer_Access;
-- Release the buffer that was allocated by Allocate_Buffer.
procedure Release_Buffer (Strategy : in Strategy_Type;
Buffer : in out Babel.Files.Buffers.Buffer_Access);
-- Returns true if there is a directory that must be processed by the current strategy.
function Has_Directory (Strategy : in Strategy_Type) return Boolean is abstract;
-- Get the next directory that must be processed by the strategy.
procedure Peek_Directory (Strategy : in out Strategy_Type;
Directory : out Babel.Files.Directory_Type) is abstract;
procedure Scan (Strategy : in out Strategy_Type;
Path : in String);
-- Read the file from the read store into the local buffer.
procedure Read_File (Strategy : in Strategy_Type;
File : in Babel.Files.File_Type;
Into : in Babel.Files.Buffers.Buffer_Access);
-- Write the file from the local buffer into the write store.
procedure Write_File (Strategy : in Strategy_Type;
File : in Babel.Files.File_Type;
Content : in Babel.Files.Buffers.Buffer_Access);
-- Backup the file from the local buffer into the write store.
procedure Backup_File (Strategy : in Strategy_Type;
File : in Babel.Files.File_Type;
Content : in out Babel.Files.Buffers.Buffer_Access);
procedure Execute (Strategy : in out Strategy_Type) is abstract;
-- Set the file filters that will be used when scanning the read store.
procedure Set_Filters (Strategy : in out Strategy_Type;
Filters : in Babel.Filters.Filter_Type_Access);
-- Set the read and write stores that the strategy will use.
procedure Set_Stores (Strategy : in out Strategy_Type;
Read : in Babel.Stores.Store_Type_Access;
Write : in Babel.Stores.Store_Type_Access);
-- Set the buffer pool to be used by Allocate_Buffer.
procedure Set_Buffers (Strategy : in out Strategy_Type;
Buffers : in Babel.Files.Buffers.Buffer_Pool_Access);
private
type Strategy_Type is abstract limited new Babel.Files.File_Container with record
Read_Store : Babel.Stores.Store_Type_Access;
Write_Store : Babel.Stores.Store_Type_Access;
Filters : Babel.Filters.Filter_Type_Access;
Buffers : Babel.Files.Buffers.Buffer_Pool_Access;
end record;
end Babel.Strategies;
|
Change the Peek_Directory to a procedure
|
Change the Peek_Directory to a procedure
|
Ada
|
apache-2.0
|
stcarrez/babel
|
dc459068758d4dbdbd17c225913c40e3440ff986
|
awa/src/awa-users-modules.adb
|
awa/src/awa-users-modules.adb
|
-----------------------------------------------------------------------
-- awa-users-model -- User management module
-- Copyright (C) 2009, 2010, 2011, 2012, 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with AWA.Modules.Beans;
with AWA.Modules.Get;
with AWA.Applications;
with AWA.Users.Beans;
with Util.Log.Loggers;
package body AWA.Users.Modules is
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("AWA.Users.Module");
package Register is new AWA.Modules.Beans (Module => User_Module,
Module_Access => User_Module_Access);
-- ------------------------------
-- Initialize the user module.
-- ------------------------------
overriding
procedure Initialize (Plugin : in out User_Module;
App : in AWA.Modules.Application_Access;
Props : in ASF.Applications.Config) is
begin
Log.Info ("Initializing the users module");
-- Setup the resource bundles.
App.Register ("userMsg", "users");
-- Register the OpenID servlets.
App.Add_Servlet (Name => "openid-auth",
Server => Plugin.Auth'Unchecked_Access);
App.Add_Servlet (Name => "openid-verify",
Server => Plugin.Verify_Auth'Unchecked_Access);
-- Setup the verify access key filter.
App.Add_Filter ("verify-access-key", Plugin.Key_Filter'Unchecked_Access);
App.Add_Filter ("auth-filter", Plugin.Auth_Filter'Unchecked_Access);
Register.Register (Plugin => Plugin,
Name => "AWA.Users.Beans.Authenticate_Bean",
Handler => AWA.Users.Beans.Create_Authenticate_Bean'Access);
Register.Register (Plugin => Plugin,
Name => "AWA.Users.Beans.Current_User_Bean",
Handler => AWA.Users.Beans.Create_Current_User_Bean'Access);
AWA.Modules.Module (Plugin).Initialize (App, Props);
-- Create the user manager when everything is initialized.
Plugin.Manager := Plugin.Create_User_Manager;
end Initialize;
-- ------------------------------
-- Get the user manager.
-- ------------------------------
function Get_User_Manager (Plugin : in User_Module) return Services.User_Service_Access is
begin
return Plugin.Manager;
end Get_User_Manager;
-- ------------------------------
-- Create a user manager. This operation can be overriden to provide another
-- user service implementation.
-- ------------------------------
function Create_User_Manager (Plugin : in User_Module) return Services.User_Service_Access is
Result : constant Services.User_Service_Access := new Services.User_Service;
begin
Result.Initialize (Plugin);
return Result;
end Create_User_Manager;
-- ------------------------------
-- Get the user module instance associated with the current application.
-- ------------------------------
function Get_User_Module return User_Module_Access is
function Get is new AWA.Modules.Get (User_Module, User_Module_Access, NAME);
begin
return Get;
end Get_User_Module;
-- ------------------------------
-- Get the user manager instance associated with the current application.
-- ------------------------------
function Get_User_Manager return Services.User_Service_Access is
Module : constant User_Module_Access := Get_User_Module;
begin
if Module = null then
Log.Error ("There is no active User_Module");
return null;
else
return Module.Get_User_Manager;
end if;
end Get_User_Manager;
end AWA.Users.Modules;
|
-----------------------------------------------------------------------
-- awa-users-model -- User management module
-- Copyright (C) 2009, 2010, 2011, 2012, 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with AWA.Modules.Beans;
with AWA.Modules.Get;
with AWA.Applications;
with AWA.Users.Beans;
with Util.Log.Loggers;
package body AWA.Users.Modules is
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("AWA.Users.Module");
package Register is new AWA.Modules.Beans (Module => User_Module,
Module_Access => User_Module_Access);
-- ------------------------------
-- Initialize the user module.
-- ------------------------------
overriding
procedure Initialize (Plugin : in out User_Module;
App : in AWA.Modules.Application_Access;
Props : in ASF.Applications.Config) is
begin
Log.Info ("Initializing the users module");
-- Setup the resource bundles.
App.Register ("userMsg", "users");
-- Register the OpenID servlets.
App.Add_Servlet (Name => "openid-auth",
Server => Plugin.Auth'Unchecked_Access);
App.Add_Servlet (Name => "openid-verify",
Server => Plugin.Verify_Auth'Unchecked_Access);
-- Setup the verify access key filter.
App.Add_Filter ("verify-access-key", Plugin.Key_Filter'Unchecked_Access);
App.Add_Filter ("auth-filter", Plugin.Auth_Filter'Unchecked_Access);
Register.Register (Plugin => Plugin,
Name => "AWA.Users.Beans.Authenticate_Bean",
Handler => AWA.Users.Beans.Create_Authenticate_Bean'Access);
Register.Register (Plugin => Plugin,
Name => "AWA.Users.Beans.Current_User_Bean",
Handler => AWA.Users.Beans.Create_Current_User_Bean'Access);
AWA.Modules.Module (Plugin).Initialize (App, Props);
end Initialize;
-- ------------------------------
-- Configures the module after its initialization and after having read its XML configuration.
-- ------------------------------
overriding
procedure Configure (Plugin : in out User_Module;
Props : in ASF.Applications.Config) is
pragma Unreferenced (Props);
begin
-- Create the user manager when everything is initialized.
Plugin.Manager := Plugin.Create_User_Manager;
end Configure;
-- ------------------------------
-- Get the user manager.
-- ------------------------------
function Get_User_Manager (Plugin : in User_Module) return Services.User_Service_Access is
begin
return Plugin.Manager;
end Get_User_Manager;
-- ------------------------------
-- Create a user manager. This operation can be overriden to provide another
-- user service implementation.
-- ------------------------------
function Create_User_Manager (Plugin : in User_Module) return Services.User_Service_Access is
Result : constant Services.User_Service_Access := new Services.User_Service;
begin
Result.Initialize (Plugin);
return Result;
end Create_User_Manager;
-- ------------------------------
-- Get the user module instance associated with the current application.
-- ------------------------------
function Get_User_Module return User_Module_Access is
function Get is new AWA.Modules.Get (User_Module, User_Module_Access, NAME);
begin
return Get;
end Get_User_Module;
-- ------------------------------
-- Get the user manager instance associated with the current application.
-- ------------------------------
function Get_User_Manager return Services.User_Service_Access is
Module : constant User_Module_Access := Get_User_Module;
begin
if Module = null then
Log.Error ("There is no active User_Module");
return null;
else
return Module.Get_User_Manager;
end if;
end Get_User_Manager;
end AWA.Users.Modules;
|
Fix configuration of users module by creating the user manager instance after the configuration is obtained
|
Fix configuration of users module by creating the user manager instance after the configuration is obtained
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
26cb239a68385c55b804c6cd8b88416cb9c2fc2d
|
awa/src/awa-users-modules.ads
|
awa/src/awa-users-modules.ads
|
-----------------------------------------------------------------------
-- awa-users-module -- User management module
-- 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 ASF.Applications;
with Security.Openid.Servlets;
with AWA.Modules;
with AWA.Users.Services;
with AWA.Users.Filters;
with AWA.Users.Servlets;
-- == Introduction ==
-- The <b>Users.Module</b> manages the creation, update, removal and authentication of users
-- in an application. The module provides the foundations for user management in
-- a web application.
--
-- A user can register himself by using a subscription form. In that case, a verification mail
-- is sent and the user has to follow the verification link defined in the mail to finish
-- the registration process. The user will authenticate using a password.
--
-- A user can also use an OpenID account and be automatically registered.
--
-- A user can have one or several permissions that allow to protect the application data.
-- User permissions are managed by the <b>Permissions.Module</b>.
--
-- == Configuration ==
-- The *users* module uses a set of configuration properties to configure the OpenID
-- integration.
--
-- @see AWA.Users.Services
package AWA.Users.Modules is
NAME : constant String := "users";
type User_Module is new AWA.Modules.Module with private;
type User_Module_Access is access all User_Module'Class;
-- Initialize the user module.
overriding
procedure Initialize (Plugin : in out User_Module;
App : in AWA.Modules.Application_Access;
Props : in ASF.Applications.Config);
-- Get the user manager.
function Get_User_Manager (Plugin : in User_Module) return Services.User_Service_Access;
-- Create a user manager. This operation can be overriden to provide another
-- user service implementation.
function Create_User_Manager (Plugin : in User_Module) return Services.User_Service_Access;
-- Get the user module instance associated with the current application.
function Get_User_Module return User_Module_Access;
-- Get the user manager instance associated with the current application.
function Get_User_Manager return Services.User_Service_Access;
private
type User_Module is new AWA.Modules.Module with record
Manager : Services.User_Service_Access := null;
Key_Filter : aliased AWA.Users.Filters.Verify_Filter;
Auth_Filter : aliased AWA.Users.Filters.Auth_Filter;
Auth : aliased Security.Openid.Servlets.Request_Auth_Servlet;
Verify_Auth : aliased AWA.Users.Servlets.Verify_Auth_Servlet;
end record;
end AWA.Users.Modules;
|
-----------------------------------------------------------------------
-- awa-users-module -- User management module
-- 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 ASF.Applications;
with Security.Openid.Servlets;
with AWA.Modules;
with AWA.Users.Services;
with AWA.Users.Filters;
with AWA.Users.Servlets;
-- == Introduction ==
-- The <b>Users.Module</b> manages the creation, update, removal and authentication of users
-- in an application. The module provides the foundations for user management in
-- a web application.
--
-- A user can register himself by using a subscription form. In that case, a verification mail
-- is sent and the user has to follow the verification link defined in the mail to finish
-- the registration process. The user will authenticate using a password.
--
-- A user can also use an OpenID account and be automatically registered.
--
-- A user can have one or several permissions that allow to protect the application data.
-- User permissions are managed by the <b>Permissions.Module</b>.
--
-- == Configuration ==
-- The *users* module uses a set of configuration properties to configure the OpenID
-- integration.
--
-- @include awa-users-services.ads
-- @include User.hbm.xml
package AWA.Users.Modules is
NAME : constant String := "users";
type User_Module is new AWA.Modules.Module with private;
type User_Module_Access is access all User_Module'Class;
-- Initialize the user module.
overriding
procedure Initialize (Plugin : in out User_Module;
App : in AWA.Modules.Application_Access;
Props : in ASF.Applications.Config);
-- Get the user manager.
function Get_User_Manager (Plugin : in User_Module) return Services.User_Service_Access;
-- Create a user manager. This operation can be overriden to provide another
-- user service implementation.
function Create_User_Manager (Plugin : in User_Module) return Services.User_Service_Access;
-- Get the user module instance associated with the current application.
function Get_User_Module return User_Module_Access;
-- Get the user manager instance associated with the current application.
function Get_User_Manager return Services.User_Service_Access;
private
type User_Module is new AWA.Modules.Module with record
Manager : Services.User_Service_Access := null;
Key_Filter : aliased AWA.Users.Filters.Verify_Filter;
Auth_Filter : aliased AWA.Users.Filters.Auth_Filter;
Auth : aliased Security.Openid.Servlets.Request_Auth_Servlet;
Verify_Auth : aliased AWA.Users.Servlets.Verify_Auth_Servlet;
end record;
end AWA.Users.Modules;
|
Integrate the data model and user's bean in the documentation
|
Integrate the data model and user's bean in the documentation
|
Ada
|
apache-2.0
|
tectronics/ada-awa,Letractively/ada-awa,Letractively/ada-awa,tectronics/ada-awa,tectronics/ada-awa,Letractively/ada-awa
|
6661104d363278feb46bb64db2f18e38e04a11f0
|
regtests/asf-servlets-tests.adb
|
regtests/asf-servlets-tests.adb
|
-----------------------------------------------------------------------
-- Sessions Tests - Unit tests for ASF.Sessions
-- Copyright (C) 2010, 2011, 2012, 2013, 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Test_Caller;
with Util.Measures;
with ASF.Applications;
with ASF.Streams;
with ASF.Routes.Servlets;
with ASF.Requests.Mockup;
with ASF.Responses.Mockup;
package body ASF.Servlets.Tests is
use Util.Tests;
procedure Do_Get (Server : in Test_Servlet1;
Request : in out Requests.Request'Class;
Response : in out Responses.Response'Class) is
pragma Unreferenced (Server);
Output : ASF.Streams.Print_Stream := Response.Get_Output_Stream;
begin
Output.Write ("URI: " & Request.Get_Request_URI);
Response.Set_Status (Responses.SC_OK);
end Do_Get;
procedure Do_Post (Server : in Test_Servlet2;
Request : in out Requests.Request'Class;
Response : in out Responses.Response'Class) is
begin
null;
end Do_Post;
S1 : aliased Test_Servlet1;
S2 : aliased Test_Servlet2;
-- ------------------------------
-- Check that the request is done on the good servlet and with the correct servlet path
-- and path info.
-- ------------------------------
procedure Check_Request (T : in out Test;
Ctx : in Servlet_Registry;
URI : in String;
Servlet_Path : in String;
Path_Info : in String) is
use type ASF.Routes.Route_Type_Access;
Dispatcher : constant Request_Dispatcher
:= Ctx.Get_Request_Dispatcher (Path => URI);
Req : ASF.Requests.Mockup.Request;
Resp : ASF.Responses.Mockup.Response;
Result : Unbounded_String;
begin
T.Assert (Dispatcher.Context.Get_Route /= null, "No mapping found for " & URI);
Req.Set_Request_URI ("test1");
Req.Set_Method ("GET");
Forward (Dispatcher, Req, Resp);
Assert_Equals (T, Servlet_Path, Req.Get_Servlet_Path, "Invalid servlet path");
Assert_Equals (T, Path_Info, Req.Get_Path_Info,
"The request path info is invalid");
-- Check the response after the Test_Servlet1.Do_Get method execution.
Resp.Read_Content (Result);
Assert_Equals (T, ASF.Responses.SC_OK, Resp.Get_Status, "Invalid status");
Assert_Equals (T, "URI: test1", Result, "Invalid content");
Req.Set_Method ("POST");
Forward (Dispatcher, Req, Resp);
Assert_Equals (T, ASF.Responses.SC_METHOD_NOT_ALLOWED, Resp.Get_Status,
"Invalid status for an operation not implemented");
end Check_Request;
-- ------------------------------
-- Test request dispatcher and servlet invocation
-- ------------------------------
procedure Test_Request_Dispatcher (T : in out Test) is
Ctx : Servlet_Registry;
S1 : aliased Test_Servlet1;
begin
Ctx.Add_Servlet ("Faces", S1'Unchecked_Access);
Ctx.Add_Mapping (Pattern => "*.jsf", Name => "Faces");
Ctx.Add_Mapping (Pattern => "/p1/p2/p3/*", Name => "Faces");
Check_Request (T, Ctx, "/home/test.jsf", "/home/test.jsf", "");
end Test_Request_Dispatcher;
-- ------------------------------
-- Test mapping and servlet path on a request.
-- ------------------------------
procedure Test_Servlet_Path (T : in out Test) is
Ctx : Servlet_Registry;
S1 : aliased Test_Servlet1;
begin
Ctx.Add_Servlet ("Faces", S1'Unchecked_Access);
Ctx.Add_Mapping (Pattern => "*.jsf", Name => "Faces");
Ctx.Add_Mapping (Pattern => "/p1/p2/p3/*", Name => "Faces");
Check_Request (T, Ctx, "/p1/p2/p3/home/test.html", "/p1/p2/p3", "/home/test.html");
end Test_Servlet_Path;
-- ------------------------------
-- Test add servlet
-- ------------------------------
procedure Test_Add_Servlet (T : in out Test) is
Ctx : Servlet_Registry;
S1 : aliased Test_Servlet1;
begin
Ctx.Add_Servlet ("Faces", S1'Unchecked_Access);
Assert_Equals (T, "Faces", S1.Get_Name, "Invalid name for the servlet");
begin
Ctx.Add_Servlet ("Faces", S1'Unchecked_Access);
T.Assert (False, "No exception raised if the servlet is registered several times");
exception
when Servlet_Error =>
null;
end;
end Test_Add_Servlet;
-- ------------------------------
-- Test getting a resource path
-- ------------------------------
procedure Test_Get_Resource (T : in out Test) is
Ctx : Servlet_Registry;
Conf : Applications.Config;
S1 : aliased Test_Servlet1;
Dir : constant String := "regtests/files";
Path : constant String := Util.Tests.Get_Path (Dir);
begin
Conf.Load_Properties ("regtests/view.properties");
Conf.Set ("view.dir", Path);
Ctx.Set_Init_Parameters (Conf);
Ctx.Add_Servlet ("Faces", S1'Unchecked_Access);
-- Resource exist, check the returned path.
declare
P : constant String := Ctx.Get_Resource ("/tests/form-text.xhtml");
begin
Assert_Matches (T, ".*/regtests/files/tests/form-text.xhtml",
P, "Invalid resource path");
end;
-- Resource does not exist
declare
P : constant String := Ctx.Get_Resource ("/tests/form-text-missing.xhtml");
begin
Assert_Equals (T, "", P, "Invalid resource path for missing resource");
end;
end Test_Get_Resource;
-- ------------------------------
-- Check that the mapping for the given URI matches the server.
-- ------------------------------
procedure Check_Mapping (T : in out Test;
Ctx : in Servlet_Registry;
URI : in String;
Server : in Servlet_Access) is
use type ASF.Routes.Route_Type_Access;
Disp : constant Request_Dispatcher := Ctx.Get_Request_Dispatcher (URI);
Route : constant ASF.Routes.Route_Type_Access := Disp.Context.Get_Route;
begin
if Server = null then
T.Assert (Route = null, "No mapping returned for URI: " & URI);
else
T.Assert (Route /= null, "A mapping is returned for URI: " & URI);
T.Assert (Route.all in ASF.Routes.Servlets.Servlet_Route_Type'Class,
"The route is not a Servlet route");
T.Assert (ASF.Routes.Servlets.Servlet_Route_Type'Class (Route.all).Servlet = Server,
"Invalid mapping returned for URI: " & URI);
end if;
end Check_Mapping;
-- ------------------------------
-- Test session creation.
-- ------------------------------
procedure Test_Create_Servlet (T : in out Test) is
Ctx : Servlet_Registry;
begin
Ctx.Add_Servlet (Name => "Faces", Server => S1'Access);
Ctx.Add_Servlet (Name => "Text", Server => S2'Access);
Ctx.Add_Mapping (Pattern => "*.jsf", Name => "Faces");
Ctx.Add_Mapping (Pattern => "*.html", Name => "Faces");
Ctx.Add_Mapping (Pattern => "*.txt", Name => "Text");
-- Ctx.Add_Mapping (Pattern => "/server", Server => S2'Access);
Ctx.Add_Mapping (Pattern => "/server/john/*", Server => S2'Access);
Ctx.Add_Mapping (Pattern => "/server/info", Server => S1'Access);
Ctx.Add_Mapping (Pattern => "/server/list", Server => S1'Access);
Ctx.Add_Mapping (Pattern => "/server/list2", Server => S2'Access);
Ctx.Add_Mapping (Pattern => "/1/2/3/4/5/6/7/8/9/server/list2", Server => S2'Access);
Ctx.Add_Mapping (Pattern => "/1/2/3/4/5/6/7/8/A/server/list2", Server => S1'Access);
-- Ctx.Mappings.Dump_Map (" ");
T.Check_Mapping (Ctx, "/joe/black/joe.jsf", S1'Access);
T.Check_Mapping (Ctx, "/joe/black/joe.txt", S2'Access);
T.Check_Mapping (Ctx, "/server/info", S1'Access);
T.Check_Mapping (Ctx, "/server/list2", S2'Access);
T.Check_Mapping (Ctx, "/1/2/3/4/5/6/7/8/9/server/list2", S2'Access);
T.Check_Mapping (Ctx, "/1/2/3/4/5/6/7/8/A/server/list2", S1'Access);
-- declare
-- St : Util.Measures.Stamp;
-- begin
-- for I in 1 .. 1000 loop
-- Map := Ctx.Find_Mapping (URI => "/joe/black/joe.jsf");
-- end loop;
-- Util.Measures.Report (St, "Find 1000 mapping (extension)");
-- end;
-- T.Assert (Map /= null, "No mapping for 'joe.jsf'");
-- T.Assert (Map.Servlet /= null, "No servlet for mapping for 'joe.jsf'");
-- T.Assert (Map.Servlet = S1'Access, "Invalid servlet");
-- Util.Measures.Report (St, "10 Session create");
-- declare
-- St : Util.Measures.Stamp;
-- begin
-- for I in 1 .. 1000 loop
-- Map := Ctx.Find_Mapping (URI => "/1/2/3/4/5/6/7/8/9/server/list2");
-- end loop;
-- Util.Measures.Report (St, "Find 1000 mapping (path)");
-- end;
--
-- T.Assert (Map /= null, "No mapping for '/server/john/joe.jsf'");
-- T.Assert (Map.Servlet /= null, "No servlet for mapping for 'joe.jsf'");
-- T.Assert (Map.Servlet = S2'Access, "Invalid servlet");
-- Util.Measures.Report (St, "10 Session create");
end Test_Create_Servlet;
package Caller is new Util.Test_Caller (Test, "Servlets");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
-- To document what is tested, register the test methods for each
-- operation that is tested.
Caller.Add_Test (Suite, "Test ASF.Servlets.Add_Mapping,Find_Mapping",
Test_Create_Servlet'Access);
Caller.Add_Test (Suite, "Test ASF.Servlets.Add_Servlet",
Test_Add_Servlet'Access);
Caller.Add_Test (Suite, "Test ASF.Servlets.Get_Request_Dispatcher",
Test_Request_Dispatcher'Access);
Caller.Add_Test (Suite, "Test ASF.Servlets.Get_Resource",
Test_Get_Resource'Access);
Caller.Add_Test (Suite, "Test ASF.Requests.Get_Servlet_Path",
Test_Servlet_Path'Access);
end Add_Tests;
end ASF.Servlets.Tests;
|
-----------------------------------------------------------------------
-- Sessions Tests - Unit tests for ASF.Sessions
-- Copyright (C) 2010, 2011, 2012, 2013, 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Test_Caller;
with Util.Measures;
with ASF.Applications;
with ASF.Streams;
with ASF.Routes.Servlets;
with ASF.Requests.Mockup;
with ASF.Responses.Mockup;
with ASF.Filters.Dump;
package body ASF.Servlets.Tests is
use Util.Tests;
procedure Do_Get (Server : in Test_Servlet1;
Request : in out Requests.Request'Class;
Response : in out Responses.Response'Class) is
pragma Unreferenced (Server);
Output : ASF.Streams.Print_Stream := Response.Get_Output_Stream;
begin
Output.Write ("URI: " & Request.Get_Request_URI);
Response.Set_Status (Responses.SC_OK);
end Do_Get;
procedure Do_Post (Server : in Test_Servlet2;
Request : in out Requests.Request'Class;
Response : in out Responses.Response'Class) is
begin
null;
end Do_Post;
S1 : aliased Test_Servlet1;
S2 : aliased Test_Servlet2;
-- ------------------------------
-- Check that the request is done on the good servlet and with the correct servlet path
-- and path info.
-- ------------------------------
procedure Check_Request (T : in out Test;
Ctx : in Servlet_Registry;
URI : in String;
Servlet_Path : in String;
Path_Info : in String) is
use type ASF.Routes.Route_Type_Access;
Dispatcher : constant Request_Dispatcher
:= Ctx.Get_Request_Dispatcher (Path => URI);
Req : ASF.Requests.Mockup.Request;
Resp : ASF.Responses.Mockup.Response;
Result : Unbounded_String;
begin
T.Assert (Dispatcher.Context.Get_Route /= null, "No mapping found for " & URI);
Req.Set_Request_URI ("test1");
Req.Set_Method ("GET");
Forward (Dispatcher, Req, Resp);
Assert_Equals (T, Servlet_Path, Req.Get_Servlet_Path, "Invalid servlet path");
Assert_Equals (T, Path_Info, Req.Get_Path_Info,
"The request path info is invalid");
-- Check the response after the Test_Servlet1.Do_Get method execution.
Resp.Read_Content (Result);
Assert_Equals (T, ASF.Responses.SC_OK, Resp.Get_Status, "Invalid status");
Assert_Equals (T, "URI: test1", Result, "Invalid content");
Req.Set_Method ("POST");
Forward (Dispatcher, Req, Resp);
Assert_Equals (T, ASF.Responses.SC_METHOD_NOT_ALLOWED, Resp.Get_Status,
"Invalid status for an operation not implemented");
end Check_Request;
-- ------------------------------
-- Test request dispatcher and servlet invocation
-- ------------------------------
procedure Test_Request_Dispatcher (T : in out Test) is
Ctx : Servlet_Registry;
S1 : aliased Test_Servlet1;
begin
Ctx.Add_Servlet ("Faces", S1'Unchecked_Access);
Ctx.Add_Mapping (Pattern => "*.jsf", Name => "Faces");
Ctx.Add_Mapping (Pattern => "/p1/p2/p3/*", Name => "Faces");
Check_Request (T, Ctx, "/home/test.jsf", "/home/test.jsf", "");
end Test_Request_Dispatcher;
-- ------------------------------
-- Test mapping and servlet path on a request.
-- ------------------------------
procedure Test_Servlet_Path (T : in out Test) is
Ctx : Servlet_Registry;
S1 : aliased Test_Servlet1;
begin
Ctx.Add_Servlet ("Faces", S1'Unchecked_Access);
Ctx.Add_Mapping (Pattern => "*.jsf", Name => "Faces");
Ctx.Add_Mapping (Pattern => "/p1/p2/p3/*", Name => "Faces");
Check_Request (T, Ctx, "/p1/p2/p3/home/test.html", "/p1/p2/p3", "/home/test.html");
end Test_Servlet_Path;
-- ------------------------------
-- Test mapping and servlet path on a request.
-- ------------------------------
procedure Test_Filter_Mapping (T : in out Test) is
Ctx : Servlet_Registry;
S1 : aliased Test_Servlet1;
S2 : aliased Test_Servlet2;
F1 : aliased ASF.Filters.Dump.Dump_Filter;
F2 : aliased ASF.Filters.Dump.Dump_Filter;
begin
Ctx.Add_Servlet ("Faces", S1'Unchecked_Access);
Ctx.Add_Servlet ("Json", S2'Unchecked_Access);
Ctx.Add_Filter ("Dump", F1'Unchecked_Access);
Ctx.Add_Filter ("Dump2", F2'Unchecked_Access);
Ctx.Add_Mapping (Pattern => "*.html", Name => "Faces");
Ctx.Add_Mapping (Pattern => "*.json", Name => "Json");
Ctx.Add_Filter_Mapping (Pattern => "/dump/file.html", Name => "Dump");
Ctx.Add_Filter_Mapping (Pattern => "/dump/result/test.html", Name => "Dump");
Ctx.Add_Filter_Mapping (Pattern => "/dump/result/test.html", Name => "Dump2");
Ctx.Start;
T.Check_Mapping (Ctx, "test.html", S1'Unchecked_Access);
T.Check_Mapping (Ctx, "file.html", S1'Unchecked_Access);
T.Check_Mapping (Ctx, "/dump/test.html", S1'Unchecked_Access);
T.Check_Mapping (Ctx, "/dump/file.html", S1'Unchecked_Access, 1);
T.Check_Mapping (Ctx, "/dump/result/test.html", S1'Unchecked_Access, 2);
T.Check_Mapping (Ctx, "test.json", S2'Unchecked_Access);
end Test_Filter_Mapping;
-- ------------------------------
-- Test add servlet
-- ------------------------------
procedure Test_Add_Servlet (T : in out Test) is
Ctx : Servlet_Registry;
S1 : aliased Test_Servlet1;
begin
Ctx.Add_Servlet ("Faces", S1'Unchecked_Access);
Assert_Equals (T, "Faces", S1.Get_Name, "Invalid name for the servlet");
begin
Ctx.Add_Servlet ("Faces", S1'Unchecked_Access);
T.Assert (False, "No exception raised if the servlet is registered several times");
exception
when Servlet_Error =>
null;
end;
end Test_Add_Servlet;
-- ------------------------------
-- Test getting a resource path
-- ------------------------------
procedure Test_Get_Resource (T : in out Test) is
Ctx : Servlet_Registry;
Conf : Applications.Config;
S1 : aliased Test_Servlet1;
Dir : constant String := "regtests/files";
Path : constant String := Util.Tests.Get_Path (Dir);
begin
Conf.Load_Properties ("regtests/view.properties");
Conf.Set ("view.dir", Path);
Ctx.Set_Init_Parameters (Conf);
Ctx.Add_Servlet ("Faces", S1'Unchecked_Access);
-- Resource exist, check the returned path.
declare
P : constant String := Ctx.Get_Resource ("/tests/form-text.xhtml");
begin
Assert_Matches (T, ".*/regtests/files/tests/form-text.xhtml",
P, "Invalid resource path");
end;
-- Resource does not exist
declare
P : constant String := Ctx.Get_Resource ("/tests/form-text-missing.xhtml");
begin
Assert_Equals (T, "", P, "Invalid resource path for missing resource");
end;
end Test_Get_Resource;
-- ------------------------------
-- Check that the mapping for the given URI matches the server.
-- ------------------------------
procedure Check_Mapping (T : in out Test;
Ctx : in Servlet_Registry;
URI : in String;
Server : in Servlet_Access;
Filter : in Natural := 0) is
use type ASF.Routes.Route_Type_Access;
use type ASF.Filters.Filter_List_Access;
Disp : constant Request_Dispatcher := Ctx.Get_Request_Dispatcher (URI);
Route : constant ASF.Routes.Route_Type_Access := Disp.Context.Get_Route;
Servlet_Route : ASF.Routes.Servlets.Servlet_Route_Type_Access;
begin
if Server = null then
T.Assert (Route = null, "No mapping returned for URI: " & URI);
else
T.Assert (Route /= null, "A mapping is returned for URI: " & URI);
T.Assert (Route.all in ASF.Routes.Servlets.Servlet_Route_Type'Class,
"The route is not a Servlet route");
Servlet_Route := ASF.Routes.Servlets.Servlet_Route_Type'Class (Route.all)'Access;
T.Assert (Servlet_Route.Servlet = Server,
"Invalid mapping returned for URI: " & URI);
if Filter = 0 then
T.Assert (Disp.Filters = null,
"Filters are configured for URI: " & URI);
else
T.Assert (Disp.Filters /= null, "No filter on the route URI: " & URI);
Util.Tests.Assert_Equals (T, Filter, Disp.Filters'Length,
"Invalid mapping returned for URI: " & URI);
end if;
end if;
end Check_Mapping;
-- ------------------------------
-- Test session creation.
-- ------------------------------
procedure Test_Create_Servlet (T : in out Test) is
Ctx : Servlet_Registry;
begin
Ctx.Add_Servlet (Name => "Faces", Server => S1'Access);
Ctx.Add_Servlet (Name => "Text", Server => S2'Access);
Ctx.Add_Mapping (Pattern => "*.jsf", Name => "Faces");
Ctx.Add_Mapping (Pattern => "*.html", Name => "Faces");
Ctx.Add_Mapping (Pattern => "*.txt", Name => "Text");
-- Ctx.Add_Mapping (Pattern => "/server", Server => S2'Access);
Ctx.Add_Mapping (Pattern => "/server/john/*", Server => S2'Access);
Ctx.Add_Mapping (Pattern => "/server/info", Server => S1'Access);
Ctx.Add_Mapping (Pattern => "/server/list", Server => S1'Access);
Ctx.Add_Mapping (Pattern => "/server/list2", Server => S2'Access);
Ctx.Add_Mapping (Pattern => "/1/2/3/4/5/6/7/8/9/server/list2", Server => S2'Access);
Ctx.Add_Mapping (Pattern => "/1/2/3/4/5/6/7/8/A/server/list2", Server => S1'Access);
-- Ctx.Mappings.Dump_Map (" ");
T.Check_Mapping (Ctx, "/joe/black/joe.jsf", S1'Access);
T.Check_Mapping (Ctx, "/joe/black/joe.txt", S2'Access);
T.Check_Mapping (Ctx, "/server/info", S1'Access);
T.Check_Mapping (Ctx, "/server/list2", S2'Access);
T.Check_Mapping (Ctx, "/1/2/3/4/5/6/7/8/9/server/list2", S2'Access);
T.Check_Mapping (Ctx, "/1/2/3/4/5/6/7/8/A/server/list2", S1'Access);
-- declare
-- St : Util.Measures.Stamp;
-- begin
-- for I in 1 .. 1000 loop
-- Map := Ctx.Find_Mapping (URI => "/joe/black/joe.jsf");
-- end loop;
-- Util.Measures.Report (St, "Find 1000 mapping (extension)");
-- end;
-- T.Assert (Map /= null, "No mapping for 'joe.jsf'");
-- T.Assert (Map.Servlet /= null, "No servlet for mapping for 'joe.jsf'");
-- T.Assert (Map.Servlet = S1'Access, "Invalid servlet");
-- Util.Measures.Report (St, "10 Session create");
-- declare
-- St : Util.Measures.Stamp;
-- begin
-- for I in 1 .. 1000 loop
-- Map := Ctx.Find_Mapping (URI => "/1/2/3/4/5/6/7/8/9/server/list2");
-- end loop;
-- Util.Measures.Report (St, "Find 1000 mapping (path)");
-- end;
--
-- T.Assert (Map /= null, "No mapping for '/server/john/joe.jsf'");
-- T.Assert (Map.Servlet /= null, "No servlet for mapping for 'joe.jsf'");
-- T.Assert (Map.Servlet = S2'Access, "Invalid servlet");
-- Util.Measures.Report (St, "10 Session create");
end Test_Create_Servlet;
package Caller is new Util.Test_Caller (Test, "Servlets");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
-- To document what is tested, register the test methods for each
-- operation that is tested.
Caller.Add_Test (Suite, "Test ASF.Servlets.Add_Mapping,Find_Mapping",
Test_Create_Servlet'Access);
Caller.Add_Test (Suite, "Test ASF.Servlets.Add_Servlet",
Test_Add_Servlet'Access);
Caller.Add_Test (Suite, "Test ASF.Servlets.Get_Request_Dispatcher",
Test_Request_Dispatcher'Access);
Caller.Add_Test (Suite, "Test ASF.Servlets.Get_Resource",
Test_Get_Resource'Access);
Caller.Add_Test (Suite, "Test ASF.Requests.Get_Servlet_Path",
Test_Servlet_Path'Access);
Caller.Add_Test (Suite, "Test ASF.Servlets.Add_Filter",
Test_Filter_Mapping'Access);
end Add_Tests;
end ASF.Servlets.Tests;
|
Implement Test_Filter_Mapping to check several filter mappings
|
Implement Test_Filter_Mapping to check several filter mappings
|
Ada
|
apache-2.0
|
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
|
f6b69ff4e7a3fd3a0b22e4dc32096836ef5a346c
|
src/asf-beans-mappers.ads
|
src/asf-beans-mappers.ads
|
-----------------------------------------------------------------------
-- asf-beans-mappers -- Read XML managed bean declaratiosn
-- Copyright (C) 2010, 2011 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Beans.Objects;
with Util.Serialize.Mappers.Record_Mapper;
with Util.Serialize.IO.XML;
with EL.Contexts;
package ASF.Beans.Mappers is
type Managed_Bean_Fields is (FIELD_NAME,
FIELD_CLASS,
FIELD_SCOPE,
FIELD_MANAGED_BEAN,
FIELD_PROPERTY,
FIELD_PROPERTY_NAME,
FIELD_PROPERTY_VALUE,
FIELD_PROPERTY_CLASS);
type Bean_Factory_Access is access all ASF.Beans.Bean_Factory;
type Managed_Bean is record
Name : Util.Beans.Objects.Object;
Class : Util.Beans.Objects.Object;
Scope : Scope_Type := REQUEST_SCOPE;
Factory : Bean_Factory_Access := null;
Params : ASF.Beans.Parameter_Bean_Ref.Ref;
Prop_Name : Util.Beans.Objects.Object;
Prop_Value : Util.Beans.Objects.Object;
Context : EL.Contexts.ELContext_Access := null;
end record;
type Managed_Bean_Access is access all Managed_Bean;
-- Set the field identified by <b>Field</b> with the <b>Value</b>.
procedure Set_Member (MBean : in out Managed_Bean;
Field : in Managed_Bean_Fields;
Value : in Util.Beans.Objects.Object);
-- Setup the XML parser to read the managed bean definitions.
generic
Reader : in out Util.Serialize.IO.XML.Parser;
Factory : in Bean_Factory_Access;
Context : in EL.Contexts.ELContext_Access;
package Reader_Config is
Config : aliased Managed_Bean;
end Reader_Config;
private
package Config_Mapper is
new Util.Serialize.Mappers.Record_Mapper (Element_Type => Managed_Bean,
Element_Type_Access => Managed_Bean_Access,
Fields => Managed_Bean_Fields,
Set_Member => Set_Member);
end ASF.Beans.Mappers;
|
-----------------------------------------------------------------------
-- asf-beans-mappers -- Read XML managed bean declaratiosn
-- Copyright (C) 2010, 2011 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Beans.Objects;
with Util.Serialize.Mappers.Record_Mapper;
with Util.Serialize.IO.XML;
with EL.Contexts;
package ASF.Beans.Mappers is
type Managed_Bean_Fields is (FIELD_NAME,
FIELD_CLASS,
FIELD_SCOPE,
FIELD_MANAGED_BEAN,
FIELD_PROPERTY,
FIELD_PROPERTY_NAME,
FIELD_PROPERTY_VALUE,
FIELD_PROPERTY_CLASS);
type Bean_Factory_Access is access all ASF.Beans.Bean_Factory;
type Managed_Bean is limited record
Name : Util.Beans.Objects.Object;
Class : Util.Beans.Objects.Object;
Scope : Scope_Type := REQUEST_SCOPE;
Factory : Bean_Factory_Access := null;
Params : ASF.Beans.Parameter_Bean_Ref.Ref;
Prop_Name : Util.Beans.Objects.Object;
Prop_Value : Util.Beans.Objects.Object;
Context : EL.Contexts.ELContext_Access := null;
end record;
type Managed_Bean_Access is access all Managed_Bean;
-- Set the field identified by <b>Field</b> with the <b>Value</b>.
procedure Set_Member (MBean : in out Managed_Bean;
Field : in Managed_Bean_Fields;
Value : in Util.Beans.Objects.Object);
-- Setup the XML parser to read the managed bean definitions.
generic
Reader : in out Util.Serialize.IO.XML.Parser;
Factory : in Bean_Factory_Access;
Context : in EL.Contexts.ELContext_Access;
package Reader_Config is
Config : aliased Managed_Bean;
end Reader_Config;
private
package Config_Mapper is
new Util.Serialize.Mappers.Record_Mapper (Element_Type => Managed_Bean,
Element_Type_Access => Managed_Bean_Access,
Fields => Managed_Bean_Fields,
Set_Member => Set_Member);
end ASF.Beans.Mappers;
|
Use a limited record for Managed_Bean since we don't need to copy these objects and this reduces the code size
|
Use a limited record for Managed_Bean since we don't need to copy these objects and this reduces the code size
|
Ada
|
apache-2.0
|
Letractively/ada-asf,Letractively/ada-asf,Letractively/ada-asf
|
73705e8fcf1739cb1b43ab099dee4b4e3012b1c9
|
mat/src/frames/mat-frames.adb
|
mat/src/frames/mat-frames.adb
|
-----------------------------------------------------------------------
-- Frames - Representation of stack frames
-- 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.Unchecked_Deallocation;
with Interfaces; use Interfaces;
with MAT.Types; use MAT.Types;
package body MAT.Frames is
procedure Free is
new Ada.Unchecked_Deallocation (Frame, Frame_Ptr);
-- Return the parent frame.
function Parent (F : in Frame_Ptr) return Frame_Ptr is
begin
return F.Parent;
end Parent;
-- Returns the backtrace of the current frame (up to the root).
function Backtrace (F : in Frame_Ptr) return PC_Table is
Pc : Pc_Table (1 .. F.Depth);
Current : Frame_Ptr := F;
Pos : Natural := Current.Depth;
New_Pos : Natural;
begin
while Pos /= 0 loop
New_Pos := Pos - Current.Local_Depth + 1;
Pc (New_Pos .. Pos) := Current.Calls (1 .. Current.Local_Depth);
Pos := New_Pos - 1;
Current := Current.Parent;
end loop;
return Pc;
end Backtrace;
-- Returns the number of children in the frame.
-- When recursive is true, compute in the sub-tree.
function Count_Children (F : in Frame_Ptr;
Recursive : in Boolean := False) return Natural is
Count : Natural := 0;
N : Natural;
Child : Frame_Ptr := F.Children;
begin
while Child /= null loop
Count := Count + 1;
if Recursive then
declare
N : Natural := Count_Children (Child, True);
begin
if N > 0 then
N := N - 1;
end if;
Count := Count + N;
end;
end if;
Child := Child.Next;
end loop;
return Count;
end Count_Children;
-- Returns all the direct calls made by the current frame.
function Calls (F : in Frame_Ptr) return PC_Table is
Nb_Calls : Natural := Count_Children (F);
Pc : Pc_Table (1 .. Nb_Calls);
Child : Frame_Ptr := F.Children;
Pos : Natural := 1;
begin
while Child /= null loop
Pc (Pos) := Child.Calls (1);
Pos := Pos + 1;
Child := Child.Next;
end loop;
return Pc;
end Calls;
-- Returns the current stack depth (# of calls from the root
-- to reach the frame).
function Current_Depth (F : in Frame_Ptr) return Natural is
begin
return F.Depth;
end Current_Depth;
-- Create a root for stack frame representation.
function Create_Root return Frame_Ptr is
begin
return new Frame;
end Create_Root;
-- Destroy the frame tree recursively.
procedure Destroy (Tree : in out Frame_Ptr) is
F : Frame_Ptr;
begin
-- Destroy its children recursively.
while Tree.Children /= null loop
F := Tree.Children;
Destroy (F);
end loop;
-- Unlink from parent list.
if Tree.Parent /= null then
F := Tree.Parent.Children;
if F = Tree then
Tree.Parent.Children := Tree.Next;
else
while F /= null and F.Next /= Tree loop
F := F.Next;
end loop;
if F = null then
raise Program_Error;
end if;
F.Next := Tree.Next;
end if;
end if;
Free (Tree);
end Destroy;
-- Release the frame when its reference is no longer necessary.
procedure Release (F : in Frame_Ptr) is
Current : Frame_Ptr := F;
begin
-- Scan the fram until the root is reached
-- and decrement the used counter. Free the frames
-- when the used counter reaches 0.
while Current /= null loop
if Current.Used <= 1 then
declare
Tree : Frame_Ptr := Current;
begin
Current := Current.Parent;
Destroy (Tree);
end;
else
Current.Used := Current.Used - 1;
Current := Current.Parent;
end if;
end loop;
end Release;
-- Split the node pointed to by `F' at the position `Pos'
-- in the caller chain. A new parent is created for the node
-- and the brothers of the node become the brothers of the
-- new parent.
--
-- Returns in `F' the new parent node.
procedure Split (F : in out Frame_Ptr; Pos : in Positive) is
-- Before: After:
--
-- +-------+ +-------+
-- /-| P | /-| P |
-- | +-------+ | +-------+
-- | ^ | ^
-- | +-------+ | +-------+
-- ...>| node |... ....>| new |... (0..N brothers)
-- +-------+ +-------+
-- | ^ | ^
-- | +-------+ | +-------+
-- ->| c | ->| node |-->0 (0 brother)
-- +-------+ +-------+
-- |
-- +-------+
-- | c |
-- +-------+
--
New_Parent : Frame_Ptr := new Frame '(Parent => F.Parent,
Next => F.Next,
Children => F,
Used => F.Used,
Depth => F.Depth,
Local_Depth => Pos,
Calls => (others => 0));
Child : Frame_Ptr := F.Parent.Children;
begin
-- Move the PC values in the new parent.
New_Parent.Calls (1 .. Pos) := F.Calls (1 .. Pos);
F.Calls (1 .. F.Local_Depth - Pos) := F.Calls (Pos + 1 .. F.Local_Depth);
F.Parent := New_Parent;
F.Next := null;
New_Parent.Depth := F.Depth - F.Local_Depth + Pos;
F.Local_Depth := F.Local_Depth - Pos;
-- Remove F from its parent children list and replace if with New_Parent.
if Child = F then
New_Parent.Parent.Children := New_Parent;
else
while Child.Next /= F loop
Child := Child.Next;
end loop;
Child.Next := New_Parent;
end if;
F := New_Parent;
end Split;
procedure Add_Frame (F : in Frame_Ptr;
Pc : in Pc_Table;
Result : out Frame_Ptr) is
Child : Frame_Ptr := F;
Pos : Positive := Pc'First;
Current_Depth : Natural := F.Depth;
Cnt : Local_Depth_Type;
begin
while Pos <= Pc'Last loop
Cnt := Frame_Group_Size;
if Pos + Cnt > Pc'Last then
Cnt := Pc'Last - Pos + 1;
end if;
Current_Depth := Current_Depth + Cnt;
Child := new Frame '(Parent => Child,
Next => Child.Children,
Children => null,
Used => 1,
Depth => Current_Depth,
Local_Depth => Cnt,
Calls => (others => 0));
Child.Calls (1 .. Cnt) := Pc (Pos .. Pos + Cnt - 1);
Pos := Pos + Cnt;
Child.Parent.Children := Child;
end loop;
Result := Child;
end Add_Frame;
procedure Insert (F : in Frame_Ptr;
Pc : in Pc_Table;
Result : out Frame_Ptr) is
Current : Frame_Ptr := F;
Child : Frame_Ptr;
Pos : Positive := Pc'First;
Lpos : Positive := 1;
Addr : Target_Addr;
begin
while Pos <= Pc'Last loop
Addr := Pc (Pos);
if Lpos <= Current.Local_Depth then
if Addr = Current.Calls (Lpos) then
Lpos := Lpos + 1;
Pos := Pos + 1;
-- Split this node
else
if Lpos > 1 then
Split (Current, Lpos - 1);
end if;
Add_Frame (Current, Pc (Pos .. Pc'Last), Result);
return;
end if;
else
-- Find the first child which has the address.
Child := Current.Children;
while Child /= null loop
exit when Child.Calls (1) = Addr;
Child := Child.Next;
end loop;
if Child = null then
Add_Frame (Current, Pc (Pos .. Pc'Last), Result);
return;
end if;
Current := Child;
Lpos := 2;
Pos := Pos + 1;
Current.Used := Current.Used + 1;
end if;
end loop;
if Lpos <= Current.Local_Depth then
Split (Current, Lpos - 1);
end if;
Result := Current;
end Insert;
-- Find the child frame which has the given PC address.
-- Returns that frame pointer or raises the Not_Found exception.
function Find (F : in Frame_Ptr; Pc : in Target_Addr) return Frame_Ptr is
Child : Frame_Ptr := F.Children;
begin
while Child /= null loop
if Child.Local_Depth >= 1 and then Child.Calls (1) = Pc then
return Child;
end if;
Child := Child.Next;
end loop;
raise Not_Found;
end Find;
-- Find the child frame which has the given PC address.
-- Returns that frame pointer or raises the Not_Found exception.
function Find (F : in Frame_Ptr; Pc : in PC_Table) return Frame_Ptr is
Child : Frame_Ptr := F;
Pos : Positive := Pc'First;
Lpos : Positive;
begin
while Pos <= Pc'Last loop
Child := Find (Child, Pc (Pos));
Pos := Pos + 1;
Lpos := 2;
-- All the PC of the child frame must match.
while Pos <= Pc'Last and Lpos <= Child.Local_Depth loop
if Child.Calls (Lpos) /= Pc (Pos) then
raise Not_Found;
end if;
Lpos := Lpos + 1;
Pos := Pos + 1;
end loop;
end loop;
return Child;
end Find;
-- Find the child frame which has the given PC address.
-- Returns that frame pointer or raises the Not_Found exception.
procedure Find (F : in Frame_Ptr;
Pc : in PC_Table;
Result : out Frame_Ptr;
Last_Pc : out Natural) is
Current : Frame_Ptr := F;
Pos : Positive := Pc'First;
Lpos : Positive;
begin
Main_Search:
while Pos <= Pc'Last loop
declare
Addr : Target_Addr := Pc (Pos);
Child : Frame_Ptr := Current.Children;
begin
-- Find the child which has the corresponding PC.
loop
exit Main_Search when Child = null;
exit when Child.Local_Depth >= 1 and Child.Calls (1) = Addr;
Child := Child.Next;
end loop;
Current := Child;
Pos := Pos + 1;
Lpos := 2;
-- All the PC of the child frame must match.
while Pos <= Pc'Last and Lpos <= Current.Local_Depth loop
exit Main_Search when Current.Calls (Lpos) /= Pc (Pos);
Lpos := Lpos + 1;
Pos := Pos + 1;
end loop;
end;
end loop Main_Search;
Result := Current;
if Pos > Pc'Last then
Last_Pc := 0;
else
Last_Pc := Pos;
end if;
end Find;
end MAT.Frames;
|
-----------------------------------------------------------------------
-- mat-frames - Representation of stack frames
-- 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.Unchecked_Deallocation;
with Interfaces; use Interfaces;
with MAT.Types; use MAT.Types;
package body MAT.Frames is
procedure Free is
new Ada.Unchecked_Deallocation (Frame, Frame_Type);
-- ------------------------------
-- Return the parent frame.
-- ------------------------------
function Parent (Frame : in Frame_Type) return Frame_Type is
begin
if Frame = null then
return null;
else
return Frame.Parent;
end if;
end Parent;
-- Returns the backtrace of the current frame (up to the root).
function Backtrace (Frame : in Frame_Type) return Frame_Table is
Pc : Prame_Table (1 .. F.Depth);
Current : Frame_Type := Frame;
Pos : Natural := Current.Depth;
New_Pos : Natural;
begin
while Pos /= 0 loop
New_Pos := Pos - Current.Local_Depth + 1;
Pc (New_Pos .. Pos) := Current.Calls (1 .. Current.Local_Depth);
Pos := New_Pos - 1;
Current := Current.Parent;
end loop;
return Pc;
end Backtrace;
-- Returns the number of children in the frame.
-- When recursive is true, compute in the sub-tree.
function Count_Children (F : in Frame_Ptr;
Recursive : in Boolean := False) return Natural is
Count : Natural := 0;
N : Natural;
Child : Frame_Ptr := F.Children;
begin
while Child /= null loop
Count := Count + 1;
if Recursive then
declare
N : Natural := Count_Children (Child, True);
begin
if N > 0 then
N := N - 1;
end if;
Count := Count + N;
end;
end if;
Child := Child.Next;
end loop;
return Count;
end Count_Children;
-- Returns all the direct calls made by the current frame.
function Calls (F : in Frame_Ptr) return PC_Table is
Nb_Calls : Natural := Count_Children (F);
Pc : Pc_Table (1 .. Nb_Calls);
Child : Frame_Ptr := F.Children;
Pos : Natural := 1;
begin
while Child /= null loop
Pc (Pos) := Child.Calls (1);
Pos := Pos + 1;
Child := Child.Next;
end loop;
return Pc;
end Calls;
-- Returns the current stack depth (# of calls from the root
-- to reach the frame).
function Current_Depth (F : in Frame_Ptr) return Natural is
begin
return F.Depth;
end Current_Depth;
-- Create a root for stack frame representation.
function Create_Root return Frame_Ptr is
begin
return new Frame;
end Create_Root;
-- Destroy the frame tree recursively.
procedure Destroy (Tree : in out Frame_Ptr) is
F : Frame_Ptr;
begin
-- Destroy its children recursively.
while Tree.Children /= null loop
F := Tree.Children;
Destroy (F);
end loop;
-- Unlink from parent list.
if Tree.Parent /= null then
F := Tree.Parent.Children;
if F = Tree then
Tree.Parent.Children := Tree.Next;
else
while F /= null and F.Next /= Tree loop
F := F.Next;
end loop;
if F = null then
raise Program_Error;
end if;
F.Next := Tree.Next;
end if;
end if;
Free (Tree);
end Destroy;
-- Release the frame when its reference is no longer necessary.
procedure Release (F : in Frame_Ptr) is
Current : Frame_Ptr := F;
begin
-- Scan the fram until the root is reached
-- and decrement the used counter. Free the frames
-- when the used counter reaches 0.
while Current /= null loop
if Current.Used <= 1 then
declare
Tree : Frame_Ptr := Current;
begin
Current := Current.Parent;
Destroy (Tree);
end;
else
Current.Used := Current.Used - 1;
Current := Current.Parent;
end if;
end loop;
end Release;
-- Split the node pointed to by `F' at the position `Pos'
-- in the caller chain. A new parent is created for the node
-- and the brothers of the node become the brothers of the
-- new parent.
--
-- Returns in `F' the new parent node.
procedure Split (F : in out Frame_Ptr; Pos : in Positive) is
-- Before: After:
--
-- +-------+ +-------+
-- /-| P | /-| P |
-- | +-------+ | +-------+
-- | ^ | ^
-- | +-------+ | +-------+
-- ...>| node |... ....>| new |... (0..N brothers)
-- +-------+ +-------+
-- | ^ | ^
-- | +-------+ | +-------+
-- ->| c | ->| node |-->0 (0 brother)
-- +-------+ +-------+
-- |
-- +-------+
-- | c |
-- +-------+
--
New_Parent : Frame_Ptr := new Frame '(Parent => F.Parent,
Next => F.Next,
Children => F,
Used => F.Used,
Depth => F.Depth,
Local_Depth => Pos,
Calls => (others => 0));
Child : Frame_Ptr := F.Parent.Children;
begin
-- Move the PC values in the new parent.
New_Parent.Calls (1 .. Pos) := F.Calls (1 .. Pos);
F.Calls (1 .. F.Local_Depth - Pos) := F.Calls (Pos + 1 .. F.Local_Depth);
F.Parent := New_Parent;
F.Next := null;
New_Parent.Depth := F.Depth - F.Local_Depth + Pos;
F.Local_Depth := F.Local_Depth - Pos;
-- Remove F from its parent children list and replace if with New_Parent.
if Child = F then
New_Parent.Parent.Children := New_Parent;
else
while Child.Next /= F loop
Child := Child.Next;
end loop;
Child.Next := New_Parent;
end if;
F := New_Parent;
end Split;
procedure Add_Frame (F : in Frame_Ptr;
Pc : in Pc_Table;
Result : out Frame_Ptr) is
Child : Frame_Ptr := F;
Pos : Positive := Pc'First;
Current_Depth : Natural := F.Depth;
Cnt : Local_Depth_Type;
begin
while Pos <= Pc'Last loop
Cnt := Frame_Group_Size;
if Pos + Cnt > Pc'Last then
Cnt := Pc'Last - Pos + 1;
end if;
Current_Depth := Current_Depth + Cnt;
Child := new Frame '(Parent => Child,
Next => Child.Children,
Children => null,
Used => 1,
Depth => Current_Depth,
Local_Depth => Cnt,
Calls => (others => 0));
Child.Calls (1 .. Cnt) := Pc (Pos .. Pos + Cnt - 1);
Pos := Pos + Cnt;
Child.Parent.Children := Child;
end loop;
Result := Child;
end Add_Frame;
procedure Insert (F : in Frame_Ptr;
Pc : in Pc_Table;
Result : out Frame_Ptr) is
Current : Frame_Ptr := F;
Child : Frame_Ptr;
Pos : Positive := Pc'First;
Lpos : Positive := 1;
Addr : Target_Addr;
begin
while Pos <= Pc'Last loop
Addr := Pc (Pos);
if Lpos <= Current.Local_Depth then
if Addr = Current.Calls (Lpos) then
Lpos := Lpos + 1;
Pos := Pos + 1;
-- Split this node
else
if Lpos > 1 then
Split (Current, Lpos - 1);
end if;
Add_Frame (Current, Pc (Pos .. Pc'Last), Result);
return;
end if;
else
-- Find the first child which has the address.
Child := Current.Children;
while Child /= null loop
exit when Child.Calls (1) = Addr;
Child := Child.Next;
end loop;
if Child = null then
Add_Frame (Current, Pc (Pos .. Pc'Last), Result);
return;
end if;
Current := Child;
Lpos := 2;
Pos := Pos + 1;
Current.Used := Current.Used + 1;
end if;
end loop;
if Lpos <= Current.Local_Depth then
Split (Current, Lpos - 1);
end if;
Result := Current;
end Insert;
-- Find the child frame which has the given PC address.
-- Returns that frame pointer or raises the Not_Found exception.
function Find (F : in Frame_Ptr; Pc : in Target_Addr) return Frame_Ptr is
Child : Frame_Ptr := F.Children;
begin
while Child /= null loop
if Child.Local_Depth >= 1 and then Child.Calls (1) = Pc then
return Child;
end if;
Child := Child.Next;
end loop;
raise Not_Found;
end Find;
-- Find the child frame which has the given PC address.
-- Returns that frame pointer or raises the Not_Found exception.
function Find (F : in Frame_Ptr; Pc : in PC_Table) return Frame_Ptr is
Child : Frame_Ptr := F;
Pos : Positive := Pc'First;
Lpos : Positive;
begin
while Pos <= Pc'Last loop
Child := Find (Child, Pc (Pos));
Pos := Pos + 1;
Lpos := 2;
-- All the PC of the child frame must match.
while Pos <= Pc'Last and Lpos <= Child.Local_Depth loop
if Child.Calls (Lpos) /= Pc (Pos) then
raise Not_Found;
end if;
Lpos := Lpos + 1;
Pos := Pos + 1;
end loop;
end loop;
return Child;
end Find;
-- Find the child frame which has the given PC address.
-- Returns that frame pointer or raises the Not_Found exception.
procedure Find (F : in Frame_Ptr;
Pc : in PC_Table;
Result : out Frame_Ptr;
Last_Pc : out Natural) is
Current : Frame_Ptr := F;
Pos : Positive := Pc'First;
Lpos : Positive;
begin
Main_Search:
while Pos <= Pc'Last loop
declare
Addr : Target_Addr := Pc (Pos);
Child : Frame_Ptr := Current.Children;
begin
-- Find the child which has the corresponding PC.
loop
exit Main_Search when Child = null;
exit when Child.Local_Depth >= 1 and Child.Calls (1) = Addr;
Child := Child.Next;
end loop;
Current := Child;
Pos := Pos + 1;
Lpos := 2;
-- All the PC of the child frame must match.
while Pos <= Pc'Last and Lpos <= Current.Local_Depth loop
exit Main_Search when Current.Calls (Lpos) /= Pc (Pos);
Lpos := Lpos + 1;
Pos := Pos + 1;
end loop;
end;
end loop Main_Search;
Result := Current;
if Pos > Pc'Last then
Last_Pc := 0;
else
Last_Pc := Pos;
end if;
end Find;
end MAT.Frames;
|
Refactor the Parent operation
|
Refactor the Parent operation
|
Ada
|
apache-2.0
|
stcarrez/mat,stcarrez/mat,stcarrez/mat
|
11d7f346f20c580ddc3327319795f2cf914680a1
|
src/wiki-parsers.ads
|
src/wiki-parsers.ads
|
-----------------------------------------------------------------------
-- wiki-parsers -- Wiki parser
-- Copyright (C) 2011, 2015, 2016 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Wide_Wide_Unbounded;
with Wiki.Documents;
with Wiki.Attributes;
with Wiki.Plugins;
with Wiki.Filters;
with Wiki.Strings;
with Wiki.Nodes;
-- == Wiki Parsers ==
-- The <b>Wikis.Parsers</b> package implements a parser for several well known wiki formats.
-- The parser works with the <b>Document_Reader</b> interface type which defines several
-- procedures that are called by the parser when the wiki text is scanned.
package Wiki.Parsers is
pragma Preelaborate;
-- Defines the possible wiki syntax supported by the parser.
type Wiki_Syntax_Type
is (
-- Google wiki syntax http://code.google.com/p/support/wiki/WikiSyntax
SYNTAX_GOOGLE,
-- Creole wiki syntax http://www.wikicreole.org/wiki/Creole1.0
SYNTAX_CREOLE,
-- Dotclear syntax http://dotclear.org/documentation/2.0/usage/syntaxes
SYNTAX_DOTCLEAR,
-- PhpBB syntax http://wiki.phpbb.com/Help:Formatting
SYNTAX_PHPBB,
-- MediaWiki syntax http://www.mediawiki.org/wiki/Help:Formatting
SYNTAX_MEDIA_WIKI,
-- Markdown
SYNTAX_MARKDOWN,
-- A mix of the above
SYNTAX_MIX,
-- The input is plain possibly incorrect HTML.
SYNTAX_HTML);
type Parser is tagged limited private;
-- Add the plugin to the wiki engine.
procedure Add_Plugin (Engine : in out Parser;
Name : in String;
Plugin : in Wiki.Plugins.Wiki_Plugin_Access);
-- Set the wiki syntax that the wiki engine must use.
procedure Set_Syntax (Engine : in out Parser;
Syntax : in Wiki_Syntax_Type := SYNTAX_MIX);
-- Add a filter in the wiki engine.
procedure Add_Filter (Engine : in out Parser;
Filter : in Wiki.Filters.Filter_Type_Access);
-- Parse the wiki text contained in <b>Text</b> according to the wiki syntax configured
-- on the wiki engine. The document reader operations are invoked while parsing the wiki
-- text.
procedure Parse (Engine : in out Parser;
Text : in Wide_Wide_String;
Into : in Wiki.Documents.Document_Reader_Access);
-- Parse the wiki text contained in <b>Text</b> according to the wiki syntax
-- specified in <b>Syntax</b> and invoke the document reader procedures defined
-- by <b>into</b>.
procedure Parse (Into : in Wiki.Documents.Document_Reader_Access;
Text : in Wide_Wide_String;
Syntax : in Wiki_Syntax_Type := SYNTAX_MIX);
private
use Ada.Strings.Wide_Wide_Unbounded;
HT : constant Wide_Wide_Character := Wide_Wide_Character'Val (16#09#);
LF : constant Wide_Wide_Character := Wide_Wide_Character'Val (16#0A#);
CR : constant Wide_Wide_Character := Wide_Wide_Character'Val (16#0D#);
type Input is interface;
type Input_Access is access all Input'Class;
procedure Read_Char (From : in out Input;
Token : out Wide_Wide_Character;
Eof : out Boolean) is abstract;
type Parser is tagged limited record
Pending : Wide_Wide_Character;
Has_Pending : Boolean;
Syntax : Wiki_Syntax_Type;
Document : Wiki.Nodes.Document;
Filters : Wiki.Filters.Filter_Type_Access;
-- Document : Wiki.Documents.Document_Reader_Access;
Format : Wiki.Documents.Format_Map;
Text : Wiki.Strings.BString (512);
Token : Wiki.Strings.BString (512);
Empty_Line : Boolean := True;
Is_Eof : Boolean := False;
In_Paragraph : Boolean := False;
In_List : Boolean := False;
Need_Paragraph : Boolean := True;
Link_Double_Bracket : Boolean := False;
Is_Dotclear : Boolean := False;
Link_Title_First : Boolean := False;
Check_Image_Link : Boolean := False;
Header_Offset : Integer := 0;
Quote_Level : Natural := 0;
Escape_Char : Wide_Wide_Character;
List_Level : Natural := 0;
Reader : Input_Access := null;
Attributes : Wiki.Attributes.Attribute_List_Type;
end record;
type Parser_Handler is access procedure (P : in out Parser;
Token : in Wide_Wide_Character);
type Parser_Table is array (0 .. 127) of Parser_Handler;
type Parser_Table_Access is access Parser_Table;
-- Peek the next character from the wiki text buffer.
procedure Peek (P : in out Parser;
Token : out Wide_Wide_Character);
-- Put back the character so that it will be returned by the next call to Peek.
procedure Put_Back (P : in out Parser;
Token : in Wide_Wide_Character);
-- Skip all the spaces and tabs as well as end of the current line (CR+LF).
procedure Skip_End_Of_Line (P : in out Parser);
-- Skip white spaces and tabs.
procedure Skip_Spaces (P : in out Parser);
-- Flush the wiki text that was collected in the text buffer.
procedure Flush_Text (P : in out Parser);
-- Flush the wiki dl/dt/dd definition list.
procedure Flush_List (P : in out Parser);
-- Append a character to the wiki text buffer.
procedure Parse_Text (P : in out Parser;
Token : in Wide_Wide_Character);
-- Check if the link refers to an image and must be rendered as an image.
function Is_Image (P : in Parser;
Link : in Wide_Wide_String) return Boolean;
procedure Start_Element (P : in out Parser;
Name : in Unbounded_Wide_Wide_String;
Attributes : in Wiki.Attributes.Attribute_List_Type);
procedure End_Element (P : in out Parser;
Name : in Ada.Strings.Wide_Wide_Unbounded.Unbounded_Wide_Wide_String);
end Wiki.Parsers;
|
-----------------------------------------------------------------------
-- wiki-parsers -- Wiki parser
-- Copyright (C) 2011, 2015, 2016 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Wide_Wide_Unbounded;
with Wiki.Documents;
with Wiki.Attributes;
with Wiki.Plugins;
with Wiki.Filters;
with Wiki.Strings;
with Wiki.Nodes;
-- == Wiki Parsers ==
-- The <b>Wikis.Parsers</b> package implements a parser for several well known wiki formats.
-- The parser works with the <b>Document_Reader</b> interface type which defines several
-- procedures that are called by the parser when the wiki text is scanned.
package Wiki.Parsers is
pragma Preelaborate;
-- Defines the possible wiki syntax supported by the parser.
type Wiki_Syntax_Type
is (
-- Google wiki syntax http://code.google.com/p/support/wiki/WikiSyntax
SYNTAX_GOOGLE,
-- Creole wiki syntax http://www.wikicreole.org/wiki/Creole1.0
SYNTAX_CREOLE,
-- Dotclear syntax http://dotclear.org/documentation/2.0/usage/syntaxes
SYNTAX_DOTCLEAR,
-- PhpBB syntax http://wiki.phpbb.com/Help:Formatting
SYNTAX_PHPBB,
-- MediaWiki syntax http://www.mediawiki.org/wiki/Help:Formatting
SYNTAX_MEDIA_WIKI,
-- Markdown
SYNTAX_MARKDOWN,
-- A mix of the above
SYNTAX_MIX,
-- The input is plain possibly incorrect HTML.
SYNTAX_HTML);
type Parser is tagged limited private;
-- Add the plugin to the wiki engine.
procedure Add_Plugin (Engine : in out Parser;
Name : in String;
Plugin : in Wiki.Plugins.Wiki_Plugin_Access);
-- Set the wiki syntax that the wiki engine must use.
procedure Set_Syntax (Engine : in out Parser;
Syntax : in Wiki_Syntax_Type := SYNTAX_MIX);
-- Add a filter in the wiki engine.
procedure Add_Filter (Engine : in out Parser;
Filter : in Wiki.Filters.Filter_Type_Access);
-- Parse the wiki text contained in <b>Text</b> according to the wiki syntax configured
-- on the wiki engine. The document reader operations are invoked while parsing the wiki
-- text.
procedure Parse (Engine : in out Parser;
Text : in Wide_Wide_String;
Into : in Wiki.Documents.Document_Reader_Access);
-- Parse the wiki text contained in <b>Text</b> according to the wiki syntax
-- specified in <b>Syntax</b> and invoke the document reader procedures defined
-- by <b>into</b>.
procedure Parse (Into : in Wiki.Documents.Document_Reader_Access;
Text : in Wide_Wide_String;
Syntax : in Wiki_Syntax_Type := SYNTAX_MIX);
private
use Ada.Strings.Wide_Wide_Unbounded;
HT : constant Wide_Wide_Character := Wide_Wide_Character'Val (16#09#);
LF : constant Wide_Wide_Character := Wide_Wide_Character'Val (16#0A#);
CR : constant Wide_Wide_Character := Wide_Wide_Character'Val (16#0D#);
type Input is interface;
type Input_Access is access all Input'Class;
procedure Read_Char (From : in out Input;
Token : out Wide_Wide_Character;
Eof : out Boolean) is abstract;
type Parser is tagged limited record
Pending : Wide_Wide_Character;
Has_Pending : Boolean;
Syntax : Wiki_Syntax_Type;
Document : Wiki.Nodes.Document;
Filters : Wiki.Filters.Filter_Type_Access;
-- Document : Wiki.Documents.Document_Reader_Access;
Format : Wiki.Documents.Format_Map;
Text : Wiki.Strings.BString (512);
Token : Wiki.Strings.BString (512);
Empty_Line : Boolean := True;
Is_Eof : Boolean := False;
In_Paragraph : Boolean := False;
In_List : Boolean := False;
Need_Paragraph : Boolean := True;
Link_Double_Bracket : Boolean := False;
Is_Dotclear : Boolean := False;
Link_Title_First : Boolean := False;
Check_Image_Link : Boolean := False;
Header_Offset : Integer := 0;
Quote_Level : Natural := 0;
Escape_Char : Wide_Wide_Character;
List_Level : Natural := 0;
Reader : Input_Access := null;
Attributes : Wiki.Attributes.Attribute_List_Type;
end record;
type Parser_Handler is access procedure (P : in out Parser;
Token : in Wide_Wide_Character);
type Parser_Table is array (0 .. 127) of Parser_Handler;
type Parser_Table_Access is access Parser_Table;
-- Peek the next character from the wiki text buffer.
procedure Peek (P : in out Parser;
Token : out Wide_Wide_Character);
-- Put back the character so that it will be returned by the next call to Peek.
procedure Put_Back (P : in out Parser;
Token : in Wide_Wide_Character);
-- Skip all the spaces and tabs as well as end of the current line (CR+LF).
procedure Skip_End_Of_Line (P : in out Parser);
-- Skip white spaces and tabs.
procedure Skip_Spaces (P : in out Parser);
-- Flush the wiki text that was collected in the text buffer.
procedure Flush_Text (P : in out Parser);
-- Flush the wiki dl/dt/dd definition list.
procedure Flush_List (P : in out Parser);
-- Append a character to the wiki text buffer.
procedure Parse_Text (P : in out Parser;
Token : in Wide_Wide_Character);
-- Check if the link refers to an image and must be rendered as an image.
function Is_Image (P : in Parser;
Link : in Wide_Wide_String) return Boolean;
procedure Start_Element (P : in out Parser;
Tag : in Wiki.Nodes.Html_Tag_Type;
Attributes : in Wiki.Attributes.Attribute_List_Type);
procedure End_Element (P : in out Parser;
Tag : in Wiki.Nodes.Html_Tag_Type);
end Wiki.Parsers;
|
Use Wiki.Nodes.Html_Tag_Type for the tag type for Start_Element and End_Element procedures
|
Use Wiki.Nodes.Html_Tag_Type for the tag type for Start_Element and End_Element procedures
|
Ada
|
apache-2.0
|
stcarrez/ada-wiki,stcarrez/ada-wiki
|
981822a9551e524b02d8f2abb74df0bb1e6c16fe
|
src/wiki-parsers.ads
|
src/wiki-parsers.ads
|
-----------------------------------------------------------------------
-- wiki-parsers -- Wiki parser
-- Copyright (C) 2011, 2015, 2016 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Wiki.Attributes;
with Wiki.Plugins;
with Wiki.Filters;
with Wiki.Strings;
with Wiki.Documents;
with Wiki.Streams;
-- === Wiki Parsers ===
-- The <b>Wikis.Parsers</b> package implements a parser for several well known wiki formats
-- but also for HTML. While reading the input, the parser populates a wiki <tt>Document</tt>
-- instance with headers, paragraphs, links, and other elements.
--
-- Engine : Wiki.Parsers.Parser;
--
-- Before using the parser, it must be configured to choose the syntax by using the
-- <tt>Set_Syntax</tt> procedure:
--
-- Engine.Set_Syntax (Wiki.SYNTAX_HTML);
--
-- The parser can be configured to use filters. A filter is added by using the
-- <tt>Add_Filter</tt> procedure. A filter is added at begining of the chain so that
-- the filter added last is called first. The wiki <tt>Document</tt> is always built through
-- the filter chain so this allows filters to change or alter the content that was parsed.
--
-- Engine.Add_Filter (TOC'Unchecked_Access);
-- Engine.Add_Filter (Filter'Unchecked_Access);
--
-- The <tt>Parse</tt> procedure is then used to parse either a string content or some stream
-- represented by the <tt>Input_Stream</tt> interface. After the <tt>Parse</tt> procedure
-- completes, the <tt>Document</tt> instance holds the wiki document.
--
-- Engine.Parse (Some_Text, Doc);
--
package Wiki.Parsers is
pragma Preelaborate;
type Parser is tagged limited private;
-- Set the plugin factory to find and use plugins.
procedure Set_Plugin_Factory (Engine : in out Parser;
Factory : in Wiki.Plugins.Plugin_Factory_Access);
-- Set the wiki syntax that the wiki engine must use.
procedure Set_Syntax (Engine : in out Parser;
Syntax : in Wiki_Syntax := SYNTAX_MIX);
-- Add a filter in the wiki engine.
procedure Add_Filter (Engine : in out Parser;
Filter : in Wiki.Filters.Filter_Type_Access);
-- Set the plugin context.
procedure Set_Context (Engine : in out Parser;
Context : in Wiki.Plugins.Plugin_Context);
-- Parse the wiki text contained in <b>Text</b> according to the wiki syntax
-- defined on the parser. The string is assumed to be in UTF-8 format.
procedure Parse (Engine : in out Parser;
Text : in String;
Doc : in out Wiki.Documents.Document);
-- Parse the wiki text contained in <b>Text</b> according to the wiki syntax
-- defined on the parser.
procedure Parse (Engine : in out Parser;
Text : in Wiki.Strings.WString;
Doc : in out Wiki.Documents.Document);
-- Parse the wiki text contained in <b>Text</b> according to the wiki syntax
-- defined on the parser.
procedure Parse (Engine : in out Parser;
Text : in Wiki.Strings.UString;
Doc : in out Wiki.Documents.Document);
-- Parse the wiki stream managed by <tt>Stream</tt> according to the wiki syntax configured
-- on the wiki engine.
procedure Parse (Engine : in out Parser;
Stream : in Wiki.Streams.Input_Stream_Access;
Doc : in out Wiki.Documents.Document);
private
type Parser_Handler is access procedure (P : in out Parser;
Token : in Wiki.Strings.WChar);
type Parser_Table is array (0 .. 127) of Parser_Handler;
type Parser_Table_Access is access constant Parser_Table;
type Parser is tagged limited record
Context : Wiki.Plugins.Plugin_Context;
Pending : Wiki.Strings.WChar;
Has_Pending : Boolean;
Previous_Syntax : Wiki_Syntax;
Table : Parser_Table_Access;
Document : Wiki.Documents.Document;
Format : Wiki.Format_Map;
Text : Wiki.Strings.BString (512);
Empty_Line : Boolean := True;
Is_Eof : Boolean := False;
In_Paragraph : Boolean := False;
In_List : Boolean := False;
Need_Paragraph : Boolean := True;
Link_Double_Bracket : Boolean := False;
Link_No_Space : Boolean := False;
Is_Dotclear : Boolean := False;
Link_Title_First : Boolean := False;
Check_Image_Link : Boolean := False;
Is_Hidden : Boolean := False;
Header_Offset : Integer := 0;
Preformat_Column : Natural := 1;
Quote_Level : Natural := 0;
Escape_Char : Wiki.Strings.WChar;
Param_Char : Wiki.Strings.WChar;
List_Level : Natural := 0;
Reader : Wiki.Streams.Input_Stream_Access := null;
Attributes : Wiki.Attributes.Attribute_List;
end record;
-- Peek the next character from the wiki text buffer.
procedure Peek (P : in out Parser'Class;
Token : out Wiki.Strings.WChar);
pragma Inline (Peek);
-- Put back the character so that it will be returned by the next call to Peek.
procedure Put_Back (P : in out Parser;
Token : in Wiki.Strings.WChar);
-- Skip all the spaces and tabs as well as end of the current line (CR+LF).
procedure Skip_End_Of_Line (P : in out Parser);
-- Skip white spaces and tabs.
procedure Skip_Spaces (P : in out Parser);
-- Flush the wiki text that was collected in the text buffer.
procedure Flush_Text (P : in out Parser);
-- Flush the wiki dl/dt/dd definition list.
procedure Flush_List (P : in out Parser);
-- Append a character to the wiki text buffer.
procedure Parse_Text (P : in out Parser;
Token : in Wiki.Strings.WChar);
-- Check if the link refers to an image and must be rendered as an image.
-- Returns a positive index of the start the the image link.
function Is_Image (P : in Parser;
Link : in Wiki.Strings.WString) return Natural;
-- Find the plugin with the given name.
-- Returns null if there is no such plugin.
function Find (P : in Parser;
Name : in Wiki.Strings.WString) return Wiki.Plugins.Wiki_Plugin_Access;
type String_Array is array (Positive range <>) of Wiki.String_Access;
-- Extract a list of parameters separated by the given separator (ex: '|').
procedure Parse_Parameters (P : in out Parser;
Separator : in Wiki.Strings.WChar;
Terminator : in Wiki.Strings.WChar;
Names : in String_Array;
Max : in Positive := 200);
procedure Start_Element (P : in out Parser;
Tag : in Wiki.Html_Tag;
Attributes : in out Wiki.Attributes.Attribute_List);
procedure End_Element (P : in out Parser;
Tag : in Wiki.Html_Tag);
procedure Parse_Token (P : in out Parser);
end Wiki.Parsers;
|
-----------------------------------------------------------------------
-- wiki-parsers -- Wiki parser
-- Copyright (C) 2011, 2015, 2016 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Wiki.Attributes;
with Wiki.Plugins;
with Wiki.Filters;
with Wiki.Strings;
with Wiki.Documents;
with Wiki.Streams;
-- === Wiki Parsers ===
-- The <b>Wikis.Parsers</b> package implements a parser for several well known wiki formats
-- but also for HTML. While reading the input, the parser populates a wiki <tt>Document</tt>
-- instance with headers, paragraphs, links, and other elements.
--
-- Engine : Wiki.Parsers.Parser;
--
-- Before using the parser, it must be configured to choose the syntax by using the
-- <tt>Set_Syntax</tt> procedure:
--
-- Engine.Set_Syntax (Wiki.SYNTAX_HTML);
--
-- The parser can be configured to use filters. A filter is added by using the
-- <tt>Add_Filter</tt> procedure. A filter is added at begining of the chain so that
-- the filter added last is called first. The wiki <tt>Document</tt> is always built through
-- the filter chain so this allows filters to change or alter the content that was parsed.
--
-- Engine.Add_Filter (TOC'Unchecked_Access);
-- Engine.Add_Filter (Filter'Unchecked_Access);
--
-- The <tt>Parse</tt> procedure is then used to parse either a string content or some stream
-- represented by the <tt>Input_Stream</tt> interface. After the <tt>Parse</tt> procedure
-- completes, the <tt>Document</tt> instance holds the wiki document.
--
-- Engine.Parse (Some_Text, Doc);
--
package Wiki.Parsers is
pragma Preelaborate;
type Parser is tagged limited private;
-- Set the plugin factory to find and use plugins.
procedure Set_Plugin_Factory (Engine : in out Parser;
Factory : in Wiki.Plugins.Plugin_Factory_Access);
-- Set the wiki syntax that the wiki engine must use.
procedure Set_Syntax (Engine : in out Parser;
Syntax : in Wiki_Syntax := SYNTAX_MIX);
-- Add a filter in the wiki engine.
procedure Add_Filter (Engine : in out Parser;
Filter : in Wiki.Filters.Filter_Type_Access);
-- Set the plugin context.
procedure Set_Context (Engine : in out Parser;
Context : in Wiki.Plugins.Plugin_Context);
-- Parse the wiki text contained in <b>Text</b> according to the wiki syntax
-- defined on the parser. The string is assumed to be in UTF-8 format.
procedure Parse (Engine : in out Parser;
Text : in String;
Doc : in out Wiki.Documents.Document);
-- Parse the wiki text contained in <b>Text</b> according to the wiki syntax
-- defined on the parser.
procedure Parse (Engine : in out Parser;
Text : in Wiki.Strings.WString;
Doc : in out Wiki.Documents.Document);
-- Parse the wiki text contained in <b>Text</b> according to the wiki syntax
-- defined on the parser.
procedure Parse (Engine : in out Parser;
Text : in Wiki.Strings.UString;
Doc : in out Wiki.Documents.Document);
-- Parse the wiki stream managed by <tt>Stream</tt> according to the wiki syntax configured
-- on the wiki engine.
procedure Parse (Engine : in out Parser;
Stream : in Wiki.Streams.Input_Stream_Access;
Doc : in out Wiki.Documents.Document);
private
type Parser_Handler is access procedure (P : in out Parser;
Token : in Wiki.Strings.WChar);
type Parser_Table is array (0 .. 127) of Parser_Handler;
type Parser_Table_Access is access constant Parser_Table;
type Parser is tagged limited record
Context : aliased Wiki.Plugins.Plugin_Context;
Pending : Wiki.Strings.WChar;
Has_Pending : Boolean;
Previous_Syntax : Wiki_Syntax;
Table : Parser_Table_Access;
Document : Wiki.Documents.Document;
Format : Wiki.Format_Map;
Text : Wiki.Strings.BString (512);
Empty_Line : Boolean := True;
Is_Eof : Boolean := False;
In_Paragraph : Boolean := False;
In_List : Boolean := False;
Need_Paragraph : Boolean := True;
Link_Double_Bracket : Boolean := False;
Link_No_Space : Boolean := False;
Is_Dotclear : Boolean := False;
Link_Title_First : Boolean := False;
Check_Image_Link : Boolean := False;
Header_Offset : Integer := 0;
Preformat_Column : Natural := 1;
Quote_Level : Natural := 0;
Escape_Char : Wiki.Strings.WChar;
Param_Char : Wiki.Strings.WChar;
List_Level : Natural := 0;
Reader : Wiki.Streams.Input_Stream_Access := null;
Attributes : Wiki.Attributes.Attribute_List;
end record;
-- Peek the next character from the wiki text buffer.
procedure Peek (P : in out Parser'Class;
Token : out Wiki.Strings.WChar);
pragma Inline (Peek);
-- Put back the character so that it will be returned by the next call to Peek.
procedure Put_Back (P : in out Parser;
Token : in Wiki.Strings.WChar);
-- Skip all the spaces and tabs as well as end of the current line (CR+LF).
procedure Skip_End_Of_Line (P : in out Parser);
-- Skip white spaces and tabs.
procedure Skip_Spaces (P : in out Parser);
-- Flush the wiki text that was collected in the text buffer.
procedure Flush_Text (P : in out Parser);
-- Flush the wiki dl/dt/dd definition list.
procedure Flush_List (P : in out Parser);
-- Append a character to the wiki text buffer.
procedure Parse_Text (P : in out Parser;
Token : in Wiki.Strings.WChar);
-- Check if the link refers to an image and must be rendered as an image.
-- Returns a positive index of the start the the image link.
function Is_Image (P : in Parser;
Link : in Wiki.Strings.WString) return Natural;
-- Find the plugin with the given name.
-- Returns null if there is no such plugin.
function Find (P : in Parser;
Name : in Wiki.Strings.WString) return Wiki.Plugins.Wiki_Plugin_Access;
type String_Array is array (Positive range <>) of Wiki.String_Access;
-- Extract a list of parameters separated by the given separator (ex: '|').
procedure Parse_Parameters (P : in out Parser;
Separator : in Wiki.Strings.WChar;
Terminator : in Wiki.Strings.WChar;
Names : in String_Array;
Max : in Positive := 200);
procedure Start_Element (P : in out Parser;
Tag : in Wiki.Html_Tag;
Attributes : in out Wiki.Attributes.Attribute_List);
procedure End_Element (P : in out Parser;
Tag : in Wiki.Html_Tag);
procedure Parse_Token (P : in out Parser);
end Wiki.Parsers;
|
Remove the Is_Hidden boolean to use the wiki context
|
Remove the Is_Hidden boolean to use the wiki context
|
Ada
|
apache-2.0
|
stcarrez/ada-wiki,stcarrez/ada-wiki
|
16decfa601bde49bedf195d127052bde1d721822
|
src/ado-sql.adb
|
src/ado-sql.adb
|
-----------------------------------------------------------------------
-- ADO SQL -- Basic SQL Generation
-- 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.
-----------------------------------------------------------------------
-- Utilities for creating SQL queries and statements.
package body ADO.SQL is
function Escape (Str : in Unbounded_String) return String is
begin
return Escape (To_String (Str));
end Escape;
function Escape (Str : in String) return String is
S : String (1 .. 2 + Str'Length * 2);
J : Positive := S'First;
begin
if Str = "" then
return "NULL";
end if;
S (J) := ''';
for K in Str'Range loop
if Str (K) = ''' then
J := J + 1;
S (J) := ''';
end if;
J := J + 1;
S (J) := Str (K);
end loop;
J := J + 1;
S (J) := ''';
return S (1 .. J);
end Escape;
-- --------------------
-- Buffer
-- --------------------
-- --------------------
-- Clear the SQL buffer.
-- --------------------
procedure Clear (Target : in out Buffer) is
begin
Target.Buf := To_Unbounded_String ("");
end Clear;
-- --------------------
-- Append an SQL extract into the buffer.
-- --------------------
procedure Append (Target : in out Buffer;
SQL : in String) is
begin
Append (Target.Buf, SQL);
end Append;
-- --------------------
-- Append a name in the buffer and escape that
-- name if this is a reserved keyword.
-- --------------------
procedure Append_Name (Target : in out Buffer;
Name : in String) is
use type ADO.Drivers.Dialects.Dialect_Access;
Dialect : constant ADO.Drivers.Dialects.Dialect_Access := Target.Get_Dialect;
begin
if Dialect /= null and then Dialect.Is_Reserved (Name) then
declare
Quote : constant Character := Dialect.Get_Identifier_Quote;
begin
Append (Target.Buf, Quote);
Append (Target.Buf, Name);
Append (Target.Buf, Quote);
end;
else
Append (Target.Buf, Name);
end if;
end Append_Name;
-- --------------------
-- Append a string value in the buffer and
-- escape any special character if necessary.
-- --------------------
procedure Append_Value (Target : in out Buffer;
Value : in String) is
begin
Append (Target.Buf, Value);
end Append_Value;
-- --------------------
-- Append a string value in the buffer and
-- escape any special character if necessary.
-- --------------------
procedure Append_Value (Target : in out Buffer;
Value : in Unbounded_String) is
begin
Append (Target.Buf, Value);
end Append_Value;
-- --------------------
-- Append the integer value in the buffer.
-- --------------------
procedure Append_Value (Target : in out Buffer;
Value : in Long_Integer) is
S : constant String := Long_Integer'Image (Value);
begin
Append (Target.Buf, S (S'First + 1 .. S'Last));
end Append_Value;
-- --------------------
-- Append the integer value in the buffer.
-- --------------------
procedure Append_Value (Target : in out Buffer;
Value : in Integer) is
S : constant String := Integer'Image (Value);
begin
Append (Target.Buf, S (S'First + 1 .. S'Last));
end Append_Value;
-- --------------------
-- Append the identifier value in the buffer.
-- --------------------
procedure Append_Value (Target : in out Buffer;
Value : in Identifier) is
S : constant String := Identifier'Image (Value);
begin
Append (Target.Buf, S (S'First + 1 .. S'Last));
end Append_Value;
-- --------------------
-- Get the SQL string that was accumulated in the buffer.
-- --------------------
function To_String (From : in Buffer) return String is
begin
return To_String (From.Buf);
end To_String;
-- --------------------
-- Clear the query object.
-- --------------------
overriding
procedure Clear (Target : in out Query) is
begin
ADO.Parameters.List (Target).Clear;
Target.Join.Clear;
Target.Filter.Clear;
Target.SQL.Clear;
end Clear;
-- --------------------
-- Set the SQL dialect description object.
-- --------------------
procedure Set_Dialect (Target : in out Query;
D : in ADO.Drivers.Dialects.Dialect_Access) is
begin
ADO.Parameters.Abstract_List (Target).Set_Dialect (D);
Set_Dialect (Target.SQL, D);
Set_Dialect (Target.Filter, D);
Set_Dialect (Target.Join, D);
end Set_Dialect;
procedure Set_Filter (Target : in out Query;
Filter : in String) is
begin
Target.Filter.Buf := To_Unbounded_String (Filter);
end Set_Filter;
function Get_Filter (Source : in Query) return String is
begin
if Source.Filter.Buf = Null_Unbounded_String then
return "";
else
return To_String (Source.Filter.Buf);
end if;
end Get_Filter;
function Has_Filter (Source : in Query) return Boolean is
begin
return Source.Filter.Buf /= Null_Unbounded_String
and Length (Source.Filter.Buf) > 0;
end Has_Filter;
-- --------------------
-- Set the join condition.
-- --------------------
procedure Set_Join (Target : in out Query;
Join : in String) is
begin
Target.Join.Buf := To_Unbounded_String (Join);
end Set_Join;
-- --------------------
-- Returns true if there is a join condition
-- --------------------
function Has_Join (Source : in Query) return Boolean is
begin
return Source.Join.Buf /= Null_Unbounded_String
and Length (Source.Join.Buf) > 0;
end Has_Join;
-- --------------------
-- Get the join condition
-- --------------------
function Get_Join (Source : in Query) return String is
begin
if Source.Join.Buf = Null_Unbounded_String then
return "";
else
return To_String (Source.Join.Buf);
end if;
end Get_Join;
-- --------------------
-- Set the parameters from another parameter list.
-- If the parameter list is a query object, also copy the filter part.
-- --------------------
procedure Set_Parameters (Params : in out Query;
From : in ADO.Parameters.Abstract_List'Class) is
begin
ADO.Parameters.List (Params).Set_Parameters (From);
if From in Query'Class then
declare
L : constant Query'Class := Query'Class (From);
begin
Params.Filter := L.Filter;
Params.Join := L.Join;
end;
end if;
end Set_Parameters;
-- --------------------
-- Expand the parameters into the query and return the expanded SQL query.
-- --------------------
function Expand (Source : in Query) return String is
begin
return ADO.Parameters.Abstract_List (Source).Expand (To_String (Source.SQL.Buf));
end Expand;
procedure Add_Field (Update : in out Update_Query'Class;
Name : in String) is
begin
Update.Pos := Update.Pos + 1;
if Update.Pos > 1 then
Append (Target => Update.Set_Fields, SQL => ",");
Append (Target => Update.Fields, SQL => ",");
end if;
Append_Name (Target => Update.Set_Fields, Name => Name);
if Update.Is_Update_Stmt then
Append (Target => Update.Set_Fields, SQL => " = ?");
end if;
Append (Target => Update.Fields, SQL => "?");
end Add_Field;
-- ------------------------------
-- Set the SQL dialect description object.
-- ------------------------------
procedure Set_Dialect (Target : in out Update_Query;
D : in ADO.Drivers.Dialects.Dialect_Access) is
begin
Target.Set_Fields.Set_Dialect (D);
Target.Fields.Set_Dialect (D);
Query (Target).Set_Dialect (D);
end Set_Dialect;
-- ------------------------------
-- Prepare the update/insert query to save the table field
-- identified by <b>Name</b> and set it to the <b>Value</b>.
-- ------------------------------
procedure Save_Field (Update : in out Update_Query;
Name : in String;
Value : in Boolean) is
begin
Update.Add_Field (Name => Name);
Update_Query'Class (Update).Bind_Param (Position => Update.Pos, Value => Value);
end Save_Field;
-- --------------------
-- Prepare the update/insert query to save the table field
-- identified by <b>Name</b> and set it to the <b>Value</b>.
-- --------------------
procedure Save_Field (Update : in out Update_Query;
Name : in String;
Value : in Integer) is
begin
Update.Add_Field (Name => Name);
Update_Query'Class (Update).Bind_Param (Position => Update.Pos, Value => Value);
end Save_Field;
-- --------------------
-- Prepare the update/insert query to save the table field
-- identified by <b>Name</b> and set it to the <b>Value</b>.
-- --------------------
procedure Save_Field (Update : in out Update_Query;
Name : in String;
Value : in Long_Long_Integer) is
begin
Update.Add_Field (Name => Name);
Update_Query'Class (Update).Bind_Param (Position => Update.Pos, Value => Value);
end Save_Field;
-- --------------------
-- Prepare the update/insert query to save the table field
-- identified by <b>Name</b> and set it to the <b>Value</b>.
-- --------------------
procedure Save_Field (Update : in out Update_Query;
Name : in String;
Value : in Identifier) is
begin
Update.Add_Field (Name => Name);
Update_Query'Class (Update).Add_Param (Value => Value);
end Save_Field;
-- --------------------
-- Prepare the update/insert query to save the table field
-- identified by <b>Name</b> and set it to the <b>Value</b>.
-- --------------------
procedure Save_Field (Update : in out Update_Query;
Name : in String;
Value : in Entity_Type) is
begin
Update.Add_Field (Name => Name);
Update_Query'Class (Update).Add_Param (Value => Integer (Value));
end Save_Field;
-- --------------------
-- Prepare the update/insert query to save the table field
-- identified by <b>Name</b> and set it to the <b>Value</b>.
-- --------------------
procedure Save_Field (Update : in out Update_Query;
Name : in String;
Value : in Ada.Calendar.Time) is
begin
Update.Add_Field (Name => Name);
Update_Query'Class (Update).Add_Param (Value => Value);
end Save_Field;
-- --------------------
-- Prepare the update/insert query to save the table field
-- identified by <b>Name</b> and set it to the <b>Value</b>.
-- --------------------
procedure Save_Field (Update : in out Update_Query;
Name : in String;
Value : in String) is
begin
Update.Add_Field (Name => Name);
Update_Query'Class (Update).Bind_Param (Position => Update.Pos, Value => Value);
end Save_Field;
-- --------------------
-- Prepare the update/insert query to save the table field
-- identified by <b>Name</b> and set it to the <b>Value</b>.
-- --------------------
procedure Save_Field (Update : in out Update_Query;
Name : in String;
Value : in Unbounded_String) is
begin
Update.Add_Field (Name => Name);
Update_Query'Class (Update).Bind_Param (Position => Update.Pos, Value => Value);
end Save_Field;
-- ------------------------------
-- Prepare the update/insert query to save the table field
-- identified by <b>Name</b> and set it to the <b>Value</b>.
-- ------------------------------
procedure Save_Field (Update : in out Update_Query;
Name : in String;
Value : in ADO.Blob_Ref) is
begin
Update.Add_Field (Name => Name);
Update_Query'Class (Update).Bind_Param (Position => Update.Pos, Value => Value);
end Save_Field;
-- ------------------------------
-- Prepare the update/insert query to save the table field
-- identified by <b>Name</b> and set it to NULL.
-- ------------------------------
procedure Save_Null_Field (Update : in out Update_Query;
Name : in String) is
begin
Update.Add_Field (Name => Name);
Update_Query'Class (Update).Bind_Null_Param (Position => Update.Pos);
end Save_Null_Field;
-- --------------------
-- Check if the update/insert query has some fields to update.
-- --------------------
function Has_Save_Fields (Update : in Update_Query) return Boolean is
begin
return Update.Pos > 0;
end Has_Save_Fields;
procedure Set_Insert_Mode (Update : in out Update_Query) is
begin
Update.Is_Update_Stmt := False;
end Set_Insert_Mode;
procedure Append_Fields (Update : in out Update_Query;
Mode : in Boolean := False) is
begin
if Mode then
Append (Target => Update.SQL, SQL => To_String (Update.Fields.Buf));
else
Append (Target => Update.SQL, SQL => To_String (Update.Set_Fields.Buf));
end if;
end Append_Fields;
end ADO.SQL;
|
-----------------------------------------------------------------------
-- ADO SQL -- Basic SQL Generation
-- 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.
-----------------------------------------------------------------------
-- Utilities for creating SQL queries and statements.
package body ADO.SQL is
-- --------------------
-- Buffer
-- --------------------
-- --------------------
-- Clear the SQL buffer.
-- --------------------
procedure Clear (Target : in out Buffer) is
begin
Target.Buf := To_Unbounded_String ("");
end Clear;
-- --------------------
-- Append an SQL extract into the buffer.
-- --------------------
procedure Append (Target : in out Buffer;
SQL : in String) is
begin
Append (Target.Buf, SQL);
end Append;
-- --------------------
-- Append a name in the buffer and escape that
-- name if this is a reserved keyword.
-- --------------------
procedure Append_Name (Target : in out Buffer;
Name : in String) is
use type ADO.Drivers.Dialects.Dialect_Access;
Dialect : constant ADO.Drivers.Dialects.Dialect_Access := Target.Get_Dialect;
begin
if Dialect /= null and then Dialect.Is_Reserved (Name) then
declare
Quote : constant Character := Dialect.Get_Identifier_Quote;
begin
Append (Target.Buf, Quote);
Append (Target.Buf, Name);
Append (Target.Buf, Quote);
end;
else
Append (Target.Buf, Name);
end if;
end Append_Name;
-- --------------------
-- Append a string value in the buffer and
-- escape any special character if necessary.
-- --------------------
procedure Append_Value (Target : in out Buffer;
Value : in String) is
begin
Append (Target.Buf, Value);
end Append_Value;
-- --------------------
-- Append a string value in the buffer and
-- escape any special character if necessary.
-- --------------------
procedure Append_Value (Target : in out Buffer;
Value : in Unbounded_String) is
begin
Append (Target.Buf, Value);
end Append_Value;
-- --------------------
-- Append the integer value in the buffer.
-- --------------------
procedure Append_Value (Target : in out Buffer;
Value : in Long_Integer) is
S : constant String := Long_Integer'Image (Value);
begin
Append (Target.Buf, S (S'First + 1 .. S'Last));
end Append_Value;
-- --------------------
-- Append the integer value in the buffer.
-- --------------------
procedure Append_Value (Target : in out Buffer;
Value : in Integer) is
S : constant String := Integer'Image (Value);
begin
Append (Target.Buf, S (S'First + 1 .. S'Last));
end Append_Value;
-- --------------------
-- Append the identifier value in the buffer.
-- --------------------
procedure Append_Value (Target : in out Buffer;
Value : in Identifier) is
S : constant String := Identifier'Image (Value);
begin
Append (Target.Buf, S (S'First + 1 .. S'Last));
end Append_Value;
-- --------------------
-- Get the SQL string that was accumulated in the buffer.
-- --------------------
function To_String (From : in Buffer) return String is
begin
return To_String (From.Buf);
end To_String;
-- --------------------
-- Clear the query object.
-- --------------------
overriding
procedure Clear (Target : in out Query) is
begin
ADO.Parameters.List (Target).Clear;
Target.Join.Clear;
Target.Filter.Clear;
Target.SQL.Clear;
end Clear;
-- --------------------
-- Set the SQL dialect description object.
-- --------------------
procedure Set_Dialect (Target : in out Query;
D : in ADO.Drivers.Dialects.Dialect_Access) is
begin
ADO.Parameters.Abstract_List (Target).Set_Dialect (D);
Set_Dialect (Target.SQL, D);
Set_Dialect (Target.Filter, D);
Set_Dialect (Target.Join, D);
end Set_Dialect;
procedure Set_Filter (Target : in out Query;
Filter : in String) is
begin
Target.Filter.Buf := To_Unbounded_String (Filter);
end Set_Filter;
function Get_Filter (Source : in Query) return String is
begin
if Source.Filter.Buf = Null_Unbounded_String then
return "";
else
return To_String (Source.Filter.Buf);
end if;
end Get_Filter;
function Has_Filter (Source : in Query) return Boolean is
begin
return Source.Filter.Buf /= Null_Unbounded_String
and Length (Source.Filter.Buf) > 0;
end Has_Filter;
-- --------------------
-- Set the join condition.
-- --------------------
procedure Set_Join (Target : in out Query;
Join : in String) is
begin
Target.Join.Buf := To_Unbounded_String (Join);
end Set_Join;
-- --------------------
-- Returns true if there is a join condition
-- --------------------
function Has_Join (Source : in Query) return Boolean is
begin
return Source.Join.Buf /= Null_Unbounded_String
and Length (Source.Join.Buf) > 0;
end Has_Join;
-- --------------------
-- Get the join condition
-- --------------------
function Get_Join (Source : in Query) return String is
begin
if Source.Join.Buf = Null_Unbounded_String then
return "";
else
return To_String (Source.Join.Buf);
end if;
end Get_Join;
-- --------------------
-- Set the parameters from another parameter list.
-- If the parameter list is a query object, also copy the filter part.
-- --------------------
procedure Set_Parameters (Params : in out Query;
From : in ADO.Parameters.Abstract_List'Class) is
begin
ADO.Parameters.List (Params).Set_Parameters (From);
if From in Query'Class then
declare
L : constant Query'Class := Query'Class (From);
begin
Params.Filter := L.Filter;
Params.Join := L.Join;
end;
end if;
end Set_Parameters;
-- --------------------
-- Expand the parameters into the query and return the expanded SQL query.
-- --------------------
function Expand (Source : in Query) return String is
begin
return ADO.Parameters.Abstract_List (Source).Expand (To_String (Source.SQL.Buf));
end Expand;
procedure Add_Field (Update : in out Update_Query'Class;
Name : in String) is
begin
Update.Pos := Update.Pos + 1;
if Update.Pos > 1 then
Append (Target => Update.Set_Fields, SQL => ",");
Append (Target => Update.Fields, SQL => ",");
end if;
Append_Name (Target => Update.Set_Fields, Name => Name);
if Update.Is_Update_Stmt then
Append (Target => Update.Set_Fields, SQL => " = ?");
end if;
Append (Target => Update.Fields, SQL => "?");
end Add_Field;
-- ------------------------------
-- Set the SQL dialect description object.
-- ------------------------------
procedure Set_Dialect (Target : in out Update_Query;
D : in ADO.Drivers.Dialects.Dialect_Access) is
begin
Target.Set_Fields.Set_Dialect (D);
Target.Fields.Set_Dialect (D);
Query (Target).Set_Dialect (D);
end Set_Dialect;
-- ------------------------------
-- Prepare the update/insert query to save the table field
-- identified by <b>Name</b> and set it to the <b>Value</b>.
-- ------------------------------
procedure Save_Field (Update : in out Update_Query;
Name : in String;
Value : in Boolean) is
begin
Update.Add_Field (Name => Name);
Update_Query'Class (Update).Bind_Param (Position => Update.Pos, Value => Value);
end Save_Field;
-- --------------------
-- Prepare the update/insert query to save the table field
-- identified by <b>Name</b> and set it to the <b>Value</b>.
-- --------------------
procedure Save_Field (Update : in out Update_Query;
Name : in String;
Value : in Integer) is
begin
Update.Add_Field (Name => Name);
Update_Query'Class (Update).Bind_Param (Position => Update.Pos, Value => Value);
end Save_Field;
-- --------------------
-- Prepare the update/insert query to save the table field
-- identified by <b>Name</b> and set it to the <b>Value</b>.
-- --------------------
procedure Save_Field (Update : in out Update_Query;
Name : in String;
Value : in Long_Long_Integer) is
begin
Update.Add_Field (Name => Name);
Update_Query'Class (Update).Bind_Param (Position => Update.Pos, Value => Value);
end Save_Field;
-- --------------------
-- Prepare the update/insert query to save the table field
-- identified by <b>Name</b> and set it to the <b>Value</b>.
-- --------------------
procedure Save_Field (Update : in out Update_Query;
Name : in String;
Value : in Identifier) is
begin
Update.Add_Field (Name => Name);
Update_Query'Class (Update).Add_Param (Value => Value);
end Save_Field;
-- --------------------
-- Prepare the update/insert query to save the table field
-- identified by <b>Name</b> and set it to the <b>Value</b>.
-- --------------------
procedure Save_Field (Update : in out Update_Query;
Name : in String;
Value : in Entity_Type) is
begin
Update.Add_Field (Name => Name);
Update_Query'Class (Update).Add_Param (Value => Integer (Value));
end Save_Field;
-- --------------------
-- Prepare the update/insert query to save the table field
-- identified by <b>Name</b> and set it to the <b>Value</b>.
-- --------------------
procedure Save_Field (Update : in out Update_Query;
Name : in String;
Value : in Ada.Calendar.Time) is
begin
Update.Add_Field (Name => Name);
Update_Query'Class (Update).Add_Param (Value => Value);
end Save_Field;
-- --------------------
-- Prepare the update/insert query to save the table field
-- identified by <b>Name</b> and set it to the <b>Value</b>.
-- --------------------
procedure Save_Field (Update : in out Update_Query;
Name : in String;
Value : in String) is
begin
Update.Add_Field (Name => Name);
Update_Query'Class (Update).Bind_Param (Position => Update.Pos, Value => Value);
end Save_Field;
-- --------------------
-- Prepare the update/insert query to save the table field
-- identified by <b>Name</b> and set it to the <b>Value</b>.
-- --------------------
procedure Save_Field (Update : in out Update_Query;
Name : in String;
Value : in Unbounded_String) is
begin
Update.Add_Field (Name => Name);
Update_Query'Class (Update).Bind_Param (Position => Update.Pos, Value => Value);
end Save_Field;
-- ------------------------------
-- Prepare the update/insert query to save the table field
-- identified by <b>Name</b> and set it to the <b>Value</b>.
-- ------------------------------
procedure Save_Field (Update : in out Update_Query;
Name : in String;
Value : in ADO.Blob_Ref) is
begin
Update.Add_Field (Name => Name);
Update_Query'Class (Update).Bind_Param (Position => Update.Pos, Value => Value);
end Save_Field;
-- ------------------------------
-- Prepare the update/insert query to save the table field
-- identified by <b>Name</b> and set it to NULL.
-- ------------------------------
procedure Save_Null_Field (Update : in out Update_Query;
Name : in String) is
begin
Update.Add_Field (Name => Name);
Update_Query'Class (Update).Bind_Null_Param (Position => Update.Pos);
end Save_Null_Field;
-- --------------------
-- Check if the update/insert query has some fields to update.
-- --------------------
function Has_Save_Fields (Update : in Update_Query) return Boolean is
begin
return Update.Pos > 0;
end Has_Save_Fields;
procedure Set_Insert_Mode (Update : in out Update_Query) is
begin
Update.Is_Update_Stmt := False;
end Set_Insert_Mode;
procedure Append_Fields (Update : in out Update_Query;
Mode : in Boolean := False) is
begin
if Mode then
Append (Target => Update.SQL, SQL => To_String (Update.Fields.Buf));
else
Append (Target => Update.SQL, SQL => To_String (Update.Set_Fields.Buf));
end if;
end Append_Fields;
end ADO.SQL;
|
Remove the Escape functions
|
Remove the Escape functions
|
Ada
|
apache-2.0
|
stcarrez/ada-ado
|
e68d660792014b5845eb3d7a2e1c6542ffdf1900
|
src/orka/interface/orka-scenes-generic_scene_trees.ads
|
src/orka/interface/orka-scenes-generic_scene_trees.ads
|
-- Copyright (c) 2016 onox <[email protected]>
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
private with Ada.Containers.Vectors;
private with Ada.Strings.Unbounded;
with Orka.Transforms.SIMD_Matrices;
generic
with package Transforms is new Orka.Transforms.SIMD_Matrices (<>);
package Orka.Scenes.Generic_Scene_Trees is
pragma Preelaborate;
subtype Matrix4 is Transforms.Matrix4;
type Tree is tagged private;
type Cursor is private;
function To_Cursor (Object : Tree; Name : String) return Cursor;
function Depth (Object : Tree) return Positive;
function Width (Object : Tree; Level : Positive) return Natural
with Pre => Level <= Object.Depth;
procedure Update_Tree (Object : in out Tree);
procedure Update_Tree (Object : in out Tree; Root_Transform : Transforms.Matrix4);
procedure Set_Visibility (Object : in out Tree; Node : Cursor; Visible : Boolean);
function Visibility (Object : Tree; Node : Cursor) return Boolean;
procedure Set_Local_Transform (Object : in out Tree; Node : Cursor; Transform : Transforms.Matrix4);
function World_Transform (Object : Tree; Node : Cursor) return Transforms.Matrix4;
function Root_Name (Object : Tree) return String;
function Create_Tree (Name : String) return Tree;
procedure Add_Node (Object : in out Tree; Name, Parent : String);
procedure Remove_Node (Object : in out Tree; Name : String);
Unknown_Node_Error : exception;
-- Exception raised if a given node does not exist
Root_Removal_Error : exception;
-- Exception raised if user tries to remove the root node
private
package SU renames Ada.Strings.Unbounded;
type Node is record
Offset : Positive;
Count : Natural;
Name : SU.Unbounded_String;
end record;
package Node_Vectors is new Ada.Containers.Vectors (Positive, Node);
package Boolean_Vectors is new Ada.Containers.Vectors (Positive, Boolean);
use type Transforms.Matrix4;
package Matrix_Vectors is new Ada.Containers.Vectors (Positive, Transforms.Matrix4);
type Level is record
Nodes : Node_Vectors.Vector;
Local_Transforms : Matrix_Vectors.Vector;
World_Transforms : Matrix_Vectors.Vector;
Local_Visibilities : Boolean_Vectors.Vector;
World_Visibilities : Boolean_Vectors.Vector;
end record;
package Level_Vectors is new Ada.Containers.Vectors (Positive, Level);
type Tree is tagged record
Levels : Level_Vectors.Vector;
end record;
type Cursor is record
Level, Offset : Positive;
end record;
function Depth (Object : Tree) return Positive is
(Positive (Object.Levels.Length));
function Width (Object : Tree; Level : Positive) return Natural is
(Natural (Object.Levels (Level).Nodes.Length));
end Orka.Scenes.Generic_Scene_Trees;
|
-- Copyright (c) 2016 onox <[email protected]>
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
private with Ada.Containers.Vectors;
private with Ada.Strings.Unbounded;
with Orka.Transforms.SIMD_Matrices;
generic
with package Transforms is new Orka.Transforms.SIMD_Matrices (<>);
package Orka.Scenes.Generic_Scene_Trees is
pragma Preelaborate;
subtype Matrix4 is Transforms.Matrix4;
type Tree is tagged private;
type Cursor is private;
function To_Cursor (Object : Tree; Name : String) return Cursor;
function Depth (Object : Tree) return Positive;
function Width (Object : Tree; Level : Positive) return Natural
with Pre => Level <= Object.Depth;
procedure Update_Tree (Object : in out Tree);
procedure Update_Tree (Object : in out Tree; Root_Transform : Transforms.Matrix4);
procedure Set_Visibility (Object : in out Tree; Node : Cursor; Visible : Boolean);
function Visibility (Object : Tree; Node : Cursor) return Boolean;
procedure Set_Local_Transform (Object : in out Tree; Node : Cursor; Transform : Transforms.Matrix4);
function World_Transform (Object : Tree; Node : Cursor) return Transforms.Matrix4;
function Root_Name (Object : Tree) return String;
function Create_Tree (Name : String) return Tree;
procedure Add_Node (Object : in out Tree; Name, Parent : String);
procedure Remove_Node (Object : in out Tree; Name : String);
Unknown_Node_Error : exception;
-- Exception raised if a given node does not exist
Root_Removal_Error : exception;
-- Exception raised if user tries to remove the root node
private
package SU renames Ada.Strings.Unbounded;
type Node is record
Offset : Positive;
Count : Natural;
Name : SU.Unbounded_String;
end record;
pragma Suppress (Tampering_Check);
-- Disabling the tampering check speeds up execution of Add_Node,
-- reducing the time to create a full scene tree to around 20 %.
package Node_Vectors is new Ada.Containers.Vectors (Positive, Node);
package Boolean_Vectors is new Ada.Containers.Vectors (Positive, Boolean);
use type Transforms.Matrix4;
package Matrix_Vectors is new Ada.Containers.Vectors (Positive, Transforms.Matrix4);
type Level is record
Nodes : Node_Vectors.Vector;
Local_Transforms : Matrix_Vectors.Vector;
World_Transforms : Matrix_Vectors.Vector;
Local_Visibilities : Boolean_Vectors.Vector;
World_Visibilities : Boolean_Vectors.Vector;
end record;
package Level_Vectors is new Ada.Containers.Vectors (Positive, Level);
type Tree is tagged record
Levels : Level_Vectors.Vector;
end record;
type Cursor is record
Level, Offset : Positive;
end record;
function Depth (Object : Tree) return Positive is
(Positive (Object.Levels.Length));
function Width (Object : Tree; Level : Positive) return Natural is
(Natural (Object.Levels (Level).Nodes.Length));
end Orka.Scenes.Generic_Scene_Trees;
|
Disable Tampering_Check to speed up adding nodes to a scene tree
|
orka: Disable Tampering_Check to speed up adding nodes to a scene tree
Signed-off-by: onox <[email protected]>
|
Ada
|
apache-2.0
|
onox/orka
|
f6dd8bcf56b3622a0f9dfe9a029337828ebe73dd
|
src/wiki-render.ads
|
src/wiki-render.ads
|
-----------------------------------------------------------------------
-- wiki-render -- Wiki renderer
-- Copyright (C) 2015, 2016 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Wiki.Nodes;
with Wiki.Strings;
with Wiki.Documents;
-- == Wiki Renderer ==
-- The <tt>Wiki.Render</tt> package represents the renderer that takes a wiki document
-- and render the result either in text, HTML or another format.
--
-- @include wiki-render-html.ads
-- @include wiki-render-text.ads
-- @include wiki-render-wiki.ads
package Wiki.Render is
pragma Preelaborate;
type Link_Renderer is limited interface;
type Link_Renderer_Access is access all Link_Renderer'Class;
-- Get the image link that must be rendered from the wiki image link.
procedure Make_Image_Link (Renderer : in Link_Renderer;
Link : in Wiki.Strings.WString;
URI : out Wiki.Strings.UString;
Width : out Natural;
Height : out Natural) is abstract;
-- Get the page link that must be rendered from the wiki page link.
procedure Make_Page_Link (Renderer : in Link_Renderer;
Link : in Wiki.Strings.WString;
URI : out Wiki.Strings.UString;
Exists : out Boolean) is abstract;
type Default_Link_Renderer is new Link_Renderer with null record;
-- 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);
-- 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);
-- ------------------------------
-- Document renderer
-- ------------------------------
type Renderer is limited interface;
type Renderer_Access is access all Renderer'Class;
-- Render the node instance from the document.
procedure Render (Engine : in out Renderer;
Doc : in Wiki.Documents.Document;
Node : in Wiki.Nodes.Node_Type) is abstract;
-- Finish the rendering pass after all the wiki document nodes are rendered.
procedure Finish (Engine : in out Renderer;
Doc : in Wiki.Documents.Document) is null;
-- Render the list of nodes from the document.
procedure Render (Engine : in out Renderer'Class;
Doc : in Wiki.Documents.Document;
List : in Wiki.Nodes.Node_List_Access);
-- Render the document.
procedure Render (Engine : in out Renderer'Class;
Doc : in Wiki.Documents.Document);
end Wiki.Render;
|
-----------------------------------------------------------------------
-- wiki-render -- Wiki renderer
-- Copyright (C) 2015, 2016 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Wiki.Nodes;
with Wiki.Strings;
with Wiki.Documents;
-- == Wiki Renderer ==
-- The <tt>Wiki.Render</tt> package represents the renderer that takes a wiki document
-- and render the result either in text, HTML or another format.
--
-- @include wiki-render-html.ads
-- @include wiki-render-links.ads
-- @include wiki-render-text.ads
-- @include wiki-render-wiki.ads
package Wiki.Render is
pragma Preelaborate;
-- ------------------------------
-- Document renderer
-- ------------------------------
type Renderer is limited interface;
type Renderer_Access is access all Renderer'Class;
-- Render the node instance from the document.
procedure Render (Engine : in out Renderer;
Doc : in Wiki.Documents.Document;
Node : in Wiki.Nodes.Node_Type) is abstract;
-- Finish the rendering pass after all the wiki document nodes are rendered.
procedure Finish (Engine : in out Renderer;
Doc : in Wiki.Documents.Document) is null;
-- Render the list of nodes from the document.
procedure Render (Engine : in out Renderer'Class;
Doc : in Wiki.Documents.Document;
List : in Wiki.Nodes.Node_List_Access);
-- Render the document.
procedure Render (Engine : in out Renderer'Class;
Doc : in Wiki.Documents.Document);
end Wiki.Render;
|
Move the Link_Renderer and Default_Link_Renderer in the Wiki.Render.Links pacakge
|
Move the Link_Renderer and Default_Link_Renderer in the Wiki.Render.Links pacakge
|
Ada
|
apache-2.0
|
stcarrez/ada-wiki,stcarrez/ada-wiki
|
f8510ae1e814a118f00026cccbd6b070bb23e7d6
|
awa/plugins/awa-workspaces/src/awa-workspaces-beans.adb
|
awa/plugins/awa-workspaces/src/awa-workspaces-beans.adb
|
-----------------------------------------------------------------------
-- awa-workspaces-beans -- Beans for module workspaces
-- Copyright (C) 2011, 2012, 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with ASF.Events.Faces.Actions;
with ASF.Contexts.Flash;
with ASF.Contexts.Faces;
with ASF.Applications.Messages.Factory;
with ADO.Utils;
with ADO.Sessions;
with ADO.Queries;
with ADO.Datasets;
with AWA.Services.Contexts;
with AWA.Workspaces.Models;
with AWA.Events.Action_Method;
with AWA.Services.Contexts;
package body AWA.Workspaces.Beans is
use ASF.Applications;
package ASC renames AWA.Services.Contexts;
-- ------------------------------
-- Get the value identified by the name.
-- ------------------------------
overriding
function Get_Value (From : in Member_Bean;
Name : in String) return Util.Beans.Objects.Object is
begin
return AWA.Workspaces.Models.Member_Bean (From).Get_Value (Name);
end Get_Value;
-- ------------------------------
-- Set the value identified by the name
-- ------------------------------
overriding
procedure Set_Value (Item : in out Member_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object) is
begin
if Name = "id" and not Util.Beans.Objects.Is_Empty (Value) then
Item.Set_Id (ADO.Utils.To_Identifier (Value));
else
AWA.Workspaces.Models.Member_Bean (Item).Set_Value (Name, Value);
end if;
end Set_Value;
overriding
procedure Load (Bean : in out Member_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
begin
null;
end Load;
overriding
procedure Delete (Bean : in out Member_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
begin
Bean.Module.Delete_Member (Bean.Get_Id);
end Delete;
-- ------------------------------
-- Create the Member_Bean bean instance.
-- ------------------------------
function Create_Member_Bean (Module : in AWA.Workspaces.Modules.Workspace_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access is
Object : constant Member_Bean_Access := new Member_Bean;
begin
Object.Module := Module;
return Object.all'Access;
end Create_Member_Bean;
-- ------------------------------
-- Get the value identified by the name.
-- ------------------------------
overriding
function Get_Value (From : in Invitation_Bean;
Name : in String) return Util.Beans.Objects.Object is
begin
if Name = "inviter" then
return From.Inviter.Get_Value ("name");
else
return AWA.Workspaces.Models.Invitation_Bean (From).Get_Value (Name);
end if;
end Get_Value;
overriding
procedure Load (Bean : in out Invitation_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
begin
Bean.Module.Load_Invitation (Key => Ada.Strings.Unbounded.To_String (Bean.Key),
Invitation => Bean,
Inviter => Bean.Inviter);
exception
when others =>
Outcome := Ada.Strings.Unbounded.To_Unbounded_String ("not-found");
end Load;
overriding
procedure Accept_Invitation (Bean : in out Invitation_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
Ctx : constant ASF.Contexts.Faces.Faces_Context_Access := ASF.Contexts.Faces.Current;
Flash : constant ASF.Contexts.Faces.Flash_Context_Access := Ctx.Get_Flash;
begin
Bean.Module.Accept_Invitation (Key => Ada.Strings.Unbounded.To_String (Bean.Key));
Flash.Set_Keep_Messages (True);
Messages.Factory.Add_Message (Ctx.all, "workspaces.workspace_welcome_message",
Messages.INFO);
end Accept_Invitation;
overriding
procedure Send (Bean : in out Invitation_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
Ctx : constant ASF.Contexts.Faces.Faces_Context_Access := ASF.Contexts.Faces.Current;
Flash : constant ASF.Contexts.Faces.Flash_Context_Access := Ctx.Get_Flash;
begin
Bean.Module.Send_Invitation (Bean);
Flash.Set_Keep_Messages (True);
Messages.Factory.Add_Message (Ctx.all, "workspaces.workspace_invitation_sent",
Messages.INFO);
end Send;
-- ------------------------------
-- Create the Invitation_Bean bean instance.
-- ------------------------------
function Create_Invitation_Bean (Module : in AWA.Workspaces.Modules.Workspace_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access is
Object : constant Invitation_Bean_Access := new Invitation_Bean;
begin
Object.Module := Module;
return Object.all'Access;
end Create_Invitation_Bean;
-- ------------------------------
-- Example of action method.
-- ------------------------------
procedure Action (Bean : in out Workspaces_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
begin
null;
end Action;
-- ------------------------------
-- Event action called to create the workspace when the given event is posted.
-- ------------------------------
procedure Create (Bean : in out Workspaces_Bean;
Event : in AWA.Events.Module_Event'Class) is
pragma Unreferenced (Bean, Event);
WS : AWA.Workspaces.Models.Workspace_Ref;
Ctx : constant AWA.Services.Contexts.Service_Context_Access := AWA.Services.Contexts.Current;
DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx);
begin
Ctx.Start;
AWA.Workspaces.Modules.Get_Workspace (Session => DB,
Context => Ctx,
Workspace => WS);
Ctx.Commit;
end Create;
package Action_Binding is
new ASF.Events.Faces.Actions.Action_Method.Bind (Bean => Workspaces_Bean,
Method => Action,
Name => "action");
package Create_Binding is
new AWA.Events.Action_Method.Bind (Name => "create",
Bean => Workspaces_Bean,
Method => Create);
Workspaces_Bean_Binding : aliased constant Util.Beans.Methods.Method_Binding_Array
:= (Action_Binding.Proxy'Access, Create_Binding.Proxy'Access);
-- ------------------------------
-- Get the value identified by the name.
-- ------------------------------
overriding
function Get_Value (From : in Workspaces_Bean;
Name : in String) return Util.Beans.Objects.Object is
begin
if Name = "count" then
return Util.Beans.Objects.To_Object (From.Count);
else
return Util.Beans.Objects.Null_Object;
end if;
end Get_Value;
-- ------------------------------
-- Set the value identified by the name.
-- ------------------------------
overriding
procedure Set_Value (From : in out Workspaces_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object) is
begin
if Name = "count" then
From.Count := Util.Beans.Objects.To_Integer (Value);
end if;
end Set_Value;
-- ------------------------------
-- This bean provides some methods that can be used in a Method_Expression
-- ------------------------------
overriding
function Get_Method_Bindings (From : in Workspaces_Bean)
return Util.Beans.Methods.Method_Binding_Array_Access is
pragma Unreferenced (From);
begin
return Workspaces_Bean_Binding'Access;
end Get_Method_Bindings;
-- ------------------------------
-- Create the Workspaces_Bean bean instance.
-- ------------------------------
function Create_Workspaces_Bean (Module : in AWA.Workspaces.Modules.Workspace_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access is
Object : constant Workspaces_Bean_Access := new Workspaces_Bean;
begin
Object.Module := Module;
return Object.all'Access;
end Create_Workspaces_Bean;
-- ------------------------------
-- Get the value identified by the name.
-- ------------------------------
overriding
function Get_Value (From : in Member_List_Bean;
Name : in String) return Util.Beans.Objects.Object is
begin
if Name = "members" then
return Util.Beans.Objects.To_Object (Value => From.Members_Bean,
Storage => Util.Beans.Objects.STATIC);
else
return AWA.Workspaces.Models.Member_List_Bean (From).Get_Value (Name);
end if;
end Get_Value;
-- ------------------------------
-- Load the list of members.
-- ------------------------------
overriding
procedure Load (Into : in out Member_List_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
Ctx : constant ASC.Service_Context_Access := ASC.Current;
User : constant ADO.Identifier := Ctx.Get_User_Identifier;
Session : ADO.Sessions.Session := Into.Module.Get_Session;
Query : ADO.Queries.Context;
Count_Query : ADO.Queries.Context;
First : constant Natural := (Into.Page - 1) * Into.Page_Size;
begin
Query.Set_Query (AWA.Workspaces.Models.Query_Workspace_Member_List);
Count_Query.Set_Count_Query (AWA.Workspaces.Models.Query_Workspace_Member_List);
Query.Bind_Param (Name => "user_id", Value => User);
Count_Query.Bind_Param (Name => "user_id", Value => User);
AWA.Workspaces.Models.List (Into.Members, Session, Query);
Into.Count := ADO.Datasets.Get_Count (Session, Count_Query);
end Load;
-- ------------------------------
-- Create the Member_List_Bean bean instance.
-- ------------------------------
function Create_Member_List_Bean (Module : in AWA.Workspaces.Modules.Workspace_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access is
Object : constant Member_List_Bean_Access := new Member_List_Bean;
begin
Object.Module := Module;
Object.Members_Bean := Object.Members'Access;
Object.Page_Size := 20;
Object.Page := 1;
Object.Count := 0;
return Object.all'Access;
end Create_Member_List_Bean;
end AWA.Workspaces.Beans;
|
-----------------------------------------------------------------------
-- awa-workspaces-beans -- Beans for module workspaces
-- Copyright (C) 2011, 2012, 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with ASF.Contexts.Flash;
with ASF.Contexts.Faces;
with ASF.Applications.Messages.Factory;
with ADO.Utils;
with ADO.Sessions;
with ADO.Queries;
with ADO.Datasets;
with AWA.Services.Contexts;
with AWA.Workspaces.Models;
with AWA.Events.Action_Method;
with AWA.Services.Contexts;
package body AWA.Workspaces.Beans is
use ASF.Applications;
package ASC renames AWA.Services.Contexts;
-- ------------------------------
-- Get the value identified by the name.
-- ------------------------------
overriding
function Get_Value (From : in Member_Bean;
Name : in String) return Util.Beans.Objects.Object is
begin
return AWA.Workspaces.Models.Member_Bean (From).Get_Value (Name);
end Get_Value;
-- ------------------------------
-- Set the value identified by the name
-- ------------------------------
overriding
procedure Set_Value (Item : in out Member_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object) is
begin
if Name = "id" and not Util.Beans.Objects.Is_Empty (Value) then
Item.Set_Id (ADO.Utils.To_Identifier (Value));
else
AWA.Workspaces.Models.Member_Bean (Item).Set_Value (Name, Value);
end if;
end Set_Value;
overriding
procedure Load (Bean : in out Member_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
begin
null;
end Load;
overriding
procedure Delete (Bean : in out Member_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
begin
Bean.Module.Delete_Member (Bean.Get_Id);
end Delete;
-- ------------------------------
-- Create the Member_Bean bean instance.
-- ------------------------------
function Create_Member_Bean (Module : in AWA.Workspaces.Modules.Workspace_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access is
Object : constant Member_Bean_Access := new Member_Bean;
begin
Object.Module := Module;
return Object.all'Access;
end Create_Member_Bean;
-- ------------------------------
-- Get the value identified by the name.
-- ------------------------------
overriding
function Get_Value (From : in Invitation_Bean;
Name : in String) return Util.Beans.Objects.Object is
begin
if Name = "inviter" then
return From.Inviter.Get_Value ("name");
else
return AWA.Workspaces.Models.Invitation_Bean (From).Get_Value (Name);
end if;
end Get_Value;
overriding
procedure Load (Bean : in out Invitation_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
begin
Bean.Module.Load_Invitation (Key => Ada.Strings.Unbounded.To_String (Bean.Key),
Invitation => Bean,
Inviter => Bean.Inviter);
exception
when others =>
Outcome := Ada.Strings.Unbounded.To_Unbounded_String ("not-found");
end Load;
overriding
procedure Accept_Invitation (Bean : in out Invitation_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
Ctx : constant ASF.Contexts.Faces.Faces_Context_Access := ASF.Contexts.Faces.Current;
Flash : constant ASF.Contexts.Faces.Flash_Context_Access := Ctx.Get_Flash;
begin
Bean.Module.Accept_Invitation (Key => Ada.Strings.Unbounded.To_String (Bean.Key));
Flash.Set_Keep_Messages (True);
Messages.Factory.Add_Message (Ctx.all, "workspaces.workspace_welcome_message",
Messages.INFO);
end Accept_Invitation;
overriding
procedure Send (Bean : in out Invitation_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
Ctx : constant ASF.Contexts.Faces.Faces_Context_Access := ASF.Contexts.Faces.Current;
Flash : constant ASF.Contexts.Faces.Flash_Context_Access := Ctx.Get_Flash;
begin
Bean.Module.Send_Invitation (Bean);
Flash.Set_Keep_Messages (True);
Messages.Factory.Add_Message (Ctx.all, "workspaces.workspace_invitation_sent",
Messages.INFO);
end Send;
-- ------------------------------
-- Create the Invitation_Bean bean instance.
-- ------------------------------
function Create_Invitation_Bean (Module : in AWA.Workspaces.Modules.Workspace_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access is
Object : constant Invitation_Bean_Access := new Invitation_Bean;
begin
Object.Module := Module;
return Object.all'Access;
end Create_Invitation_Bean;
-- ------------------------------
-- Event action called to create the workspace when the given event is posted.
-- ------------------------------
procedure Create (Bean : in out Workspaces_Bean;
Event : in AWA.Events.Module_Event'Class) is
pragma Unreferenced (Bean, Event);
WS : AWA.Workspaces.Models.Workspace_Ref;
Ctx : constant AWA.Services.Contexts.Service_Context_Access := AWA.Services.Contexts.Current;
DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx);
begin
Ctx.Start;
AWA.Workspaces.Modules.Get_Workspace (Session => DB,
Context => Ctx,
Workspace => WS);
Ctx.Commit;
end Create;
package Create_Binding is
new AWA.Events.Action_Method.Bind (Name => "create",
Bean => Workspaces_Bean,
Method => Create);
Workspaces_Bean_Binding : aliased constant Util.Beans.Methods.Method_Binding_Array
:= (1 => Create_Binding.Proxy'Access);
-- ------------------------------
-- Get the value identified by the name.
-- ------------------------------
overriding
function Get_Value (From : in Workspaces_Bean;
Name : in String) return Util.Beans.Objects.Object is
begin
if Name = "count" then
return Util.Beans.Objects.To_Object (From.Count);
else
return Util.Beans.Objects.Null_Object;
end if;
end Get_Value;
-- ------------------------------
-- Set the value identified by the name.
-- ------------------------------
overriding
procedure Set_Value (From : in out Workspaces_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object) is
begin
if Name = "count" then
From.Count := Util.Beans.Objects.To_Integer (Value);
end if;
end Set_Value;
-- ------------------------------
-- This bean provides some methods that can be used in a Method_Expression
-- ------------------------------
overriding
function Get_Method_Bindings (From : in Workspaces_Bean)
return Util.Beans.Methods.Method_Binding_Array_Access is
pragma Unreferenced (From);
begin
return Workspaces_Bean_Binding'Access;
end Get_Method_Bindings;
-- ------------------------------
-- Create the Workspaces_Bean bean instance.
-- ------------------------------
function Create_Workspaces_Bean (Module : in AWA.Workspaces.Modules.Workspace_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access is
Object : constant Workspaces_Bean_Access := new Workspaces_Bean;
begin
Object.Module := Module;
return Object.all'Access;
end Create_Workspaces_Bean;
-- ------------------------------
-- Get the value identified by the name.
-- ------------------------------
overriding
function Get_Value (From : in Member_List_Bean;
Name : in String) return Util.Beans.Objects.Object is
begin
if Name = "members" then
return Util.Beans.Objects.To_Object (Value => From.Members_Bean,
Storage => Util.Beans.Objects.STATIC);
else
return AWA.Workspaces.Models.Member_List_Bean (From).Get_Value (Name);
end if;
end Get_Value;
-- ------------------------------
-- Load the list of members.
-- ------------------------------
overriding
procedure Load (Into : in out Member_List_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
Ctx : constant ASC.Service_Context_Access := ASC.Current;
User : constant ADO.Identifier := Ctx.Get_User_Identifier;
Session : ADO.Sessions.Session := Into.Module.Get_Session;
Query : ADO.Queries.Context;
Count_Query : ADO.Queries.Context;
First : constant Natural := (Into.Page - 1) * Into.Page_Size;
begin
Query.Set_Query (AWA.Workspaces.Models.Query_Workspace_Member_List);
Count_Query.Set_Count_Query (AWA.Workspaces.Models.Query_Workspace_Member_List);
Query.Bind_Param (Name => "user_id", Value => User);
Count_Query.Bind_Param (Name => "user_id", Value => User);
AWA.Workspaces.Models.List (Into.Members, Session, Query);
Into.Count := ADO.Datasets.Get_Count (Session, Count_Query);
end Load;
-- ------------------------------
-- Create the Member_List_Bean bean instance.
-- ------------------------------
function Create_Member_List_Bean (Module : in AWA.Workspaces.Modules.Workspace_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access is
Object : constant Member_List_Bean_Access := new Member_List_Bean;
begin
Object.Module := Module;
Object.Members_Bean := Object.Members'Access;
Object.Page_Size := 20;
Object.Page := 1;
Object.Count := 0;
return Object.all'Access;
end Create_Member_List_Bean;
end AWA.Workspaces.Beans;
|
Remove the Action procedure that is not used and update the Workspace_Bean action bindings
|
Remove the Action procedure that is not used and update the Workspace_Bean action bindings
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
436d30f640462c0997269c9a176adf02b5f7d6b6
|
src/file_operations.adb
|
src/file_operations.adb
|
-- This file is covered by the Internet Software Consortium (ISC) License
-- Reference: ../License.txt
with Ada.Directories;
with Ada.Direct_IO;
with Ada.Text_IO;
with HelperText;
package body File_Operations is
package DIR renames Ada.Directories;
package TIO renames Ada.Text_IO;
package HT renames HelperText;
--------------------------------------------------------------------------------------------
-- get_file_contents
--------------------------------------------------------------------------------------------
function get_file_contents (dossier : String) return String
is
File_Size : constant Natural := Natural (DIR.Size (dossier));
begin
if File_Size = 0 then
return "";
end if;
declare
subtype File_String is String (1 .. File_Size);
package File_String_IO is new Ada.Direct_IO (File_String);
file_handle : File_String_IO.File_Type;
contents : File_String;
attempts : Natural := 0;
begin
-- The introduction of variants causes a buildsheet to be scanned once per variant.
-- It's possible (even common) for simultaneous requests to scan the same buildsheet to
-- occur. Thus, if the file is already open, wait and try again (up to 5 times)
loop
begin
File_String_IO.Open (File => file_handle,
Mode => File_String_IO.In_File,
Name => dossier);
exit;
exception
when File_String_IO.Status_Error | File_String_IO.Use_Error =>
if attempts = 5 then
raise file_handling with "get_file_contents: failed open: " & dossier;
end if;
attempts := attempts + 1;
delay 0.1;
end;
end loop;
File_String_IO.Read (File => file_handle, Item => contents);
File_String_IO.Close (file_handle);
return contents;
exception
when others =>
if File_String_IO.Is_Open (file_handle) then
File_String_IO.Close (file_handle);
end if;
raise file_handling with "get_file_contents(" & dossier & ") failed";
end;
exception
when Storage_Error =>
raise file_handling with "get_file_contents(" & dossier & ") failed to allocate memory";
end get_file_contents;
--------------------------------------------------------------------------------------------
-- dump_contents_to_file
--------------------------------------------------------------------------------------------
procedure dump_contents_to_file
(contents : String;
dossier : String)
is
File_Size : Natural := contents'Length;
subtype File_String is String (1 .. File_Size);
package File_String_IO is new Ada.Direct_IO (File_String);
file_handle : File_String_IO.File_Type;
begin
mkdirp_from_filename (dossier);
File_String_IO.Create (File => file_handle,
Mode => File_String_IO.Out_File,
Name => dossier);
File_String_IO.Write (File => file_handle,
Item => contents);
File_String_IO.Close (file_handle);
exception
when Storage_Error =>
if File_String_IO.Is_Open (file_handle) then
File_String_IO.Close (file_handle);
end if;
raise file_handling
with "dump_contents_to_file(" & dossier & ") failed to allocate memory";
when others =>
if File_String_IO.Is_Open (file_handle) then
File_String_IO.Close (file_handle);
end if;
raise file_handling
with "dump_contents_to_file(" & dossier & ") error";
end dump_contents_to_file;
--------------------------------------------------------------------------------------------
-- create_subdirectory
--------------------------------------------------------------------------------------------
procedure create_subdirectory
(extraction_directory : String;
subdirectory : String)
is
abspath : String := extraction_directory & "/" & subdirectory;
begin
if subdirectory = "" then
return;
end if;
if not DIR.Exists (abspath) then
DIR.Create_Directory (abspath);
end if;
end create_subdirectory;
--------------------------------------------------------------------------------------------
-- head_n1
--------------------------------------------------------------------------------------------
function head_n1 (filename : String) return String
is
handle : TIO.File_Type;
begin
TIO.Open (File => handle, Mode => TIO.In_File, Name => filename);
if TIO.End_Of_File (handle) then
TIO.Close (handle);
return "";
end if;
declare
line : constant String := TIO.Get_Line (handle);
begin
TIO.Close (handle);
return line;
end;
end head_n1;
--------------------------------------------------------------------------------------------
-- create_pidfile
--------------------------------------------------------------------------------------------
procedure create_pidfile (pidfile : String)
is
pidtext : constant String := HT.int2str (Get_PID);
handle : TIO.File_Type;
begin
TIO.Create (File => handle, Mode => TIO.Out_File, Name => pidfile);
TIO.Put_Line (handle, pidtext);
TIO.Close (handle);
end create_pidfile;
--------------------------------------------------------------------------------------------
-- destroy_pidfile
--------------------------------------------------------------------------------------------
procedure destroy_pidfile (pidfile : String) is
begin
if DIR.Exists (pidfile) then
DIR.Delete_File (pidfile);
end if;
exception
when others => null;
end destroy_pidfile;
--------------------------------------------------------------------------------------------
-- mkdirp_from_filename
--------------------------------------------------------------------------------------------
procedure mkdirp_from_filename (filename : String)
is
condir : String := DIR.Containing_Directory (Name => filename);
begin
DIR.Create_Path (New_Directory => condir);
end mkdirp_from_filename;
--------------------------------------------------------------------------------------------
-- concatenate_file
--------------------------------------------------------------------------------------------
procedure concatenate_file (basefile : String; another_file : String)
is
handle : TIO.File_Type;
begin
if not DIR.Exists (another_file) then
raise file_handling with "concatenate_file: new_file does not exist => " & another_file;
end if;
if DIR.Exists (basefile) then
TIO.Open (File => handle,
Mode => TIO.Append_File,
Name => basefile);
declare
contents : constant String := get_file_contents (another_file);
begin
TIO.Put (handle, contents);
end;
TIO.Close (handle);
else
DIR.Copy_File (Source_Name => another_file,
Target_Name => basefile);
end if;
exception
when others =>
if TIO.Is_Open (handle) then
TIO.Close (handle);
end if;
raise file_handling;
end concatenate_file;
--------------------------------------------------------------------------------------------
-- create_cookie
--------------------------------------------------------------------------------------------
procedure create_cookie (fullpath : String)
is
subtype File_String is String (1 .. 1);
package File_String_IO is new Ada.Direct_IO (File_String);
file_handle : File_String_IO.File_Type;
begin
mkdirp_from_filename (fullpath);
File_String_IO.Create (File => file_handle,
Mode => File_String_IO.Out_File,
Name => fullpath);
File_String_IO.Close (file_handle);
exception
when others =>
raise file_handling;
end create_cookie;
--------------------------------------------------------------------------------------------
-- replace_directory_contents
--------------------------------------------------------------------------------------------
procedure replace_directory_contents
(source_directory : String;
target_directory : String;
pattern : String)
is
search : DIR.Search_Type;
dirent : DIR.Directory_Entry_Type;
filter : constant DIR.Filter_Type := (DIR.Ordinary_File => True, others => False);
begin
if not DIR.Exists (target_directory) then
return;
end if;
DIR.Start_Search (Search => search,
Directory => target_directory,
Pattern => pattern,
Filter => filter);
while DIR.More_Entries (search) loop
DIR.Get_Next_Entry (search, dirent);
declare
SN : constant String := DIR.Simple_Name (dirent);
oldfile : constant String := target_directory & "/" & SN;
newfile : constant String := source_directory & "/" & SN;
begin
if DIR.Exists (newfile) then
DIR.Copy_File (Source_Name => newfile, Target_Name => oldfile);
end if;
exception
when others =>
TIO.Put_Line ("Failed to copy " & newfile & " over to " & oldfile);
end;
end loop;
DIR.End_Search (search);
end replace_directory_contents;
--------------------------------------------------------------------------------------------
-- convert_ORIGIN_in_runpath
--------------------------------------------------------------------------------------------
function convert_ORIGIN_in_runpath (filename : String; runpath : String) return String
is
ORIGIN : constant String := "$ORIGIN";
begin
if not HT.contains (runpath, ORIGIN) then
return runpath;
end if;
declare
basedir : constant String := HT.head (filename, "/");
new_runpath : HT.Text := HT.replace_substring (US => HT.SUS (runpath),
old_string => ORIGIN,
new_string => basedir);
begin
return HT.USS (new_runpath);
end;
end convert_ORIGIN_in_runpath;
end File_Operations;
|
-- This file is covered by the Internet Software Consortium (ISC) License
-- Reference: ../License.txt
with Ada.Directories;
with Ada.Direct_IO;
with Ada.Text_IO;
with HelperText;
package body File_Operations is
package DIR renames Ada.Directories;
package TIO renames Ada.Text_IO;
package HT renames HelperText;
--------------------------------------------------------------------------------------------
-- get_file_contents
--------------------------------------------------------------------------------------------
function get_file_contents (dossier : String) return String
is
File_Size : constant Natural := Natural (DIR.Size (dossier));
begin
if File_Size = 0 then
return "";
end if;
declare
subtype File_String is String (1 .. File_Size);
package File_String_IO is new Ada.Direct_IO (File_String);
file_handle : File_String_IO.File_Type;
contents : File_String;
attempts : Natural := 0;
begin
-- The introduction of variants causes a buildsheet to be scanned once per variant.
-- It's possible (even common) for simultaneous requests to scan the same buildsheet to
-- occur. Thus, if the file is already open, wait and try again (up to 5 times)
loop
begin
File_String_IO.Open (File => file_handle,
Mode => File_String_IO.In_File,
Name => dossier);
exit;
exception
when File_String_IO.Status_Error | File_String_IO.Use_Error =>
if attempts = 5 then
raise file_handling with "get_file_contents: failed open: " & dossier;
end if;
attempts := attempts + 1;
delay 0.1;
end;
end loop;
File_String_IO.Read (File => file_handle, Item => contents);
File_String_IO.Close (file_handle);
return contents;
exception
when others =>
if File_String_IO.Is_Open (file_handle) then
File_String_IO.Close (file_handle);
end if;
raise file_handling with "get_file_contents(" & dossier & ") failed";
end;
exception
when Storage_Error =>
raise file_handling with "get_file_contents(" & dossier & ") failed to allocate memory";
end get_file_contents;
--------------------------------------------------------------------------------------------
-- dump_contents_to_file
--------------------------------------------------------------------------------------------
procedure dump_contents_to_file
(contents : String;
dossier : String)
is
File_Size : Natural := contents'Length;
subtype File_String is String (1 .. File_Size);
package File_String_IO is new Ada.Direct_IO (File_String);
file_handle : File_String_IO.File_Type;
begin
mkdirp_from_filename (dossier);
File_String_IO.Create (File => file_handle,
Mode => File_String_IO.Out_File,
Name => dossier);
File_String_IO.Write (File => file_handle,
Item => contents);
File_String_IO.Close (file_handle);
exception
when Storage_Error =>
if File_String_IO.Is_Open (file_handle) then
File_String_IO.Close (file_handle);
end if;
raise file_handling
with "dump_contents_to_file(" & dossier & ") failed to allocate memory";
when others =>
if File_String_IO.Is_Open (file_handle) then
File_String_IO.Close (file_handle);
end if;
raise file_handling
with "dump_contents_to_file(" & dossier & ") error";
end dump_contents_to_file;
--------------------------------------------------------------------------------------------
-- create_subdirectory
--------------------------------------------------------------------------------------------
procedure create_subdirectory
(extraction_directory : String;
subdirectory : String)
is
abspath : String := extraction_directory & "/" & subdirectory;
begin
if subdirectory = "" then
return;
end if;
if not DIR.Exists (abspath) then
DIR.Create_Directory (abspath);
end if;
end create_subdirectory;
--------------------------------------------------------------------------------------------
-- head_n1
--------------------------------------------------------------------------------------------
function head_n1 (filename : String) return String
is
handle : TIO.File_Type;
begin
TIO.Open (File => handle, Mode => TIO.In_File, Name => filename);
if TIO.End_Of_File (handle) then
TIO.Close (handle);
return "";
end if;
declare
line : constant String := TIO.Get_Line (handle);
begin
TIO.Close (handle);
return line;
end;
end head_n1;
--------------------------------------------------------------------------------------------
-- create_pidfile
--------------------------------------------------------------------------------------------
procedure create_pidfile (pidfile : String)
is
pidtext : constant String := HT.int2str (Get_PID);
handle : TIO.File_Type;
begin
TIO.Create (File => handle, Mode => TIO.Out_File, Name => pidfile);
TIO.Put_Line (handle, pidtext);
TIO.Close (handle);
end create_pidfile;
--------------------------------------------------------------------------------------------
-- destroy_pidfile
--------------------------------------------------------------------------------------------
procedure destroy_pidfile (pidfile : String) is
begin
if DIR.Exists (pidfile) then
DIR.Delete_File (pidfile);
end if;
exception
when others => null;
end destroy_pidfile;
--------------------------------------------------------------------------------------------
-- mkdirp_from_filename
--------------------------------------------------------------------------------------------
procedure mkdirp_from_filename (filename : String)
is
condir : String := DIR.Containing_Directory (Name => filename);
begin
DIR.Create_Path (New_Directory => condir);
end mkdirp_from_filename;
--------------------------------------------------------------------------------------------
-- concatenate_file
--------------------------------------------------------------------------------------------
procedure concatenate_file (basefile : String; another_file : String)
is
handle : TIO.File_Type;
begin
if not DIR.Exists (another_file) then
raise file_handling with "concatenate_file: new_file does not exist => " & another_file;
end if;
if DIR.Exists (basefile) then
TIO.Open (File => handle,
Mode => TIO.Append_File,
Name => basefile);
declare
contents : constant String := get_file_contents (another_file);
begin
TIO.Put (handle, contents);
end;
TIO.Close (handle);
else
DIR.Copy_File (Source_Name => another_file,
Target_Name => basefile);
end if;
exception
when others =>
if TIO.Is_Open (handle) then
TIO.Close (handle);
end if;
raise file_handling;
end concatenate_file;
--------------------------------------------------------------------------------------------
-- create_cookie
--------------------------------------------------------------------------------------------
procedure create_cookie (fullpath : String)
is
subtype File_String is String (1 .. 1);
package File_String_IO is new Ada.Direct_IO (File_String);
file_handle : File_String_IO.File_Type;
begin
mkdirp_from_filename (fullpath);
File_String_IO.Create (File => file_handle,
Mode => File_String_IO.Out_File,
Name => fullpath);
File_String_IO.Close (file_handle);
exception
when others =>
raise file_handling;
end create_cookie;
--------------------------------------------------------------------------------------------
-- replace_directory_contents
--------------------------------------------------------------------------------------------
procedure replace_directory_contents
(source_directory : String;
target_directory : String;
pattern : String)
is
search : DIR.Search_Type;
dirent : DIR.Directory_Entry_Type;
filter : constant DIR.Filter_Type := (DIR.Ordinary_File => True, others => False);
begin
if not DIR.Exists (target_directory) then
return;
end if;
DIR.Start_Search (Search => search,
Directory => target_directory,
Pattern => pattern,
Filter => filter);
while DIR.More_Entries (search) loop
DIR.Get_Next_Entry (search, dirent);
declare
SN : constant String := DIR.Simple_Name (dirent);
oldfile : constant String := target_directory & "/" & SN;
newfile : constant String := source_directory & "/" & SN;
begin
if DIR.Exists (newfile) then
DIR.Copy_File (Source_Name => newfile, Target_Name => oldfile);
end if;
exception
when others =>
TIO.Put_Line ("Failed to copy " & newfile & " over to " & oldfile);
end;
end loop;
DIR.End_Search (search);
end replace_directory_contents;
--------------------------------------------------------------------------------------------
-- convert_ORIGIN_in_runpath
--------------------------------------------------------------------------------------------
function convert_ORIGIN_in_runpath (filename : String; runpath : String) return String
is
ORIGIN : constant String := "$ORIGIN";
begin
if not HT.contains (runpath, ORIGIN) then
return runpath;
end if;
declare
basedir : constant String := HT.head (filename, "/");
new_runpath : HT.Text := HT.SUS (runpath);
begin
loop
new_runpath := HT.replace_substring (US => new_runpath,
old_string => ORIGIN,
new_string => basedir);
exit when not HT.contains (new_runpath, ORIGIN);
end loop;
return HT.USS (new_runpath);
end;
end convert_ORIGIN_in_runpath;
end File_Operations;
|
Handle multiple $ORIGIN tags
|
Handle multiple $ORIGIN tags
|
Ada
|
isc
|
jrmarino/ravenadm,jrmarino/ravenadm,jrmarino/ravenadm
|
82646910029921052a8a0e5a7c92bfb22e420ea0
|
awa/regtests/awa-wikis-parsers-tests.adb
|
awa/regtests/awa-wikis-parsers-tests.adb
|
-----------------------------------------------------------------------
-- awa-wikis-parsers-tests -- Unit tests for wiki parsing
-- Copyright (C) 2011, 2012, 2013 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Test_Caller;
with AWA.Wikis.Writers;
package body AWA.Wikis.Parsers.Tests is
package Caller is new Util.Test_Caller (Test, "Wikis.Parsers");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test AWA.Wikis.Parsers.Parse (bold)",
Test_Wiki_Bold'Access);
Caller.Add_Test (Suite, "Test AWA.Wikis.Parsers.Parse (italic)",
Test_Wiki_Italic'Access);
Caller.Add_Test (Suite, "Test AWA.Wikis.Parsers.Parse (italic, bold)",
Test_Wiki_Formats'Access);
Caller.Add_Test (Suite, "Test AWA.Wikis.Parsers.Parse (headings)",
Test_Wiki_Section'Access);
Caller.Add_Test (Suite, "Test AWA.Wikis.Parsers.Parse (lists)",
Test_Wiki_List'Access);
Caller.Add_Test (Suite, "Test AWA.Wikis.Parsers.Parse (links)",
Test_Wiki_Link'Access);
Caller.Add_Test (Suite, "Test AWA.Wikis.Parsers.Parse (quote)",
Test_Wiki_Quote'Access);
Caller.Add_Test (Suite, "Test AWA.Wikis.Parsers.Parse (line break)",
Test_Wiki_Line_Break'Access);
Caller.Add_Test (Suite, "Test AWA.Wikis.Parsers.Parse (image)",
Test_Wiki_Image'Access);
Caller.Add_Test (Suite, "Test AWA.Wikis.Parsers.Parse (preformatted)",
Test_Wiki_Preformatted'Access);
Caller.Add_Test (Suite, "Test AWA.Wikis.Text.Renderer",
Test_Wiki_Text_Renderer'Access);
end Add_Tests;
-- ------------------------------
-- Test bold rendering.
-- ------------------------------
procedure Test_Wiki_Bold (T : in out Test) is
begin
Util.Tests.Assert_Equals (T, "<p><b>bold</b></p>",
Writers.To_Html ("*bold*", SYNTAX_GOOGLE),
"Bold rendering invalid");
Util.Tests.Assert_Equals (T, "<p>x <b>bold</b> y</p>",
Writers.To_Html ("x *bold* y", SYNTAX_GOOGLE),
"Bold rendering invalid");
Util.Tests.Assert_Equals (T, "<p>x <b>bold y</b></p>",
Writers.To_Html ("x *bold y", SYNTAX_MIX),
"Bold rendering invalid (MIX)");
Util.Tests.Assert_Equals (T, "<p>x <b>item y</b> p</p>",
Writers.To_Html ("x __item y__ p", SYNTAX_DOTCLEAR),
"Bold rendering invalid");
Util.Tests.Assert_Equals (T, "<p>x _item y_ p</p>",
Writers.To_Html ("x _item y_ p", SYNTAX_DOTCLEAR),
"No bold rendering invalid");
Util.Tests.Assert_Equals (T, "<p>x <b>bold</b> y</p>",
Writers.To_Html ("x '''bold''' y", SYNTAX_PHPBB),
"Bold rendering invalid (PHPBB)");
end Test_Wiki_Bold;
-- ------------------------------
-- Test italic rendering.
-- ------------------------------
procedure Test_Wiki_Italic (T : in out Test) is
begin
Util.Tests.Assert_Equals (T, "<p><i>item</i></p>",
Writers.To_Html ("_item_", SYNTAX_GOOGLE),
"Italic rendering invalid");
Util.Tests.Assert_Equals (T, "<p>x <i>item</i> y</p>",
Writers.To_Html ("x _item_ y", SYNTAX_GOOGLE),
"Italic rendering invalid");
Util.Tests.Assert_Equals (T, "<p>x <i>item y</i></p>",
Writers.To_Html ("x _item y", SYNTAX_MIX),
"Italic rendering invalid");
Util.Tests.Assert_Equals (T, "<p>x <i>item y</i> p</p>",
Writers.To_Html ("x ''item y'' p", SYNTAX_DOTCLEAR),
"Italic rendering invalid");
Util.Tests.Assert_Equals (T, "<p>x <i>item y</i> p</p>",
Writers.To_Html ("x ''item y'' p", SYNTAX_PHPBB),
"Italic rendering invalid");
Util.Tests.Assert_Equals (T, "<p>x 'item y<i> p</i></p>",
Writers.To_Html ("x 'item y'' p", SYNTAX_PHPBB),
"Italic rendering invalid");
end Test_Wiki_Italic;
-- ------------------------------
-- Test various format rendering.
-- ------------------------------
procedure Test_Wiki_Formats (T : in out Test) is
begin
Util.Tests.Assert_Equals (T, "<p><i>it</i><b><i>bold</i></b><i>em</i></p>",
Writers.To_Html ("_it*bold*em_", SYNTAX_GOOGLE),
"Italic+Bold rendering invalid");
Util.Tests.Assert_Equals (T, "<p>x <i>item</i> y</p>",
Writers.To_Html ("x _item_ y", SYNTAX_GOOGLE),
"Italic rendering invalid");
Util.Tests.Assert_Equals (T, "<p>x <i>item y</i></p>",
Writers.To_Html ("x _item y", SYNTAX_GOOGLE),
"Italic rendering invalid");
end Test_Wiki_Formats;
-- ------------------------------
-- Test heading rendering.
-- ------------------------------
procedure Test_Wiki_Section (T : in out Test) is
begin
Util.Tests.Assert_Equals (T, "<h1>item</h1>",
Writers.To_Html ("= item =", SYNTAX_GOOGLE),
"H1 rendering invalid");
Util.Tests.Assert_Equals (T, "<h2>item</h2>",
Writers.To_Html ("== item == ", SYNTAX_GOOGLE),
"H2 rendering invalid");
Util.Tests.Assert_Equals (T, "<h3>item</h3>",
Writers.To_Html ("=== item === ", SYNTAX_GOOGLE),
"H3 rendering invalid");
Util.Tests.Assert_Equals (T, "<h4>item</h4>",
Writers.To_Html ("==== item ==== ", SYNTAX_GOOGLE),
"H4 rendering invalid");
Util.Tests.Assert_Equals (T, "<h5>item</h5>",
Writers.To_Html ("===== item =====", SYNTAX_GOOGLE),
"H5 rendering invalid");
Util.Tests.Assert_Equals (T, "<h6>item</h6>",
Writers.To_Html ("====== item ===", SYNTAX_GOOGLE),
"H6 rendering invalid");
Util.Tests.Assert_Equals (T, "<h1>item</h1><h2>item2</h2>",
Writers.To_Html ("= item =" & CR & "== item2 ==", SYNTAX_GOOGLE),
"H1 rendering invalid");
Util.Tests.Assert_Equals (T, "<h1>item</h1><h2>item2</h2><h1>item3</h1>",
Writers.To_Html ("= item =" & CR & "== item2 ==" & CR & "= item3 =",
SYNTAX_GOOGLE),
"H1 rendering invalid");
end Test_Wiki_Section;
-- ------------------------------
-- Test list rendering.
-- ------------------------------
procedure Test_Wiki_List (T : in out Test) is
begin
Util.Tests.Assert_Equals (T, "<ol><li>item</li></ol>",
Writers.To_Html ("# item", SYNTAX_GOOGLE),
"Ordered list rendering invalid");
Util.Tests.Assert_Equals (T, "<ol><li>item item " & ASCII.LF &
"</li><li>item2 item2" & ASCII.LF &
"</li><li><ol>item3</li></ol></ol>",
Writers.To_Html ("# item item " & LF & "# item2 item2" & LF & "## item3",
SYNTAX_GOOGLE),
"Ordered rendering invalid");
Util.Tests.Assert_Equals (T, "<ul><li>item</li></ul>",
Writers.To_Html (" * item", SYNTAX_GOOGLE),
"Bullet list rendering invalid");
Util.Tests.Assert_Equals (T, "<ul><li>item</li></ul>",
Writers.To_Html ("* item", SYNTAX_DOTCLEAR),
"Bullet list rendering invalid");
end Test_Wiki_List;
-- ------------------------------
-- Test link rendering.
-- ------------------------------
procedure Test_Wiki_Link (T : in out Test) is
begin
Util.Tests.Assert_Equals (T, "<p><a href="""">name</a></p>",
Writers.To_Html ("[name]", SYNTAX_GOOGLE),
"Link rendering invalid");
Util.Tests.Assert_Equals (T, "<p><a title=""some"" lang=""en"" " &
"href=""http://www.joe.com/item"">name </a></p>",
Writers.To_Html ("[name |http://www.joe.com/item|en|some]",
SYNTAX_DOTCLEAR),
"Link rendering invalid");
Util.Tests.Assert_Equals (T, "<p><a href="""">name</a></p>",
Writers.To_Html ("[[name]]", SYNTAX_CREOLE),
"Link rendering invalid");
Util.Tests.Assert_Equals (T, "<p>[d</p>",
Writers.To_Html ("[d", SYNTAX_CREOLE),
"No link rendering invalid");
end Test_Wiki_Link;
-- ------------------------------
-- Test quote rendering.
-- ------------------------------
procedure Test_Wiki_Quote (T : in out Test) is
begin
Util.Tests.Assert_Equals (T, "<p><q>quote</q></p>",
Writers.To_Html ("{{quote}}", SYNTAX_DOTCLEAR),
"Quote rendering invalid");
Util.Tests.Assert_Equals (T, "<p><q lang=""en"">quote</q></p>",
Writers.To_Html ("{{quote|en}}", SYNTAX_DOTCLEAR),
"Quote rendering invalid");
Util.Tests.Assert_Equals (T, "<p><q lang=""en"" cite=""http://www.sun.com"">quote</q></p>",
Writers.To_Html ("{{quote|en|http://www.sun.com}}",
SYNTAX_DOTCLEAR),
"Quote rendering invalid");
Util.Tests.Assert_Equals (T, "<p>{quote}}</p>",
Writers.To_Html ("{quote}}", SYNTAX_DOTCLEAR),
"No quote rendering invalid");
end Test_Wiki_Quote;
-- ------------------------------
-- Test line break rendering.
-- ------------------------------
procedure Test_Wiki_Line_Break (T : in out Test) is
begin
Util.Tests.Assert_Equals (T, "<p>a<br></br>b</p>",
Writers.To_Html ("a%%%b", SYNTAX_DOTCLEAR),
"Line break rendering invalid");
Util.Tests.Assert_Equals (T, "<p>a<br></br>b</p>",
Writers.To_Html ("a\\b", SYNTAX_CREOLE),
"Line break rendering invalid");
Util.Tests.Assert_Equals (T, "<p>a%%b</p>",
Writers.To_Html ("a%%b", SYNTAX_DOTCLEAR),
"No line break rendering invalid");
Util.Tests.Assert_Equals (T, "<p>a%b</p>",
Writers.To_Html ("a%b", SYNTAX_DOTCLEAR),
"No line break rendering invalid");
end Test_Wiki_Line_Break;
-- ------------------------------
-- Test image rendering.
-- ------------------------------
procedure Test_Wiki_Image (T : in out Test) is
begin
Util.Tests.Assert_Equals (T, "<p><img src=""/image/t.png""></img></p>",
Writers.To_Html ("((/image/t.png))", SYNTAX_DOTCLEAR),
"Image rendering invalid");
Util.Tests.Assert_Equals (T, "<p><img alt=""title"" src=""/image/t.png""></img></p>",
Writers.To_Html ("((/image/t.png|title))", SYNTAX_DOTCLEAR),
"Image rendering invalid");
Util.Tests.Assert_Equals (T, "<p><img alt=""title"" longdesc=""describe"" " &
"src=""/image/t.png""></img></p>",
Writers.To_Html ("((/image/t.png|title|D|describe))",
SYNTAX_DOTCLEAR),
"Image rendering invalid");
end Test_Wiki_Image;
-- ------------------------------
-- Test preformatted rendering.
-- ------------------------------
procedure Test_Wiki_Preformatted (T : in out Test) is
begin
Util.Tests.Assert_Equals (T, "<p><tt>code</tt></p>",
Writers.To_Html ("{{{code}}}", SYNTAX_GOOGLE),
"Preformat rendering invalid");
Util.Tests.Assert_Equals (T, "<pre>* code *" & ASCII.LF & "</pre>",
Writers.To_Html ("///" & LF & "* code *" & LF & "///",
SYNTAX_DOTCLEAR),
"Preformat rendering invalid");
end Test_Wiki_Preformatted;
-- ------------------------------
-- Test the text renderer.
-- ------------------------------
procedure Test_Wiki_Text_Renderer (T : in out Test) is
begin
Util.Tests.Assert_Equals (T, "code" & ASCII.LF,
Writers.To_Text ("{{{code}}}", SYNTAX_GOOGLE),
"Preformat rendering invalid");
Util.Tests.Assert_Equals (T, "bold item my_title" & ASCII.LF,
Writers.To_Text ("_bold_ __item__ [my_title]", SYNTAX_GOOGLE),
"Preformat rendering invalid");
end Test_Wiki_Text_Renderer;
end AWA.Wikis.Parsers.Tests;
|
-----------------------------------------------------------------------
-- awa-wikis-parsers-tests -- Unit tests for wiki parsing
-- Copyright (C) 2011, 2012, 2013 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Test_Caller;
with AWA.Wikis.Writers;
package body AWA.Wikis.Parsers.Tests is
package Caller is new Util.Test_Caller (Test, "Wikis.Parsers");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test AWA.Wikis.Parsers.Parse (bold)",
Test_Wiki_Bold'Access);
Caller.Add_Test (Suite, "Test AWA.Wikis.Parsers.Parse (italic)",
Test_Wiki_Italic'Access);
Caller.Add_Test (Suite, "Test AWA.Wikis.Parsers.Parse (italic, bold)",
Test_Wiki_Formats'Access);
Caller.Add_Test (Suite, "Test AWA.Wikis.Parsers.Parse (headings)",
Test_Wiki_Section'Access);
Caller.Add_Test (Suite, "Test AWA.Wikis.Parsers.Parse (lists)",
Test_Wiki_List'Access);
Caller.Add_Test (Suite, "Test AWA.Wikis.Parsers.Parse (links)",
Test_Wiki_Link'Access);
Caller.Add_Test (Suite, "Test AWA.Wikis.Parsers.Parse (quote)",
Test_Wiki_Quote'Access);
Caller.Add_Test (Suite, "Test AWA.Wikis.Parsers.Parse (line break)",
Test_Wiki_Line_Break'Access);
Caller.Add_Test (Suite, "Test AWA.Wikis.Parsers.Parse (image)",
Test_Wiki_Image'Access);
Caller.Add_Test (Suite, "Test AWA.Wikis.Parsers.Parse (preformatted)",
Test_Wiki_Preformatted'Access);
Caller.Add_Test (Suite, "Test AWA.Wikis.Text.Renderer",
Test_Wiki_Text_Renderer'Access);
end Add_Tests;
-- ------------------------------
-- Test bold rendering.
-- ------------------------------
procedure Test_Wiki_Bold (T : in out Test) is
begin
Util.Tests.Assert_Equals (T, "<p><b>bold</b></p>",
Writers.To_Html ("*bold*", SYNTAX_GOOGLE),
"Bold rendering invalid");
Util.Tests.Assert_Equals (T, "<p>x <b>bold</b> y</p>",
Writers.To_Html ("x *bold* y", SYNTAX_GOOGLE),
"Bold rendering invalid");
Util.Tests.Assert_Equals (T, "<p>x <b>bold y</b></p>",
Writers.To_Html ("x *bold y", SYNTAX_MIX),
"Bold rendering invalid (MIX)");
Util.Tests.Assert_Equals (T, "<p>x <b>item y</b> p</p>",
Writers.To_Html ("x __item y__ p", SYNTAX_DOTCLEAR),
"Bold rendering invalid");
Util.Tests.Assert_Equals (T, "<p>x _item y_ p</p>",
Writers.To_Html ("x _item y_ p", SYNTAX_DOTCLEAR),
"No bold rendering invalid");
Util.Tests.Assert_Equals (T, "<p>x <b>bold</b> y</p>",
Writers.To_Html ("x '''bold''' y", SYNTAX_PHPBB),
"Bold rendering invalid (PHPBB)");
end Test_Wiki_Bold;
-- ------------------------------
-- Test italic rendering.
-- ------------------------------
procedure Test_Wiki_Italic (T : in out Test) is
begin
Util.Tests.Assert_Equals (T, "<p><i>item</i></p>",
Writers.To_Html ("_item_", SYNTAX_GOOGLE),
"Italic rendering invalid");
Util.Tests.Assert_Equals (T, "<p>x <i>item</i> y</p>",
Writers.To_Html ("x _item_ y", SYNTAX_GOOGLE),
"Italic rendering invalid");
Util.Tests.Assert_Equals (T, "<p>x <i>item y</i></p>",
Writers.To_Html ("x _item y", SYNTAX_MIX),
"Italic rendering invalid");
Util.Tests.Assert_Equals (T, "<p>x <i>item y</i> p</p>",
Writers.To_Html ("x ''item y'' p", SYNTAX_DOTCLEAR),
"Italic rendering invalid");
Util.Tests.Assert_Equals (T, "<p>x <i>item y</i> p</p>",
Writers.To_Html ("x ''item y'' p", SYNTAX_PHPBB),
"Italic rendering invalid");
Util.Tests.Assert_Equals (T, "<p>x 'item y<i> p</i></p>",
Writers.To_Html ("x 'item y'' p", SYNTAX_PHPBB),
"Italic rendering invalid");
end Test_Wiki_Italic;
-- ------------------------------
-- Test various format rendering.
-- ------------------------------
procedure Test_Wiki_Formats (T : in out Test) is
begin
Util.Tests.Assert_Equals (T, "<p><i>it</i><b><i>bold</i></b><i>em</i></p>",
Writers.To_Html ("_it*bold*em_", SYNTAX_GOOGLE),
"Italic+Bold rendering invalid");
Util.Tests.Assert_Equals (T, "<p>x <i>item</i> y</p>",
Writers.To_Html ("x _item_ y", SYNTAX_GOOGLE),
"Italic rendering invalid");
Util.Tests.Assert_Equals (T, "<p>x <i>item y</i></p>",
Writers.To_Html ("x _item y", SYNTAX_GOOGLE),
"Italic rendering invalid");
end Test_Wiki_Formats;
-- ------------------------------
-- Test heading rendering.
-- ------------------------------
procedure Test_Wiki_Section (T : in out Test) is
begin
Util.Tests.Assert_Equals (T, "<h1>item</h1>",
Writers.To_Html ("= item =", SYNTAX_GOOGLE),
"H1 rendering invalid");
Util.Tests.Assert_Equals (T, "<h2>item</h2>",
Writers.To_Html ("== item == ", SYNTAX_GOOGLE),
"H2 rendering invalid");
Util.Tests.Assert_Equals (T, "<h3>item</h3>",
Writers.To_Html ("=== item === ", SYNTAX_GOOGLE),
"H3 rendering invalid");
Util.Tests.Assert_Equals (T, "<h4>item</h4>",
Writers.To_Html ("==== item ==== ", SYNTAX_GOOGLE),
"H4 rendering invalid");
Util.Tests.Assert_Equals (T, "<h5>item</h5>",
Writers.To_Html ("===== item =====", SYNTAX_GOOGLE),
"H5 rendering invalid");
Util.Tests.Assert_Equals (T, "<h6>item</h6>",
Writers.To_Html ("====== item ===", SYNTAX_GOOGLE),
"H6 rendering invalid");
Util.Tests.Assert_Equals (T, "<h1>item</h1><h2>item2</h2>",
Writers.To_Html ("= item =" & CR & "== item2 ==", SYNTAX_GOOGLE),
"H1 rendering invalid");
Util.Tests.Assert_Equals (T, "<h1>item</h1><h2>item2</h2><h1>item3</h1>",
Writers.To_Html ("= item =" & CR & "== item2 ==" & CR & "= item3 =",
SYNTAX_GOOGLE),
"H1 rendering invalid");
end Test_Wiki_Section;
-- ------------------------------
-- Test list rendering.
-- ------------------------------
procedure Test_Wiki_List (T : in out Test) is
begin
Util.Tests.Assert_Equals (T, "<ol><li>item</li></ol>",
Writers.To_Html ("# item", SYNTAX_GOOGLE),
"Ordered list rendering invalid");
Util.Tests.Assert_Equals (T, "<ol><li>item item " & ASCII.LF &
"</li><li>item2 item2" & ASCII.LF &
"</li><li><ol>item3</li></ol></ol>",
Writers.To_Html ("# item item " & LF & "# item2 item2" & LF & "## item3",
SYNTAX_GOOGLE),
"Ordered rendering invalid");
Util.Tests.Assert_Equals (T, "<ul><li>item</li></ul>",
Writers.To_Html (" * item", SYNTAX_GOOGLE),
"Bullet list rendering invalid");
Util.Tests.Assert_Equals (T, "<ul><li>item</li></ul>",
Writers.To_Html ("* item", SYNTAX_DOTCLEAR),
"Bullet list rendering invalid");
end Test_Wiki_List;
-- ------------------------------
-- Test link rendering.
-- ------------------------------
procedure Test_Wiki_Link (T : in out Test) is
begin
Util.Tests.Assert_Equals (T, "<p><a href="""">name</a></p>",
Writers.To_Html ("[name]", SYNTAX_GOOGLE),
"Link rendering invalid");
Util.Tests.Assert_Equals (T, "<p><a title=""some"" lang=""en"" " &
"href=""http://www.joe.com/item"">name </a></p>",
Writers.To_Html ("[name |http://www.joe.com/item|en|some]",
SYNTAX_DOTCLEAR),
"Link rendering invalid");
Util.Tests.Assert_Equals (T, "<p><a href="""">name</a></p>",
Writers.To_Html ("[[name]]", SYNTAX_CREOLE),
"Link rendering invalid");
Util.Tests.Assert_Equals (T, "<p>[d</p>",
Writers.To_Html ("[d", SYNTAX_CREOLE),
"No link rendering invalid");
end Test_Wiki_Link;
-- ------------------------------
-- Test quote rendering.
-- ------------------------------
procedure Test_Wiki_Quote (T : in out Test) is
begin
Util.Tests.Assert_Equals (T, "<p><q>quote</q></p>",
Writers.To_Html ("{{quote}}", SYNTAX_DOTCLEAR),
"Quote rendering invalid");
Util.Tests.Assert_Equals (T, "<p><q lang=""en"">quote</q></p>",
Writers.To_Html ("{{quote|en}}", SYNTAX_DOTCLEAR),
"Quote rendering invalid");
Util.Tests.Assert_Equals (T, "<p><q lang=""en"" cite=""http://www.sun.com"">quote</q></p>",
Writers.To_Html ("{{quote|en|http://www.sun.com}}",
SYNTAX_DOTCLEAR),
"Quote rendering invalid");
Util.Tests.Assert_Equals (T, "<p>{quote}}</p>",
Writers.To_Html ("{quote}}", SYNTAX_DOTCLEAR),
"No quote rendering invalid");
end Test_Wiki_Quote;
-- ------------------------------
-- Test line break rendering.
-- ------------------------------
procedure Test_Wiki_Line_Break (T : in out Test) is
begin
Util.Tests.Assert_Equals (T, "<p>a<br></br>b</p>",
Writers.To_Html ("a%%%b", SYNTAX_DOTCLEAR),
"Line break rendering invalid");
Util.Tests.Assert_Equals (T, "<p>a<br></br>b</p>",
Writers.To_Html ("a\\b", SYNTAX_CREOLE),
"Line break rendering invalid");
Util.Tests.Assert_Equals (T, "<p>a%%b</p>",
Writers.To_Html ("a%%b", SYNTAX_DOTCLEAR),
"No line break rendering invalid");
Util.Tests.Assert_Equals (T, "<p>a%b</p>",
Writers.To_Html ("a%b", SYNTAX_DOTCLEAR),
"No line break rendering invalid");
end Test_Wiki_Line_Break;
-- ------------------------------
-- Test image rendering.
-- ------------------------------
procedure Test_Wiki_Image (T : in out Test) is
begin
Util.Tests.Assert_Equals (T, "<p><img src=""/image/t.png""></img></p>",
Writers.To_Html ("((/image/t.png))", SYNTAX_DOTCLEAR),
"Image rendering invalid");
Util.Tests.Assert_Equals (T, "<p><img alt=""title"" src=""/image/t.png""></img></p>",
Writers.To_Html ("((/image/t.png|title))", SYNTAX_DOTCLEAR),
"Image rendering invalid");
Util.Tests.Assert_Equals (T, "<p><img alt=""title"" longdesc=""describe"" " &
"src=""/image/t.png""></img></p>",
Writers.To_Html ("((/image/t.png|title|D|describe))",
SYNTAX_DOTCLEAR),
"Image rendering invalid");
end Test_Wiki_Image;
-- ------------------------------
-- Test preformatted rendering.
-- ------------------------------
procedure Test_Wiki_Preformatted (T : in out Test) is
begin
Util.Tests.Assert_Equals (T, "<p><tt>code</tt></p>",
Writers.To_Html ("{{{code}}}", SYNTAX_GOOGLE),
"Preformat rendering invalid");
Util.Tests.Assert_Equals (T, "<pre>* code *" & ASCII.LF & "</pre>",
Writers.To_Html ("///" & LF & "* code *" & LF & "///",
SYNTAX_DOTCLEAR),
"Preformat rendering invalid");
end Test_Wiki_Preformatted;
-- ------------------------------
-- Test the text renderer.
-- ------------------------------
procedure Test_Wiki_Text_Renderer (T : in out Test) is
begin
Util.Tests.Assert_Equals (T, ASCII.LF & "code",
Writers.To_Text ("{{{code}}}", SYNTAX_GOOGLE),
"Preformat rendering invalid");
Util.Tests.Assert_Equals (T, ASCII.LF & "bold item my_title" & ASCII.LF,
Writers.To_Text ("_bold_ __item__ [my_title]", SYNTAX_GOOGLE),
"Preformat rendering invalid");
end Test_Wiki_Text_Renderer;
end AWA.Wikis.Parsers.Tests;
|
Fix the unit test
|
Fix the unit test
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
8377e04b0d9ed4ddc8ce09c32032b8793608a2d6
|
src/wiki-render-html.ads
|
src/wiki-render-html.ads
|
-----------------------------------------------------------------------
-- wiki-render-html -- Wiki HTML renderer
-- Copyright (C) 2011, 2012, 2013, 2015, 2016, 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 Wiki.Attributes;
with Wiki.Streams.Html;
with Wiki.Strings;
with Wiki.Render.Links;
-- === HTML Renderer ===
-- The `Html_Renderer` allows to render a wiki document into an HTML content.
--
package Wiki.Render.Html is
-- ------------------------------
-- Wiki to HTML renderer
-- ------------------------------
type Html_Renderer is new Renderer with private;
-- Set the output stream.
procedure Set_Output_Stream (Engine : in out Html_Renderer;
Stream : in Wiki.Streams.Html.Html_Output_Stream_Access);
-- Set the link renderer.
procedure Set_Link_Renderer (Engine : in out Html_Renderer;
Links : in Wiki.Render.Links.Link_Renderer_Access);
-- Set the render TOC flag that controls the TOC rendering.
procedure Set_Render_TOC (Engine : in out Html_Renderer;
State : in Boolean);
-- Set the no-newline mode to avoid emitting newlines (disabled by default).
procedure Set_No_Newline (Engine : in out Html_Renderer;
Enable : in Boolean);
-- Render the node instance from the document.
overriding
procedure Render (Engine : in out Html_Renderer;
Doc : in Wiki.Documents.Document;
Node : in Wiki.Nodes.Node_Type);
-- Get the current section number.
function Get_Section_Number (Engine : in Html_Renderer;
Prefix : in Wiki.Strings.WString;
Separator : in Wiki.Strings.WChar) return Wiki.Strings.WString;
-- Add a blockquote (<blockquote>). The level indicates the blockquote nested level.
-- The blockquote must be closed at the next header.
procedure Add_Blockquote (Engine : in out Html_Renderer;
Level : in Natural);
-- Render a list item (<li>). Close the previous paragraph and list item if any.
-- The list item will be closed at the next list item, next paragraph or next header.
procedure Render_List_Item (Engine : in out Html_Renderer;
Level : in Positive;
Ordered : in Boolean);
-- Add a text block with the given format.
procedure Add_Text (Engine : in out Html_Renderer;
Text : in Wiki.Strings.WString;
Format : in Wiki.Format_Map);
-- Render a text block that is pre-formatted.
procedure Render_Preformatted (Engine : in out Html_Renderer;
Text : in Wiki.Strings.WString;
Format : in Wiki.Strings.WString);
-- Render a table component such as N_TABLE, N_ROW or N_COLUMN.
procedure Render_Table (Engine : in out Html_Renderer;
Doc : in Wiki.Documents.Document;
Node : in Wiki.Nodes.Node_Type;
Tag : in String);
-- Finish the document after complete wiki text has been parsed.
overriding
procedure Finish (Engine : in out Html_Renderer;
Doc : in Wiki.Documents.Document);
private
procedure Close_Paragraph (Engine : in out Html_Renderer);
procedure Open_Paragraph (Engine : in out Html_Renderer);
type Toc_Number_Array is array (1 .. 6) of Natural;
type List_Style_Array is array (1 .. 32) of Boolean;
Default_Links : aliased Wiki.Render.Links.Default_Link_Renderer;
type Html_Renderer is new Renderer with record
Output : Wiki.Streams.Html.Html_Output_Stream_Access := null;
Format : Wiki.Format_Map := (others => False);
Links : Wiki.Render.Links.Link_Renderer_Access := Default_Links'Access;
Has_Paragraph : Boolean := False;
Need_Paragraph : Boolean := False;
Has_Item : Boolean := False;
Enable_Render_TOC : Boolean := False;
TOC_Rendered : Boolean := False;
No_Newline : Boolean := False;
Current_Level : Natural := 0;
Html_Tag : Wiki.Html_Tag := BODY_TAG;
List_Styles : List_Style_Array := (others => False);
Quote_Level : Natural := 0;
Html_Level : Natural := 0;
Current_Section : Toc_Number_Array := (others => 0);
Section_Level : Natural := 0;
Column : Natural := 0;
end record;
procedure Render_Tag (Engine : in out Html_Renderer;
Doc : in Wiki.Documents.Document;
Node : in Wiki.Nodes.Node_Type);
-- Render a section header in the document.
procedure Render_Header (Engine : in out Html_Renderer;
Doc : in Wiki.Documents.Document;
Header : in Wiki.Strings.WString;
Level : in Positive);
-- Render the table of content.
procedure Render_TOC (Engine : in out Html_Renderer;
Doc : in Wiki.Documents.Document;
Level : in Natural);
-- Render a link.
procedure Render_Link (Engine : in out Html_Renderer;
Doc : in Wiki.Documents.Document;
Title : in Wiki.Strings.WString;
Attr : in Wiki.Attributes.Attribute_List);
-- Render an image.
procedure Render_Image (Engine : in out Html_Renderer;
Doc : in Wiki.Documents.Document;
Title : in Wiki.Strings.WString;
Attr : in Wiki.Attributes.Attribute_List);
-- Render a quote.
procedure Render_Quote (Engine : in out Html_Renderer;
Doc : in Wiki.Documents.Document;
Title : in Wiki.Strings.WString;
Attr : in Wiki.Attributes.Attribute_List);
-- Returns true if the HTML element being included is already contained in a paragraph.
-- This include: a, em, strong, small, b, i, u, s, span, ins, del, sub, sup.
function Has_Html_Paragraph (Engine : in Html_Renderer) return Boolean;
procedure Newline (Engine : in out Html_Renderer);
end Wiki.Render.Html;
|
-----------------------------------------------------------------------
-- wiki-render-html -- Wiki HTML renderer
-- Copyright (C) 2011, 2012, 2013, 2015, 2016, 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 Wiki.Attributes;
with Wiki.Streams.Html;
with Wiki.Strings;
with Wiki.Render.Links;
-- === HTML Renderer ===
-- The `Html_Renderer` allows to render a wiki document into an HTML content.
--
package Wiki.Render.Html is
-- ------------------------------
-- Wiki to HTML renderer
-- ------------------------------
type Html_Renderer is new Renderer with private;
-- Set the output stream.
procedure Set_Output_Stream (Engine : in out Html_Renderer;
Stream : in Wiki.Streams.Html.Html_Output_Stream_Access);
-- Set the link renderer.
procedure Set_Link_Renderer (Engine : in out Html_Renderer;
Links : in Wiki.Render.Links.Link_Renderer_Access);
-- Set the render TOC flag that controls the TOC rendering.
procedure Set_Render_TOC (Engine : in out Html_Renderer;
State : in Boolean);
-- Set the no-newline mode to avoid emitting newlines (disabled by default).
procedure Set_No_Newline (Engine : in out Html_Renderer;
Enable : in Boolean);
-- Render the node instance from the document.
overriding
procedure Render (Engine : in out Html_Renderer;
Doc : in Wiki.Documents.Document;
Node : in Wiki.Nodes.Node_Type);
-- Get the current section number.
function Get_Section_Number (Engine : in Html_Renderer;
Prefix : in Wiki.Strings.WString;
Separator : in Wiki.Strings.WChar) return Wiki.Strings.WString;
-- Add a blockquote (<blockquote>). The level indicates the blockquote nested level.
-- The blockquote must be closed at the next header.
procedure Add_Blockquote (Engine : in out Html_Renderer;
Level : in Natural);
procedure Render_List_Start (Engine : in out Html_Renderer;
Tag : in String;
Level : in Positive);
-- Render a list item (<li>). Close the previous paragraph and list item if any.
-- The list item will be closed at the next list item, next paragraph or next header.
procedure Render_List_Item (Engine : in out Html_Renderer);
-- Render a list item end (</ul> or </ol>).
-- Close the previous paragraph and list item if any.
procedure Render_List_End (Engine : in out Html_Renderer;
Tag : in String);
-- Add a text block with the given format.
procedure Add_Text (Engine : in out Html_Renderer;
Text : in Wiki.Strings.WString;
Format : in Wiki.Format_Map);
-- Render a text block that is pre-formatted.
procedure Render_Preformatted (Engine : in out Html_Renderer;
Text : in Wiki.Strings.WString;
Format : in Wiki.Strings.WString);
-- Render a table component such as N_TABLE, N_ROW or N_COLUMN.
procedure Render_Table (Engine : in out Html_Renderer;
Doc : in Wiki.Documents.Document;
Node : in Wiki.Nodes.Node_Type;
Tag : in String);
-- Finish the document after complete wiki text has been parsed.
overriding
procedure Finish (Engine : in out Html_Renderer;
Doc : in Wiki.Documents.Document);
private
procedure Close_Paragraph (Engine : in out Html_Renderer);
procedure Open_Paragraph (Engine : in out Html_Renderer);
type Toc_Number_Array is array (1 .. 6) of Natural;
type List_Style_Array is array (1 .. 32) of Boolean;
Default_Links : aliased Wiki.Render.Links.Default_Link_Renderer;
type Html_Renderer is new Renderer with record
Output : Wiki.Streams.Html.Html_Output_Stream_Access := null;
Format : Wiki.Format_Map := (others => False);
Links : Wiki.Render.Links.Link_Renderer_Access := Default_Links'Access;
Has_Paragraph : Boolean := False;
Need_Paragraph : Boolean := False;
Has_Item : Boolean := False;
Enable_Render_TOC : Boolean := False;
TOC_Rendered : Boolean := False;
No_Newline : Boolean := False;
Current_Level : Natural := 0;
Html_Tag : Wiki.Html_Tag := BODY_TAG;
List_Styles : List_Style_Array := (others => False);
Quote_Level : Natural := 0;
Html_Level : Natural := 0;
Current_Section : Toc_Number_Array := (others => 0);
Section_Level : Natural := 0;
Column : Natural := 0;
In_Definition : Boolean := False;
end record;
procedure Render_Tag (Engine : in out Html_Renderer;
Doc : in Wiki.Documents.Document;
Node : in Wiki.Nodes.Node_Type);
-- Render a section header in the document.
procedure Render_Header (Engine : in out Html_Renderer;
Doc : in Wiki.Documents.Document;
Header : in Wiki.Strings.WString;
Level : in Positive);
-- Render the table of content.
procedure Render_TOC (Engine : in out Html_Renderer;
Doc : in Wiki.Documents.Document;
Level : in Natural);
-- Render a link.
procedure Render_Link (Engine : in out Html_Renderer;
Doc : in Wiki.Documents.Document;
Title : in Wiki.Strings.WString;
Attr : in Wiki.Attributes.Attribute_List);
-- Render an image.
procedure Render_Image (Engine : in out Html_Renderer;
Doc : in Wiki.Documents.Document;
Title : in Wiki.Strings.WString;
Attr : in Wiki.Attributes.Attribute_List);
-- Render a quote.
procedure Render_Quote (Engine : in out Html_Renderer;
Doc : in Wiki.Documents.Document;
Title : in Wiki.Strings.WString;
Attr : in Wiki.Attributes.Attribute_List);
-- Returns true if the HTML element being included is already contained in a paragraph.
-- This include: a, em, strong, small, b, i, u, s, span, ins, del, sub, sup.
function Has_Html_Paragraph (Engine : in Html_Renderer) return Boolean;
procedure Newline (Engine : in out Html_Renderer);
end Wiki.Render.Html;
|
Add Render_List_Start, Render_List_End for the list rendering Add In_Definition member to track whether we are within a <dl><dt><dd> list
|
Add Render_List_Start, Render_List_End for the list rendering
Add In_Definition member to track whether we are within a <dl><dt><dd> list
|
Ada
|
apache-2.0
|
stcarrez/ada-wiki,stcarrez/ada-wiki
|
db686ecbc4d4fb4ba9902aa6f661f898b49e0660
|
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.
-----------------------------------------------------------------------
with Ada.Characters.Conversions;
package body Wiki.Streams.Html is
-- ------------------------------
-- Write an XML attribute within an XML element.
-- The attribute value is escaped according to the XML escape rules.
-- ------------------------------
procedure Write_Attribute (Writer : in out Html_Output_Stream'Class;
Name : in String;
Content : in String) is
begin
Writer.Write_Wide_Attribute (Name, Ada.Characters.Conversions.To_Wide_Wide_String (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
-- ------------------------------
-- 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;
|
Use Wiki.Strings.To_WString function
|
Use Wiki.Strings.To_WString function
|
Ada
|
apache-2.0
|
stcarrez/ada-wiki,stcarrez/ada-wiki
|
350a65f70fc9f59f82b677679af458ca2bc8cbc8
|
src/wiki-streams-html.ads
|
src/wiki-streams-html.ads
|
-----------------------------------------------------------------------
-- wiki-streams-html -- Wiki HTML output stream
-- Copyright (C) 2011, 2012, 2013, 2015, 2016, 2020 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Wiki.Strings;
-- === HTML Output Stream ===
-- The `Wiki.Writers` package defines the interfaces used by the renderer to write
-- their outputs.
--
-- The `Input_Stream` interface defines the interface that must be implemented to
-- read the source Wiki content. The `Read` procedure is called by the parser
-- repeatedly while scanning the Wiki content.
package Wiki.Streams.Html is
type Html_Output_Stream is limited interface and Output_Stream;
type Html_Output_Stream_Access is access all Html_Output_Stream'Class;
-- Write an XML attribute within an XML element.
-- The attribute value is escaped according to the XML escape rules.
procedure Write_Wide_Attribute (Writer : in out Html_Output_Stream;
Name : in String;
Content : in Wiki.Strings.UString) is abstract;
-- Write an XML attribute within an XML element.
-- The attribute value is escaped according to the XML escape rules.
procedure Write_Wide_Attribute (Writer : in out Html_Output_Stream;
Name : in String;
Content : in Wide_Wide_String) is abstract;
-- Start an XML element with the given name.
procedure Start_Element (Writer : in out Html_Output_Stream;
Name : in String) is abstract;
-- Closes an XML element of the given name.
procedure End_Element (Writer : in out Html_Output_Stream;
Name : in String) is abstract;
-- Write a text escaping any character as necessary.
procedure Write_Wide_Text (Writer : in out Html_Output_Stream;
Content : in Wiki.Strings.WString) is abstract;
-- 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);
-- 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);
-- 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);
-- 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);
end Wiki.Streams.Html;
|
-----------------------------------------------------------------------
-- wiki-streams-html -- Wiki HTML output stream
-- Copyright (C) 2011, 2012, 2013, 2015, 2016, 2020, 2022 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Wiki.Strings;
-- === HTML Output Stream ===
-- The `Wiki.Writers` package defines the interfaces used by the renderer to write
-- their outputs.
--
-- The `Input_Stream` interface defines the interface that must be implemented to
-- read the source Wiki content. The `Read` procedure is called by the parser
-- repeatedly while scanning the Wiki content.
package Wiki.Streams.Html is
type Html_Output_Stream is limited interface and Output_Stream;
type Html_Output_Stream_Access is access all Html_Output_Stream'Class;
-- Write an XML attribute within an XML element.
-- The attribute value is escaped according to the XML escape rules.
procedure Write_Wide_Attribute (Writer : in out Html_Output_Stream;
Name : in String;
Content : in Wiki.Strings.UString) is abstract;
-- Write an XML attribute within an XML element.
-- The attribute value is escaped according to the XML escape rules.
procedure Write_Wide_Attribute (Writer : in out Html_Output_Stream;
Name : in String;
Content : in Wide_Wide_String) is abstract;
-- Start an XML element with the given name.
procedure Start_Element (Writer : in out Html_Output_Stream;
Name : in String) is abstract;
-- Closes an XML element of the given name.
procedure End_Element (Writer : in out Html_Output_Stream;
Name : in String) is abstract;
-- Write a text escaping any character as necessary.
procedure Write_Wide_Text (Writer : in out Html_Output_Stream;
Content : in Wiki.Strings.WString) is abstract;
-- Write an optional newline or space.
procedure Newline (Writer : in out Html_Output_Stream) is abstract;
-- 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);
-- 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);
-- 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);
-- 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);
end Wiki.Streams.Html;
|
Add the Newline procedure to emit a newline
|
Add the Newline procedure to emit a newline
|
Ada
|
apache-2.0
|
stcarrez/ada-wiki,stcarrez/ada-wiki
|
450693cd2f72ba52b1e994099dae530f3e94b5d6
|
src/ado-sessions.ads
|
src/ado-sessions.ads
|
-----------------------------------------------------------------------
-- ADO Sessions -- Sessions Management
-- Copyright (C) 2009, 2010, 2011, 2012, 2013, 2015, 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Finalization;
with ADO.Schemas;
with ADO.Statements;
with ADO.Objects;
with ADO.Objects.Cache;
with ADO.Drivers.Connections;
with ADO.Queries;
with ADO.SQL;
with ADO.Caches;
with Util.Concurrent.Counters;
limited with ADO.Sequences;
limited with ADO.Schemas.Entities;
-- == Session ==
-- The <tt>ADO.Sessions</tt> package defines the control and management of database sessions.
-- The database session is represented by the <tt>Session</tt> or <tt>Master_Session</tt> types.
-- It provides operation to create a database statement that can be executed.
-- The <tt>Session</tt> type is used to represent read-only database sessions. It provides
-- operations to query the database but it does not allow to update or delete content.
-- The <tt>Master_Session</tt> type extends the <tt>Session</tt> type to provide write
-- access and it provides operations to get update or delete statements. The differentiation
-- between the two sessions is provided for the support of database replications with
-- databases such as MySQL.
--
-- @include ado-sessions-factory.ads
--
package ADO.Sessions is
use ADO.Statements;
-- Raised for all errors reported by the database
DB_Error : exception;
-- Raised if the database connection is not open.
NOT_OPEN : exception;
NOT_FOUND : exception;
NO_DATABASE : exception;
-- Raised when the connection URI is invalid.
Connection_Error : exception;
-- The database connection status
type Connection_Status is (OPEN, CLOSED);
type Object_Factory is tagged private;
-- ---------
-- Session
-- ---------
-- Read-only database connection (or slave connection).
--
type Session is tagged private;
-- Get the session status.
function Get_Status (Database : in Session) return Connection_Status;
-- Get the database driver which manages this connection.
function Get_Driver (Database : in Session) return ADO.Drivers.Connections.Driver_Access;
-- Close the session.
procedure Close (Database : in out Session);
-- Insert a new cache in the manager. The cache is identified by the given name.
procedure Add_Cache (Database : in out Session;
Name : in String;
Cache : in ADO.Caches.Cache_Type_Access);
-- Attach the object to the session.
procedure Attach (Database : in out Session;
Object : in ADO.Objects.Object_Ref'Class);
-- Check if the session contains the object identified by the given key.
function Contains (Database : in Session;
Item : in ADO.Objects.Object_Key) return Boolean;
-- Remove the object from the session cache.
procedure Evict (Database : in out Session;
Item : in ADO.Objects.Object_Key);
-- Create a query statement. The statement is not prepared
function Create_Statement (Database : in Session;
Table : in ADO.Schemas.Class_Mapping_Access)
return Query_Statement;
-- Create a query statement. The statement is not prepared
function Create_Statement (Database : in Session;
Query : in String)
return Query_Statement;
-- Create a query statement. The statement is not prepared
function Create_Statement (Database : in Session;
Query : in ADO.Queries.Context'Class)
return Query_Statement;
-- Create a query statement and initialize the SQL statement with the query definition.
function Create_Statement (Database : in Session;
Query : in ADO.Queries.Query_Definition_Access)
return Query_Statement;
-- Create a query statement. The statement is not prepared
function Create_Statement (Database : in Session;
Query : in ADO.SQL.Query'Class;
Table : in ADO.Schemas.Class_Mapping_Access)
return Query_Statement;
-- Load the database schema definition for the current database.
procedure Load_Schema (Database : in Session;
Schema : out ADO.Schemas.Schema_Definition);
-- Internal method to get the session proxy associated with the given database session.
-- The session proxy is associated with some ADO objects to be able to retrieve the database
-- session for the implementation of lazy loading. The session proxy is kept until the
-- session exist and at least one ADO object is refering to it.
function Get_Session_Proxy (Database : in Session) return ADO.Objects.Session_Proxy_Access;
-- ---------
-- Master Session
-- ---------
-- Read-write session.
--
type Master_Session is new Session with private;
-- Start a transaction.
procedure Begin_Transaction (Database : in out Master_Session);
-- Commit the current transaction.
procedure Commit (Database : in out Master_Session);
-- Rollback the current transaction.
procedure Rollback (Database : in out Master_Session);
-- Allocate an identifier for the table.
procedure Allocate (Database : in out Master_Session;
Id : in out ADO.Objects.Object_Record'Class);
-- Flush the objects that were modified.
procedure Flush (Database : in out Master_Session);
-- Create a delete statement
function Create_Statement (Database : in Master_Session;
Table : in ADO.Schemas.Class_Mapping_Access)
return Delete_Statement;
-- Create an update statement
function Create_Statement (Database : in Master_Session;
Table : in ADO.Schemas.Class_Mapping_Access)
return Update_Statement;
-- Create an insert statement
function Create_Statement (Database : in Master_Session;
Table : in ADO.Schemas.Class_Mapping_Access)
return Insert_Statement;
type Session_Record is limited private;
type Session_Record_Access is access all Session_Record;
private
type Entity_Cache_Access is access ADO.Schemas.Entities.Entity_Cache;
type Object_Factory is tagged record
A : Integer;
end record;
type Object_Factory_Access is access all Object_Factory'Class;
-- The <b>Session_Record</b> maintains the connection information to the database for
-- the duration of the session. It also maintains a cache of application objects
-- which is used when session objects are fetched (either through Load or a Find).
-- The connection is released and the session record is deleted when the session
-- is closed with <b>Close</b>.
--
-- For the lazy loading support, each object is associated with a shared <b>Session_Proxy</b>
-- object that allows to give access to the session record associated with the object.
-- When a session is closed, the <b>Session_Proxy</b> is not deleted but it is simply
-- unlinked from the session record.
type Session_Record is limited record
Counter : Util.Concurrent.Counters.Counter := Util.Concurrent.Counters.ONE;
Database : ADO.Drivers.Connections.Ref.Ref;
Proxy : ADO.Objects.Session_Proxy_Access;
Cache : ADO.Objects.Cache.Object_Cache;
Entities : Entity_Cache_Access;
Values : ADO.Caches.Cache_Manager_Access;
end record;
type Session is new Ada.Finalization.Controlled with record
Impl : Session_Record_Access := null;
end record;
overriding
procedure Adjust (Object : in out Session);
overriding
procedure Finalize (Object : in out Session);
type Factory_Access is access all ADO.Sequences.Factory;
type Master_Session is new Session with record
Sequences : Factory_Access;
end record;
procedure Check_Session (Database : in Session'Class;
Message : in String := "");
pragma Inline (Check_Session);
end ADO.Sessions;
|
-----------------------------------------------------------------------
-- ADO Sessions -- Sessions Management
-- Copyright (C) 2009, 2010, 2011, 2012, 2013, 2015, 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Finalization;
with ADO.Schemas;
with ADO.Statements;
with ADO.Objects;
with ADO.Objects.Cache;
with ADO.Drivers.Connections;
with ADO.Queries;
with ADO.SQL;
with ADO.Caches;
with Util.Concurrent.Counters;
limited with ADO.Sequences;
limited with ADO.Schemas.Entities;
-- == Session ==
-- The `ADO.Sessions` package defines the control and management of database sessions.
-- The database session is represented by the `Session` or `Master_Session` types.
-- It provides operation to create a database statement that can be executed.
-- The `Session` type is used to represent read-only database sessions. It provides
-- operations to query the database but it does not allow to update or delete content.
-- The `Master_Session` type extends the `Session` type to provide write
-- access and it provides operations to get update or delete statements. The differentiation
-- between the two sessions is provided for the support of database replications with
-- databases such as MySQL.
--
-- @include ado-sessions-factory.ads
-- @include ado-sequences.ads
--
package ADO.Sessions is
use ADO.Statements;
-- Raised for all errors reported by the database
DB_Error : exception;
-- Raised if the database connection is not open.
NOT_OPEN : exception;
NOT_FOUND : exception;
NO_DATABASE : exception;
-- Raised when the connection URI is invalid.
Connection_Error : exception;
-- The database connection status
type Connection_Status is (OPEN, CLOSED);
type Object_Factory is tagged private;
-- ---------
-- Session
-- ---------
-- Read-only database connection (or slave connection).
--
type Session is tagged private;
-- Get the session status.
function Get_Status (Database : in Session) return Connection_Status;
-- Get the database driver which manages this connection.
function Get_Driver (Database : in Session) return ADO.Drivers.Connections.Driver_Access;
-- Close the session.
procedure Close (Database : in out Session);
-- Insert a new cache in the manager. The cache is identified by the given name.
procedure Add_Cache (Database : in out Session;
Name : in String;
Cache : in ADO.Caches.Cache_Type_Access);
-- Attach the object to the session.
procedure Attach (Database : in out Session;
Object : in ADO.Objects.Object_Ref'Class);
-- Check if the session contains the object identified by the given key.
function Contains (Database : in Session;
Item : in ADO.Objects.Object_Key) return Boolean;
-- Remove the object from the session cache.
procedure Evict (Database : in out Session;
Item : in ADO.Objects.Object_Key);
-- Create a query statement. The statement is not prepared
function Create_Statement (Database : in Session;
Table : in ADO.Schemas.Class_Mapping_Access)
return Query_Statement;
-- Create a query statement. The statement is not prepared
function Create_Statement (Database : in Session;
Query : in String)
return Query_Statement;
-- Create a query statement. The statement is not prepared
function Create_Statement (Database : in Session;
Query : in ADO.Queries.Context'Class)
return Query_Statement;
-- Create a query statement and initialize the SQL statement with the query definition.
function Create_Statement (Database : in Session;
Query : in ADO.Queries.Query_Definition_Access)
return Query_Statement;
-- Create a query statement. The statement is not prepared
function Create_Statement (Database : in Session;
Query : in ADO.SQL.Query'Class;
Table : in ADO.Schemas.Class_Mapping_Access)
return Query_Statement;
-- Load the database schema definition for the current database.
procedure Load_Schema (Database : in Session;
Schema : out ADO.Schemas.Schema_Definition);
-- Internal method to get the session proxy associated with the given database session.
-- The session proxy is associated with some ADO objects to be able to retrieve the database
-- session for the implementation of lazy loading. The session proxy is kept until the
-- session exist and at least one ADO object is refering to it.
function Get_Session_Proxy (Database : in Session) return ADO.Objects.Session_Proxy_Access;
-- ---------
-- Master Session
-- ---------
-- Read-write session.
--
type Master_Session is new Session with private;
-- Start a transaction.
procedure Begin_Transaction (Database : in out Master_Session);
-- Commit the current transaction.
procedure Commit (Database : in out Master_Session);
-- Rollback the current transaction.
procedure Rollback (Database : in out Master_Session);
-- Allocate an identifier for the table.
procedure Allocate (Database : in out Master_Session;
Id : in out ADO.Objects.Object_Record'Class);
-- Flush the objects that were modified.
procedure Flush (Database : in out Master_Session);
-- Create a delete statement
function Create_Statement (Database : in Master_Session;
Table : in ADO.Schemas.Class_Mapping_Access)
return Delete_Statement;
-- Create an update statement
function Create_Statement (Database : in Master_Session;
Table : in ADO.Schemas.Class_Mapping_Access)
return Update_Statement;
-- Create an insert statement
function Create_Statement (Database : in Master_Session;
Table : in ADO.Schemas.Class_Mapping_Access)
return Insert_Statement;
type Session_Record is limited private;
type Session_Record_Access is access all Session_Record;
private
type Entity_Cache_Access is access ADO.Schemas.Entities.Entity_Cache;
type Object_Factory is tagged record
A : Integer;
end record;
type Object_Factory_Access is access all Object_Factory'Class;
-- The <b>Session_Record</b> maintains the connection information to the database for
-- the duration of the session. It also maintains a cache of application objects
-- which is used when session objects are fetched (either through Load or a Find).
-- The connection is released and the session record is deleted when the session
-- is closed with <b>Close</b>.
--
-- For the lazy loading support, each object is associated with a shared <b>Session_Proxy</b>
-- object that allows to give access to the session record associated with the object.
-- When a session is closed, the <b>Session_Proxy</b> is not deleted but it is simply
-- unlinked from the session record.
type Session_Record is limited record
Counter : Util.Concurrent.Counters.Counter := Util.Concurrent.Counters.ONE;
Database : ADO.Drivers.Connections.Ref.Ref;
Proxy : ADO.Objects.Session_Proxy_Access;
Cache : ADO.Objects.Cache.Object_Cache;
Entities : Entity_Cache_Access;
Values : ADO.Caches.Cache_Manager_Access;
end record;
type Session is new Ada.Finalization.Controlled with record
Impl : Session_Record_Access := null;
end record;
overriding
procedure Adjust (Object : in out Session);
overriding
procedure Finalize (Object : in out Session);
type Factory_Access is access all ADO.Sequences.Factory;
type Master_Session is new Session with record
Sequences : Factory_Access;
end record;
procedure Check_Session (Database : in Session'Class;
Message : in String := "");
pragma Inline (Check_Session);
end ADO.Sessions;
|
Add some documentation
|
Add some documentation
|
Ada
|
apache-2.0
|
stcarrez/ada-ado
|
77984a7b82cc911833a84c10415f5634a4ac448c
|
src/sqlite/sqlite3_h-perfect_hash.ads
|
src/sqlite/sqlite3_h-perfect_hash.ads
|
-- Generated by gperfhash
package Sqlite3_H.Perfect_Hash is
function Hash (S : String) return Natural;
-- Returns true if the string <b>S</b> is a keyword.
function Is_Keyword (S : in String) return Boolean;
type Name_Access is access constant String;
type Keyword_Array is array (Natural range <>) of Name_Access;
Keywords : constant Keyword_Array;
private
K_0 : aliased constant String := "ABORT";
K_1 : aliased constant String := "ACTION";
K_2 : aliased constant String := "ADD";
K_3 : aliased constant String := "AFTER";
K_4 : aliased constant String := "ALL";
K_5 : aliased constant String := "ALTER";
K_6 : aliased constant String := "ANALYZE";
K_7 : aliased constant String := "AND";
K_8 : aliased constant String := "AS";
K_9 : aliased constant String := "ASC";
K_10 : aliased constant String := "ATTACH";
K_11 : aliased constant String := "AUTOINCREMENT";
K_12 : aliased constant String := "BEFORE";
K_13 : aliased constant String := "BEGIN";
K_14 : aliased constant String := "BETWEEN";
K_15 : aliased constant String := "BY";
K_16 : aliased constant String := "CASCADE";
K_17 : aliased constant String := "CASE";
K_18 : aliased constant String := "CAST";
K_19 : aliased constant String := "CHECK";
K_20 : aliased constant String := "COLLATE";
K_21 : aliased constant String := "COLUMN";
K_22 : aliased constant String := "COMMIT";
K_23 : aliased constant String := "CONFLICT";
K_24 : aliased constant String := "CONSTRAINT";
K_25 : aliased constant String := "CREATE";
K_26 : aliased constant String := "CROSS";
K_27 : aliased constant String := "CURRENT_DATE";
K_28 : aliased constant String := "CURRENT_TIME";
K_29 : aliased constant String := "CURRENT_TIMESTAMP";
K_30 : aliased constant String := "DATABASE";
K_31 : aliased constant String := "DEFAULT";
K_32 : aliased constant String := "DEFERRABLE";
K_33 : aliased constant String := "DEFERRED";
K_34 : aliased constant String := "DELETE";
K_35 : aliased constant String := "DESC";
K_36 : aliased constant String := "DETACH";
K_37 : aliased constant String := "DISTINCT";
K_38 : aliased constant String := "DROP";
K_39 : aliased constant String := "EACH";
K_40 : aliased constant String := "ELSE";
K_41 : aliased constant String := "END";
K_42 : aliased constant String := "ESCAPE";
K_43 : aliased constant String := "EXCEPT";
K_44 : aliased constant String := "EXCLUSIVE";
K_45 : aliased constant String := "EXISTS";
K_46 : aliased constant String := "EXPLAIN";
K_47 : aliased constant String := "FAIL";
K_48 : aliased constant String := "FOR";
K_49 : aliased constant String := "FOREIGN";
K_50 : aliased constant String := "FROM";
K_51 : aliased constant String := "FULL";
K_52 : aliased constant String := "GLOB";
K_53 : aliased constant String := "GROUP";
K_54 : aliased constant String := "HAVING";
K_55 : aliased constant String := "IF";
K_56 : aliased constant String := "IGNORE";
K_57 : aliased constant String := "IMMEDIATE";
K_58 : aliased constant String := "IN";
K_59 : aliased constant String := "INDEX";
K_60 : aliased constant String := "INDEXED";
K_61 : aliased constant String := "INITIALLY";
K_62 : aliased constant String := "INNER";
K_63 : aliased constant String := "INSERT";
K_64 : aliased constant String := "INSTEAD";
K_65 : aliased constant String := "INTERSECT";
K_66 : aliased constant String := "INTO";
K_67 : aliased constant String := "IS";
K_68 : aliased constant String := "ISNULL";
K_69 : aliased constant String := "JOIN";
K_70 : aliased constant String := "KEY";
K_71 : aliased constant String := "LEFT";
K_72 : aliased constant String := "LIKE";
K_73 : aliased constant String := "LIMIT";
K_74 : aliased constant String := "MATCH";
K_75 : aliased constant String := "NATURAL";
K_76 : aliased constant String := "NO";
K_77 : aliased constant String := "NOT";
K_78 : aliased constant String := "NOTNULL";
K_79 : aliased constant String := "NULL";
K_80 : aliased constant String := "OF";
K_81 : aliased constant String := "OFFSET";
K_82 : aliased constant String := "ON";
K_83 : aliased constant String := "OR";
K_84 : aliased constant String := "ORDER";
K_85 : aliased constant String := "OUTER";
K_86 : aliased constant String := "PLAN";
K_87 : aliased constant String := "PRAGMA";
K_88 : aliased constant String := "PRIMARY";
K_89 : aliased constant String := "QUERY";
K_90 : aliased constant String := "RAISE";
K_91 : aliased constant String := "REFERENCES";
K_92 : aliased constant String := "REGEXP";
K_93 : aliased constant String := "REINDEX";
K_94 : aliased constant String := "RELEASE";
K_95 : aliased constant String := "RENAME";
K_96 : aliased constant String := "REPLACE";
K_97 : aliased constant String := "RESTRICT";
K_98 : aliased constant String := "RIGHT";
K_99 : aliased constant String := "ROLLBACK";
K_100 : aliased constant String := "ROW";
K_101 : aliased constant String := "SAVEPOINT";
K_102 : aliased constant String := "SELECT";
K_103 : aliased constant String := "SET";
K_104 : aliased constant String := "TABLE";
K_105 : aliased constant String := "TEMP";
K_106 : aliased constant String := "TEMPORARY";
K_107 : aliased constant String := "THEN";
K_108 : aliased constant String := "TO";
K_109 : aliased constant String := "TRANSACTION";
K_110 : aliased constant String := "TRIGGER";
K_111 : aliased constant String := "UNION";
K_112 : aliased constant String := "UNIQUE";
K_113 : aliased constant String := "UPDATE";
K_114 : aliased constant String := "USING";
K_115 : aliased constant String := "VACUUM";
K_116 : aliased constant String := "VALUES";
K_117 : aliased constant String := "VIEW";
K_118 : aliased constant String := "VIRTUAL";
K_119 : aliased constant String := "WHEN";
K_120 : aliased constant String := "WHERE";
Keywords : constant Keyword_Array := (
K_0'Access, K_1'Access, K_2'Access, K_3'Access,
K_4'Access, K_5'Access, K_6'Access, K_7'Access,
K_8'Access, K_9'Access, K_10'Access, K_11'Access,
K_12'Access, K_13'Access, K_14'Access, K_15'Access,
K_16'Access, K_17'Access, K_18'Access, K_19'Access,
K_20'Access, K_21'Access, K_22'Access, K_23'Access,
K_24'Access, K_25'Access, K_26'Access, K_27'Access,
K_28'Access, K_29'Access, K_30'Access, K_31'Access,
K_32'Access, K_33'Access, K_34'Access, K_35'Access,
K_36'Access, K_37'Access, K_38'Access, K_39'Access,
K_40'Access, K_41'Access, K_42'Access, K_43'Access,
K_44'Access, K_45'Access, K_46'Access, K_47'Access,
K_48'Access, K_49'Access, K_50'Access, K_51'Access,
K_52'Access, K_53'Access, K_54'Access, K_55'Access,
K_56'Access, K_57'Access, K_58'Access, K_59'Access,
K_60'Access, K_61'Access, K_62'Access, K_63'Access,
K_64'Access, K_65'Access, K_66'Access, K_67'Access,
K_68'Access, K_69'Access, K_70'Access, K_71'Access,
K_72'Access, K_73'Access, K_74'Access, K_75'Access,
K_76'Access, K_77'Access, K_78'Access, K_79'Access,
K_80'Access, K_81'Access, K_82'Access, K_83'Access,
K_84'Access, K_85'Access, K_86'Access, K_87'Access,
K_88'Access, K_89'Access, K_90'Access, K_91'Access,
K_92'Access, K_93'Access, K_94'Access, K_95'Access,
K_96'Access, K_97'Access, K_98'Access, K_99'Access,
K_100'Access, K_101'Access, K_102'Access, K_103'Access,
K_104'Access, K_105'Access, K_106'Access, K_107'Access,
K_108'Access, K_109'Access, K_110'Access, K_111'Access,
K_112'Access, K_113'Access, K_114'Access, K_115'Access,
K_116'Access, K_117'Access, K_118'Access, K_119'Access,
K_120'Access);
end Sqlite3_H.Perfect_Hash;
|
-- Generated by gperfhash
package Sqlite3_H.Perfect_Hash is
pragma Preelaborate;
function Hash (S : String) return Natural;
-- Returns true if the string <b>S</b> is a keyword.
function Is_Keyword (S : in String) return Boolean;
type Name_Access is access constant String;
type Keyword_Array is array (Natural range <>) of Name_Access;
Keywords : constant Keyword_Array;
private
K_0 : aliased constant String := "ABORT";
K_1 : aliased constant String := "ACTION";
K_2 : aliased constant String := "ADD";
K_3 : aliased constant String := "AFTER";
K_4 : aliased constant String := "ALL";
K_5 : aliased constant String := "ALTER";
K_6 : aliased constant String := "ANALYZE";
K_7 : aliased constant String := "AND";
K_8 : aliased constant String := "AS";
K_9 : aliased constant String := "ASC";
K_10 : aliased constant String := "ATTACH";
K_11 : aliased constant String := "AUTOINCREMENT";
K_12 : aliased constant String := "BEFORE";
K_13 : aliased constant String := "BEGIN";
K_14 : aliased constant String := "BETWEEN";
K_15 : aliased constant String := "BY";
K_16 : aliased constant String := "CASCADE";
K_17 : aliased constant String := "CASE";
K_18 : aliased constant String := "CAST";
K_19 : aliased constant String := "CHECK";
K_20 : aliased constant String := "COLLATE";
K_21 : aliased constant String := "COLUMN";
K_22 : aliased constant String := "COMMIT";
K_23 : aliased constant String := "CONFLICT";
K_24 : aliased constant String := "CONSTRAINT";
K_25 : aliased constant String := "CREATE";
K_26 : aliased constant String := "CROSS";
K_27 : aliased constant String := "CURRENT_DATE";
K_28 : aliased constant String := "CURRENT_TIME";
K_29 : aliased constant String := "CURRENT_TIMESTAMP";
K_30 : aliased constant String := "DATABASE";
K_31 : aliased constant String := "DEFAULT";
K_32 : aliased constant String := "DEFERRABLE";
K_33 : aliased constant String := "DEFERRED";
K_34 : aliased constant String := "DELETE";
K_35 : aliased constant String := "DESC";
K_36 : aliased constant String := "DETACH";
K_37 : aliased constant String := "DISTINCT";
K_38 : aliased constant String := "DROP";
K_39 : aliased constant String := "EACH";
K_40 : aliased constant String := "ELSE";
K_41 : aliased constant String := "END";
K_42 : aliased constant String := "ESCAPE";
K_43 : aliased constant String := "EXCEPT";
K_44 : aliased constant String := "EXCLUSIVE";
K_45 : aliased constant String := "EXISTS";
K_46 : aliased constant String := "EXPLAIN";
K_47 : aliased constant String := "FAIL";
K_48 : aliased constant String := "FOR";
K_49 : aliased constant String := "FOREIGN";
K_50 : aliased constant String := "FROM";
K_51 : aliased constant String := "FULL";
K_52 : aliased constant String := "GLOB";
K_53 : aliased constant String := "GROUP";
K_54 : aliased constant String := "HAVING";
K_55 : aliased constant String := "IF";
K_56 : aliased constant String := "IGNORE";
K_57 : aliased constant String := "IMMEDIATE";
K_58 : aliased constant String := "IN";
K_59 : aliased constant String := "INDEX";
K_60 : aliased constant String := "INDEXED";
K_61 : aliased constant String := "INITIALLY";
K_62 : aliased constant String := "INNER";
K_63 : aliased constant String := "INSERT";
K_64 : aliased constant String := "INSTEAD";
K_65 : aliased constant String := "INTERSECT";
K_66 : aliased constant String := "INTO";
K_67 : aliased constant String := "IS";
K_68 : aliased constant String := "ISNULL";
K_69 : aliased constant String := "JOIN";
K_70 : aliased constant String := "KEY";
K_71 : aliased constant String := "LEFT";
K_72 : aliased constant String := "LIKE";
K_73 : aliased constant String := "LIMIT";
K_74 : aliased constant String := "MATCH";
K_75 : aliased constant String := "NATURAL";
K_76 : aliased constant String := "NO";
K_77 : aliased constant String := "NOT";
K_78 : aliased constant String := "NOTNULL";
K_79 : aliased constant String := "NULL";
K_80 : aliased constant String := "OF";
K_81 : aliased constant String := "OFFSET";
K_82 : aliased constant String := "ON";
K_83 : aliased constant String := "OR";
K_84 : aliased constant String := "ORDER";
K_85 : aliased constant String := "OUTER";
K_86 : aliased constant String := "PLAN";
K_87 : aliased constant String := "PRAGMA";
K_88 : aliased constant String := "PRIMARY";
K_89 : aliased constant String := "QUERY";
K_90 : aliased constant String := "RAISE";
K_91 : aliased constant String := "REFERENCES";
K_92 : aliased constant String := "REGEXP";
K_93 : aliased constant String := "REINDEX";
K_94 : aliased constant String := "RELEASE";
K_95 : aliased constant String := "RENAME";
K_96 : aliased constant String := "REPLACE";
K_97 : aliased constant String := "RESTRICT";
K_98 : aliased constant String := "RIGHT";
K_99 : aliased constant String := "ROLLBACK";
K_100 : aliased constant String := "ROW";
K_101 : aliased constant String := "SAVEPOINT";
K_102 : aliased constant String := "SELECT";
K_103 : aliased constant String := "SET";
K_104 : aliased constant String := "TABLE";
K_105 : aliased constant String := "TEMP";
K_106 : aliased constant String := "TEMPORARY";
K_107 : aliased constant String := "THEN";
K_108 : aliased constant String := "TO";
K_109 : aliased constant String := "TRANSACTION";
K_110 : aliased constant String := "TRIGGER";
K_111 : aliased constant String := "UNION";
K_112 : aliased constant String := "UNIQUE";
K_113 : aliased constant String := "UPDATE";
K_114 : aliased constant String := "USING";
K_115 : aliased constant String := "VACUUM";
K_116 : aliased constant String := "VALUES";
K_117 : aliased constant String := "VIEW";
K_118 : aliased constant String := "VIRTUAL";
K_119 : aliased constant String := "WHEN";
K_120 : aliased constant String := "WHERE";
Keywords : constant Keyword_Array := (
K_0'Access, K_1'Access, K_2'Access, K_3'Access,
K_4'Access, K_5'Access, K_6'Access, K_7'Access,
K_8'Access, K_9'Access, K_10'Access, K_11'Access,
K_12'Access, K_13'Access, K_14'Access, K_15'Access,
K_16'Access, K_17'Access, K_18'Access, K_19'Access,
K_20'Access, K_21'Access, K_22'Access, K_23'Access,
K_24'Access, K_25'Access, K_26'Access, K_27'Access,
K_28'Access, K_29'Access, K_30'Access, K_31'Access,
K_32'Access, K_33'Access, K_34'Access, K_35'Access,
K_36'Access, K_37'Access, K_38'Access, K_39'Access,
K_40'Access, K_41'Access, K_42'Access, K_43'Access,
K_44'Access, K_45'Access, K_46'Access, K_47'Access,
K_48'Access, K_49'Access, K_50'Access, K_51'Access,
K_52'Access, K_53'Access, K_54'Access, K_55'Access,
K_56'Access, K_57'Access, K_58'Access, K_59'Access,
K_60'Access, K_61'Access, K_62'Access, K_63'Access,
K_64'Access, K_65'Access, K_66'Access, K_67'Access,
K_68'Access, K_69'Access, K_70'Access, K_71'Access,
K_72'Access, K_73'Access, K_74'Access, K_75'Access,
K_76'Access, K_77'Access, K_78'Access, K_79'Access,
K_80'Access, K_81'Access, K_82'Access, K_83'Access,
K_84'Access, K_85'Access, K_86'Access, K_87'Access,
K_88'Access, K_89'Access, K_90'Access, K_91'Access,
K_92'Access, K_93'Access, K_94'Access, K_95'Access,
K_96'Access, K_97'Access, K_98'Access, K_99'Access,
K_100'Access, K_101'Access, K_102'Access, K_103'Access,
K_104'Access, K_105'Access, K_106'Access, K_107'Access,
K_108'Access, K_109'Access, K_110'Access, K_111'Access,
K_112'Access, K_113'Access, K_114'Access, K_115'Access,
K_116'Access, K_117'Access, K_118'Access, K_119'Access,
K_120'Access);
end Sqlite3_H.Perfect_Hash;
|
Make the package Preelaborate
|
Make the package Preelaborate
|
Ada
|
apache-2.0
|
Letractively/ada-ado
|
298efaf5a80af1eca0becc70ef6f1619791b1fc5
|
mat/src/gtk/mat-callbacks.ads
|
mat/src/gtk/mat-callbacks.ads
|
-----------------------------------------------------------------------
-- mat-callbacks - Callbacks for Gtk
-- 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 Gtkada.Builder;
with MAT.Targets.Gtkmat;
package MAT.Callbacks is
-- Initialize and register the callbacks.
procedure Initialize (Target : in MAT.Targets.Gtkmat.Target_Type_Access;
Builder : in Gtkada.Builder.Gtkada_Builder);
-- Callback executed when the "quit" action is executed from the menu.
procedure On_Menu_Quit (Object : access Gtkada.Builder.Gtkada_Builder_Record'Class);
-- Callback executed when the "about" action is executed from the menu.
procedure On_Menu_About (Object : access Gtkada.Builder.Gtkada_Builder_Record'Class);
-- Callback executed when the "close-about" action is executed from the about box.
procedure On_Close_About (Object : access Gtkada.Builder.Gtkada_Builder_Record'Class);
end MAT.Callbacks;
|
-----------------------------------------------------------------------
-- mat-callbacks - Callbacks for Gtk
-- 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 Gtkada.Builder;
with MAT.Targets.Gtkmat;
package MAT.Callbacks is
-- Initialize and register the callbacks.
procedure Initialize (Target : in MAT.Targets.Gtkmat.Target_Type_Access;
Builder : in Gtkada.Builder.Gtkada_Builder);
-- Callback executed when the "quit" action is executed from the menu.
procedure On_Menu_Quit (Object : access Gtkada.Builder.Gtkada_Builder_Record'Class);
-- Callback executed when the "about" action is executed from the menu.
procedure On_Menu_About (Object : access Gtkada.Builder.Gtkada_Builder_Record'Class);
-- Callback executed when the "close-about" action is executed from the about box.
procedure On_Close_About (Object : access Gtkada.Builder.Gtkada_Builder_Record'Class);
-- Callback executed when the "cmd-sizes" action is executed from the "Sizes" action.
procedure On_Btn_Sizes (Object : access Gtkada.Builder.Gtkada_Builder_Record'Class);
end MAT.Callbacks;
|
Declare the On_Btn_Sizes procedure
|
Declare the On_Btn_Sizes procedure
|
Ada
|
apache-2.0
|
stcarrez/mat,stcarrez/mat,stcarrez/mat
|
b2840b1e28fd2d5db6f8038738f6742a082547ac
|
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;
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;
|
-----------------------------------------------------------------------
-- volume_server -- Example of server with a servlet
-- Copyright (C) 2010, 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with ASF.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 : constant 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;
|
Fix compilation warnings
|
Fix compilation warnings
|
Ada
|
apache-2.0
|
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
|
51246f5920f93b2e3f1f0484cad4e40863a31656
|
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;
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);
-- 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) 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;
end Load_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;
begin
Log.Info ("Sending invitation to {0}", String '(Invitation.Get_Email));
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 (String '(Invitation.Get_Email));
Email.Find (DB, Query, Found);
if not Found then
Email.Set_User_Id (0);
Email.Set_Email (String '(Invitation.Get_Email));
Email.Save (DB);
Invitee.Set_Email (Email);
Invitee.Set_Name (String '(Invitation.Get_Email));
Invitee.Save (DB);
else
Invitee.Load (DB, Email.Get_User_Id);
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);
Ctx.Commit;
end Send_Invitation;
end AWA.Workspaces.Modules;
|
-----------------------------------------------------------------------
-- 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;
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);
-- 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) 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;
end Load_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;
begin
Log.Info ("Sending invitation to {0}", String '(Invitation.Get_Email));
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 (String '(Invitation.Get_Email));
Email.Find (DB, Query, Found);
if not Found then
Email.Set_User_Id (0);
Email.Set_Email (String '(Invitation.Get_Email));
Email.Save (DB);
Invitee.Set_Email (Email);
Invitee.Set_Name (String '(Invitation.Get_Email));
Invitee.Save (DB);
Email.Set_User_Id (Invitee.Get_Id);
Email.Save (DB);
else
Invitee.Load (DB, Email.Get_User_Id);
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);
Ctx.Commit;
end Send_Invitation;
end AWA.Workspaces.Modules;
|
Fix the email user link
|
Fix the email user link
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
70d4e469234995e51113c5f098947498fa52888f
|
src/orka/implementation/orka-terminals.adb
|
src/orka/implementation/orka-terminals.adb
|
-- 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.Calendar.Formatting;
with Ada.Characters.Latin_1;
with Ada.Real_Time;
with Ada.Strings.Fixed;
with Ada.Text_IO;
with Orka.Strings;
package body Orka.Terminals is
Style_Codes : constant array (Style) of Natural :=
(Default => 0,
Bold => 1,
Dark => 2,
Italic => 3,
Underline => 4,
Blink => 5,
Reversed => 7,
Cross_Out => 9);
Foreground_Color_Codes : constant array (Color) of Natural :=
(Default => 0,
Grey => 30,
Red => 31,
Green => 32,
Yellow => 33,
Blue => 34,
Magenta => 35,
Cyan => 36,
White => 37);
Background_Color_Codes : constant array (Color) of Natural :=
(Default => 0,
Grey => 40,
Red => 41,
Green => 42,
Yellow => 43,
Blue => 44,
Magenta => 45,
Cyan => 46,
White => 47);
package L renames Ada.Characters.Latin_1;
package SF renames Ada.Strings.Fixed;
Reset : constant String := L.ESC & "[0m";
function Sequence (Code : Natural) return String is
Image : constant String := SF.Trim (Code'Image, Ada.Strings.Both);
begin
return (if Code /= 0 then L.ESC & "[" & Image & "m" else "");
end Sequence;
function Colorize (Text : String; Foreground, Background : Color := Default;
Attribute : Style := Default) return String is
FG : constant String := Sequence (Foreground_Color_Codes (Foreground));
BG : constant String := Sequence (Background_Color_Codes (Background));
ST : constant String := Sequence (Style_Codes (Attribute));
begin
return Reset & FG & BG & ST & Text & Reset;
end Colorize;
-----------------------------------------------------------------------------
Time_Zero : constant Ada.Real_Time.Time := Ada.Real_Time.Clock;
Days_Since_Zero : Natural := 0;
function Time_Image return String is
use Ada.Real_Time;
use Ada.Calendar.Formatting;
Hour : Hour_Number;
Minute : Minute_Number;
Second : Second_Number;
Sub_Second : Second_Duration;
Seconds_Since_Zero : Duration := To_Duration (Clock - Time_Zero);
begin
if Seconds_Since_Zero > Ada.Calendar.Day_Duration'Last then
Seconds_Since_Zero := Seconds_Since_Zero - Ada.Calendar.Day_Duration'Last;
Days_Since_Zero := Days_Since_Zero + 1;
end if;
Split (Seconds_Since_Zero, Hour, Minute, Second, Sub_Second);
declare
-- Remove first character (space) from ' hhmmss' image and then pad it to six digits
Image1 : constant String := Natural'Image
((Days_Since_Zero * 24 + Hour) * 1e4 + Minute * 1e2 + Second);
Image2 : constant String := SF.Tail (Image1 (2 .. Image1'Last), 6, '0');
-- Insert ':' characters to get 'hh:mm:ss'
Image3 : constant String := SF.Insert (Image2, 5, ":");
Image4 : constant String := SF.Insert (Image3, 3, ":");
-- Take image without first character (space) and then pad it to six digits
Image5 : constant String := Natural'Image (Natural (Sub_Second * 1e6));
Image6 : constant String := SF.Tail (Image5 (2 .. Image5'Last), 6, '0');
begin
return Image4 & "." & Image6;
end;
end Time_Image;
package Duration_IO is new Ada.Text_IO.Fixed_IO (Duration);
type String_Access is not null access String;
Suffices : constant array (1 .. 3) of String_Access
:= (new String'("s"),
new String'("ms"),
new String'("us"));
Last_Suffix : constant String_Access := Suffices (Suffices'Last);
function Image (Value : Duration) return String is
Result : String := "-9999.999";
Number : Duration := Value;
Suffix : String_Access := Suffices (Suffices'First);
begin
for S of Suffices loop
Suffix := S;
exit when Number >= 1.0 or else Number <= -1.0 or else S = Last_Suffix;
Number := Number * 1e3;
end loop;
begin
Duration_IO.Put (Result, Item => Number, Aft => 3);
exception
when others =>
return Number'Image & " " & Suffix.all;
end;
return Result & " " & Suffix.all;
end Image;
function Trim (Value : String) return String renames Orka.Strings.Trim;
function Strip_Line_Term (Value : String) return String renames Orka.Strings.Strip_Line_Term;
end Orka.Terminals;
|
-- 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.Calendar.Formatting;
with Ada.Characters.Latin_1;
with Ada.Strings.Fixed;
with Ada.Text_IO;
with Orka.OS;
with Orka.Strings;
package body Orka.Terminals is
Style_Codes : constant array (Style) of Natural :=
(Default => 0,
Bold => 1,
Dark => 2,
Italic => 3,
Underline => 4,
Blink => 5,
Reversed => 7,
Cross_Out => 9);
Foreground_Color_Codes : constant array (Color) of Natural :=
(Default => 0,
Grey => 30,
Red => 31,
Green => 32,
Yellow => 33,
Blue => 34,
Magenta => 35,
Cyan => 36,
White => 37);
Background_Color_Codes : constant array (Color) of Natural :=
(Default => 0,
Grey => 40,
Red => 41,
Green => 42,
Yellow => 43,
Blue => 44,
Magenta => 45,
Cyan => 46,
White => 47);
package L renames Ada.Characters.Latin_1;
package SF renames Ada.Strings.Fixed;
Reset : constant String := L.ESC & "[0m";
function Sequence (Code : Natural) return String is
Image : constant String := SF.Trim (Code'Image, Ada.Strings.Both);
begin
return (if Code /= 0 then L.ESC & "[" & Image & "m" else "");
end Sequence;
function Colorize (Text : String; Foreground, Background : Color := Default;
Attribute : Style := Default) return String is
FG : constant String := Sequence (Foreground_Color_Codes (Foreground));
BG : constant String := Sequence (Background_Color_Codes (Background));
ST : constant String := Sequence (Style_Codes (Attribute));
begin
return Reset & FG & BG & ST & Text & Reset;
end Colorize;
-----------------------------------------------------------------------------
Time_Zero : constant Duration := Orka.OS.Monotonic_Clock;
Days_Since_Zero : Natural := 0;
function Time_Image return String is
use Ada.Calendar.Formatting;
Hour : Hour_Number;
Minute : Minute_Number;
Second : Second_Number;
Sub_Second : Second_Duration;
Seconds_Since_Zero : Duration := Orka.OS.Monotonic_Clock - Time_Zero;
begin
if Seconds_Since_Zero > Ada.Calendar.Day_Duration'Last then
Seconds_Since_Zero := Seconds_Since_Zero - Ada.Calendar.Day_Duration'Last;
Days_Since_Zero := Days_Since_Zero + 1;
end if;
Split (Seconds_Since_Zero, Hour, Minute, Second, Sub_Second);
declare
-- Remove first character (space) from ' hhmmss' image and then pad it to six digits
Image1 : constant String := Natural'Image
((Days_Since_Zero * 24 + Hour) * 1e4 + Minute * 1e2 + Second);
Image2 : constant String := SF.Tail (Image1 (2 .. Image1'Last), 6, '0');
-- Insert ':' characters to get 'hh:mm:ss'
Image3 : constant String := SF.Insert (Image2, 5, ":");
Image4 : constant String := SF.Insert (Image3, 3, ":");
-- Take image without first character (space) and then pad it to six digits
Image5 : constant String := Natural'Image (Natural (Sub_Second * 1e6));
Image6 : constant String := SF.Tail (Image5 (2 .. Image5'Last), 6, '0');
begin
return Image4 & "." & Image6;
end;
end Time_Image;
package Duration_IO is new Ada.Text_IO.Fixed_IO (Duration);
type String_Access is not null access String;
Suffices : constant array (1 .. 3) of String_Access
:= (new String'("s"),
new String'("ms"),
new String'("us"));
Last_Suffix : constant String_Access := Suffices (Suffices'Last);
function Image (Value : Duration) return String is
Result : String := "-9999.999";
Number : Duration := Value;
Suffix : String_Access := Suffices (Suffices'First);
begin
for S of Suffices loop
Suffix := S;
exit when Number >= 1.0 or else Number <= -1.0 or else S = Last_Suffix;
Number := Number * 1e3;
end loop;
begin
Duration_IO.Put (Result, Item => Number, Aft => 3);
exception
when others =>
return Number'Image & " " & Suffix.all;
end;
return Result & " " & Suffix.all;
end Image;
function Trim (Value : String) return String renames Orka.Strings.Trim;
function Strip_Line_Term (Value : String) return String renames Orka.Strings.Strip_Line_Term;
end Orka.Terminals;
|
Use monotonic clock in function Time_Image
|
orka: Use monotonic clock in function Time_Image
Signed-off-by: onox <[email protected]>
|
Ada
|
apache-2.0
|
onox/orka
|
fe656db70f74b5877fe787c27983312e34be013b
|
src/ado-drivers.ads
|
src/ado-drivers.ads
|
-----------------------------------------------------------------------
-- ADO Drivers -- Database Drivers
-- Copyright (C) 2010, 2011, 2012, 2013 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Properties;
-- The <b>ADO.Drivers</b> package represents the database driver that will create
-- database connections and provide the database specific implementation.
package ADO.Drivers is
use Ada.Strings.Unbounded;
-- Raised when the connection URI is invalid.
Connection_Error : exception;
-- Raised for all errors reported by the database
DB_Error : exception;
type Driver_Index is new Natural range 0 .. 4;
-- Initialize the drivers and the library by reading the property file
-- and configure the runtime with it.
procedure Initialize (Config : in String);
-- Initialize the drivers and the library and configure the runtime with the given properties.
procedure Initialize (Config : in Util.Properties.Manager'Class);
-- Get the global configuration property identified by the name.
-- If the configuration property does not exist, returns the default value.
function Get_Config (Name : in String;
Default : in String := "") return String;
end ADO.Drivers;
|
-----------------------------------------------------------------------
-- ADO Drivers -- Database Drivers
-- Copyright (C) 2010, 2011, 2012, 2013 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Properties;
-- == Introduction ==
-- The <b>ADO.Drivers</b> package represents the database driver that will create
-- database connections and provide the database specific implementation. The driver
-- is either statically linked to the application and can be loaded dynamically if it was
-- built as a shared library. For a dynamic load, the driver shared library name must be
-- prefixed by <b>libada_ado_</b>. For example, for a <tt>mysql</tt> driver, the shared
-- library name is <tt>libada_ado_mysql.so</tt>.
--
-- === Initialization ===
-- The <b>ADO</b> runtime must be initialized by calling one of the <b>Initialize</b> operation.
-- A property file contains the configuration for the database drivers and the database
-- connection properties.
--
-- ADO.Drivers.Initialize ("db.properties");
--
-- Once initialized, a configuration property can be retrieved by using the <tt>Get_Config</tt>
-- operation.
--
-- URI : constant String := ADO.Drivers.Get_Config ("ado.database");
--
-- === Connection string ===
-- The database connection string is an URI that specifies the database driver to use as well
-- as the information for the database driver to connect to the database.
-- The driver connection is a string of the form:
--
-- driver://[host][:port]/[database][?property1][=value1]...
--
-- The database connection string is passed to the session factory that maintains connections
-- to the database (see ADO.Sessions.Factory).
--
package ADO.Drivers is
use Ada.Strings.Unbounded;
-- Raised when the connection URI is invalid.
Connection_Error : exception;
-- Raised for all errors reported by the database
DB_Error : exception;
type Driver_Index is new Natural range 0 .. 4;
-- Initialize the drivers and the library by reading the property file
-- and configure the runtime with it.
procedure Initialize (Config : in String);
-- Initialize the drivers and the library and configure the runtime with the given properties.
procedure Initialize (Config : in Util.Properties.Manager'Class);
-- Get the global configuration property identified by the name.
-- If the configuration property does not exist, returns the default value.
function Get_Config (Name : in String;
Default : in String := "") return String;
end ADO.Drivers;
|
Add some documentation on database drivers
|
Add some documentation on database drivers
|
Ada
|
apache-2.0
|
stcarrez/ada-ado
|
abb98127c9a3db305cf5cd5b9455806d4278e366
|
src/util-dates.adb
|
src/util-dates.adb
|
-----------------------------------------------------------------------
-- util-dates -- Date utilities
-- 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.
-----------------------------------------------------------------------
package body Util.Dates is
-- ------------------------------
-- Split the date into a date record (See Ada.Calendar.Formatting.Split).
-- ------------------------------
procedure Split (Into : out Date_Record;
Date : in Ada.Calendar.Time;
Time_Zone : in Ada.Calendar.Time_Zones.Time_Offset := 0) is
use Ada.Calendar;
D : Ada.Calendar.Time := Date;
begin
Into.Date := Date;
Into.Time_Zone := Time_Zone;
Ada.Calendar.Formatting.Split (Date => Date,
Year => Into.Year,
Month => Into.Month,
Day => Into.Month_Day,
Hour => Into.Hour,
Minute => Into.Minute,
Second => Into.Second,
Sub_Second => Into.Sub_Second,
Leap_Second => Into.Leap_Second,
Time_Zone => Time_Zone);
-- The Day_Of_Week function uses the local timezone to find the week day.
-- The wrong day is computed if the timezone is different. If the current
-- date is 23:30 GMT and the current system timezone is GMT+2, then the computed
-- day of week will be the next day due to the +2 hour offset (01:30 AM).
-- To avoid the timezone issue, we virtually force the hour to 12:00 am.
if Into.Hour > 12 then
D := D - Duration ((Into.Hour - 12) * 3600);
elsif Into.Hour < 12 then
D := D + Duration ((12 - Into.Hour) * 3600);
end if;
D := D - Duration ((60 - Into.Minute) * 60);
Into.Day := Ada.Calendar.Formatting.Day_Of_Week (D);
end Split;
-- ------------------------------
-- Returns true if the given year is a leap year.
-- ------------------------------
function Is_Leap_Year (Year : in Ada.Calendar.Year_Number) return Boolean is
begin
if Year mod 400 = 0 then
return True;
elsif Year mod 100 = 0 then
return False;
elsif Year mod 4 = 0 then
return True;
else
return False;
end if;
end Is_Leap_Year;
-- ------------------------------
-- Get the number of days in the given year.
-- ------------------------------
function Get_Day_Count (Year : in Ada.Calendar.Year_Number)
return Ada.Calendar.Arithmetic.Day_Count is
begin
if Is_Leap_Year (Year) then
return 365;
else
return 366;
end if;
end Get_Day_Count;
Month_Day_Count : constant array (Ada.Calendar.Month_Number)
of Ada.Calendar.Arithmetic.Day_Count
:= (1 => 31, 2 => 28, 3 => 31, 4 => 30, 5 => 31, 6 => 30,
7 => 31, 8 => 31, 9 => 30, 10 => 31, 11 => 30, 12 => 31);
-- ------------------------------
-- Get the number of days in the given month.
-- ------------------------------
function Get_Day_Count (Year : in Ada.Calendar.Year_Number;
Month : in Ada.Calendar.Month_Number)
return Ada.Calendar.Arithmetic.Day_Count is
begin
if Month /= 2 then
return Month_Day_Count (Month);
elsif Is_Leap_Year (Year) then
return 29;
else
return 28;
end if;
end Get_Day_Count;
-- ------------------------------
-- Get a time representing the given date at 00:00:00.
-- ------------------------------
function Get_Day_Start (Date : in Date_Record) return Ada.Calendar.Time is
begin
return Ada.Calendar.Formatting.Time_Of (Year => Date.Year,
Month => Date.Month,
Day => Date.Month_Day,
Hour => 0,
Minute => 0,
Second => 0,
Sub_Second => 0.0,
Time_Zone => Date.Time_Zone);
end Get_Day_Start;
function Get_Day_Start (Date : in Ada.Calendar.Time) return Ada.Calendar.Time is
D : Date_Record;
begin
Split (D, Date);
return Get_Day_Start (D);
end Get_Day_Start;
-- ------------------------------
-- Get a time representing the given date at 23:59:59.
-- ------------------------------
function Get_Day_End (Date : in Date_Record) return Ada.Calendar.Time is
begin
return Ada.Calendar.Formatting.Time_Of (Year => Date.Year,
Month => Date.Month,
Day => Date.Month_Day,
Hour => 23,
Minute => 59,
Second => 59,
Sub_Second => 0.999,
Time_Zone => Date.Time_Zone);
end Get_Day_End;
function Get_Day_End (Date : in Ada.Calendar.Time) return Ada.Calendar.Time is
D : Date_Record;
begin
Split (D, Date);
return Get_Day_End (D);
end Get_Day_End;
-- ------------------------------
-- Get a time representing the beginning of the week at 00:00:00.
-- ------------------------------
function Get_Week_Start (Date : in Date_Record) return Ada.Calendar.Time is
use Ada.Calendar.Formatting;
use Ada.Calendar.Arithmetic;
T : constant Ada.Calendar.Time := Time_Of (Year => Date.Year,
Month => Date.Month,
Day => Date.Month_Day,
Hour => 0,
Minute => 0,
Second => 0,
Sub_Second => 0.0,
Time_Zone => Date.Time_Zone);
begin
if Date.Day = Ada.Calendar.Formatting.Monday then
return T;
else
return T - Day_Count (Day_Name'Pos (Date.Day) - Day_Name'Pos (Monday));
end if;
end Get_Week_Start;
function Get_Week_Start (Date : in Ada.Calendar.Time) return Ada.Calendar.Time is
D : Date_Record;
begin
Split (D, Date);
return Get_Week_Start (D);
end Get_Week_Start;
-- ------------------------------
-- Get a time representing the end of the week at 23:59:99.
-- ------------------------------
function Get_Week_End (Date : in Date_Record) return Ada.Calendar.Time is
use Ada.Calendar.Formatting;
use Ada.Calendar.Arithmetic;
T : constant Ada.Calendar.Time := Time_Of (Year => Date.Year,
Month => Date.Month,
Day => Date.Month_Day,
Hour => 23,
Minute => 59,
Second => 59,
Sub_Second => 0.999,
Time_Zone => Date.Time_Zone);
begin
-- End of week is 6 days + 23:59:59
if Date.Day = Ada.Calendar.Formatting.Sunday then
return T;
else
return T + Day_Count (6 - (Day_Name'Pos (Date.Day) - Day_Name'Pos (Monday)));
end if;
end Get_Week_End;
function Get_Week_End (Date : in Ada.Calendar.Time) return Ada.Calendar.Time is
D : Date_Record;
begin
Split (D, Date);
return Get_Week_End (D);
end Get_Week_End;
-- ------------------------------
-- Get a time representing the beginning of the month at 00:00:00.
-- ------------------------------
function Get_Month_Start (Date : in Date_Record) return Ada.Calendar.Time is
begin
return Ada.Calendar.Formatting.Time_Of (Year => Date.Year,
Month => Date.Month,
Day => Ada.Calendar.Day_Number'First,
Hour => 0,
Minute => 0,
Second => 0,
Sub_Second => 0.0,
Time_Zone => Date.Time_Zone);
end Get_Month_Start;
function Get_Month_Start (Date : in Ada.Calendar.Time) return Ada.Calendar.Time is
D : Date_Record;
begin
Split (D, Date);
return Get_Month_Start (D);
end Get_Month_Start;
-- ------------------------------
-- Get a time representing the end of the month at 23:59:59.
-- ------------------------------
function Get_Month_End (Date : in Date_Record) return Ada.Calendar.Time is
Last_Day : constant Ada.Calendar.Day_Number
:= Ada.Calendar.Day_Number (Get_Day_Count (Date.Year, Date.Month));
begin
return Ada.Calendar.Formatting.Time_Of (Year => Date.Year,
Month => Date.Month,
Day => Last_Day,
Hour => 23,
Minute => 59,
Second => 59,
Sub_Second => 0.999,
Time_Zone => Date.Time_Zone);
end Get_Month_End;
function Get_Month_End (Date : in Ada.Calendar.Time) return Ada.Calendar.Time is
D : Date_Record;
begin
Split (D, Date);
return Get_Month_End (D);
end Get_Month_End;
end Util.Dates;
|
-----------------------------------------------------------------------
-- util-dates -- Date utilities
-- Copyright (C) 2011, 2013, 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.
-----------------------------------------------------------------------
package body Util.Dates is
-- ------------------------------
-- Split the date into a date record (See Ada.Calendar.Formatting.Split).
-- ------------------------------
procedure Split (Into : out Date_Record;
Date : in Ada.Calendar.Time;
Time_Zone : in Ada.Calendar.Time_Zones.Time_Offset := 0) is
use Ada.Calendar;
D : Ada.Calendar.Time := Date;
begin
Into.Date := Date;
Into.Time_Zone := Time_Zone;
Ada.Calendar.Formatting.Split (Date => Date,
Year => Into.Year,
Month => Into.Month,
Day => Into.Month_Day,
Hour => Into.Hour,
Minute => Into.Minute,
Second => Into.Second,
Sub_Second => Into.Sub_Second,
Leap_Second => Into.Leap_Second,
Time_Zone => Time_Zone);
-- The Day_Of_Week function uses the local timezone to find the week day.
-- The wrong day is computed if the timezone is different. If the current
-- date is 23:30 GMT and the current system timezone is GMT+2, then the computed
-- day of week will be the next day due to the +2 hour offset (01:30 AM).
-- To avoid the timezone issue, we virtually force the hour to 12:00 am.
if Into.Hour > 12 then
D := D - Duration ((Into.Hour - 12) * 3600);
elsif Into.Hour < 12 then
D := D + Duration ((12 - Into.Hour) * 3600);
end if;
D := D - Duration ((60 - Into.Minute) * 60);
Into.Day := Ada.Calendar.Formatting.Day_Of_Week (D);
end Split;
-- ------------------------------
-- Return the date from the date record (See Ada.Calendar.Formatting.Time_Of).
-- ------------------------------
function Time_Of (Date : in Date_Record) return Ada.Calendar.Time is
begin
return Ada.Calendar.Formatting.Time_Of (Year => Date.Year,
Month => Date.Month,
Day => Date.Month_Day,
Hour => Date.Hour,
Minute => Date.Minute,
Second => Date.Second,
Sub_Second => Date.Sub_Second,
Time_Zone => Date.Time_Zone);
end Time_Of;
-- ------------------------------
-- Returns true if the given year is a leap year.
-- ------------------------------
function Is_Leap_Year (Year : in Ada.Calendar.Year_Number) return Boolean is
begin
if Year mod 400 = 0 then
return True;
elsif Year mod 100 = 0 then
return False;
elsif Year mod 4 = 0 then
return True;
else
return False;
end if;
end Is_Leap_Year;
-- ------------------------------
-- Get the number of days in the given year.
-- ------------------------------
function Get_Day_Count (Year : in Ada.Calendar.Year_Number)
return Ada.Calendar.Arithmetic.Day_Count is
begin
if Is_Leap_Year (Year) then
return 365;
else
return 366;
end if;
end Get_Day_Count;
Month_Day_Count : constant array (Ada.Calendar.Month_Number)
of Ada.Calendar.Arithmetic.Day_Count
:= (1 => 31, 2 => 28, 3 => 31, 4 => 30, 5 => 31, 6 => 30,
7 => 31, 8 => 31, 9 => 30, 10 => 31, 11 => 30, 12 => 31);
-- ------------------------------
-- Get the number of days in the given month.
-- ------------------------------
function Get_Day_Count (Year : in Ada.Calendar.Year_Number;
Month : in Ada.Calendar.Month_Number)
return Ada.Calendar.Arithmetic.Day_Count is
begin
if Month /= 2 then
return Month_Day_Count (Month);
elsif Is_Leap_Year (Year) then
return 29;
else
return 28;
end if;
end Get_Day_Count;
-- ------------------------------
-- Get a time representing the given date at 00:00:00.
-- ------------------------------
function Get_Day_Start (Date : in Date_Record) return Ada.Calendar.Time is
begin
return Ada.Calendar.Formatting.Time_Of (Year => Date.Year,
Month => Date.Month,
Day => Date.Month_Day,
Hour => 0,
Minute => 0,
Second => 0,
Sub_Second => 0.0,
Time_Zone => Date.Time_Zone);
end Get_Day_Start;
function Get_Day_Start (Date : in Ada.Calendar.Time) return Ada.Calendar.Time is
D : Date_Record;
begin
Split (D, Date);
return Get_Day_Start (D);
end Get_Day_Start;
-- ------------------------------
-- Get a time representing the given date at 23:59:59.
-- ------------------------------
function Get_Day_End (Date : in Date_Record) return Ada.Calendar.Time is
begin
return Ada.Calendar.Formatting.Time_Of (Year => Date.Year,
Month => Date.Month,
Day => Date.Month_Day,
Hour => 23,
Minute => 59,
Second => 59,
Sub_Second => 0.999,
Time_Zone => Date.Time_Zone);
end Get_Day_End;
function Get_Day_End (Date : in Ada.Calendar.Time) return Ada.Calendar.Time is
D : Date_Record;
begin
Split (D, Date);
return Get_Day_End (D);
end Get_Day_End;
-- ------------------------------
-- Get a time representing the beginning of the week at 00:00:00.
-- ------------------------------
function Get_Week_Start (Date : in Date_Record) return Ada.Calendar.Time is
use Ada.Calendar.Formatting;
use Ada.Calendar.Arithmetic;
T : constant Ada.Calendar.Time := Time_Of (Year => Date.Year,
Month => Date.Month,
Day => Date.Month_Day,
Hour => 0,
Minute => 0,
Second => 0,
Sub_Second => 0.0,
Time_Zone => Date.Time_Zone);
begin
if Date.Day = Ada.Calendar.Formatting.Monday then
return T;
else
return T - Day_Count (Day_Name'Pos (Date.Day) - Day_Name'Pos (Monday));
end if;
end Get_Week_Start;
function Get_Week_Start (Date : in Ada.Calendar.Time) return Ada.Calendar.Time is
D : Date_Record;
begin
Split (D, Date);
return Get_Week_Start (D);
end Get_Week_Start;
-- ------------------------------
-- Get a time representing the end of the week at 23:59:99.
-- ------------------------------
function Get_Week_End (Date : in Date_Record) return Ada.Calendar.Time is
use Ada.Calendar.Formatting;
use Ada.Calendar.Arithmetic;
T : constant Ada.Calendar.Time := Time_Of (Year => Date.Year,
Month => Date.Month,
Day => Date.Month_Day,
Hour => 23,
Minute => 59,
Second => 59,
Sub_Second => 0.999,
Time_Zone => Date.Time_Zone);
begin
-- End of week is 6 days + 23:59:59
if Date.Day = Ada.Calendar.Formatting.Sunday then
return T;
else
return T + Day_Count (6 - (Day_Name'Pos (Date.Day) - Day_Name'Pos (Monday)));
end if;
end Get_Week_End;
function Get_Week_End (Date : in Ada.Calendar.Time) return Ada.Calendar.Time is
D : Date_Record;
begin
Split (D, Date);
return Get_Week_End (D);
end Get_Week_End;
-- ------------------------------
-- Get a time representing the beginning of the month at 00:00:00.
-- ------------------------------
function Get_Month_Start (Date : in Date_Record) return Ada.Calendar.Time is
begin
return Ada.Calendar.Formatting.Time_Of (Year => Date.Year,
Month => Date.Month,
Day => Ada.Calendar.Day_Number'First,
Hour => 0,
Minute => 0,
Second => 0,
Sub_Second => 0.0,
Time_Zone => Date.Time_Zone);
end Get_Month_Start;
function Get_Month_Start (Date : in Ada.Calendar.Time) return Ada.Calendar.Time is
D : Date_Record;
begin
Split (D, Date);
return Get_Month_Start (D);
end Get_Month_Start;
-- ------------------------------
-- Get a time representing the end of the month at 23:59:59.
-- ------------------------------
function Get_Month_End (Date : in Date_Record) return Ada.Calendar.Time is
Last_Day : constant Ada.Calendar.Day_Number
:= Ada.Calendar.Day_Number (Get_Day_Count (Date.Year, Date.Month));
begin
return Ada.Calendar.Formatting.Time_Of (Year => Date.Year,
Month => Date.Month,
Day => Last_Day,
Hour => 23,
Minute => 59,
Second => 59,
Sub_Second => 0.999,
Time_Zone => Date.Time_Zone);
end Get_Month_End;
function Get_Month_End (Date : in Ada.Calendar.Time) return Ada.Calendar.Time is
D : Date_Record;
begin
Split (D, Date);
return Get_Month_End (D);
end Get_Month_End;
end Util.Dates;
|
Implement Time_Of function
|
Implement Time_Of function
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
a9b53e90aed8433994684f1bada7868f68917d61
|
symbolica/ada/src/Symbolica.adb
|
symbolica/ada/src/Symbolica.adb
|
with Ada.Text_IO;
with Ada.Command_Line;
procedure Symbolica is
NumColors : constant := 4;
NumSymbols : constant := 3;
Length : constant := 5;
Width : constant := 5;
package IO renames Ada.Text_IO;
type Color_T is new Natural range 0 .. NumColors - 1;
type Symbol_T is new Natural range 0 .. NumSymbols - 1;
type Column_T is new Natural range 1 .. Length;
type Row_T is new Natural range 1 .. Width;
type Tile_T is record
Color : Color_T;
Symbol : Symbol_T;
end record;
type Board_T is Array(Row_T, Column_T) of Tile_T;
type Count_T is Array(Color_T, Symbol_T) of Natural;
colors : constant Array(Color_T) of Character := ('R', 'B', 'G', 'Y');
symbols : constant Array(Symbol_T) of Character := ('a', 'g', 'c');
original_board, best_board, board : Board_T;
best_distance : Natural := Length * Width;
total_solutions : Natural := 0;
iterations : Natural := 0;
tile_count : Count_T := (others => (others => 0));
Not_In : exception;
function GetColor(c: Character) return Color_T is
begin
for color in Color_T'Range loop
if colors(color) = c then
return color;
end if;
end loop;
raise Not_In;
end GetColor;
function GetSymbol(s: Character) return Symbol_T is
begin
for symbol in Symbol_T'Range loop
if symbols(symbol) = s then
return symbol;
end if;
end loop;
raise Not_In;
end GetSymbol;
function TileImage(tile : Tile_T) return String is
begin
return (colors(tile.Color), symbols(tile.Symbol));
end TileImage;
procedure PrintBoard(b : Board_T) is
begin
for r in Row_T loop
for c in Column_T loop
IO.Put(TileImage(b(r,c)) & " ");
end loop;
IO.New_Line;
end loop;
end PrintBoard;
procedure ReadBoard(filename: in String; b : out Board_T) is
f : IO.File_Type;
c,s : Character;
eol : Boolean;
begin
IO.Open(f, IO.In_File, filename);
for row in Row_T'Range loop
for col in Column_T'Range loop
IO.Get(f, c);
IO.Get(f, s);
b(row, col) := (GetColor(c), GetSymbol(s));
loop
IO.Look_Ahead(f,c,eol);
exit when eol or else c /= ' ';
IO.Get(f, c);
end loop;
end loop;
end loop;
IO.Put_Line("Read in original Board");
PrintBoard(b);
end ReadBoard;
procedure CompareBoards is
distance : Natural := 0;
chain : Natural := 0;
waiting : Array(Color_T, Symbol_T, Color_T, Symbol_T) of Natural := (others => (others => (others => (others => 0))));
begin
total_solutions := total_solutions + 1;
for row in Row_T'Range loop
for col in Column_T'Range loop
declare
o : Tile_T renames original_board(row, col);
b : Tile_T renames board(row, col);
w : natural renames waiting(o.Color, o.Symbol, b.Color, b.Symbol);
ow : natural renames waiting(b.Color, b.Symbol, o.Color, o.Symbol);
begin
if o.Color /= b.Color or else o.Symbol /= b.Symbol then
if ow > 0 then
ow := ow - 1;
chain := chain - 1;
distance := distance + 1;
else
chain := chain + 1;
w := w + 1;
end if;
end if;
end;
end loop;
end loop;
if chain > 0 then
distance := distance + chain - 1;
end if;
if distance < best_distance then
best_board := board;
best_distance := distance;
end if;
end CompareBoards;
procedure Solve(row : Row_T; col : Column_T) is
procedure NextSolve(c : Color_T; s : Symbol_T) is
tc : Natural renames tile_count(c, s);
begin
if tc = 0 then
return;
end if;
board(row, col) := (c, s);
if col = Column_T'Last then
if row = Row_T'Last then
CompareBoards;
else
tc := tc - 1;
Solve(row + 1, 1);
tc := tc + 1;
end if;
else
tc := tc - 1;
Solve(row, col + 1);
tc := tc + 1;
end if;
end NextSolve;
pragma inline(NextSolve);
begin
iterations := iterations + 1;
if row = 1 then
declare
left : Tile_T renames board(row, col - 1);
begin
for color in Color_T'Range loop
if color /= left.Color then
NextSolve(color, left.Symbol);
end if;
end loop;
for symbol in Symbol_T'Range loop
if symbol /= left.Symbol then
NextSolve(left.Color, symbol);
end if;
end loop;
end;
elsif col = 1 then
declare
above : Tile_T renames board(row - 1, col);
begin
for color in Color_T'Range loop
if color /= above.Color then
NextSolve(color, above.Symbol);
end if;
end loop;
for symbol in Symbol_T'Range loop
if symbol /= above.Symbol then
NextSolve(above.Color, symbol);
end if;
end loop;
end;
else
declare
left : Tile_T renames board(row, col -1);
above : Tile_T renames board(row - 1, col);
begin
if left.Color = above.Color then
for symbol in Symbol_T'Range loop
if symbol /= left.Symbol and then symbol /= above.Symbol then
NextSolve(left.Color, symbol);
end if;
end loop;
elsif left.Symbol = above.Symbol then
for color in Color_T'Range loop
if color /= left.Color and then color /= above.Color then
NextSolve(color, left.Symbol);
end if;
end loop;
else
NextSolve(left.Color, above.Symbol);
NextSolve(above.Color, left.Symbol);
end if;
end;
end if;
end Solve;
begin
ReadBoard(Ada.Command_Line.Argument(1), original_board);
for row in Row_T'Range loop
for col in Column_T'Range loop
declare
tile : constant Tile_T := original_board(row, col);
begin
tile_count(tile.Color, tile.Symbol) := tile_count(tile.Color, tile.Symbol) + 1;
end;
end loop;
end loop;
for color in Color_T'Range loop
for symbol in Symbol_T'Range loop
board(1, 1) := (color, symbol);
Solve(1, 2);
end loop;
end loop;
IO.Put_Line("Total Iterations" & Natural'Image(iterations));
IO.Put_Line("Total Solutions found:" & Natural'Image(total_solutions));
IO.Put_Line("Total Swaps: " & Natural'Image(best_distance));
PrintBoard(best_board);
end Symbolica;
|
with Ada.Text_IO;
with Ada.Command_Line;
procedure Symbolica is
NumColors : constant := 4;
NumSymbols : constant := 3;
Length : constant := 5;
Width : constant := 5;
package IO renames Ada.Text_IO;
type Color_T is new Natural range 0 .. NumColors - 1;
type Symbol_T is new Natural range 0 .. NumSymbols - 1;
type Column_T is new Natural range 1 .. Length;
type Row_T is new Natural range 1 .. Width;
type Tile_T is record
Color : Color_T;
Symbol : Symbol_T;
end record;
type Board_T is Array(Row_T, Column_T) of Tile_T;
type Count_T is Array(Color_T, Symbol_T) of Natural;
colors : constant Array(Color_T) of Character := ('R', 'B', 'G', 'Y');
symbols : constant Array(Symbol_T) of Character := ('a', 'g', 'c');
original_board, best_board, board : Board_T;
best_distance : Natural := Length * Width;
total_solutions : Natural := 0;
iterations : Natural := 0;
tile_count : Count_T := (others => (others => 0));
function TileImage(tile : Tile_T) return String is
begin
return (colors(tile.Color), symbols(tile.Symbol));
end TileImage;
procedure PrintBoard(b : Board_T) is
begin
for r in Row_T loop
for c in Column_T loop
IO.Put(TileImage(b(r,c)) & " ");
end loop;
IO.New_Line;
end loop;
end PrintBoard;
procedure ReadBoard(filename: in String; b : out Board_T) is
Not_In : exception;
function GetColor(c: Character) return Color_T is
begin
for color in Color_T'Range loop
if colors(color) = c then
return color;
end if;
end loop;
raise Not_In;
end GetColor;
function GetSymbol(s: Character) return Symbol_T is
begin
for symbol in Symbol_T'Range loop
if symbols(symbol) = s then
return symbol;
end if;
end loop;
raise Not_In;
end GetSymbol;
f : IO.File_Type;
c,s : Character;
eol : Boolean;
begin
IO.Open(f, IO.In_File, filename);
for row in Row_T'Range loop
for col in Column_T'Range loop
IO.Get(f, c);
IO.Get(f, s);
b(row, col) := (GetColor(c), GetSymbol(s));
loop
IO.Look_Ahead(f,c,eol);
exit when eol or else c /= ' ';
IO.Get(f, c);
end loop;
end loop;
end loop;
IO.Put_Line("Read in original Board");
PrintBoard(b);
end ReadBoard;
procedure CompareBoards is
distance : Natural := 0;
chain : Natural := 0;
waiting : Array(Color_T, Symbol_T, Color_T, Symbol_T) of Natural := (others => (others => (others => (others => 0))));
begin
total_solutions := total_solutions + 1;
for row in Row_T'Range loop
for col in Column_T'Range loop
declare
o : Tile_T renames original_board(row, col);
b : Tile_T renames board(row, col);
w : natural renames waiting(o.Color, o.Symbol, b.Color, b.Symbol);
ow : natural renames waiting(b.Color, b.Symbol, o.Color, o.Symbol);
begin
if o.Color /= b.Color or else o.Symbol /= b.Symbol then
if ow > 0 then
ow := ow - 1;
chain := chain - 1;
distance := distance + 1;
else
chain := chain + 1;
w := w + 1;
end if;
end if;
end;
end loop;
end loop;
if chain > 0 then
distance := distance + chain - 1;
end if;
if distance < best_distance then
best_board := board;
best_distance := distance;
end if;
end CompareBoards;
procedure Solve(row : Row_T; col : Column_T) is
procedure NextSolve(c : Color_T; s : Symbol_T) is
tc : Natural renames tile_count(c, s);
begin
if tc = 0 then
return;
end if;
board(row, col) := (c, s);
if col = Column_T'Last then
if row = Row_T'Last then
CompareBoards;
else
tc := tc - 1;
Solve(row + 1, 1);
tc := tc + 1;
end if;
else
tc := tc - 1;
Solve(row, col + 1);
tc := tc + 1;
end if;
end NextSolve;
pragma inline(NextSolve);
begin
iterations := iterations + 1;
if row = 1 then
declare
left : Tile_T renames board(row, col - 1);
begin
for color in Color_T'Range loop
if color /= left.Color then
NextSolve(color, left.Symbol);
end if;
end loop;
for symbol in Symbol_T'Range loop
if symbol /= left.Symbol then
NextSolve(left.Color, symbol);
end if;
end loop;
end;
elsif col = 1 then
declare
above : Tile_T renames board(row - 1, col);
begin
for color in Color_T'Range loop
if color /= above.Color then
NextSolve(color, above.Symbol);
end if;
end loop;
for symbol in Symbol_T'Range loop
if symbol /= above.Symbol then
NextSolve(above.Color, symbol);
end if;
end loop;
end;
else
declare
left : Tile_T renames board(row, col -1);
above : Tile_T renames board(row - 1, col);
begin
if left.Color = above.Color then
for symbol in Symbol_T'Range loop
if symbol /= left.Symbol and then symbol /= above.Symbol then
NextSolve(left.Color, symbol);
end if;
end loop;
elsif left.Symbol = above.Symbol then
for color in Color_T'Range loop
if color /= left.Color and then color /= above.Color then
NextSolve(color, left.Symbol);
end if;
end loop;
else
NextSolve(left.Color, above.Symbol);
NextSolve(above.Color, left.Symbol);
end if;
end;
end if;
end Solve;
begin
ReadBoard(Ada.Command_Line.Argument(1), original_board);
for row in Row_T'Range loop
for col in Column_T'Range loop
declare
tile : constant Tile_T := original_board(row, col);
begin
tile_count(tile.Color, tile.Symbol) := tile_count(tile.Color, tile.Symbol) + 1;
end;
end loop;
end loop;
for color in Color_T'Range loop
for symbol in Symbol_T'Range loop
board(1, 1) := (color, symbol);
Solve(1, 2);
end loop;
end loop;
IO.Put_Line("Total Iterations" & Natural'Image(iterations));
IO.Put_Line("Total Solutions found:" & Natural'Image(total_solutions));
IO.Put_Line("Total Swaps: " & Natural'Image(best_distance));
PrintBoard(best_board);
end Symbolica;
|
Move the functions dealing with turning characters into symbols inside the parsing function to clean up the cognitive load on them.
|
Move the functions dealing with turning characters into symbols inside the parsing
function to clean up the cognitive load on them.
|
Ada
|
unlicense
|
Tim-Tom/scratch,Tim-Tom/scratch,Tim-Tom/scratch,Tim-Tom/scratch,Tim-Tom/scratch,Tim-Tom/scratch,Tim-Tom/scratch,Tim-Tom/scratch,Tim-Tom/scratch,Tim-Tom/scratch
|
4d92c36969c80b1ef678a4a4585fbb19461887c5
|
src/gen-utils.ads
|
src/gen-utils.ads
|
-----------------------------------------------------------------------
-- gen-utils -- Utilities for model generator
-- Copyright (C) 2010, 2011 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Ada.Strings.Unbounded.Hash;
with Ada.Containers.Hashed_Sets;
with Ada.Containers.Indefinite_Vectors;
with DOM.Core;
package Gen.Utils is
-- Generic procedure to iterate over the DOM nodes children of <b>node</b>
-- and having the entity name <b>name</b>.
generic
type T is limited private;
with procedure Process (Closure : in out T;
Node : DOM.Core.Node);
procedure Iterate_Nodes (Closure : in out T;
Node : DOM.Core.Node;
Name : String);
-- Get the content of the node
function Get_Data_Content (Node : in DOM.Core.Node) return String;
-- Get the Ada package name from a qualified type
function Get_Package_Name (Name : in String) return String;
-- Get the Ada type name from a full qualified type
function Get_Type_Name (Name : in String) return String;
-- Get a query name from the XML query file name
function Get_Query_Name (Path : in String) return String;
use Ada.Strings.Unbounded;
package String_Set is
new Ada.Containers.Hashed_Sets (Element_Type => Ada.Strings.Unbounded.Unbounded_String,
Hash => Ada.Strings.Unbounded.Hash,
Equivalent_Elements => Ada.Strings.Unbounded."=");
package String_List is new Ada.Containers.Indefinite_Vectors (Index_Type => Positive,
Element_Type => String,
"=" => "=");
-- Returns True if the Name is a valid project or module name.
-- The name must be a valid Ada identifier.
function Is_Valid_Name (Name : in String) return Boolean;
end Gen.Utils;
|
-----------------------------------------------------------------------
-- gen-utils -- Utilities for model generator
-- Copyright (C) 2010, 2011 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Ada.Containers.Ordered_Sets;
with Ada.Containers.Indefinite_Vectors;
with DOM.Core;
package Gen.Utils is
-- Generic procedure to iterate over the DOM nodes children of <b>node</b>
-- and having the entity name <b>name</b>.
generic
type T is limited private;
with procedure Process (Closure : in out T;
Node : DOM.Core.Node);
procedure Iterate_Nodes (Closure : in out T;
Node : DOM.Core.Node;
Name : String);
-- Get the content of the node
function Get_Data_Content (Node : in DOM.Core.Node) return String;
-- Get the Ada package name from a qualified type
function Get_Package_Name (Name : in String) return String;
-- Get the Ada type name from a full qualified type
function Get_Type_Name (Name : in String) return String;
-- Get a query name from the XML query file name
function Get_Query_Name (Path : in String) return String;
use Ada.Strings.Unbounded;
package String_Set is
new Ada.Containers.Ordered_Sets (Element_Type => Ada.Strings.Unbounded.Unbounded_String,
"<" => Ada.Strings.Unbounded."<",
"=" => Ada.Strings.Unbounded."=");
package String_List is new Ada.Containers.Indefinite_Vectors (Index_Type => Positive,
Element_Type => String,
"=" => "=");
-- Returns True if the Name is a valid project or module name.
-- The name must be a valid Ada identifier.
function Is_Valid_Name (Name : in String) return Boolean;
end Gen.Utils;
|
Change to an Ordered_Sets to ensure a coherent and reproducible code generation
|
Change to an Ordered_Sets to ensure a coherent and reproducible code generation
|
Ada
|
apache-2.0
|
Letractively/ada-gen,Letractively/ada-gen,Letractively/ada-gen,Letractively/ada-gen
|
85f44dc89a0ae1c2a4b89934d9adf18b2d771818
|
regtests/ado-audits-tests.adb
|
regtests/ado-audits-tests.adb
|
-----------------------------------------------------------------------
-- ado-audits-tests -- Audit tests
-- Copyright (C) 2018, 2019 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Test_Caller;
with Util.Strings;
with Ada.Text_IO;
with Regtests.Audits.Model;
with ADO.SQL;
with ADO.Sessions.Entities;
package body ADO.Audits.Tests is
use type ADO.Objects.Object_Key_Type;
package Caller is new Util.Test_Caller (Test, "ADO.Audits");
type Test_Audit_Manager is new Audit_Manager with null record;
-- Save the audit changes in the database.
overriding
procedure Save (Manager : in out Test_Audit_Manager;
Session : in out ADO.Sessions.Master_Session'Class;
Object : in Auditable_Object_Record'Class;
Changes : in Audit_Array);
Audit_Instance : aliased Test_Audit_Manager;
-- Save the audit changes in the database.
overriding
procedure Save (Manager : in out Test_Audit_Manager;
Session : in out ADO.Sessions.Master_Session'Class;
Object : in Auditable_Object_Record'Class;
Changes : in Audit_Array) is
pragma Unreferenced (Manager);
Now : constant Ada.Calendar.Time := Ada.Calendar.Clock;
Kind : constant ADO.Entity_Type
:= ADO.Sessions.Entities.Find_Entity_Type (Session, Object.Get_Key);
begin
for C of Changes loop
declare
Audit : Regtests.Audits.Model.Audit_Ref;
begin
if Object.Key_Type = ADO.Objects.KEY_INTEGER then
Audit.Set_Entity_Id (ADO.Objects.Get_Value (Object.Get_Key));
end if;
Audit.Set_Entity_Type (Kind);
Audit.Set_Old_Value (UBO.To_String (C.Old_Value));
Audit.Set_New_Value (UBO.To_String (C.New_Value));
Audit.Set_Date (Now);
Audit.Save (Session);
end;
end loop;
end Save;
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test ADO.Audits.Audit_Field",
Test_Audit_Field'Access);
end Add_Tests;
procedure Set_Up (T : in out Test) is
pragma Unreferenced (T);
begin
Regtests.Set_Audit_Manager (Audit_Instance'Access);
end Set_Up;
-- ------------------------------
-- Test populating Audit_Fields
-- ------------------------------
procedure Test_Audit_Field (T : in out Test) is
type Identifier_Array is array (1 .. 10) of ADO.Identifier;
DB : ADO.Sessions.Master_Session := Regtests.Get_Master_Database;
Email : Regtests.Audits.Model.Email_Ref;
List : Identifier_Array;
begin
for I in List'Range loop
Email := Regtests.Audits.Model.Null_Email;
Email.Set_Email ("Email" & Util.Strings.Image (I) & "@nowhere.com");
Email.Set_Status (ADO.Nullable_Integer '(23, False));
Email.Save (DB);
List (I) := Email.Get_Id;
end loop;
DB.Commit;
for Id of List loop
Email.Load (DB, Id);
Email.Set_Status (ADO.Nullable_Integer '(Email.Get_Status.Value + 1, False));
Email.Save (DB);
Email.Set_Email ("Email" & Util.Strings.Image (Email.Get_Status.Value) & "@here.com");
Email.Save (DB);
Email.Set_Email ("Email" & Util.Strings.Image (Email.Get_Status.Value) & "@there.com");
Email.Set_Status (ADO.Nullable_Integer '(Email.Get_Status.Value + 1, False));
Email.Save (DB);
end loop;
DB.Commit;
for Id of List loop
Email.Load (DB, Id);
Email.Set_Status (ADO.Null_Integer);
Email.Save (DB);
end loop;
DB.Commit;
declare
Query : ADO.SQL.Query;
Audit_List : Regtests.Audits.Model.Audit_Vector;
begin
Query.Set_Filter ("entity_id = :entity_id");
for Id of List loop
Query.Bind_Param ("entity_id", Id);
Regtests.Audits.Model.List (Audit_List, DB, Query);
for A of Audit_List loop
Ada.Text_IO.Put_Line (ADO.Identifier'Image (Id) & " "
& ADO.Identifier'Image (A.Get_Id)
& " " & A.Get_Old_Value & " - "
& A.Get_New_Value);
Util.Tests.Assert_Equals (T, Natural (Id), Natural (A.Get_Entity_Id),
"Invalid audit record: id is wrong");
end loop;
Util.Tests.Assert_Equals (T, 7, Natural (Audit_List.Length),
"Invalid number of audit records");
end loop;
end;
end Test_Audit_Field;
end ADO.Audits.Tests;
|
-----------------------------------------------------------------------
-- ado-audits-tests -- Audit tests
-- Copyright (C) 2018, 2019 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Test_Caller;
with Util.Strings;
with Ada.Text_IO;
with Regtests.Audits.Model;
with ADO.SQL;
with ADO.Sessions.Entities;
package body ADO.Audits.Tests is
use type ADO.Objects.Object_Key_Type;
package Caller is new Util.Test_Caller (Test, "ADO.Audits");
type Test_Audit_Manager is new Audit_Manager with null record;
-- Save the audit changes in the database.
overriding
procedure Save (Manager : in out Test_Audit_Manager;
Session : in out ADO.Sessions.Master_Session'Class;
Object : in Auditable_Object_Record'Class;
Changes : in Audit_Array);
Audit_Instance : aliased Test_Audit_Manager;
-- Save the audit changes in the database.
overriding
procedure Save (Manager : in out Test_Audit_Manager;
Session : in out ADO.Sessions.Master_Session'Class;
Object : in Auditable_Object_Record'Class;
Changes : in Audit_Array) is
pragma Unreferenced (Manager);
Now : constant Ada.Calendar.Time := Ada.Calendar.Clock;
Kind : constant ADO.Entity_Type
:= ADO.Sessions.Entities.Find_Entity_Type (Session, Object.Get_Key);
begin
for C of Changes loop
declare
Audit : Regtests.Audits.Model.Audit_Ref;
begin
if Object.Key_Type = ADO.Objects.KEY_INTEGER then
Audit.Set_Entity_Id (ADO.Objects.Get_Value (Object.Get_Key));
end if;
Audit.Set_Entity_Type (Kind);
Audit.Set_Old_Value (UBO.To_String (C.Old_Value));
Audit.Set_New_Value (UBO.To_String (C.New_Value));
Audit.Set_Date (Now);
Audit.Save (Session);
end;
end loop;
end Save;
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test ADO.Audits.Audit_Field",
Test_Audit_Field'Access);
end Add_Tests;
procedure Set_Up (T : in out Test) is
pragma Unreferenced (T);
begin
Regtests.Set_Audit_Manager (Audit_Instance'Access);
end Set_Up;
-- ------------------------------
-- Test populating Audit_Fields
-- ------------------------------
procedure Test_Audit_Field (T : in out Test) is
type Identifier_Array is array (1 .. 10) of ADO.Identifier;
DB : ADO.Sessions.Master_Session := Regtests.Get_Master_Database;
Email : Regtests.Audits.Model.Email_Ref;
Prop : Regtests.Audits.Model.Property_Ref;
List : Identifier_Array;
begin
for I in List'Range loop
Email := Regtests.Audits.Model.Null_Email;
Email.Set_Email ("Email" & Util.Strings.Image (I) & "@nowhere.com");
Email.Set_Status (ADO.Nullable_Integer '(23, False));
Email.Save (DB);
List (I) := Email.Get_Id;
end loop;
DB.Commit;
for Id of List loop
Email.Load (DB, Id);
Email.Set_Status (ADO.Nullable_Integer '(Email.Get_Status.Value + 1, False));
Email.Save (DB);
Email.Set_Email ("Email" & Util.Strings.Image (Email.Get_Status.Value) & "@here.com");
Email.Save (DB);
Email.Set_Email ("Email" & Util.Strings.Image (Email.Get_Status.Value) & "@there.com");
Email.Set_Status (ADO.Nullable_Integer '(Email.Get_Status.Value + 1, False));
Email.Save (DB);
end loop;
DB.Commit;
for Id of List loop
Email.Load (DB, Id);
Email.Set_Status (ADO.Null_Integer);
Email.Save (DB);
end loop;
DB.Commit;
for I in 1 .. 10 loop
Prop.Set_Value ((Value => I, Is_Null => False));
Prop.Set_Float_Value (3.0 * Float (I));
Prop.Save (DB);
end loop;
declare
Query : ADO.SQL.Query;
Audit_List : Regtests.Audits.Model.Audit_Vector;
begin
Query.Set_Filter ("entity_id = :entity_id");
for Id of List loop
Query.Bind_Param ("entity_id", Id);
Regtests.Audits.Model.List (Audit_List, DB, Query);
for A of Audit_List loop
Ada.Text_IO.Put_Line (ADO.Identifier'Image (Id) & " "
& ADO.Identifier'Image (A.Get_Id)
& " " & A.Get_Old_Value & " - "
& A.Get_New_Value);
Util.Tests.Assert_Equals (T, Natural (Id), Natural (A.Get_Entity_Id),
"Invalid audit record: id is wrong");
end loop;
Util.Tests.Assert_Equals (T, 7, Natural (Audit_List.Length),
"Invalid number of audit records");
end loop;
end;
end Test_Audit_Field;
end ADO.Audits.Tests;
|
Add test on Property_Def with float
|
Add test on Property_Def with float
|
Ada
|
apache-2.0
|
stcarrez/ada-ado
|
b54aa80ffc9e805174366f4c0f626029097ec2ab
|
awa/plugins/awa-questions/regtests/awa-questions-services-tests.adb
|
awa/plugins/awa-questions/regtests/awa-questions-services-tests.adb
|
-----------------------------------------------------------------------
-- awa-questions-services-tests -- Unit tests for storage service
-- Copyright (C) 2013 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Streams;
with Ada.Strings.Unbounded;
with Util.Test_Caller;
with ADO;
with ADO.Objects;
with Security.Contexts;
with AWA.Services.Contexts;
with AWA.Questions.Modules;
with AWA.Tests.Helpers.Users;
package body AWA.Questions.Services.Tests is
use Util.Tests;
use ADO;
package Caller is new Util.Test_Caller (Test, "Questions.Services");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test AWA.Storages.Services.Save (DATABASE)",
Test_Create_Question'Access);
end Add_Tests;
-- ------------------------------
-- Test creation of a question.
-- ------------------------------
procedure Test_Create_Question (T : in out Test) is
Sec_Ctx : Security.Contexts.Security_Context;
Context : AWA.Services.Contexts.Service_Context;
Q : AWA.Questions.Models.Question_Ref;
begin
AWA.Tests.Helpers.Users.Login (Context, Sec_Ctx, "[email protected]");
T.Manager := AWA.Questions.Modules.Get_Question_Manager;
T.Assert (T.Manager /= null, "There is no question manager");
Q.Set_Title ("How can I append strings in Ada?");
Q.Set_Description ("I have two strings that I want to concatenate. + does not work.");
T.Manager.Save_Question (Q);
T.Assert (Q.Is_Inserted, "The new question was not inserted");
Q.Set_Description ("I have two strings that I want to concatenate. + does not work. "
& "I also tried '.' without success. What should I do?");
T.Manager.Save_Question (Q);
Q.Set_Description ("I have two strings that I want to concatenate. + does not work. "
& "I also tried '.' without success. What should I do? "
& "This is a stupid question for someone who reads this file. "
& "But I need some long text for the unit test.");
T.Manager.Save_Question (Q);
end Test_Create_Question;
end AWA.Questions.Services.Tests;
|
-----------------------------------------------------------------------
-- awa-questions-services-tests -- Unit tests for storage service
-- Copyright (C) 2013 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Streams;
with Ada.Strings.Unbounded;
with Util.Test_Caller;
with Util.Beans.Basic;
with Util.Beans.Objects;
with ADO;
with ADO.Objects;
with Security.Contexts;
with AWA.Services.Contexts;
with AWA.Questions.Modules;
with AWA.Questions.Beans;
with AWA.Tests.Helpers.Users;
package body AWA.Questions.Services.Tests is
use Util.Tests;
use ADO;
package Caller is new Util.Test_Caller (Test, "Questions.Services");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test AWA.Questions.Services.Save_Question",
Test_Create_Question'Access);
Caller.Add_Test (Suite, "Test AWA.Questions.Queries question-list",
Test_List_Questions'Access);
end Add_Tests;
-- ------------------------------
-- Test creation of a question.
-- ------------------------------
procedure Test_Create_Question (T : in out Test) is
Sec_Ctx : Security.Contexts.Security_Context;
Context : AWA.Services.Contexts.Service_Context;
Q : AWA.Questions.Models.Question_Ref;
begin
AWA.Tests.Helpers.Users.Login (Context, Sec_Ctx, "[email protected]");
T.Manager := AWA.Questions.Modules.Get_Question_Manager;
T.Assert (T.Manager /= null, "There is no question manager");
Q.Set_Title ("How can I append strings in Ada?");
Q.Set_Description ("I have two strings that I want to concatenate. + does not work.");
T.Manager.Save_Question (Q);
T.Assert (Q.Is_Inserted, "The new question was not inserted");
Q.Set_Description ("I have two strings that I want to concatenate. + does not work. "
& "I also tried '.' without success. What should I do?");
T.Manager.Save_Question (Q);
Q.Set_Description ("I have two strings that I want to concatenate. + does not work. "
& "I also tried '.' without success. What should I do? "
& "This is a stupid question for someone who reads this file. "
& "But I need some long text for the unit test.");
T.Manager.Save_Question (Q);
end Test_Create_Question;
-- ------------------------------
-- Test list of questions.
-- ------------------------------
procedure Test_List_Questions (T : in out Test) is
use AWA.Questions.Models;
use type Util.Beans.Basic.Readonly_Bean_Access;
Sec_Ctx : Security.Contexts.Security_Context;
Context : AWA.Services.Contexts.Service_Context;
Q : AWA.Questions.Models.Question_Ref;
Module : AWA.Questions.Modules.Question_Module_Access;
List : Util.Beans.Basic.Readonly_Bean_Access;
Bean : Util.Beans.Objects.Object;
Count : Natural;
begin
AWA.Tests.Helpers.Users.Anonymous (Context, Sec_Ctx);
Module := AWA.Questions.Modules.Get_Question_Module;
List := AWA.Questions.Beans.Create_Question_List_Bean (Module);
T.Assert (List /= null, "The Create_Question_List_Bean returned null");
Bean := Util.Beans.Objects.To_Object (List);
T.Assert (not Util.Beans.Objects.Is_Null (Bean), "The list bean should not be null");
Count := Questions.Models.Question_Info_List_Bean'Class (List.all).Get_Count;
T.Assert (Count > 0, "The list of question is empty");
end Test_List_Questions;
end AWA.Questions.Services.Tests;
|
Add new unit test to check list of questions from anonymous user
|
Add new unit test to check list of questions from anonymous user
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
657de22395f47916c72ba96bff73f3862e6238d0
|
src/security-auth.ads
|
src/security-auth.ads
|
-----------------------------------------------------------------------
-- security-auth -- Authentication Support
-- Copyright (C) 2009, 2010, 2011, 2012, 2013, 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Ada.Calendar;
with Ada.Finalization;
-- == Auth ==
-- The <b>Security.Auth</b> package implements an authentication framework that is
-- suitable for OpenID 2.0, OAuth 2.0 and later for OpenID Connect. It allows an application
-- to authenticate users using an external authorization server such as Google, Facebook,
-- Google +, Twitter and others.
--
-- See OpenID Authentication 2.0 - Final
-- http://openid.net/specs/openid-authentication-2_0.html
--
-- See OpenID Connect Standard 1.0
-- http://openid.net/specs/openid-connect-standard-1_0.html
--
-- See Facebook API: The Login Flow for Web (without JavaScript SDK)
-- https://developers.facebook.com/docs/facebook-login/login-flow-for-web-no-jssdk/
--
-- Despite their subtle differences, all these authentication frameworks share almost
-- a common flow. The API provided by <b>Security.Auth</b> defines an abstraction suitable
-- for all these frameworks.
--
-- There are basically two steps that an application must implement:
--
-- * <b>Discovery</b>: to resolve and use the OpenID provider and redirect the user to the
-- provider authentication form.
-- * <b>Verify</b>: to decode the authentication and check its result.
--
-- [[images/OpenID.png]]
--
-- The authentication process is the following:
--
-- * The application should redirect the user to the authentication URL.
-- * The OpenID provider authenticate the user and redirects the user to the callback CB.
-- * The association is decoded from the callback parameter.
-- * The <b>Verify</b> procedure is called with the association to check the result and
-- obtain the authentication results.
--
-- === Initialization ===
-- The initialization process must be done before each two steps (discovery and verify).
-- The Authentication manager must be declared and configured.
--
-- Mgr : Security.Auth.Manager;
--
-- For the configuration, the <b>Initialize</b> procedure is called to configure
-- the Auth realm and set the authentication return callback URL. The return callback
-- must be a valid URL that is based on the realm. Example:
--
-- Mgr.Initialize (Name => "http://app.site.com/auth",
-- Return_To => "http://app.site.com/auth/verify",
-- Realm => "openid");
--
-- After this initialization, the authentication manager can be used in the authentication
-- process.
--
-- @include security-auth-openid.ads
-- @include security-auth-oauth.ads
--
-- === Discovery: creating the authentication URL ===
-- The first step is to create an authentication URL to which the user must be redirected.
-- In this step, we have to create an OpenID manager, discover the OpenID provider,
-- do the association and get an <b>End_Point</b>. The OpenID provider is specified as an
-- URL, below is an example for Google OpenID:
--
-- Provider : constant String := "https://www.google.com/accounts/o8/id";
-- OP : Security.Auth.End_Point;
-- Assoc : constant Security.Auth.Association_Access := new Security.Auth.Association;
--
-- The following steps are performed:
--
-- * The <b>Discover</b> procedure is called to retrieve from the OpenID provider the XRDS
-- stream and identify the provider. An <b>End_Point</b> is returned in <tt>OP</tt>.
-- * The <b>Associate</b> procedure is called to make the association with the <b>End_Point</b>.
-- The <b>Association</b> record holds session, and authentication.
--
-- Mgr.Discover (Provider, OP); -- Yadis discovery (get the XRDS file).
-- Mgr.Associate (OP, Assoc.all);-- Associate and get an end-point with a key.
--
-- After this first step, you must manage to save the association in the HTTP session.
-- Then you must redirect to the authentication URL that is obtained by using:
--
-- Auth_URL : constant String := Mgr.Get_Authentication_URL (OP, Assoc.all);
--
-- === Verify: acknowledge the authentication in the callback URL ===
-- The second step is done when the user has finished the authentication successfully or not.
-- For this step, the application must get back the association that was saved in the session.
-- It must also prepare a parameters object that allows the OpenID framework to get the
-- URI parameters from the return callback.
--
-- Assoc : Association_Access := ...; -- Get the association saved in the session.
-- Credential : Security.Auth.Authentication;
-- Params : Auth_Params;
--
-- The auth manager must be initialized and the <b>Verify</b> procedure is called with
-- the association, parameters and the authentication result. The <b>Get_Status</b> function
-- must be used to check that the authentication succeeded.
--
-- Mgr.Verify (Assoc.all, Params, Credential);
-- if Security.Auth.Get_Status (Credential) = Security.Auth.AUTHENTICATED then ... -- Success.
--
-- === Principal creation ===
-- After the user is successfully authenticated, a user principal can be created and saved in
-- the session. The user principal can then be used to assign permissions to that user and
-- enforce the application permissions using the security policy manger.
--
-- P : Security.Auth.Principal_Access := Security.Auth.Create_Principal (Credential);
--
package Security.Auth is
-- Use an authentication server implementing OpenID 2.0.
PROVIDER_OPENID : constant String := "openid";
-- Use the Facebook OAuth 2.0 - draft 12 authentication server.
PROVIDER_FACEBOOK : constant String := "facebook";
-- Use the Google+ OpenID Connect Basic Client
PROVIDER_GOOGLE_PLUS : constant String := "google-plus";
Invalid_End_Point : exception;
Service_Error : exception;
type Parameters is limited interface;
function Get_Parameter (Params : in Parameters;
Name : in String) return String is abstract;
-- ------------------------------
-- Auth provider
-- ------------------------------
-- The <b>End_Point</b> represents the authentication provider that will authenticate
-- the user.
type End_Point is private;
function To_String (OP : End_Point) return String;
-- ------------------------------
-- Association
-- ------------------------------
-- The association contains the shared secret between the relying party
-- and the authentication provider. The association can be cached and reused to authenticate
-- different users using the same authentication provider. The association also has an
-- expiration date.
type Association is private;
-- Get the provider.
function Get_Provider (Assoc : in Association) return String;
-- Dump the association as a string (for debugging purposes)
function To_String (Assoc : Association) return String;
type Auth_Result is (AUTHENTICATED, CANCEL, SETUP_NEEDED, UNKNOWN, INVALID_SIGNATURE);
-- ------------------------------
-- Authentication result
-- ------------------------------
--
type Authentication is private;
-- Get the email address
function Get_Email (Auth : in Authentication) return String;
-- Get the user first name.
function Get_First_Name (Auth : in Authentication) return String;
-- Get the user last name.
function Get_Last_Name (Auth : in Authentication) return String;
-- Get the user full name.
function Get_Full_Name (Auth : in Authentication) return String;
-- Get the user identity.
function Get_Identity (Auth : in Authentication) return String;
-- Get the user claimed identity.
function Get_Claimed_Id (Auth : in Authentication) return String;
-- Get the user language.
function Get_Language (Auth : in Authentication) return String;
-- Get the user country.
function Get_Country (Auth : in Authentication) return String;
-- Get the result of the authentication.
function Get_Status (Auth : in Authentication) return Auth_Result;
-- ------------------------------
-- Default principal
-- ------------------------------
type Principal is new Security.Principal with private;
type Principal_Access is access all Principal'Class;
-- Get the principal name.
function Get_Name (From : in Principal) return String;
-- Get the user email address.
function Get_Email (From : in Principal) return String;
-- Get the authentication data.
function Get_Authentication (From : in Principal) return Authentication;
-- Create a principal with the given authentication results.
function Create_Principal (Auth : in Authentication) return Principal_Access;
-- ------------------------------
-- Authentication Manager
-- ------------------------------
-- The <b>Manager</b> provides the core operations for the authentication process.
type Manager is tagged limited private;
-- Initialize the authentication realm.
procedure Initialize (Realm : in out Manager;
Params : in Parameters'Class;
Name : in String := PROVIDER_OPENID);
-- Discover the authentication provider that must be used to authenticate the user.
-- The <b>Name</b> can be an URL or an alias that identifies the provider.
-- A cached OpenID provider can be returned. The discover step may do nothing for
-- authentication providers based on OAuth.
-- (See OpenID Section 7.3 Discovery)
procedure Discover (Realm : in out Manager;
Name : in String;
Result : out End_Point);
-- Associate the application (relying party) with the authentication provider.
-- The association can be cached.
-- (See OpenID Section 8 Establishing Associations)
procedure Associate (Realm : in out Manager;
OP : in End_Point;
Result : out Association);
-- Get the authentication URL to which the user must be redirected for authentication
-- by the authentication server.
function Get_Authentication_URL (Realm : in Manager;
OP : in End_Point;
Assoc : in Association) return String;
-- Verify the authentication result
procedure Verify (Realm : in out Manager;
Assoc : in Association;
Request : in Parameters'Class;
Result : out Authentication);
private
use Ada.Strings.Unbounded;
type Association is record
Provider : Unbounded_String;
Session_Type : Unbounded_String;
Assoc_Type : Unbounded_String;
Assoc_Handle : Unbounded_String;
Mac_Key : Unbounded_String;
Expired : Ada.Calendar.Time;
end record;
type Authentication is record
Status : Auth_Result;
Identity : Unbounded_String;
Claimed_Id : Unbounded_String;
Email : Unbounded_String;
Full_Name : Unbounded_String;
First_Name : Unbounded_String;
Last_Name : Unbounded_String;
Language : Unbounded_String;
Country : Unbounded_String;
Gender : Unbounded_String;
Timezone : Unbounded_String;
Nickname : Unbounded_String;
end record;
type End_Point is record
URL : Unbounded_String;
Alias : Unbounded_String;
Expired : Ada.Calendar.Time;
end record;
type Manager_Access is access all Manager'Class;
type Manager is new Ada.Finalization.Limited_Controlled with record
Provider : Unbounded_String;
Delegate : Manager_Access;
end record;
type Principal is new Security.Principal with record
Auth : Authentication;
end record;
procedure Set_Result (Result : in out Authentication;
Status : in Auth_Result;
Message : in String);
end Security.Auth;
|
-----------------------------------------------------------------------
-- security-auth -- Authentication Support
-- Copyright (C) 2009, 2010, 2011, 2012, 2013, 2015, 2018 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Ada.Calendar;
with Ada.Finalization;
-- = Authentication =
-- The `Security.Auth` package implements an authentication framework that is
-- suitable for OpenID 2.0, OAuth 2.0 and later for OpenID Connect. It allows an application
-- to authenticate users using an external authorization server such as Google, Facebook,
-- Google +, Twitter and others.
--
-- See OpenID Authentication 2.0 - Final
-- http://openid.net/specs/openid-authentication-2_0.html
--
-- See OpenID Connect Standard 1.0
-- http://openid.net/specs/openid-connect-standard-1_0.html
--
-- See Facebook API: The Login Flow for Web (without JavaScript SDK)
-- https://developers.facebook.com/docs/facebook-login/login-flow-for-web-no-jssdk/
--
-- Despite their subtle differences, all these authentication frameworks share almost
-- a common flow. The API provided by `Security.Auth` defines an abstraction suitable
-- for all these frameworks.
--
-- There are basically two steps that an application must implement:
--
-- * `Discovery`: to resolve and use the OpenID provider and redirect the user to the
-- provider authentication form.
-- * `Verify`: to decode the authentication and check its result.
--
-- [[images/OpenID.png]]
--
-- The authentication process is the following:
--
-- * The application should redirect the user to the authentication URL.
-- * The OpenID provider authenticate the user and redirects the user to the callback CB.
-- * The association is decoded from the callback parameter.
-- * The `Verify` procedure is called with the association to check the result and
-- obtain the authentication results.
--
-- == Initialization ==
-- The initialization process must be done before each two steps (discovery and verify).
-- The Authentication manager must be declared and configured.
--
-- Mgr : Security.Auth.Manager;
--
-- For the configuration, the <b>Initialize</b> procedure is called to configure
-- the Auth realm and set the authentication return callback URL. The return callback
-- must be a valid URL that is based on the realm. Example:
--
-- Mgr.Initialize (Name => "http://app.site.com/auth",
-- Return_To => "http://app.site.com/auth/verify",
-- Realm => "openid");
--
-- After this initialization, the authentication manager can be used in the authentication
-- process.
--
-- @include security-auth-openid.ads
-- @include security-auth-oauth-googleplus.ads
--
-- == Discovery: creating the authentication URL ==
-- The first step is to create an authentication URL to which the user must be redirected.
-- In this step, we have to create an OpenID manager, discover the OpenID provider,
-- do the association and get an <b>End_Point</b>. The OpenID provider is specified as an
-- URL, below is an example for Google OpenID:
--
-- Provider : constant String := "https://www.google.com/accounts/o8/id";
-- OP : Security.Auth.End_Point;
-- Assoc : constant Security.Auth.Association_Access := new Security.Auth.Association;
--
-- The following steps are performed:
--
-- * The <b>Discover</b> procedure is called to retrieve from the OpenID provider the XRDS
-- stream and identify the provider. An <b>End_Point</b> is returned in <tt>OP</tt>.
-- * The <b>Associate</b> procedure is called to make the association with the <b>End_Point</b>.
-- The <b>Association</b> record holds session, and authentication.
--
-- Mgr.Discover (Provider, OP); -- Yadis discovery (get the XRDS file).
-- Mgr.Associate (OP, Assoc.all);-- Associate and get an end-point with a key.
--
-- After this first step, you must manage to save the association in the HTTP session.
-- Then you must redirect to the authentication URL that is obtained by using:
--
-- Auth_URL : constant String := Mgr.Get_Authentication_URL (OP, Assoc.all);
--
-- == Verify: acknowledge the authentication in the callback URL ==
-- The second step is done when the user has finished the authentication successfully or not.
-- For this step, the application must get back the association that was saved in the session.
-- It must also prepare a parameters object that allows the OpenID framework to get the
-- URI parameters from the return callback.
--
-- Assoc : Association_Access := ...; -- Get the association saved in the session.
-- Credential : Security.Auth.Authentication;
-- Params : Auth_Params;
--
-- The auth manager must be initialized and the <b>Verify</b> procedure is called with
-- the association, parameters and the authentication result. The <b>Get_Status</b> function
-- must be used to check that the authentication succeeded.
--
-- Mgr.Verify (Assoc.all, Params, Credential);
-- if Security.Auth.Get_Status (Credential) = Security.Auth.AUTHENTICATED then ... -- Success.
--
-- == Principal creation ==
-- After the user is successfully authenticated, a user principal can be created and saved in
-- the session. The user principal can then be used to assign permissions to that user and
-- enforce the application permissions using the security policy manger.
--
-- P : Security.Auth.Principal_Access := Security.Auth.Create_Principal (Credential);
--
package Security.Auth is
-- Use an authentication server implementing OpenID 2.0.
PROVIDER_OPENID : constant String := "openid";
-- Use the Facebook OAuth 2.0 - draft 12 authentication server.
PROVIDER_FACEBOOK : constant String := "facebook";
-- Use the Google+ OpenID Connect Basic Client
PROVIDER_GOOGLE_PLUS : constant String := "google-plus";
Invalid_End_Point : exception;
Service_Error : exception;
type Parameters is limited interface;
function Get_Parameter (Params : in Parameters;
Name : in String) return String is abstract;
-- ------------------------------
-- Auth provider
-- ------------------------------
-- The <b>End_Point</b> represents the authentication provider that will authenticate
-- the user.
type End_Point is private;
function To_String (OP : End_Point) return String;
-- ------------------------------
-- Association
-- ------------------------------
-- The association contains the shared secret between the relying party
-- and the authentication provider. The association can be cached and reused to authenticate
-- different users using the same authentication provider. The association also has an
-- expiration date.
type Association is private;
-- Get the provider.
function Get_Provider (Assoc : in Association) return String;
-- Dump the association as a string (for debugging purposes)
function To_String (Assoc : Association) return String;
type Auth_Result is (AUTHENTICATED, CANCEL, SETUP_NEEDED, UNKNOWN, INVALID_SIGNATURE);
-- ------------------------------
-- Authentication result
-- ------------------------------
--
type Authentication is private;
-- Get the email address
function Get_Email (Auth : in Authentication) return String;
-- Get the user first name.
function Get_First_Name (Auth : in Authentication) return String;
-- Get the user last name.
function Get_Last_Name (Auth : in Authentication) return String;
-- Get the user full name.
function Get_Full_Name (Auth : in Authentication) return String;
-- Get the user identity.
function Get_Identity (Auth : in Authentication) return String;
-- Get the user claimed identity.
function Get_Claimed_Id (Auth : in Authentication) return String;
-- Get the user language.
function Get_Language (Auth : in Authentication) return String;
-- Get the user country.
function Get_Country (Auth : in Authentication) return String;
-- Get the result of the authentication.
function Get_Status (Auth : in Authentication) return Auth_Result;
-- ------------------------------
-- Default principal
-- ------------------------------
type Principal is new Security.Principal with private;
type Principal_Access is access all Principal'Class;
-- Get the principal name.
function Get_Name (From : in Principal) return String;
-- Get the user email address.
function Get_Email (From : in Principal) return String;
-- Get the authentication data.
function Get_Authentication (From : in Principal) return Authentication;
-- Create a principal with the given authentication results.
function Create_Principal (Auth : in Authentication) return Principal_Access;
-- ------------------------------
-- Authentication Manager
-- ------------------------------
-- The <b>Manager</b> provides the core operations for the authentication process.
type Manager is tagged limited private;
-- Initialize the authentication realm.
procedure Initialize (Realm : in out Manager;
Params : in Parameters'Class;
Name : in String := PROVIDER_OPENID);
-- Discover the authentication provider that must be used to authenticate the user.
-- The <b>Name</b> can be an URL or an alias that identifies the provider.
-- A cached OpenID provider can be returned. The discover step may do nothing for
-- authentication providers based on OAuth.
-- (See OpenID Section 7.3 Discovery)
procedure Discover (Realm : in out Manager;
Name : in String;
Result : out End_Point);
-- Associate the application (relying party) with the authentication provider.
-- The association can be cached.
-- (See OpenID Section 8 Establishing Associations)
procedure Associate (Realm : in out Manager;
OP : in End_Point;
Result : out Association);
-- Get the authentication URL to which the user must be redirected for authentication
-- by the authentication server.
function Get_Authentication_URL (Realm : in Manager;
OP : in End_Point;
Assoc : in Association) return String;
-- Verify the authentication result
procedure Verify (Realm : in out Manager;
Assoc : in Association;
Request : in Parameters'Class;
Result : out Authentication);
private
use Ada.Strings.Unbounded;
type Association is record
Provider : Unbounded_String;
Session_Type : Unbounded_String;
Assoc_Type : Unbounded_String;
Assoc_Handle : Unbounded_String;
Mac_Key : Unbounded_String;
Expired : Ada.Calendar.Time;
end record;
type Authentication is record
Status : Auth_Result;
Identity : Unbounded_String;
Claimed_Id : Unbounded_String;
Email : Unbounded_String;
Full_Name : Unbounded_String;
First_Name : Unbounded_String;
Last_Name : Unbounded_String;
Language : Unbounded_String;
Country : Unbounded_String;
Gender : Unbounded_String;
Timezone : Unbounded_String;
Nickname : Unbounded_String;
end record;
type End_Point is record
URL : Unbounded_String;
Alias : Unbounded_String;
Expired : Ada.Calendar.Time;
end record;
type Manager_Access is access all Manager'Class;
type Manager is new Ada.Finalization.Limited_Controlled with record
Provider : Unbounded_String;
Delegate : Manager_Access;
end record;
type Principal is new Security.Principal with record
Auth : Authentication;
end record;
procedure Set_Result (Result : in out Authentication;
Status : in Auth_Result;
Message : in String);
end Security.Auth;
|
Update the documentation
|
Update the documentation
|
Ada
|
apache-2.0
|
stcarrez/ada-security
|
dc9049ec96e3e775b190a3877e64a7c5c408b14d
|
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 MAT.Commands;
with MAT.Targets;
with MAT.Consoles.Text;
procedure Matp is
Target : MAT.Targets.Target_Type;
Console : aliased MAT.Consoles.Text.Console_Type;
begin
Target.Console (Console'Unchecked_Access);
Target.Initialize_Options;
MAT.Commands.Initialize_Files (Target);
Target.Start;
MAT.Commands.Interactive (Target);
Target.Stop;
exception
when Ada.IO_Exceptions.End_Error | MAT.Targets.Usage_Error =>
Target.Stop;
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 MAT.Commands;
with MAT.Targets;
with MAT.Consoles.Text;
procedure Matp is
Target : MAT.Targets.Target_Type;
Console : aliased MAT.Consoles.Text.Console_Type;
begin
Target.Console (Console'Unchecked_Access);
Target.Initialize_Options;
MAT.Commands.Initialize_Files (Target);
Target.Start;
Target.Interactive;
Target.Stop;
exception
when Ada.IO_Exceptions.End_Error | MAT.Targets.Usage_Error =>
Target.Stop;
end Matp;
|
Use MAT.Targets.Interactive procedure
|
Use MAT.Targets.Interactive procedure
|
Ada
|
apache-2.0
|
stcarrez/mat,stcarrez/mat,stcarrez/mat
|
eb2c42a2ce1ce162d49492dc51f51ae0f03945d5
|
src/util-strings.ads
|
src/util-strings.ads
|
-----------------------------------------------------------------------
-- Util-strings -- Various String Utility
-- Copyright (C) 2001, 2002, 2003, 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.Containers;
with Ada.Containers.Hashed_Maps;
with Ada.Containers.Indefinite_Hashed_Sets;
with Util.Concurrent.Counters;
package Util.Strings is
pragma Preelaborate;
-- Constant string access
type Name_Access is access constant String;
-- Compute the hash value of the string.
function Hash (Key : Name_Access) return Ada.Containers.Hash_Type;
-- Returns true if left and right strings are equivalent.
function Equivalent_Keys (Left, Right : Name_Access) return Boolean;
-- Search for the first occurrence of the character in the string
-- after the from index. This implementation is 3-times faster than
-- the Ada.Strings.Fixed version.
-- Returns the index of the first occurrence or 0.
function Index (Source : in String;
Char : in Character;
From : in Natural := 0) return Natural;
-- Search for the first occurrence of the character in the string
-- before the from index and going backward.
-- This implementation is 3-times faster than the Ada.Strings.Fixed version.
-- Returns the index of the first occurrence or 0.
function Rindex (Source : in String;
Ch : in Character;
From : in Natural := 0) return Natural;
-- Returns Integer'Image (Value) with the possible space stripped.
function Image (Value : in Integer) return String;
-- Returns Integer'Image (Value) with the possible space stripped.
function Image (Value : in Long_Long_Integer) return String;
package String_Access_Map is new Ada.Containers.Hashed_Maps
(Key_Type => Name_Access,
Element_Type => Name_Access,
Hash => Hash,
Equivalent_Keys => Equivalent_Keys);
package String_Set is new Ada.Containers.Indefinite_Hashed_Sets
(Element_Type => Name_Access,
Hash => Hash,
Equivalent_Elements => Equivalent_Keys);
-- String reference
type String_Ref is private;
-- Create a string reference from a string.
function To_String_Ref (S : in String) return String_Ref;
-- Create a string reference from an unbounded string.
function To_String_Ref (S : in Ada.Strings.Unbounded.Unbounded_String) return String_Ref;
-- Get the string
function To_String (S : in String_Ref) return String;
-- Get the string as an unbounded string
function To_Unbounded_String (S : in String_Ref) return Ada.Strings.Unbounded.Unbounded_String;
-- Compute the hash value of the string reference.
function Hash (Key : in String_Ref) return Ada.Containers.Hash_Type;
-- Returns true if left and right string references are equivalent.
function Equivalent_Keys (Left, Right : in String_Ref) return Boolean;
function "=" (Left, Right : in String_Ref) return Boolean renames Equivalent_Keys;
function "=" (Left : in String_Ref;
Right : in String) return Boolean;
function "=" (Left : in String_Ref;
Right : in Ada.Strings.Unbounded.Unbounded_String) return Boolean;
-- Returns the string length.
function Length (S : in String_Ref) return Natural;
private
pragma Inline (To_String_Ref);
pragma Inline (To_String);
type String_Record (Len : Natural) is limited record
Counter : Util.Concurrent.Counters.Counter;
Str : String (1 .. Len);
end record;
type String_Record_Access is access all String_Record;
type String_Ref is new Ada.Finalization.Controlled with record
Str : String_Record_Access := null;
end record;
-- Increment the reference counter.
overriding
procedure Adjust (Object : in out String_Ref);
-- Decrement the reference counter and free the allocated string.
overriding
procedure Finalize (Object : in out String_Ref);
end Util.Strings;
|
-----------------------------------------------------------------------
-- Util-strings -- Various String Utility
-- Copyright (C) 2001, 2002, 2003, 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.Containers;
with Ada.Containers.Hashed_Maps;
with Ada.Containers.Hashed_Sets;
with Util.Concurrent.Counters;
package Util.Strings is
pragma Preelaborate;
-- Constant string access
type Name_Access is access constant String;
-- Compute the hash value of the string.
function Hash (Key : Name_Access) return Ada.Containers.Hash_Type;
-- Returns true if left and right strings are equivalent.
function Equivalent_Keys (Left, Right : Name_Access) return Boolean;
-- Search for the first occurrence of the character in the string
-- after the from index. This implementation is 3-times faster than
-- the Ada.Strings.Fixed version.
-- Returns the index of the first occurrence or 0.
function Index (Source : in String;
Char : in Character;
From : in Natural := 0) return Natural;
-- Search for the first occurrence of the character in the string
-- before the from index and going backward.
-- This implementation is 3-times faster than the Ada.Strings.Fixed version.
-- Returns the index of the first occurrence or 0.
function Rindex (Source : in String;
Ch : in Character;
From : in Natural := 0) return Natural;
-- Returns Integer'Image (Value) with the possible space stripped.
function Image (Value : in Integer) return String;
-- Returns Integer'Image (Value) with the possible space stripped.
function Image (Value : in Long_Long_Integer) return String;
package String_Access_Map is new Ada.Containers.Hashed_Maps
(Key_Type => Name_Access,
Element_Type => Name_Access,
Hash => Hash,
Equivalent_Keys => Equivalent_Keys);
package String_Set is new Ada.Containers.Hashed_Sets
(Element_Type => Name_Access,
Hash => Hash,
Equivalent_Elements => Equivalent_Keys);
-- String reference
type String_Ref is private;
-- Create a string reference from a string.
function To_String_Ref (S : in String) return String_Ref;
-- Create a string reference from an unbounded string.
function To_String_Ref (S : in Ada.Strings.Unbounded.Unbounded_String) return String_Ref;
-- Get the string
function To_String (S : in String_Ref) return String;
-- Get the string as an unbounded string
function To_Unbounded_String (S : in String_Ref) return Ada.Strings.Unbounded.Unbounded_String;
-- Compute the hash value of the string reference.
function Hash (Key : in String_Ref) return Ada.Containers.Hash_Type;
-- Returns true if left and right string references are equivalent.
function Equivalent_Keys (Left, Right : in String_Ref) return Boolean;
function "=" (Left, Right : in String_Ref) return Boolean renames Equivalent_Keys;
function "=" (Left : in String_Ref;
Right : in String) return Boolean;
function "=" (Left : in String_Ref;
Right : in Ada.Strings.Unbounded.Unbounded_String) return Boolean;
-- Returns the string length.
function Length (S : in String_Ref) return Natural;
private
pragma Inline (To_String_Ref);
pragma Inline (To_String);
type String_Record (Len : Natural) is limited record
Counter : Util.Concurrent.Counters.Counter;
Str : String (1 .. Len);
end record;
type String_Record_Access is access all String_Record;
type String_Ref is new Ada.Finalization.Controlled with record
Str : String_Record_Access := null;
end record;
-- Increment the reference counter.
overriding
procedure Adjust (Object : in out String_Ref);
-- Decrement the reference counter and free the allocated string.
overriding
procedure Finalize (Object : in out String_Ref);
end Util.Strings;
|
Use Hashed_Sets instead of Indefinite_Hashed_Sets
|
Use Hashed_Sets instead of Indefinite_Hashed_Sets
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
661ab157f5970105f7dd6883b1558897050dd4d0
|
src/util-strings-sets.ads
|
src/util-strings-sets.ads
|
-----------------------------------------------------------------------
-- Util-strings-sets -- Set of strings
-- 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.Hash;
with Ada.Containers.Indefinite_Hashed_Sets;
-- The <b>Util.Strings.Sets</b> package provides an instantiation
-- of a hashed set with Strings.
package Util.Strings.Sets is new Ada.Containers.Indefinite_Hashed_Sets
(Element_Type => String,
Hash => Ada.Strings.Hash,
Equivalent_Elements => "=");
|
-----------------------------------------------------------------------
-- util-strings-sets -- Set of strings
-- 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.Hash;
with Ada.Containers.Indefinite_Hashed_Sets;
-- The <b>Util.Strings.Sets</b> package provides an instantiation
-- of a hashed set with Strings.
package Util.Strings.Sets is new Ada.Containers.Indefinite_Hashed_Sets
(Element_Type => String,
Hash => Ada.Strings.Hash,
Equivalent_Elements => "=");
|
Fix header style
|
Fix header style
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
14026f1028465aeb992c63b1a7b6856c27745ebe
|
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) 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;
begin
Wiki.Strings.Clear (Parser.Preformat_Format);
Common.Skip_Spaces (Buffer, Pos);
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
Common.Skip_Spaces (Buffer, Pos);
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) 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);
Common.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
Common.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;
|
Update calls to Skip_Spaces
|
Update calls to Skip_Spaces
|
Ada
|
apache-2.0
|
stcarrez/ada-wiki,stcarrez/ada-wiki
|
de245f6c91d691131e8b062477c0d3847114353e
|
examples/orka/orka_test-test_8_ktx.adb
|
examples/orka/orka_test-test_8_ktx.adb
|
-- Copyright (c) 2017 onox <[email protected]>
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
with System.Multiprocessors.Dispatching_Domains;
with Ada.Command_Line;
with Ada.Exceptions;
with Ada.Real_Time;
with Ada.Text_IO;
with GL.Buffers;
with GL.Debug.Logs;
with GL.Objects.Textures;
with GL.Types;
with Orka.Behaviors;
with Orka.Contexts;
with Orka.Cameras;
with Orka.Loops;
with Orka.Debug;
with Orka.Futures;
with Orka.Rendering.Framebuffers;
with Orka.Rendering.Programs.Modules;
with Orka.Rendering.Programs.Uniforms;
with Orka.Rendering.Vertex_Formats;
with Orka.Resources.Loaders;
with Orka.Resources.Locations.Directories;
with Orka.Resources.Managers;
with Orka.Resources.Textures.KTX;
with Orka.Windows.GLFW;
with Orka_Test.Package_6_glTF;
procedure Orka_Test.Test_8_KTX is
Width : constant := 1280;
Height : constant := 720;
Initialized : constant Orka.Windows.GLFW.Active_GLFW'Class
:= Orka.Windows.GLFW.Initialize (Major => 3, Minor => 2, Debug => True);
pragma Unreferenced (Initialized);
W : constant Orka.Windows.Window'Class := Orka.Windows.GLFW.Create_Window
(Width, Height, Resizable => False);
W_Ptr : constant Orka.Windows.Window_Ptr := Orka.Windows.Window_Ptr'(W'Unchecked_Access);
Context : Orka.Contexts.Context;
package Boss renames Orka_Test.Package_6_glTF.Boss;
package Loader renames Orka_Test.Package_6_glTF.Loader;
use Ada.Exceptions;
begin
if Ada.Command_Line.Argument_Count /= 2 then
Ada.Text_IO.Put_Line ("Usage: <path to resources folder> <relative path to .ktx file>");
Boss.Shutdown;
Loader.Shutdown;
return;
end if;
System.Multiprocessors.Dispatching_Domains.Set_CPU (1);
Ada.Text_IO.Put_Line ("Flushing" & GL.Types.Size'Image (GL.Debug.Logs.Logged_Messages) & " messages in the debug log:");
Orka.Debug.Flush_Log;
Orka.Debug.Enable_Print_Callback;
Ada.Text_IO.Put_Line ("Set callback for debug messages");
-- Enable some features
Context.Enable (Orka.Contexts.Reversed_Z);
declare
Location_Path : constant String := Ada.Command_Line.Argument (1);
Texture_Path : constant String := Ada.Command_Line.Argument (2);
package Textures renames Orka.Resources.Textures;
package Formats renames Orka.Rendering.Vertex_Formats;
use Orka.Rendering.Programs;
use Orka.Rendering.Framebuffers;
use GL.Types;
P_1 : Program := Create_Program (Modules.Create_Module
(VS => "../examples/orka/shaders/test-8-module-1.vert",
FS => "../examples/orka/shaders/test-8-module-1.frag"));
Uni_Texture : constant Uniforms.Uniform_Sampler := P_1.Uniform_Sampler ("colorTexture");
Screen_Size : constant Uniforms.TS.Vector4
:= (Single (Width), Single (Height), 0.0, 0.0);
Uni_Screen : constant Uniforms.Uniform := P_1.Uniform ("screenSize");
-- Create an empty vertex format. Vertex shader contains the data needed
-- to generate a quad
VF_1 : constant Formats.Vertex_Format
:= Formats.Create_Vertex_Format (GL.Types.Triangles, GL.Types.UInt_Type);
FB_D : constant Framebuffer_Ptr
:= new Framebuffer'(Create_Default_Framebuffer (Width, Height));
-- The camera provides a view and projection matrices, but are unused
-- in the shaders. The object is created because package Loops needs it
use Orka.Cameras;
Lens : constant Lens_Ptr
:= new Camera_Lens'Class'(Create_Lens (Width, Height, 45.0, Context));
Current_Camera : constant Camera_Ptr
:= new Camera'Class'(Create_Camera (Rotate_Around, W.Pointer_Input, Lens, FB_D));
task Load_Resource;
use Orka.Resources;
use Ada.Real_Time;
Manager : constant Managers.Manager_Ptr := Managers.Create_Manager;
task body Load_Resource is
Loader_KTX : constant Loaders.Loader_Ptr := Textures.KTX.Create_Loader (Manager);
Location_Textures : constant Locations.Location_Ptr
:= Locations.Directories.Create_Location (Location_Path);
begin
Loader.Add_Location (Location_Textures, Loader_KTX);
Ada.Text_IO.Put_Line ("Registered resource locations");
declare
T1 : constant Time := Clock;
T2 : Time;
Future_Ref : Orka.Futures.Pointers.Reference := Loader.Load (Texture_Path);
use type Orka.Futures.Status;
Resource_Status : Orka.Futures.Status;
begin
Future_Ref.Wait_Until_Done (Resource_Status);
T2 := Clock;
pragma Assert (Resource_Status = Orka.Futures.Done);
pragma Assert (Manager.Contains (Texture_Path));
declare
Loading_Time : constant Duration := 1e3 * To_Duration (T2 - T1);
begin
Ada.Text_IO.Put_Line ("Loaded in " & Loading_Time'Image & " ms");
end;
-- Here we should either create a GPU job to set the
-- texture to the uniform or just simply set it in the
-- render callback below
end;
exception
when Error : others =>
Ada.Text_IO.Put_Line ("Error loading resource: " & Exception_Information (Error));
end Load_Resource;
begin
Uni_Screen.Set_Vector (Screen_Size);
declare
use GL.Objects.Textures;
Loaded : Boolean := False;
procedure Render
(Scene : not null Orka.Behaviors.Behavior_Array_Access;
Camera : Orka.Cameras.Camera_Ptr) is
begin
GL.Buffers.Clear (GL.Buffers.Buffer_Bits'
(Color => True, Depth => True, others => False));
Camera.FB.Use_Framebuffer;
P_1.Use_Program;
if not Loaded and then Manager.Contains (Texture_Path) then
declare
T_1 : constant Textures.Texture_Ptr
:= Textures.Texture_Ptr (Manager.Resource (Texture_Path));
T_2 : constant GL.Objects.Textures.Texture_Base'Class := T_1.Element;
-- TODO Handle non-Texture_2D textures
begin
T_2.Set_X_Wrapping (Clamp_To_Edge);
T_2.Set_X_Wrapping (Clamp_To_Edge);
T_2.Set_Minifying_Filter (Nearest);
T_2.Set_Magnifying_Filter (Nearest);
Uni_Texture.Set_Texture (T_2, 0);
end;
Ada.Text_IO.Put_Line ("Set texture");
Loaded := True;
end if;
VF_1.Draw (0, 6);
end Render;
package Loops is new Orka.Loops
(Time_Step => Ada.Real_Time.Microseconds (2_083),
Frame_Limit => Ada.Real_Time.Microseconds (2_083),
Window => W_Ptr,
Camera => Current_Camera,
Render => Render'Unrestricted_Access,
Job_Manager => Boss);
begin
Loops.Scene.Add (Orka.Behaviors.Null_Behavior);
Ada.Text_IO.Put_Line ("Running render loop...");
Loops.Run_Loop;
end;
Ada.Text_IO.Put_Line ("Shutting down...");
Boss.Shutdown;
Loader.Shutdown;
Ada.Text_IO.Put_Line ("Shutdown job system and loader");
end;
exception
when Error : others =>
Ada.Text_IO.Put_Line ("Error: " & Exception_Information (Error));
end Orka_Test.Test_8_KTX;
|
-- Copyright (c) 2017 onox <[email protected]>
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
with System.Multiprocessors.Dispatching_Domains;
with Ada.Command_Line;
with Ada.Exceptions;
with Ada.Real_Time;
with Ada.Text_IO;
with GL.Buffers;
with GL.Debug.Logs;
with GL.Objects.Textures;
with GL.Types;
with Orka.Behaviors;
with Orka.Contexts;
with Orka.Cameras;
with Orka.Loops;
with Orka.Debug;
with Orka.Futures;
with Orka.Rendering.Framebuffers;
with Orka.Rendering.Programs.Modules;
with Orka.Rendering.Programs.Uniforms;
with Orka.Rendering.Vertex_Formats;
with Orka.Resources.Loaders;
with Orka.Resources.Locations.Directories;
with Orka.Resources.Managers;
with Orka.Resources.Textures.KTX;
with Orka.Windows.GLFW;
with Orka_Test.Package_6_glTF;
procedure Orka_Test.Test_8_KTX is
Width : constant := 1280;
Height : constant := 720;
Initialized : constant Orka.Windows.GLFW.Active_GLFW'Class
:= Orka.Windows.GLFW.Initialize (Major => 3, Minor => 2, Debug => True);
pragma Unreferenced (Initialized);
W : constant Orka.Windows.Window'Class := Orka.Windows.GLFW.Create_Window
(Width, Height, Resizable => False);
W_Ptr : constant Orka.Windows.Window_Ptr := Orka.Windows.Window_Ptr'(W'Unchecked_Access);
Context : Orka.Contexts.Context;
package Boss renames Orka_Test.Package_6_glTF.Boss;
package Loader renames Orka_Test.Package_6_glTF.Loader;
use Ada.Exceptions;
begin
if Ada.Command_Line.Argument_Count /= 2 then
Ada.Text_IO.Put_Line ("Usage: <path to resources folder> <relative path to .ktx file>");
Boss.Shutdown;
Loader.Shutdown;
return;
end if;
System.Multiprocessors.Dispatching_Domains.Set_CPU (1);
Ada.Text_IO.Put_Line ("Flushing" & GL.Types.Size'Image (GL.Debug.Logs.Logged_Messages) & " messages in the debug log:");
Orka.Debug.Flush_Log;
Orka.Debug.Enable_Print_Callback;
Ada.Text_IO.Put_Line ("Set callback for debug messages");
-- Enable some features
Context.Enable (Orka.Contexts.Reversed_Z);
declare
Location_Path : constant String := Ada.Command_Line.Argument (1);
Texture_Path : constant String := Ada.Command_Line.Argument (2);
package Textures renames Orka.Resources.Textures;
package Formats renames Orka.Rendering.Vertex_Formats;
use Orka.Rendering.Programs;
use Orka.Rendering.Framebuffers;
use GL.Types;
P_1 : Program := Create_Program (Modules.Create_Module
(VS => "../examples/orka/shaders/test-8-module-1.vert",
FS => "../examples/orka/shaders/test-8-module-1.frag"));
Uni_Texture : constant Uniforms.Uniform_Sampler := P_1.Uniform_Sampler ("colorTexture");
Screen_Size : constant Uniforms.TS.Vector4
:= (Single (Width), Single (Height), 0.0, 0.0);
Uni_Screen : constant Uniforms.Uniform := P_1.Uniform ("screenSize");
-- Create an empty vertex format. Vertex shader contains the data needed
-- to generate a quad
VF_1 : constant Formats.Vertex_Format
:= Formats.Create_Vertex_Format (GL.Types.Triangles, GL.Types.UInt_Type);
FB_D : constant Framebuffer_Ptr
:= new Framebuffer'(Create_Default_Framebuffer (Width, Height));
-- The camera provides a view and projection matrices, but are unused
-- in the shaders. The object is created because package Loops needs it
use Orka.Cameras;
Lens : constant Lens_Ptr
:= new Camera_Lens'Class'(Create_Lens (Width, Height, 45.0, Context));
Current_Camera : constant Camera_Ptr
:= new Camera'Class'(Create_Camera (Rotate_Around, W.Pointer_Input, Lens, FB_D));
task Load_Resource;
use Orka.Resources;
use Ada.Real_Time;
Manager : constant Managers.Manager_Ptr := Managers.Create_Manager;
task body Load_Resource is
Loader_KTX : constant Loaders.Loader_Ptr := Textures.KTX.Create_Loader (Manager);
Location_Textures : constant Locations.Location_Ptr
:= Locations.Directories.Create_Location (Location_Path);
begin
Loader.Add_Location (Location_Textures, Loader_KTX);
Ada.Text_IO.Put_Line ("Registered resource locations");
declare
T1 : constant Time := Clock;
T2 : Time;
Future_Ref : Orka.Futures.Pointers.Reference := Loader.Load (Texture_Path);
use type Orka.Futures.Status;
Resource_Status : Orka.Futures.Status;
begin
Future_Ref.Wait_Until_Done (Resource_Status);
T2 := Clock;
pragma Assert (Resource_Status = Orka.Futures.Done);
pragma Assert (Manager.Contains (Texture_Path));
declare
Loading_Time : constant Duration := 1e3 * To_Duration (T2 - T1);
begin
Ada.Text_IO.Put_Line ("Loaded in " & Loading_Time'Image & " ms");
end;
-- Here we should either create a GPU job to set the
-- texture to the uniform or just simply set it in the
-- render callback below
end;
exception
when Error : others =>
Ada.Text_IO.Put_Line ("Error loading resource: " & Exception_Information (Error));
end Load_Resource;
begin
Uni_Screen.Set_Vector (Screen_Size);
declare
use GL.Objects.Textures;
Loaded : Boolean := False;
procedure Render
(Scene : not null Orka.Behaviors.Behavior_Array_Access;
Camera : Orka.Cameras.Camera_Ptr) is
begin
GL.Buffers.Clear (GL.Buffers.Buffer_Bits'
(Color => True, Depth => True, others => False));
Camera.FB.Use_Framebuffer;
P_1.Use_Program;
if not Loaded and then Manager.Contains (Texture_Path) then
declare
T_1 : constant Textures.Texture_Ptr
:= Textures.Texture_Ptr (Manager.Resource (Texture_Path));
T_2 : constant GL.Objects.Textures.Texture_Base'Class := T_1.Element;
-- TODO Handle non-Texture_2D textures
begin
T_2.Set_X_Wrapping (Clamp_To_Edge);
T_2.Set_X_Wrapping (Clamp_To_Edge);
T_2.Set_Minifying_Filter (Nearest);
T_2.Set_Magnifying_Filter (Nearest);
Uni_Texture.Set_Texture (T_2, 0);
end;
Ada.Text_IO.Put_Line ("Set texture");
Loaded := True;
end if;
VF_1.Draw (0, 6);
end Render;
package Loops is new Orka.Loops
(Time_Step => Ada.Real_Time.Microseconds (2_083),
Frame_Limit => Ada.Real_Time.Microseconds (16_667),
Window => W_Ptr,
Camera => Current_Camera,
Render => Render'Unrestricted_Access,
Job_Manager => Boss);
begin
Loops.Scene.Add (Orka.Behaviors.Null_Behavior);
Ada.Text_IO.Put_Line ("Running render loop...");
Loops.Run_Loop;
end;
Ada.Text_IO.Put_Line ("Shutting down...");
Boss.Shutdown;
Loader.Shutdown;
Ada.Text_IO.Put_Line ("Shutdown job system and loader");
end;
exception
when Error : others =>
Ada.Text_IO.Put_Line ("Error: " & Exception_Information (Error));
end Orka_Test.Test_8_KTX;
|
Set frame limit to 60 FPS in KTX example
|
examples: Set frame limit to 60 FPS in KTX example
Signed-off-by: onox <[email protected]>
|
Ada
|
apache-2.0
|
onox/orka
|
36f11ab7353195dfda1eddeaa5f5004b929e67c9
|
src/asf-views-nodes-core.adb
|
src/asf-views-nodes-core.adb
|
-----------------------------------------------------------------------
-- nodes-core -- Core nodes
-- 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.Strings.Transforms;
package body ASF.Views.Nodes.Core is
-- ------------------------------
-- Set Tag
-- ------------------------------
-- ------------------------------
-- Create the Set Tag
-- ------------------------------
function Create_Set_Tag_Node (Name : Unbounded_String;
Line : Line_Info;
Parent : Tag_Node_Access;
Attributes : Tag_Attribute_Array_Access)
return Tag_Node_Access is
Node : constant Set_Tag_Node_Access := new Set_Tag_Node;
begin
Initialize (Node.all'Access, Name, Line, Parent, Attributes);
Node.Value := Find_Attribute (Attributes, "value");
Node.Var := Find_Attribute (Attributes, "var");
if Node.Value = null then
Node.Error ("Missing 'value' attribute");
end if;
if Node.Var = null then
Node.Error ("Missing 'var' attribute");
end if;
return Node.all'Access;
end Create_Set_Tag_Node;
-- ------------------------------
-- Build the component tree from the tag node and attach it as
-- the last child of the given parent. Calls recursively the
-- method to create children.
-- ------------------------------
overriding
procedure Build_Components (Node : access Set_Tag_Node;
Parent : in UIComponent_Access;
Context : in out Facelet_Context'Class) is
pragma Unreferenced (Parent);
Value : constant EL.Expressions.Expression
:= Get_Expression (Node.Value.all);
begin
Context.Set_Variable (Node.Var.Value, Value);
end Build_Components;
-- ------------------------------
-- If Tag
-- ------------------------------
-- ------------------------------
-- Create the If Tag
-- ------------------------------
function Create_If_Tag_Node (Name : Unbounded_String;
Line : Line_Info;
Parent : Tag_Node_Access;
Attributes : Tag_Attribute_Array_Access)
return Tag_Node_Access is
Node : constant If_Tag_Node_Access := new If_Tag_Node;
begin
Initialize (Node.all'Access, Name, Line, Parent, Attributes);
Node.Condition := Find_Attribute (Attributes, "test");
Node.Var := Find_Attribute (Attributes, "var");
if Node.Condition = null then
Node.Error ("Missing 'test' attribute");
end if;
return Node.all'Access;
end Create_If_Tag_Node;
-- ------------------------------
-- Build the component tree from the tag node and attach it as
-- the last child of the given parent. Calls recursively the
-- method to create children.
-- ------------------------------
overriding
procedure Build_Components (Node : access If_Tag_Node;
Parent : in UIComponent_Access;
Context : in out Facelet_Context'Class) is
Value : constant EL.Objects.Object := Get_Value (Node.Condition.all, Context);
begin
if Node.Var /= null then
Context.Set_Attribute (Node.Var.Value, Value);
end if;
if EL.Objects.To_Boolean (Value) then
Tag_Node (Node.all).Build_Children (Parent, Context);
end if;
end Build_Components;
-- ------------------------------
-- Choose Tag
-- ------------------------------
-- ------------------------------
-- Create the Choose Tag
-- ------------------------------
function Create_Choose_Tag_Node (Name : Unbounded_String;
Line : Line_Info;
Parent : Tag_Node_Access;
Attributes : Tag_Attribute_Array_Access)
return Tag_Node_Access is
Node : constant Choose_Tag_Node_Access := new Choose_Tag_Node;
begin
Initialize (Node.all'Access, Name, Line, Parent, Attributes);
return Node.all'Access;
end Create_Choose_Tag_Node;
-- ------------------------------
-- Freeze the tag node tree and perform any initialization steps
-- necessary to build the components efficiently.
-- Prepare the evaluation of choices by identifying the <c:when> and
-- <c:otherwise> conditions.
-- ------------------------------
overriding
procedure Freeze (Node : access Choose_Tag_Node) is
Child : Tag_Node_Access := Node.First_Child;
Choice : When_Tag_Node_Access := null;
begin
while Child /= null loop
if Child.all in Otherwise_Tag_Node'Class then
Node.Otherwise := Child;
elsif Child.all in When_Tag_Node'Class then
if Choice = null then
Node.Choices := When_Tag_Node (Child.all)'Access;
else
Choice.Next_Choice := When_Tag_Node (Child.all)'Access;
end if;
Choice := When_Tag_Node (Child.all)'Access;
else
null;
-- @todo: report a warning in a log
-- @todo: clean the sub-tree and remove what is not necessary
end if;
Child := Child.Next;
end loop;
end Freeze;
-- ------------------------------
-- Build the component tree from the tag node and attach it as
-- the last child of the given parent. Calls recursively the
-- method to create children.
-- ------------------------------
overriding
procedure Build_Components (Node : access Choose_Tag_Node;
Parent : in UIComponent_Access;
Context : in out Facelet_Context'Class) is
Choice : When_Tag_Node_Access := Node.Choices;
begin
-- Evaluate the choices and stop at the first which succeeds
while Choice /= null loop
if Choice.Is_Selected (Context) then
Choice.Build_Children (Parent, Context);
return;
end if;
Choice := Choice.Next_Choice;
end loop;
-- No choice matched, build the otherwise clause.
if Node.Otherwise /= null then
Node.Otherwise.Build_Children (Parent, Context);
end if;
end Build_Components;
-- ------------------------------
-- Create the When Tag
-- ------------------------------
function Create_When_Tag_Node (Name : Unbounded_String;
Line : Line_Info;
Parent : Tag_Node_Access;
Attributes : Tag_Attribute_Array_Access)
return Tag_Node_Access is
Node : constant When_Tag_Node_Access := new When_Tag_Node;
begin
Initialize (Node.all'Access, Name, Line, Parent, Attributes);
Node.Condition := Find_Attribute (Attributes, "test");
if Node.Condition = null then
Node.Error ("Missing 'test' attribute");
end if;
-- Node.Var := Find_Attribute (Attributes, "var");
return Node.all'Access;
end Create_When_Tag_Node;
-- ------------------------------
-- Check whether the node condition is selected.
-- ------------------------------
function Is_Selected (Node : When_Tag_Node;
Context : Facelet_Context'Class) return Boolean is
begin
return EL.Objects.To_Boolean (Get_Value (Node.Condition.all, Context));
end Is_Selected;
-- ------------------------------
-- Create the Otherwise Tag
-- ------------------------------
function Create_Otherwise_Tag_Node (Name : Unbounded_String;
Line : Line_Info;
Parent : Tag_Node_Access;
Attributes : Tag_Attribute_Array_Access)
return Tag_Node_Access is
Node : constant Otherwise_Tag_Node_Access := new Otherwise_Tag_Node;
begin
Initialize (Node.all'Access, Name, Line, Parent, Attributes);
return Node.all'Access;
end Create_Otherwise_Tag_Node;
-- Tag names
CHOOSE_TAG : aliased constant String := "choose";
IF_TAG : aliased constant String := "if";
OTHERWISE_TAG : aliased constant String := "otherwise";
SET_TAG : aliased constant String := "set";
WHEN_TAG : aliased constant String := "when";
-- Name-space URI. Use the JSTL name-space to make the XHTML views compatible
-- the JSF.
URI : aliased constant String := "http://java.sun.com/jstl/core";
-- Tag library definition. Names must be sorted.
Tag_Bindings : aliased constant ASF.Factory.Binding_Array
:= ((Name => CHOOSE_TAG'Access,
Component => null,
Tag => Create_Choose_Tag_Node'Access),
(Name => IF_TAG'Access,
Component => null,
Tag => Create_If_Tag_Node'Access),
(Name => OTHERWISE_TAG'Access,
Component => null,
Tag => Create_Otherwise_Tag_Node'Access),
(Name => SET_TAG'Access,
Component => null,
Tag => Create_Set_Tag_Node'Access),
(Name => WHEN_TAG'Access,
Component => null,
Tag => Create_When_Tag_Node'Access));
Tag_Factory : aliased constant ASF.Factory.Factory_Bindings
:= (URI => URI'Access, Bindings => Tag_Bindings'Access);
-- ------------------------------
-- Tag factory for nodes defined in this package.
-- ------------------------------
function Definition return ASF.Factory.Factory_Bindings_Access is
begin
return Tag_Factory'Access;
end Definition;
-- Function names
CAPITALIZE_FN : aliased constant String := "capitalize";
TO_UPPER_CASE_FN : aliased constant String := "toUpperCase";
TO_LOWER_CASE_FN : aliased constant String := "toLowerCase";
function Capitalize (Value : EL.Objects.Object) return EL.Objects.Object;
function To_Upper_Case (Value : EL.Objects.Object) return EL.Objects.Object;
function To_Lower_Case (Value : EL.Objects.Object) return EL.Objects.Object;
function Capitalize (Value : EL.Objects.Object) return EL.Objects.Object is
S : constant String := EL.Objects.To_String (Value);
begin
return EL.Objects.To_Object (Util.Strings.Transforms.Capitalize (S));
end Capitalize;
function To_Upper_Case (Value : EL.Objects.Object) return EL.Objects.Object is
S : constant String := EL.Objects.To_String (Value);
begin
return EL.Objects.To_Object (Util.Strings.Transforms.To_Upper_Case (S));
end To_Upper_Case;
function To_Lower_Case (Value : EL.Objects.Object) return EL.Objects.Object is
S : constant String := EL.Objects.To_String (Value);
begin
return EL.Objects.To_Object (Util.Strings.Transforms.To_Lower_Case (S));
end To_Lower_Case;
-- ------------------------------
-- Register a set of functions in the namespace
-- xmlns:fn="http://java.sun.com/jsp/jstl/functions"
-- Functions:
-- capitalize, toUpperCase, toLowerCase
-- ------------------------------
procedure Set_Functions (Mapper : in out EL.Functions.Function_Mapper'Class) is
URI : constant String := "http://java.sun.com/jsp/jstl/functions";
begin
Mapper.Set_Function (Name => CAPITALIZE_FN,
Namespace => URI,
Func => Capitalize'Access);
Mapper.Set_Function (Name => TO_LOWER_CASE_FN,
Namespace => URI,
Func => To_Lower_Case'Access);
Mapper.Set_Function (Name => TO_UPPER_CASE_FN,
Namespace => URI,
Func => To_Upper_Case'Access);
end Set_Functions;
end ASF.Views.Nodes.Core;
|
-----------------------------------------------------------------------
-- nodes-core -- Core nodes
-- 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.Strings.Transforms;
with Ada.Strings.Fixed;
package body ASF.Views.Nodes.Core is
-- ------------------------------
-- Set Tag
-- ------------------------------
-- ------------------------------
-- Create the Set Tag
-- ------------------------------
function Create_Set_Tag_Node (Name : Unbounded_String;
Line : Line_Info;
Parent : Tag_Node_Access;
Attributes : Tag_Attribute_Array_Access)
return Tag_Node_Access is
Node : constant Set_Tag_Node_Access := new Set_Tag_Node;
begin
Initialize (Node.all'Access, Name, Line, Parent, Attributes);
Node.Value := Find_Attribute (Attributes, "value");
Node.Var := Find_Attribute (Attributes, "var");
if Node.Value = null then
Node.Error ("Missing 'value' attribute");
end if;
if Node.Var = null then
Node.Error ("Missing 'var' attribute");
end if;
return Node.all'Access;
end Create_Set_Tag_Node;
-- ------------------------------
-- Build the component tree from the tag node and attach it as
-- the last child of the given parent. Calls recursively the
-- method to create children.
-- ------------------------------
overriding
procedure Build_Components (Node : access Set_Tag_Node;
Parent : in UIComponent_Access;
Context : in out Facelet_Context'Class) is
pragma Unreferenced (Parent);
Value : constant EL.Expressions.Expression
:= Get_Expression (Node.Value.all);
begin
Context.Set_Variable (Node.Var.Value, Value);
end Build_Components;
-- ------------------------------
-- If Tag
-- ------------------------------
-- ------------------------------
-- Create the If Tag
-- ------------------------------
function Create_If_Tag_Node (Name : Unbounded_String;
Line : Line_Info;
Parent : Tag_Node_Access;
Attributes : Tag_Attribute_Array_Access)
return Tag_Node_Access is
Node : constant If_Tag_Node_Access := new If_Tag_Node;
begin
Initialize (Node.all'Access, Name, Line, Parent, Attributes);
Node.Condition := Find_Attribute (Attributes, "test");
Node.Var := Find_Attribute (Attributes, "var");
if Node.Condition = null then
Node.Error ("Missing 'test' attribute");
end if;
return Node.all'Access;
end Create_If_Tag_Node;
-- ------------------------------
-- Build the component tree from the tag node and attach it as
-- the last child of the given parent. Calls recursively the
-- method to create children.
-- ------------------------------
overriding
procedure Build_Components (Node : access If_Tag_Node;
Parent : in UIComponent_Access;
Context : in out Facelet_Context'Class) is
Value : constant EL.Objects.Object := Get_Value (Node.Condition.all, Context);
begin
if Node.Var /= null then
Context.Set_Attribute (Node.Var.Value, Value);
end if;
if EL.Objects.To_Boolean (Value) then
Tag_Node (Node.all).Build_Children (Parent, Context);
end if;
end Build_Components;
-- ------------------------------
-- Choose Tag
-- ------------------------------
-- ------------------------------
-- Create the Choose Tag
-- ------------------------------
function Create_Choose_Tag_Node (Name : Unbounded_String;
Line : Line_Info;
Parent : Tag_Node_Access;
Attributes : Tag_Attribute_Array_Access)
return Tag_Node_Access is
Node : constant Choose_Tag_Node_Access := new Choose_Tag_Node;
begin
Initialize (Node.all'Access, Name, Line, Parent, Attributes);
return Node.all'Access;
end Create_Choose_Tag_Node;
-- ------------------------------
-- Freeze the tag node tree and perform any initialization steps
-- necessary to build the components efficiently.
-- Prepare the evaluation of choices by identifying the <c:when> and
-- <c:otherwise> conditions.
-- ------------------------------
overriding
procedure Freeze (Node : access Choose_Tag_Node) is
Child : Tag_Node_Access := Node.First_Child;
Choice : When_Tag_Node_Access := null;
begin
while Child /= null loop
if Child.all in Otherwise_Tag_Node'Class then
Node.Otherwise := Child;
elsif Child.all in When_Tag_Node'Class then
if Choice = null then
Node.Choices := When_Tag_Node (Child.all)'Access;
else
Choice.Next_Choice := When_Tag_Node (Child.all)'Access;
end if;
Choice := When_Tag_Node (Child.all)'Access;
else
null;
-- @todo: report a warning in a log
-- @todo: clean the sub-tree and remove what is not necessary
end if;
Child := Child.Next;
end loop;
end Freeze;
-- ------------------------------
-- Build the component tree from the tag node and attach it as
-- the last child of the given parent. Calls recursively the
-- method to create children.
-- ------------------------------
overriding
procedure Build_Components (Node : access Choose_Tag_Node;
Parent : in UIComponent_Access;
Context : in out Facelet_Context'Class) is
Choice : When_Tag_Node_Access := Node.Choices;
begin
-- Evaluate the choices and stop at the first which succeeds
while Choice /= null loop
if Choice.Is_Selected (Context) then
Choice.Build_Children (Parent, Context);
return;
end if;
Choice := Choice.Next_Choice;
end loop;
-- No choice matched, build the otherwise clause.
if Node.Otherwise /= null then
Node.Otherwise.Build_Children (Parent, Context);
end if;
end Build_Components;
-- ------------------------------
-- Create the When Tag
-- ------------------------------
function Create_When_Tag_Node (Name : Unbounded_String;
Line : Line_Info;
Parent : Tag_Node_Access;
Attributes : Tag_Attribute_Array_Access)
return Tag_Node_Access is
Node : constant When_Tag_Node_Access := new When_Tag_Node;
begin
Initialize (Node.all'Access, Name, Line, Parent, Attributes);
Node.Condition := Find_Attribute (Attributes, "test");
if Node.Condition = null then
Node.Error ("Missing 'test' attribute");
end if;
-- Node.Var := Find_Attribute (Attributes, "var");
return Node.all'Access;
end Create_When_Tag_Node;
-- ------------------------------
-- Check whether the node condition is selected.
-- ------------------------------
function Is_Selected (Node : When_Tag_Node;
Context : Facelet_Context'Class) return Boolean is
begin
return EL.Objects.To_Boolean (Get_Value (Node.Condition.all, Context));
end Is_Selected;
-- ------------------------------
-- Create the Otherwise Tag
-- ------------------------------
function Create_Otherwise_Tag_Node (Name : Unbounded_String;
Line : Line_Info;
Parent : Tag_Node_Access;
Attributes : Tag_Attribute_Array_Access)
return Tag_Node_Access is
Node : constant Otherwise_Tag_Node_Access := new Otherwise_Tag_Node;
begin
Initialize (Node.all'Access, Name, Line, Parent, Attributes);
return Node.all'Access;
end Create_Otherwise_Tag_Node;
-- Tag names
CHOOSE_TAG : aliased constant String := "choose";
IF_TAG : aliased constant String := "if";
OTHERWISE_TAG : aliased constant String := "otherwise";
SET_TAG : aliased constant String := "set";
WHEN_TAG : aliased constant String := "when";
-- Name-space URI. Use the JSTL name-space to make the XHTML views compatible
-- the JSF.
URI : aliased constant String := "http://java.sun.com/jstl/core";
-- Tag library definition. Names must be sorted.
Tag_Bindings : aliased constant ASF.Factory.Binding_Array
:= ((Name => CHOOSE_TAG'Access,
Component => null,
Tag => Create_Choose_Tag_Node'Access),
(Name => IF_TAG'Access,
Component => null,
Tag => Create_If_Tag_Node'Access),
(Name => OTHERWISE_TAG'Access,
Component => null,
Tag => Create_Otherwise_Tag_Node'Access),
(Name => SET_TAG'Access,
Component => null,
Tag => Create_Set_Tag_Node'Access),
(Name => WHEN_TAG'Access,
Component => null,
Tag => Create_When_Tag_Node'Access));
Tag_Factory : aliased constant ASF.Factory.Factory_Bindings
:= (URI => URI'Access, Bindings => Tag_Bindings'Access);
-- ------------------------------
-- Tag factory for nodes defined in this package.
-- ------------------------------
function Definition return ASF.Factory.Factory_Bindings_Access is
begin
return Tag_Factory'Access;
end Definition;
-- Function names
CAPITALIZE_FN : aliased constant String := "capitalize";
TO_UPPER_CASE_FN : aliased constant String := "toUpperCase";
TO_LOWER_CASE_FN : aliased constant String := "toLowerCase";
SUBSTRING_AFTER_FN : aliased constant String := "substringAfter";
SUBSTRING_BEFORE_FN : aliased constant String := "substringBefore";
function Capitalize (Value : EL.Objects.Object) return EL.Objects.Object;
function To_Upper_Case (Value : EL.Objects.Object) return EL.Objects.Object;
function To_Lower_Case (Value : EL.Objects.Object) return EL.Objects.Object;
function Substring_Before (Value : in EL.Objects.Object;
Token : in EL.Objects.Object) return EL.Objects.Object;
function Substring_After (Value : in EL.Objects.Object;
Token : in EL.Objects.Object) return EL.Objects.Object;
function Capitalize (Value : EL.Objects.Object) return EL.Objects.Object is
S : constant String := EL.Objects.To_String (Value);
begin
return EL.Objects.To_Object (Util.Strings.Transforms.Capitalize (S));
end Capitalize;
function To_Upper_Case (Value : EL.Objects.Object) return EL.Objects.Object is
S : constant String := EL.Objects.To_String (Value);
begin
return EL.Objects.To_Object (Util.Strings.Transforms.To_Upper_Case (S));
end To_Upper_Case;
function To_Lower_Case (Value : EL.Objects.Object) return EL.Objects.Object is
S : constant String := EL.Objects.To_String (Value);
begin
return EL.Objects.To_Object (Util.Strings.Transforms.To_Lower_Case (S));
end To_Lower_Case;
-- ------------------------------
-- Return the substring before the token string
-- ------------------------------
function Substring_Before (Value : in EL.Objects.Object;
Token : in EL.Objects.Object) return EL.Objects.Object is
S : constant String := EL.Objects.To_String (Value);
T : constant String := EL.Objects.To_String (Token);
Pos : constant Natural := Ada.Strings.Fixed.Index (S, T);
begin
if Pos = 0 then
return EL.Objects.Null_Object;
else
return EL.Objects.To_Object (S (S'First .. Pos - 1));
end if;
end Substring_Before;
-- ------------------------------
-- Return the substring after the token string
-- ------------------------------
function Substring_After (Value : in EL.Objects.Object;
Token : in EL.Objects.Object) return EL.Objects.Object is
S : constant String := EL.Objects.To_String (Value);
T : constant String := EL.Objects.To_String (Token);
Pos : constant Natural := Ada.Strings.Fixed.Index (S, T);
begin
if Pos = 0 then
return EL.Objects.Null_Object;
else
return EL.Objects.To_Object (S (Pos + T'Length .. S'Last));
end if;
end Substring_After;
-- ------------------------------
-- Register a set of functions in the namespace
-- xmlns:fn="http://java.sun.com/jsp/jstl/functions"
-- Functions:
-- capitalize, toUpperCase, toLowerCase
-- ------------------------------
procedure Set_Functions (Mapper : in out EL.Functions.Function_Mapper'Class) is
URI : constant String := "http://java.sun.com/jsp/jstl/functions";
begin
Mapper.Set_Function (Name => CAPITALIZE_FN,
Namespace => URI,
Func => Capitalize'Access);
Mapper.Set_Function (Name => TO_LOWER_CASE_FN,
Namespace => URI,
Func => To_Lower_Case'Access);
Mapper.Set_Function (Name => TO_UPPER_CASE_FN,
Namespace => URI,
Func => To_Upper_Case'Access);
Mapper.Set_Function (Name => SUBSTRING_BEFORE_FN,
Namespace => URI,
Func => Substring_Before'Access);
Mapper.Set_Function (Name => SUBSTRING_AFTER_FN,
Namespace => URI,
Func => Substring_After'Access);
end Set_Functions;
end ASF.Views.Nodes.Core;
|
Add substring before and substring after EL functions
|
Add substring before and substring after EL functions
|
Ada
|
apache-2.0
|
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
|
7c6e6547010fd969e00e00f05313acfc449bd6e2
|
src/gen-model-operations.adb
|
src/gen-model-operations.adb
|
-----------------------------------------------------------------------
-- gen-model-operations -- Operation declarations
-- Copyright (C) 2012, 2016, 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
package body Gen.Model.Operations 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 : in Operation_Definition;
Name : in String) return Util.Beans.Objects.Object is
begin
if Name = "parameters" or Name = "columns" then
return From.Parameters_Bean;
elsif Name = "return" then
return Util.Beans.Objects.To_Object (From.Return_Type);
elsif Name = "type" then
return Util.Beans.Objects.To_Object (Operation_Type'Image (From.Kind));
else
return Definition (From).Get_Value (Name);
end if;
end Get_Value;
-- Prepare the generation of the model.
overriding
procedure Prepare (O : in out Operation_Definition) is
begin
null;
end Prepare;
-- ------------------------------
-- Initialize the operation definition instance.
-- ------------------------------
overriding
procedure Initialize (O : in out Operation_Definition) is
begin
O.Parameters_Bean := Util.Beans.Objects.To_Object (O.Parameters'Unchecked_Access,
Util.Beans.Objects.STATIC);
end Initialize;
-- ------------------------------
-- Add an operation parameter with the given name and type.
-- ------------------------------
procedure Add_Parameter (Into : in out Operation_Definition;
Name : in Unbounded_String;
Of_Type : in Unbounded_String;
Parameter : out Parameter_Definition_Access) is
begin
Parameter := new Parameter_Definition;
Parameter.Name := Name;
Parameter.Type_Name := Of_Type;
Into.Parameters.Append (Parameter);
if Into.Kind = UNKNOWN and then Of_Type = "ASF.Parts.Part" then
Into.Kind := ASF_UPLOAD;
elsif Into.Kind = UNKNOWN and then Of_Type = "AWA.Events.Module_Event" then
Into.Kind := AWA_EVENT;
elsif Into.Kind = UNKNOWN then
Into.Kind := ASF_ACTION;
end if;
end Add_Parameter;
-- ------------------------------
-- Get the operation type.
-- ------------------------------
function Get_Type (From : in Operation_Definition) return Operation_Type is
begin
return From.Kind;
end Get_Type;
-- ------------------------------
-- Create an operation with the given name.
-- ------------------------------
function Create_Operation (Name : in Unbounded_String) return Operation_Definition_Access is
pragma Unreferenced (Name);
Result : constant Operation_Definition_Access := new Operation_Definition;
begin
return Result;
end Create_Operation;
end Gen.Model.Operations;
|
-----------------------------------------------------------------------
-- gen-model-operations -- Operation declarations
-- Copyright (C) 2012, 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.
-----------------------------------------------------------------------
package body Gen.Model.Operations 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 : in Operation_Definition;
Name : in String) return Util.Beans.Objects.Object is
begin
if Name = "parameters" or Name = "columns" then
return From.Parameters_Bean;
elsif Name = "return" then
return Util.Beans.Objects.To_Object (From.Return_Type);
elsif Name = "type" then
return Util.Beans.Objects.To_Object (Operation_Type'Image (From.Kind));
else
return Definition (From).Get_Value (Name);
end if;
end Get_Value;
-- Prepare the generation of the model.
overriding
procedure Prepare (O : in out Operation_Definition) is
begin
null;
end Prepare;
-- ------------------------------
-- Initialize the operation definition instance.
-- ------------------------------
overriding
procedure Initialize (O : in out Operation_Definition) is
begin
O.Parameters_Bean := Util.Beans.Objects.To_Object (O.Parameters'Unchecked_Access,
Util.Beans.Objects.STATIC);
end Initialize;
-- ------------------------------
-- Add an operation parameter with the given name and type.
-- ------------------------------
procedure Add_Parameter (Into : in out Operation_Definition;
Name : in Unbounded_String;
Of_Type : in Unbounded_String;
Parameter : out Parameter_Definition_Access) is
begin
Parameter := new Parameter_Definition;
Parameter.Set_Name (Name);
Parameter.Type_Name := Of_Type;
Into.Parameters.Append (Parameter);
if Into.Kind = UNKNOWN and then Of_Type = "ASF.Parts.Part" then
Into.Kind := ASF_UPLOAD;
elsif Into.Kind = UNKNOWN and then Of_Type = "AWA.Events.Module_Event" then
Into.Kind := AWA_EVENT;
elsif Into.Kind = UNKNOWN then
Into.Kind := ASF_ACTION;
end if;
end Add_Parameter;
-- ------------------------------
-- Get the operation type.
-- ------------------------------
function Get_Type (From : in Operation_Definition) return Operation_Type is
begin
return From.Kind;
end Get_Type;
-- ------------------------------
-- Create an operation with the given name.
-- ------------------------------
function Create_Operation (Name : in Unbounded_String) return Operation_Definition_Access is
pragma Unreferenced (Name);
Result : constant Operation_Definition_Access := new Operation_Definition;
begin
return Result;
end Create_Operation;
end Gen.Model.Operations;
|
Update to use Get_Location and Set_Name
|
Update to use Get_Location and Set_Name
|
Ada
|
apache-2.0
|
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
|
200593fb1b017d5def4423f115034719b8dc56dd
|
awa/src/awa-permissions-controllers.ads
|
awa/src/awa-permissions-controllers.ads
|
-----------------------------------------------------------------------
-- awa-permissions-controllers -- Permission controllers
-- Copyright (C) 2011, 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Security.Contexts;
with Security.Controllers;
package AWA.Permissions.Controllers is
-- ------------------------------
-- Security Controller
-- ------------------------------
-- The <b>Entity_Controller</b> implements an entity based permission check.
-- The controller is configured through an XML description. It uses an SQL statement
-- to verify that a permission is granted.
--
-- The SQL query can use the following query parameters:
--
-- <dl>
-- <dt>entity_type</dt>
-- <dd>The entity type identifier defined by the entity permission</dd>
-- <dt>entity_id</dt>
-- <dd>The entity identifier which is associated with an <b>ACL</b> entry to check</dd>
-- <dt>user_id</dt>
-- <dd>The user identifier</dd>
-- </dl>
type Entity_Controller (Len : Positive) is
limited new Security.Controllers.Controller with record
SQL : String (1 .. Len);
Entity : ADO.Entity_Type;
end record;
type Entity_Controller_Access is access all Entity_Controller'Class;
-- Returns true if the user associated with the security context <b>Context</b> has
-- the permission to access a database entity. The security context contains some
-- information about the entity to check and the permission controller will use an
-- SQL statement to verify the permission.
overriding
function Has_Permission (Handler : in Entity_Controller;
Context : in Security.Contexts.Security_Context'Class;
Permission : in Security.Permissions.Permission'Class)
return Boolean;
end AWA.Permissions.Controllers;
|
-----------------------------------------------------------------------
-- awa-permissions-controllers -- Permission controllers
-- 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 Security.Contexts;
with Security.Controllers;
package AWA.Permissions.Controllers is
-- ------------------------------
-- Security Controller
-- ------------------------------
-- The <b>Entity_Controller</b> implements an entity based permission check.
-- The controller is configured through an XML description. It uses an SQL statement
-- to verify that a permission is granted.
--
-- The SQL query can use the following query parameters:
--
-- <dl>
-- <dt>entity_type</dt>
-- <dd>The entity type identifier defined by the entity permission</dd>
-- <dt>entity_id</dt>
-- <dd>The entity identifier which is associated with an <b>ACL</b> entry to check</dd>
-- <dt>user_id</dt>
-- <dd>The user identifier</dd>
-- </dl>
type Entity_Controller (Len : Positive) is
limited new Security.Controllers.Controller with record
Entities : Entity_Type_Array;
SQL : String (1 .. Len);
end record;
type Entity_Controller_Access is access all Entity_Controller'Class;
-- Returns true if the user associated with the security context <b>Context</b> has
-- the permission to access a database entity. The security context contains some
-- information about the entity to check and the permission controller will use an
-- SQL statement to verify the permission.
overriding
function Has_Permission (Handler : in Entity_Controller;
Context : in Security.Contexts.Security_Context'Class;
Permission : in Security.Permissions.Permission'Class)
return Boolean;
end AWA.Permissions.Controllers;
|
Store several entity types in the entity permission definition
|
Store several entity types in the entity permission definition
|
Ada
|
apache-2.0
|
tectronics/ada-awa,Letractively/ada-awa,Letractively/ada-awa,tectronics/ada-awa,Letractively/ada-awa,tectronics/ada-awa
|
a1f876fbe3302f66c361b1028f21d5cb833ec865
|
src/portscan.ads
|
src/portscan.ads
|
-- This file is covered by the Internet Software Consortium (ISC) License
-- Reference: ../License.txt
-- GCC 6.0 only (skip Container_Checks until identified need arises)
pragma Suppress (Tampering_Check);
with Ada.Text_IO;
with Ada.Calendar;
with Ada.Containers.Hashed_Maps;
with Ada.Containers.Ordered_Sets;
with Ada.Containers.Vectors;
with Ada.Characters.Latin_1;
with Ada.Directories;
with Ada.Exceptions;
with JohnnyText;
with Parameters;
with Definitions; use Definitions;
private with Replicant.Platform;
package PortScan is
package JT renames JohnnyText;
package AC renames Ada.Containers;
package CAL renames Ada.Calendar;
package AD renames Ada.Directories;
package EX renames Ada.Exceptions;
package TIO renames Ada.Text_IO;
package LAT renames Ada.Characters.Latin_1;
package PM renames Parameters;
type count_type is (total, success, failure, ignored, skipped);
type dim_handlers is array (count_type) of TIO.File_Type;
type port_id is private;
port_match_failed : constant port_id;
-- Scan the entire ports tree in order with a single, non-recursive pass
-- Return True on success
function scan_entire_ports_tree (portsdir : String) return Boolean;
-- Starting with a single port, recurse to determine a limited but complete
-- dependency tree. Repeated calls will augment already existing data.
-- Return True on success
function scan_single_port (catport : String; always_build : Boolean;
fatal : out Boolean)
return Boolean;
-- This procedure causes the reverse dependencies to be calculated, and
-- then the extended (recursive) reverse dependencies. The former is
-- used progressively to determine when a port is free to build and the
-- latter sets the build priority.
procedure set_build_priority;
-- Wipe out all scan data so new scan can be performed
procedure reset_ports_tree;
-- Returns the number of cores. The set_cores procedure must be run first.
-- set_cores was private previously, but we need the information to set
-- intelligent defaults for the configuration file.
procedure set_cores;
function cores_available return cpu_range;
-- Return " (port deleted)" if the catport doesn't exist
-- Return " (directory empty)" if the directory exists but has no contents
-- Return " (Makefile missing)" when makefile is missing
-- otherwise return blank string
function obvious_problem (portsdir, catport : String) return String;
private
package REP renames Replicant;
package PLAT renames Replicant.Platform;
max_ports : constant := 28000;
scan_slave : constant builders := 9;
ss_base : constant String := "/SL09";
dir_ports : constant String := "/xports";
chroot : constant String := "/usr/sbin/chroot ";
type port_id is range -1 .. max_ports - 1;
subtype port_index is port_id range 0 .. port_id'Last;
port_match_failed : constant port_id := port_id'First;
-- skip "package" because every port has same dependency on ports-mgmt/pkg
-- except for pkg itself. Skip "test" because these dependencies are
-- not required to build packages.
type dependency_type is (fetch, extract, patch, build, library, runtime);
subtype LR_set is dependency_type range library .. runtime;
bmake_execution : exception;
pkgng_execution : exception;
make_garbage : exception;
nonexistent_port : exception;
circular_logic : exception;
seek_failure : exception;
unknown_format : exception;
package subqueue is new AC.Vectors
(Element_Type => port_index,
Index_Type => port_index);
package string_crate is new AC.Vectors
(Element_Type => JT.Text,
Index_Type => port_index,
"=" => JT.SU."=");
type queue_record is
record
ap_index : port_index;
reverse_score : port_index;
end record;
-- Functions for ranking_crate definitions
function "<" (L, R : queue_record) return Boolean;
package ranking_crate is new AC.Ordered_Sets (Element_Type => queue_record);
-- Functions for portkey_crate and package_crate definitions
function port_hash (key : JT.Text) return AC.Hash_Type;
package portkey_crate is new AC.Hashed_Maps
(Key_Type => JT.Text,
Element_Type => port_index,
Hash => port_hash,
Equivalent_Keys => JT.equivalent);
package package_crate is new AC.Hashed_Maps
(Key_Type => JT.Text,
Element_Type => Boolean,
Hash => port_hash,
Equivalent_Keys => JT.equivalent);
-- Functions for block_crate definitions
function block_hash (key : port_index) return AC.Hash_Type;
function block_ekey (left, right : port_index) return Boolean;
package block_crate is new AC.Hashed_Maps
(Key_Type => port_index,
Element_Type => port_index,
Hash => block_hash,
Equivalent_Keys => block_ekey);
type port_record is
record
sequence_id : port_index := 0;
key_cursor : portkey_crate.Cursor := portkey_crate.No_Element;
jobs : builders := 1;
ignore_reason : JT.Text := JT.blank;
port_version : JT.Text := JT.blank;
package_name : JT.Text := JT.blank;
pkg_dep_query : JT.Text := JT.blank;
ignored : Boolean := False;
scanned : Boolean := False;
rev_scanned : Boolean := False;
unlist_failed : Boolean := False;
work_locked : Boolean := False;
scan_locked : Boolean := False;
pkg_present : Boolean := False;
remote_pkg : Boolean := False;
never_remote : Boolean := False;
deletion_due : Boolean := False;
use_procfs : Boolean := False;
use_linprocfs : Boolean := False;
reverse_score : port_index := 0;
min_librun : Natural := 0;
librun : block_crate.Map;
blocked_by : block_crate.Map;
blocks : block_crate.Map;
all_reverse : block_crate.Map;
options : package_crate.Map;
end record;
type port_record_access is access all port_record;
type dim_make_queue is array (scanners) of subqueue.Vector;
type dim_progress is array (scanners) of port_index;
type dim_all_ports is array (port_index) of aliased port_record;
all_ports : dim_all_ports;
ports_keys : portkey_crate.Map;
portlist : portkey_crate.Map;
make_queue : dim_make_queue;
mq_progress : dim_progress := (others => 0);
rank_queue : ranking_crate.Set;
number_cores : cpu_range := cpu_range'First;
lot_number : scanners := 1;
lot_counter : port_index := 0;
last_port : port_index := 0;
prescanned : Boolean := False;
procedure iterate_reverse_deps;
procedure iterate_drill_down;
procedure populate_set_depends (target : port_index;
catport : String;
line : JT.Text;
dtype : dependency_type);
procedure populate_set_options (target : port_index;
line : JT.Text;
on : Boolean);
procedure populate_port_data (target : port_index);
procedure populate_port_data_fpc (target : port_index);
procedure populate_port_data_nps (target : port_index);
procedure drill_down (next_target : port_index;
original_target : port_index);
-- subroutines for populate_port_data
procedure prescan_ports_tree (portsdir : String);
procedure grep_Makefile (portsdir, category : String);
procedure walk_all_subdirectories (portsdir, category : String);
procedure wipe_make_queue;
procedure parallel_deep_scan (success : out Boolean;
show_progress : Boolean);
-- some helper routines
function find_colon (Source : String) return Natural;
function scrub_phase (Source : String) return JT.Text;
function get_catport (PR : port_record) return String;
function scan_progress return String;
function get_max_lots return scanners;
function get_pkg_name (origin : String) return String;
function timestamp (hack : CAL.Time; www_format : Boolean := False) return String;
function clean_up_pkgsrc_ignore_reason (dirty_string : String) return JT.Text;
type dim_counters is array (count_type) of Natural;
-- bulk run variables
Flog : dim_handlers;
start_time : CAL.Time;
stop_time : CAL.Time;
scan_start : CAL.Time;
scan_stop : CAL.Time;
bld_counter : dim_counters := (0, 0, 0, 0, 0);
end PortScan;
|
-- This file is covered by the Internet Software Consortium (ISC) License
-- Reference: ../License.txt
-- GCC 6.0 only (skip Container_Checks until identified need arises)
pragma Suppress (Tampering_Check);
with Ada.Text_IO;
with Ada.Calendar;
with Ada.Containers.Hashed_Maps;
with Ada.Containers.Ordered_Sets;
with Ada.Containers.Vectors;
with Ada.Characters.Latin_1;
with Ada.Directories;
with Ada.Exceptions;
with JohnnyText;
with Parameters;
with Definitions; use Definitions;
private with Replicant.Platform;
package PortScan is
package JT renames JohnnyText;
package AC renames Ada.Containers;
package CAL renames Ada.Calendar;
package AD renames Ada.Directories;
package EX renames Ada.Exceptions;
package TIO renames Ada.Text_IO;
package LAT renames Ada.Characters.Latin_1;
package PM renames Parameters;
type count_type is (total, success, failure, ignored, skipped);
type dim_handlers is array (count_type) of TIO.File_Type;
type port_id is private;
port_match_failed : constant port_id;
-- Scan the entire ports tree in order with a single, non-recursive pass
-- Return True on success
function scan_entire_ports_tree (portsdir : String) return Boolean;
-- Starting with a single port, recurse to determine a limited but complete
-- dependency tree. Repeated calls will augment already existing data.
-- Return True on success
function scan_single_port (catport : String; always_build : Boolean;
fatal : out Boolean)
return Boolean;
-- This procedure causes the reverse dependencies to be calculated, and
-- then the extended (recursive) reverse dependencies. The former is
-- used progressively to determine when a port is free to build and the
-- latter sets the build priority.
procedure set_build_priority;
-- Wipe out all scan data so new scan can be performed
procedure reset_ports_tree;
-- Returns the number of cores. The set_cores procedure must be run first.
-- set_cores was private previously, but we need the information to set
-- intelligent defaults for the configuration file.
procedure set_cores;
function cores_available return cpu_range;
-- Return " (port deleted)" if the catport doesn't exist
-- Return " (directory empty)" if the directory exists but has no contents
-- Return " (Makefile missing)" when makefile is missing
-- otherwise return blank string
function obvious_problem (portsdir, catport : String) return String;
private
package REP renames Replicant;
package PLAT renames Replicant.Platform;
max_ports : constant := 32000;
scan_slave : constant builders := 9;
ss_base : constant String := "/SL09";
dir_ports : constant String := "/xports";
chroot : constant String := "/usr/sbin/chroot ";
type port_id is range -1 .. max_ports - 1;
subtype port_index is port_id range 0 .. port_id'Last;
port_match_failed : constant port_id := port_id'First;
-- skip "package" because every port has same dependency on ports-mgmt/pkg
-- except for pkg itself. Skip "test" because these dependencies are
-- not required to build packages.
type dependency_type is (fetch, extract, patch, build, library, runtime);
subtype LR_set is dependency_type range library .. runtime;
bmake_execution : exception;
pkgng_execution : exception;
make_garbage : exception;
nonexistent_port : exception;
circular_logic : exception;
seek_failure : exception;
unknown_format : exception;
package subqueue is new AC.Vectors
(Element_Type => port_index,
Index_Type => port_index);
package string_crate is new AC.Vectors
(Element_Type => JT.Text,
Index_Type => port_index,
"=" => JT.SU."=");
type queue_record is
record
ap_index : port_index;
reverse_score : port_index;
end record;
-- Functions for ranking_crate definitions
function "<" (L, R : queue_record) return Boolean;
package ranking_crate is new AC.Ordered_Sets (Element_Type => queue_record);
-- Functions for portkey_crate and package_crate definitions
function port_hash (key : JT.Text) return AC.Hash_Type;
package portkey_crate is new AC.Hashed_Maps
(Key_Type => JT.Text,
Element_Type => port_index,
Hash => port_hash,
Equivalent_Keys => JT.equivalent);
package package_crate is new AC.Hashed_Maps
(Key_Type => JT.Text,
Element_Type => Boolean,
Hash => port_hash,
Equivalent_Keys => JT.equivalent);
-- Functions for block_crate definitions
function block_hash (key : port_index) return AC.Hash_Type;
function block_ekey (left, right : port_index) return Boolean;
package block_crate is new AC.Hashed_Maps
(Key_Type => port_index,
Element_Type => port_index,
Hash => block_hash,
Equivalent_Keys => block_ekey);
type port_record is
record
sequence_id : port_index := 0;
key_cursor : portkey_crate.Cursor := portkey_crate.No_Element;
jobs : builders := 1;
ignore_reason : JT.Text := JT.blank;
port_version : JT.Text := JT.blank;
package_name : JT.Text := JT.blank;
pkg_dep_query : JT.Text := JT.blank;
ignored : Boolean := False;
scanned : Boolean := False;
rev_scanned : Boolean := False;
unlist_failed : Boolean := False;
work_locked : Boolean := False;
scan_locked : Boolean := False;
pkg_present : Boolean := False;
remote_pkg : Boolean := False;
never_remote : Boolean := False;
deletion_due : Boolean := False;
use_procfs : Boolean := False;
use_linprocfs : Boolean := False;
reverse_score : port_index := 0;
min_librun : Natural := 0;
librun : block_crate.Map;
blocked_by : block_crate.Map;
blocks : block_crate.Map;
all_reverse : block_crate.Map;
options : package_crate.Map;
end record;
type port_record_access is access all port_record;
type dim_make_queue is array (scanners) of subqueue.Vector;
type dim_progress is array (scanners) of port_index;
type dim_all_ports is array (port_index) of aliased port_record;
all_ports : dim_all_ports;
ports_keys : portkey_crate.Map;
portlist : portkey_crate.Map;
make_queue : dim_make_queue;
mq_progress : dim_progress := (others => 0);
rank_queue : ranking_crate.Set;
number_cores : cpu_range := cpu_range'First;
lot_number : scanners := 1;
lot_counter : port_index := 0;
last_port : port_index := 0;
prescanned : Boolean := False;
procedure iterate_reverse_deps;
procedure iterate_drill_down;
procedure populate_set_depends (target : port_index;
catport : String;
line : JT.Text;
dtype : dependency_type);
procedure populate_set_options (target : port_index;
line : JT.Text;
on : Boolean);
procedure populate_port_data (target : port_index);
procedure populate_port_data_fpc (target : port_index);
procedure populate_port_data_nps (target : port_index);
procedure drill_down (next_target : port_index;
original_target : port_index);
-- subroutines for populate_port_data
procedure prescan_ports_tree (portsdir : String);
procedure grep_Makefile (portsdir, category : String);
procedure walk_all_subdirectories (portsdir, category : String);
procedure wipe_make_queue;
procedure parallel_deep_scan (success : out Boolean;
show_progress : Boolean);
-- some helper routines
function find_colon (Source : String) return Natural;
function scrub_phase (Source : String) return JT.Text;
function get_catport (PR : port_record) return String;
function scan_progress return String;
function get_max_lots return scanners;
function get_pkg_name (origin : String) return String;
function timestamp (hack : CAL.Time; www_format : Boolean := False) return String;
function clean_up_pkgsrc_ignore_reason (dirty_string : String) return JT.Text;
type dim_counters is array (count_type) of Natural;
-- bulk run variables
Flog : dim_handlers;
start_time : CAL.Time;
stop_time : CAL.Time;
scan_start : CAL.Time;
scan_stop : CAL.Time;
bld_counter : dim_counters := (0, 0, 0, 0, 0);
end PortScan;
|
Bump maximum number of ports to 32000
|
Bump maximum number of ports to 32000
We've crossed over 28,000. Apparently nobody builds the entire tree
with Synth, otherwise someone would have complained.
|
Ada
|
isc
|
jrmarino/synth,jrmarino/synth,jrmarino/synth,jrmarino/synth
|
d28e0bcab87f199d54e2fff73be0e8bbd4bfbd51
|
src/base/files/util-files.adb
|
src/base/files/util-files.adb
|
-----------------------------------------------------------------------
-- util-files -- Various File Utility Packages
-- Copyright (C) 2001 - 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 Interfaces.C.Strings;
with Ada.Directories;
with Ada.IO_Exceptions;
with Ada.Streams;
with Ada.Streams.Stream_IO;
with Ada.Text_IO;
with Util.Strings.Builders;
with Util.Strings.Tokenizers;
package body Util.Files is
-- ------------------------------
-- Read a complete file into a string.
-- The <b>Max_Size</b> parameter indicates the maximum size that is read.
-- ------------------------------
procedure Read_File (Path : in String;
Into : out Unbounded_String;
Max_Size : in Natural := 0) is
use Ada.Streams;
use Ada.Streams.Stream_IO;
F : File_Type;
Buffer : Stream_Element_Array (1 .. 10_000);
Pos : Positive_Count := 1;
Last : Stream_Element_Offset;
Space : Natural;
begin
if Max_Size = 0 then
Space := Natural'Last;
else
Space := Max_Size;
end if;
Open (Name => Path, File => F, Mode => In_File);
loop
Read (File => F, Item => Buffer, From => Pos, Last => Last);
if Natural (Last) > Space then
Last := Stream_Element_Offset (Space);
end if;
for I in 1 .. Last loop
Append (Into, Character'Val (Buffer (I)));
end loop;
exit when Last < Buffer'Length;
Pos := Pos + Positive_Count (Last);
end loop;
Close (F);
exception
when others =>
if Is_Open (F) then
Close (F);
end if;
raise;
end Read_File;
-- ------------------------------
-- Read the file with the given path, one line at a time and execute the <b>Process</b>
-- procedure with each line as argument.
-- ------------------------------
procedure Read_File (Path : in String;
Process : not null access procedure (Line : in String)) is
File : Ada.Text_IO.File_Type;
begin
Ada.Text_IO.Open (File => File,
Mode => Ada.Text_IO.In_File,
Name => Path);
while not Ada.Text_IO.End_Of_File (File) loop
Process (Ada.Text_IO.Get_Line (File));
end loop;
Ada.Text_IO.Close (File);
end Read_File;
-- ------------------------------
-- Read the file with the given path, one line at a time and append each line to
-- the <b>Into</b> vector.
-- ------------------------------
procedure Read_File (Path : in String;
Into : in out Util.Strings.Vectors.Vector) is
procedure Append (Line : in String);
procedure Append (Line : in String) is
begin
Into.Append (Line);
end Append;
begin
Read_File (Path, Append'Access);
end Read_File;
-- ------------------------------
-- Save the string into a file creating the file if necessary
-- ------------------------------
procedure Write_File (Path : in String;
Content : in String) is
use Ada.Streams;
use Ada.Streams.Stream_IO;
use Ada.Directories;
F : File_Type;
Buffer : Stream_Element_Array (Stream_Element_Offset (Content'First)
.. Stream_Element_Offset (Content'Last));
Dir : constant String := Containing_Directory (Path);
begin
if not Exists (Dir) then
Create_Path (Dir);
end if;
Create (File => F, Name => Path);
for I in Content'Range loop
Buffer (Stream_Element_Offset (I))
:= Stream_Element (Character'Pos (Content (I)));
end loop;
Write (F, Buffer);
Close (F);
exception
when others =>
if Is_Open (F) then
Close (F);
end if;
raise;
end Write_File;
-- ------------------------------
-- Save the string into a file creating the file if necessary
-- ------------------------------
procedure Write_File (Path : in String;
Content : in Unbounded_String) is
begin
Write_File (Path, Ada.Strings.Unbounded.To_String (Content));
end Write_File;
-- ------------------------------
-- Iterate over the search directories defined in <b>Paths</b> and execute
-- <b>Process</b> with each directory until it returns <b>True</b> in <b>Done</b>
-- or the last search directory is found. Each search directory
-- is separated by ';' (yes, even on Unix). When <b>Going</b> is set to Backward, the
-- directories are searched in reverse order.
-- ------------------------------
procedure Iterate_Path (Path : in String;
Process : not null access procedure (Dir : in String;
Done : out Boolean);
Going : in Direction := Ada.Strings.Forward) is
begin
Util.Strings.Tokenizers.Iterate_Tokens (Content => Path,
Pattern => ";",
Process => Process,
Going => Going);
end Iterate_Path;
-- ------------------------------
-- Find the file `Name` in one of the search directories defined in `Paths`.
-- Each search directory is separated by ';' by default (yes, even on Unix).
-- This can be changed by specifying the `Separator` value.
-- Returns the path to be used for reading the file.
-- ------------------------------
function Find_File_Path (Name : in String;
Paths : in String;
Separator : in Character := ';') return String is
Sep_Pos : Natural;
Pos : Positive := Paths'First;
Last : constant Natural := Paths'Last;
begin
while Pos <= Last loop
Sep_Pos := Util.Strings.Index (Paths, Separator, Pos);
if Sep_Pos = 0 then
Sep_Pos := Last;
else
Sep_Pos := Sep_Pos - 1;
end if;
declare
use Ada.Directories;
Path : constant String := Util.Files.Compose (Paths (Pos .. Sep_Pos), Name);
begin
if Exists (Path) and then Kind (Path) = Ordinary_File then
return Path;
end if;
exception
when Name_Error =>
null;
end;
Pos := Sep_Pos + 2;
end loop;
return Name;
end Find_File_Path;
-- ------------------------------
-- Iterate over the search directories defined in <b>Path</b> and search
-- for files matching the pattern defined by <b>Pattern</b>. For each file,
-- execute <b>Process</b> with the file basename and the full file path.
-- Stop iterating when the <b>Process</b> procedure returns True.
-- Each search directory is separated by ';'. When <b>Going</b> is set to Backward, the
-- directories are searched in reverse order.
-- ------------------------------
procedure Iterate_Files_Path (Pattern : in String;
Path : in String;
Process : not null access procedure (Name : in String;
File : in String;
Done : out Boolean);
Going : in Direction := Ada.Strings.Forward) is
procedure Find_Files (Dir : in String;
Done : out Boolean);
-- ------------------------------
-- Find the files matching the pattern in <b>Dir</b>.
-- ------------------------------
procedure Find_Files (Dir : in String;
Done : out Boolean) is
use Ada.Directories;
Filter : constant Filter_Type := (Ordinary_File => True, others => False);
Ent : Directory_Entry_Type;
Search : Search_Type;
begin
Done := False;
Start_Search (Search, Directory => Dir,
Pattern => Pattern, Filter => Filter);
while More_Entries (Search) loop
Get_Next_Entry (Search, Ent);
declare
Name : constant String := Simple_Name (Ent);
File_Path : constant String := Full_Name (Ent);
begin
Process (Name, File_Path, Done);
exit when Done;
end;
end loop;
end Find_Files;
begin
Iterate_Path (Path => Path, Process => Find_Files'Access, Going => Going);
end Iterate_Files_Path;
-- ------------------------------
-- Find the files which match the pattern in the directories specified in the
-- search path <b>Path</b>. Each search directory is separated by ';'.
-- File names are added to the string set in <b>Into</b>.
-- ------------------------------
procedure Find_Files_Path (Pattern : in String;
Path : in String;
Into : in out Util.Strings.Maps.Map) is
procedure Add_File (Name : in String;
File_Path : in String;
Done : out Boolean);
-- ------------------------------
-- Find the files matching the pattern in <b>Dir</b>.
-- ------------------------------
procedure Add_File (Name : in String;
File_Path : in String;
Done : out Boolean) is
begin
if not Into.Contains (Name) then
Into.Insert (Name, File_Path);
end if;
Done := False;
end Add_File;
begin
Iterate_Files_Path (Pattern => Pattern, Path => Path, Process => Add_File'Access);
end Find_Files_Path;
-- ------------------------------
-- Compose an existing path by adding the specified name to each path component
-- and return a new paths having only existing directories. Each directory is
-- separated by ';' (this can be overriding with the `Separator` parameter).
-- If the composed path exists, it is added to the result path.
-- Example:
-- paths = 'web;regtests' name = 'info'
-- result = 'web/info;regtests/info'
-- Returns the composed path.
-- ------------------------------
function Compose_Path (Paths : in String;
Name : in String;
Separator : in Character := ';') return String is
procedure Compose (Dir : in String;
Done : out Boolean);
Result : Util.Strings.Builders.Builder (256);
-- ------------------------------
-- Build the new path by checking if <b>Name</b> exists in <b>Dir</b>
-- and appending the new path in the <b>Result</b>.
-- ------------------------------
procedure Compose (Dir : in String;
Done : out Boolean) is
use Ada.Directories;
Path : constant String := Util.Files.Compose (Dir, Name);
begin
Done := False;
if Exists (Path) and then Kind (Path) = Directory then
if Util.Strings.Builders.Length (Result) > 0 then
Util.Strings.Builders.Append (Result, Separator);
end if;
Util.Strings.Builders.Append (Result, Path);
end if;
exception
when Name_Error =>
null;
end Compose;
begin
Iterate_Path (Path => Paths, Process => Compose'Access);
return Util.Strings.Builders.To_Array (Result);
end Compose_Path;
-- ------------------------------
-- Returns the name of the external file with the specified directory
-- and the name. Unlike the Ada.Directories.Compose, the name can represent
-- a relative path and thus include directory separators.
-- ------------------------------
function Compose (Directory : in String;
Name : in String) return String is
begin
if Name'Length = 0 then
return Directory;
elsif Directory'Length = 0 then
return Name;
elsif Directory = "." or else Directory = "./" then
if Name (Name'First) = '/' then
return Compose (Directory, Name (Name'First + 1 .. Name'Last));
else
return Name;
end if;
elsif Directory (Directory'Last) = '/' and then Name (Name'First) = '/' then
return Directory & Name (Name'First + 1 .. Name'Last);
elsif Directory (Directory'Last) = '/' or else Name (Name'First) = '/' then
return Directory & Name;
else
return Directory & "/" & Name;
end if;
end Compose;
-- ------------------------------
-- Returns a relative path whose origin is defined by <b>From</b> and which refers
-- to the absolute path referenced by <b>To</b>. Both <b>From</b> and <b>To</b> are
-- assumed to be absolute paths. Returns the absolute path <b>To</b> if the relative
-- path could not be found. Both paths must have at least one root component in common.
-- ------------------------------
function Get_Relative_Path (From : in String;
To : in String) return String is
Result : Unbounded_String;
Last : Natural := 0;
begin
for I in From'Range loop
if I > To'Last or else From (I) /= To (I) then
-- Nothing in common, return the absolute path <b>To</b>.
if Last <= From'First + 1 then
return To;
end if;
for J in Last .. From'Last - 1 loop
if From (J) = '/' or From (J) = '\' then
Append (Result, "../");
end if;
end loop;
if Last <= To'Last and From (I) /= '/' and From (I) /= '\' then
Append (Result, "../");
Append (Result, To (Last .. To'Last));
end if;
return To_String (Result);
elsif I < From'Last and then (From (I) = '/' or From (I) = '\') then
Last := I + 1;
end if;
end loop;
if To'Last = From'Last or (To'Last = From'Last + 1
and (To (To'Last) = '/' or To (To'Last) = '\'))
then
return ".";
elsif Last = 0 then
return To;
elsif To (From'Last + 1) = '/' or To (From'Last + 1) = '\' then
return To (From'Last + 2 .. To'Last);
else
return To (Last .. To'Last);
end if;
end Get_Relative_Path;
-- ------------------------------
-- Rename the old name into a new name.
-- ------------------------------
procedure Rename (Old_Name, New_Name : in String) is
-- Rename a file (the Ada.Directories.Rename does not allow to use the
-- Unix atomic file rename!)
function Sys_Rename (Oldpath : in Interfaces.C.Strings.chars_ptr;
Newpath : in Interfaces.C.Strings.chars_ptr) return Integer;
pragma Import (C, Sys_Rename, "rename");
Old_Path : Interfaces.C.Strings.chars_ptr;
New_Path : Interfaces.C.Strings.chars_ptr;
Result : Integer;
begin
-- Do a system atomic rename of old file in the new file.
-- Ada.Directories.Rename does not allow this.
Old_Path := Interfaces.C.Strings.New_String (Old_Name);
New_Path := Interfaces.C.Strings.New_String (New_Name);
Result := Sys_Rename (Old_Path, New_Path);
Interfaces.C.Strings.Free (Old_Path);
Interfaces.C.Strings.Free (New_Path);
if Result /= 0 then
raise Ada.IO_Exceptions.Use_Error with "Cannot rename file";
end if;
end Rename;
end Util.Files;
|
-----------------------------------------------------------------------
-- util-files -- Various File Utility Packages
-- Copyright (C) 2001 - 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 Interfaces.C.Strings;
with System;
with Ada.Directories;
with Ada.IO_Exceptions;
with Ada.Streams;
with Ada.Streams.Stream_IO;
with Ada.Text_IO;
with Util.Strings.Builders;
with Util.Strings.Tokenizers;
package body Util.Files is
-- ------------------------------
-- Read a complete file into a string.
-- The <b>Max_Size</b> parameter indicates the maximum size that is read.
-- ------------------------------
procedure Read_File (Path : in String;
Into : out Unbounded_String;
Max_Size : in Natural := 0) is
use Ada.Streams;
use Ada.Streams.Stream_IO;
F : File_Type;
Buffer : Stream_Element_Array (1 .. 10_000);
Pos : Positive_Count := 1;
Last : Stream_Element_Offset;
Space : Natural;
begin
if Max_Size = 0 then
Space := Natural'Last;
else
Space := Max_Size;
end if;
Open (Name => Path, File => F, Mode => In_File);
loop
Read (File => F, Item => Buffer, From => Pos, Last => Last);
if Natural (Last) > Space then
Last := Stream_Element_Offset (Space);
end if;
for I in 1 .. Last loop
Append (Into, Character'Val (Buffer (I)));
end loop;
exit when Last < Buffer'Length;
Pos := Pos + Positive_Count (Last);
end loop;
Close (F);
exception
when others =>
if Is_Open (F) then
Close (F);
end if;
raise;
end Read_File;
-- ------------------------------
-- Read the file with the given path, one line at a time and execute the <b>Process</b>
-- procedure with each line as argument.
-- ------------------------------
procedure Read_File (Path : in String;
Process : not null access procedure (Line : in String)) is
File : Ada.Text_IO.File_Type;
begin
Ada.Text_IO.Open (File => File,
Mode => Ada.Text_IO.In_File,
Name => Path);
while not Ada.Text_IO.End_Of_File (File) loop
Process (Ada.Text_IO.Get_Line (File));
end loop;
Ada.Text_IO.Close (File);
end Read_File;
-- ------------------------------
-- Read the file with the given path, one line at a time and append each line to
-- the <b>Into</b> vector.
-- ------------------------------
procedure Read_File (Path : in String;
Into : in out Util.Strings.Vectors.Vector) is
procedure Append (Line : in String);
procedure Append (Line : in String) is
begin
Into.Append (Line);
end Append;
begin
Read_File (Path, Append'Access);
end Read_File;
-- ------------------------------
-- Save the string into a file creating the file if necessary
-- ------------------------------
procedure Write_File (Path : in String;
Content : in String) is
use Ada.Streams;
use Ada.Streams.Stream_IO;
use Ada.Directories;
F : File_Type;
Buffer : Stream_Element_Array (Stream_Element_Offset (Content'First)
.. Stream_Element_Offset (Content'Last));
Dir : constant String := Containing_Directory (Path);
begin
if not Exists (Dir) then
Create_Path (Dir);
end if;
Create (File => F, Name => Path);
for I in Content'Range loop
Buffer (Stream_Element_Offset (I))
:= Stream_Element (Character'Pos (Content (I)));
end loop;
Write (F, Buffer);
Close (F);
exception
when others =>
if Is_Open (F) then
Close (F);
end if;
raise;
end Write_File;
-- ------------------------------
-- Save the string into a file creating the file if necessary
-- ------------------------------
procedure Write_File (Path : in String;
Content : in Unbounded_String) is
begin
Write_File (Path, Ada.Strings.Unbounded.To_String (Content));
end Write_File;
-- ------------------------------
-- Iterate over the search directories defined in <b>Paths</b> and execute
-- <b>Process</b> with each directory until it returns <b>True</b> in <b>Done</b>
-- or the last search directory is found. Each search directory
-- is separated by ';' (yes, even on Unix). When <b>Going</b> is set to Backward, the
-- directories are searched in reverse order.
-- ------------------------------
procedure Iterate_Path (Path : in String;
Process : not null access procedure (Dir : in String;
Done : out Boolean);
Going : in Direction := Ada.Strings.Forward) is
begin
Util.Strings.Tokenizers.Iterate_Tokens (Content => Path,
Pattern => ";",
Process => Process,
Going => Going);
end Iterate_Path;
-- ------------------------------
-- Find the file `Name` in one of the search directories defined in `Paths`.
-- Each search directory is separated by ';' by default (yes, even on Unix).
-- This can be changed by specifying the `Separator` value.
-- Returns the path to be used for reading the file.
-- ------------------------------
function Find_File_Path (Name : in String;
Paths : in String;
Separator : in Character := ';') return String is
Sep_Pos : Natural;
Pos : Positive := Paths'First;
Last : constant Natural := Paths'Last;
begin
while Pos <= Last loop
Sep_Pos := Util.Strings.Index (Paths, Separator, Pos);
if Sep_Pos = 0 then
Sep_Pos := Last;
else
Sep_Pos := Sep_Pos - 1;
end if;
declare
use Ada.Directories;
Path : constant String := Util.Files.Compose (Paths (Pos .. Sep_Pos), Name);
begin
if Exists (Path) and then Kind (Path) = Ordinary_File then
return Path;
end if;
exception
when Name_Error =>
null;
end;
Pos := Sep_Pos + 2;
end loop;
return Name;
end Find_File_Path;
-- ------------------------------
-- Iterate over the search directories defined in <b>Path</b> and search
-- for files matching the pattern defined by <b>Pattern</b>. For each file,
-- execute <b>Process</b> with the file basename and the full file path.
-- Stop iterating when the <b>Process</b> procedure returns True.
-- Each search directory is separated by ';'. When <b>Going</b> is set to Backward, the
-- directories are searched in reverse order.
-- ------------------------------
procedure Iterate_Files_Path (Pattern : in String;
Path : in String;
Process : not null access procedure (Name : in String;
File : in String;
Done : out Boolean);
Going : in Direction := Ada.Strings.Forward) is
procedure Find_Files (Dir : in String;
Done : out Boolean);
-- ------------------------------
-- Find the files matching the pattern in <b>Dir</b>.
-- ------------------------------
procedure Find_Files (Dir : in String;
Done : out Boolean) is
use Ada.Directories;
Filter : constant Filter_Type := (Ordinary_File => True, others => False);
Ent : Directory_Entry_Type;
Search : Search_Type;
begin
Done := False;
Start_Search (Search, Directory => Dir,
Pattern => Pattern, Filter => Filter);
while More_Entries (Search) loop
Get_Next_Entry (Search, Ent);
declare
Name : constant String := Simple_Name (Ent);
File_Path : constant String := Full_Name (Ent);
begin
Process (Name, File_Path, Done);
exit when Done;
end;
end loop;
end Find_Files;
begin
Iterate_Path (Path => Path, Process => Find_Files'Access, Going => Going);
end Iterate_Files_Path;
-- ------------------------------
-- Find the files which match the pattern in the directories specified in the
-- search path <b>Path</b>. Each search directory is separated by ';'.
-- File names are added to the string set in <b>Into</b>.
-- ------------------------------
procedure Find_Files_Path (Pattern : in String;
Path : in String;
Into : in out Util.Strings.Maps.Map) is
procedure Add_File (Name : in String;
File_Path : in String;
Done : out Boolean);
-- ------------------------------
-- Find the files matching the pattern in <b>Dir</b>.
-- ------------------------------
procedure Add_File (Name : in String;
File_Path : in String;
Done : out Boolean) is
begin
if not Into.Contains (Name) then
Into.Insert (Name, File_Path);
end if;
Done := False;
end Add_File;
begin
Iterate_Files_Path (Pattern => Pattern, Path => Path, Process => Add_File'Access);
end Find_Files_Path;
-- ------------------------------
-- Compose an existing path by adding the specified name to each path component
-- and return a new paths having only existing directories. Each directory is
-- separated by ';' (this can be overriding with the `Separator` parameter).
-- If the composed path exists, it is added to the result path.
-- Example:
-- paths = 'web;regtests' name = 'info'
-- result = 'web/info;regtests/info'
-- Returns the composed path.
-- ------------------------------
function Compose_Path (Paths : in String;
Name : in String;
Separator : in Character := ';') return String is
procedure Compose (Dir : in String;
Done : out Boolean);
Result : Util.Strings.Builders.Builder (256);
-- ------------------------------
-- Build the new path by checking if <b>Name</b> exists in <b>Dir</b>
-- and appending the new path in the <b>Result</b>.
-- ------------------------------
procedure Compose (Dir : in String;
Done : out Boolean) is
use Ada.Directories;
Path : constant String := Util.Files.Compose (Dir, Name);
begin
Done := False;
if Exists (Path) and then Kind (Path) = Directory then
if Util.Strings.Builders.Length (Result) > 0 then
Util.Strings.Builders.Append (Result, Separator);
end if;
Util.Strings.Builders.Append (Result, Path);
end if;
exception
when Name_Error =>
null;
end Compose;
begin
Iterate_Path (Path => Paths, Process => Compose'Access);
return Util.Strings.Builders.To_Array (Result);
end Compose_Path;
-- ------------------------------
-- Returns the name of the external file with the specified directory
-- and the name. Unlike the Ada.Directories.Compose, the name can represent
-- a relative path and thus include directory separators.
-- ------------------------------
function Compose (Directory : in String;
Name : in String) return String is
begin
if Name'Length = 0 then
return Directory;
elsif Directory'Length = 0 then
return Name;
elsif Directory = "." or else Directory = "./" then
if Name (Name'First) = '/' then
return Compose (Directory, Name (Name'First + 1 .. Name'Last));
else
return Name;
end if;
elsif Directory (Directory'Last) = '/' and then Name (Name'First) = '/' then
return Directory & Name (Name'First + 1 .. Name'Last);
elsif Directory (Directory'Last) = '/' or else Name (Name'First) = '/' then
return Directory & Name;
else
return Directory & "/" & Name;
end if;
end Compose;
-- ------------------------------
-- Returns a relative path whose origin is defined by <b>From</b> and which refers
-- to the absolute path referenced by <b>To</b>. Both <b>From</b> and <b>To</b> are
-- assumed to be absolute paths. Returns the absolute path <b>To</b> if the relative
-- path could not be found. Both paths must have at least one root component in common.
-- ------------------------------
function Get_Relative_Path (From : in String;
To : in String) return String is
Result : Unbounded_String;
Last : Natural := 0;
begin
for I in From'Range loop
if I > To'Last or else From (I) /= To (I) then
-- Nothing in common, return the absolute path <b>To</b>.
if Last <= From'First + 1 then
return To;
end if;
for J in Last .. From'Last - 1 loop
if From (J) = '/' or From (J) = '\' then
Append (Result, "../");
end if;
end loop;
if Last <= To'Last and From (I) /= '/' and From (I) /= '\' then
Append (Result, "../");
Append (Result, To (Last .. To'Last));
end if;
return To_String (Result);
elsif I < From'Last and then (From (I) = '/' or From (I) = '\') then
Last := I + 1;
end if;
end loop;
if To'Last = From'Last or (To'Last = From'Last + 1
and (To (To'Last) = '/' or To (To'Last) = '\'))
then
return ".";
elsif Last = 0 then
return To;
elsif To (From'Last + 1) = '/' or To (From'Last + 1) = '\' then
return To (From'Last + 2 .. To'Last);
else
return To (Last .. To'Last);
end if;
end Get_Relative_Path;
-- ------------------------------
-- Rename the old name into a new name.
-- ------------------------------
procedure Rename (Old_Name, New_Name : in String) is
-- Rename a file (the Ada.Directories.Rename does not allow to use the
-- Unix atomic file rename!)
function Sys_Rename (Oldpath : in Interfaces.C.Strings.chars_ptr;
Newpath : in Interfaces.C.Strings.chars_ptr) return Integer;
pragma Import (C, Sys_Rename, "rename");
Old_Path : Interfaces.C.Strings.chars_ptr;
New_Path : Interfaces.C.Strings.chars_ptr;
Result : Integer;
begin
-- Do a system atomic rename of old file in the new file.
-- Ada.Directories.Rename does not allow this.
Old_Path := Interfaces.C.Strings.New_String (Old_Name);
New_Path := Interfaces.C.Strings.New_String (New_Name);
Result := Sys_Rename (Old_Path, New_Path);
Interfaces.C.Strings.Free (Old_Path);
Interfaces.C.Strings.Free (New_Path);
if Result /= 0 then
raise Ada.IO_Exceptions.Use_Error with "Cannot rename file";
end if;
end Rename;
-- ------------------------------
-- Delete the file including missing symbolic link
-- or socket files (which GNAT fails to delete,
-- see gcc/63222 and gcc/56055).
-- ------------------------------
procedure Delete_File (Path : in String) is
function Sys_Unlink (Path : in System.Address) return Integer;
pragma Import (C, Sys_Unlink, "unlink");
C_Path : String (1 .. Path'Length + 1);
Result : Integer;
begin
C_Path (1 .. Path'Length) := Path;
C_Path (C_Path'Last) := ASCII.NUL;
Result := Sys_Unlink (C_Path'Address);
if Result /= 0 then
raise Ada.IO_Exceptions.Use_Error with "file """ & Path & """ could not be deleted";
end if;
end Delete_File;
end Util.Files;
|
Implement Delete_File procedure
|
Implement Delete_File procedure
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
c7e2a3bceae1391e091c330f45aa3cb06a24559e
|
mat/src/events/mat-events-targets.ads
|
mat/src/events/mat-events-targets.ads
|
-----------------------------------------------------------------------
-- mat-events-targets - Events received and collected from a target
-- Copyright (C) 2014, 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.Ordered_Maps;
with Ada.Containers.Vectors;
with Util.Concurrent.Counters;
with MAT.Frames;
package MAT.Events.Targets is
Not_Found : exception;
type Event_Type is mod 16;
type Probe_Index_Type is mod 16;
type Event_Id_Type is new Natural;
type Probe_Event_Type is record
Id : Event_Id_Type;
Event : MAT.Types.Uint16;
Index : Probe_Index_Type;
Time : MAT.Types.Target_Tick_Ref;
Thread : MAT.Types.Target_Thread_Ref;
Frame : MAT.Frames.Frame_Type;
Addr : MAT.Types.Target_Addr;
Size : MAT.Types.Target_Size;
Old_Addr : MAT.Types.Target_Addr;
end record;
subtype Target_Event is Probe_Event_Type;
package Target_Event_Vectors is
new Ada.Containers.Vectors (Positive, Target_Event);
subtype Target_Event_Vector is Target_Event_Vectors.Vector;
subtype Target_Event_Cursor is Target_Event_Vectors.Cursor;
type Target_Events is tagged limited private;
type Target_Events_Access is access all Target_Events'Class;
-- Add the event in the list of events and increment the event counter.
procedure Insert (Target : in out Target_Events;
Event : in Probe_Event_Type);
procedure Get_Events (Target : in out Target_Events;
Start : in MAT.Types.Target_Time;
Finish : in MAT.Types.Target_Time;
Into : in out Target_Event_Vector);
-- Get the start and finish time for the events that have been received.
procedure Get_Time_Range (Target : in out Target_Events;
Start : out MAT.Types.Target_Time;
Finish : out MAT.Types.Target_Time);
-- Get the probe event with the given allocated unique id.
function Get_Event (Target : in Target_Events;
Id : in Event_Id_Type) return Probe_Event_Type;
-- Get the current event counter.
function Get_Event_Counter (Target : in Target_Events) return Integer;
-- Iterate over the events starting from the <tt>Start</tt> event and until the
-- <tt>Finish</tt> event is found (inclusive). Execute the <tt>Process</tt> procedure
-- with each event instance.
procedure Iterate (Target : in out Target_Events;
Start : in Event_Id_Type;
Finish : in Event_Id_Type;
Process : access procedure (Event : in Probe_Event_Type));
private
EVENT_BLOCK_SIZE : constant Event_Id_Type := 1024;
type Probe_Event_Array is array (1 .. EVENT_BLOCK_SIZE) of Probe_Event_Type;
type Event_Block is record
Start : MAT.Types.Target_Time;
Finish : MAT.Types.Target_Time;
Count : Event_Id_Type := 0;
Events : Probe_Event_Array;
end record;
type Event_Block_Access is access all Event_Block;
use type MAT.Types.Target_Time;
package Event_Maps is
new Ada.Containers.Ordered_Maps (Key_Type => MAT.Types.Target_Time,
Element_Type => Event_Block_Access);
subtype Event_Map is Event_Maps.Map;
subtype Event_Cursor is Event_Maps.Cursor;
package Event_Id_Maps is
new Ada.Containers.Ordered_Maps (Key_Type => Event_Id_Type,
Element_Type => Event_Block_Access);
subtype Event_Id_Map is Event_Id_Maps.Map;
subtype Event_Id_Cursor is Event_Id_Maps.Cursor;
protected type Event_Collector is
-- Add the event in the list of events.
procedure Insert (Event : in Probe_Event_Type);
procedure Get_Events (Start : in MAT.Types.Target_Time;
Finish : in MAT.Types.Target_Time;
Into : in out Target_Event_Vector);
-- Get the first and last event that have been received.
procedure Get_Limits (First : out Probe_Event_Type;
Last : out Probe_Event_Type);
-- Get the start and finish time for the events that have been received.
procedure Get_Time_Range (Start : out MAT.Types.Target_Time;
Finish : out MAT.Types.Target_Time);
-- Get the probe event with the given allocated unique id.
function Get_Event (Id : in Event_Id_Type) return Probe_Event_Type;
-- Iterate over the events starting from the <tt>Start</tt> event and until the
-- <tt>Finish</tt> event is found (inclusive). Execute the <tt>Process</tt> procedure
-- with each event instance.
procedure Iterate (Start : in Event_Id_Type;
Finish : in Event_Id_Type;
Process : access procedure (Event : in Probe_Event_Type));
private
Current : Event_Block_Access := null;
Events : Event_Map;
Ids : Event_Id_Map;
Last_Id : Event_Id_Type := 0;
end Event_Collector;
type Target_Events is tagged limited record
Events : Event_Collector;
Event_Count : Util.Concurrent.Counters.Counter;
end record;
end MAT.Events.Targets;
|
-----------------------------------------------------------------------
-- mat-events-targets - Events received and collected from a target
-- Copyright (C) 2014, 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.Ordered_Maps;
with Ada.Containers.Vectors;
with Util.Concurrent.Counters;
with MAT.Frames;
package MAT.Events.Targets is
Not_Found : exception;
type Event_Type is mod 16;
type Probe_Index_Type is mod 16;
type Event_Id_Type is new Natural;
type Probe_Event_Type is record
Id : Event_Id_Type;
Event : MAT.Types.Uint16;
Index : Probe_Index_Type;
Time : MAT.Types.Target_Tick_Ref;
Thread : MAT.Types.Target_Thread_Ref;
Frame : MAT.Frames.Frame_Type;
Addr : MAT.Types.Target_Addr;
Size : MAT.Types.Target_Size;
Old_Addr : MAT.Types.Target_Addr;
end record;
subtype Target_Event is Probe_Event_Type;
package Target_Event_Vectors is
new Ada.Containers.Vectors (Positive, Target_Event);
subtype Target_Event_Vector is Target_Event_Vectors.Vector;
subtype Target_Event_Cursor is Target_Event_Vectors.Cursor;
type Target_Events is tagged limited private;
type Target_Events_Access is access all Target_Events'Class;
-- Add the event in the list of events and increment the event counter.
procedure Insert (Target : in out Target_Events;
Event : in Probe_Event_Type);
procedure Get_Events (Target : in out Target_Events;
Start : in MAT.Types.Target_Time;
Finish : in MAT.Types.Target_Time;
Into : in out Target_Event_Vector);
-- Get the start and finish time for the events that have been received.
procedure Get_Time_Range (Target : in out Target_Events;
Start : out MAT.Types.Target_Time;
Finish : out MAT.Types.Target_Time);
-- Get the probe event with the given allocated unique id.
function Get_Event (Target : in Target_Events;
Id : in Event_Id_Type) return Probe_Event_Type;
-- Get the first and last event that have been received.
procedure Get_Limits (Target : in out Target_Events;
First : out Probe_Event_Type;
Last : out Probe_Event_Type);
-- Get the current event counter.
function Get_Event_Counter (Target : in Target_Events) return Integer;
-- Iterate over the events starting from the <tt>Start</tt> event and until the
-- <tt>Finish</tt> event is found (inclusive). Execute the <tt>Process</tt> procedure
-- with each event instance.
procedure Iterate (Target : in out Target_Events;
Start : in Event_Id_Type;
Finish : in Event_Id_Type;
Process : access procedure (Event : in Probe_Event_Type));
private
EVENT_BLOCK_SIZE : constant Event_Id_Type := 1024;
type Probe_Event_Array is array (1 .. EVENT_BLOCK_SIZE) of Probe_Event_Type;
type Event_Block is record
Start : MAT.Types.Target_Time;
Finish : MAT.Types.Target_Time;
Count : Event_Id_Type := 0;
Events : Probe_Event_Array;
end record;
type Event_Block_Access is access all Event_Block;
use type MAT.Types.Target_Time;
package Event_Maps is
new Ada.Containers.Ordered_Maps (Key_Type => MAT.Types.Target_Time,
Element_Type => Event_Block_Access);
subtype Event_Map is Event_Maps.Map;
subtype Event_Cursor is Event_Maps.Cursor;
package Event_Id_Maps is
new Ada.Containers.Ordered_Maps (Key_Type => Event_Id_Type,
Element_Type => Event_Block_Access);
subtype Event_Id_Map is Event_Id_Maps.Map;
subtype Event_Id_Cursor is Event_Id_Maps.Cursor;
protected type Event_Collector is
-- Add the event in the list of events.
procedure Insert (Event : in Probe_Event_Type);
procedure Get_Events (Start : in MAT.Types.Target_Time;
Finish : in MAT.Types.Target_Time;
Into : in out Target_Event_Vector);
-- Get the first and last event that have been received.
procedure Get_Limits (First : out Probe_Event_Type;
Last : out Probe_Event_Type);
-- Get the start and finish time for the events that have been received.
procedure Get_Time_Range (Start : out MAT.Types.Target_Time;
Finish : out MAT.Types.Target_Time);
-- Get the probe event with the given allocated unique id.
function Get_Event (Id : in Event_Id_Type) return Probe_Event_Type;
-- Iterate over the events starting from the <tt>Start</tt> event and until the
-- <tt>Finish</tt> event is found (inclusive). Execute the <tt>Process</tt> procedure
-- with each event instance.
procedure Iterate (Start : in Event_Id_Type;
Finish : in Event_Id_Type;
Process : access procedure (Event : in Probe_Event_Type));
private
Current : Event_Block_Access := null;
Events : Event_Map;
Ids : Event_Id_Map;
Last_Id : Event_Id_Type := 0;
end Event_Collector;
type Target_Events is tagged limited record
Events : Event_Collector;
Event_Count : Util.Concurrent.Counters.Counter;
end record;
end MAT.Events.Targets;
|
Declare the Get_Limits procedure
|
Declare the Get_Limits procedure
|
Ada
|
apache-2.0
|
stcarrez/mat,stcarrez/mat,stcarrez/mat
|
42f746f4440529a09b971631744384db0235b597
|
awa/regtests/awa-commands-tests.adb
|
awa/regtests/awa-commands-tests.adb
|
-----------------------------------------------------------------------
-- awa-commands-tests -- Test the AWA.Commands
-- Copyright (C) 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.Text_IO;
with Ada.Exceptions;
with Util.Processes;
with Util.Streams.Pipes;
with Util.Streams.Buffered;
with Util.Test_Caller;
with Util.Log.Loggers;
with AWA.Tests.Helpers.Users;
with AWA.Users.Services;
package body AWA.Commands.Tests is
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("AWA.Commands.Tests");
package Caller is new Util.Test_Caller (Test, "Commands");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test AWA.Commands.Start_Stop",
Test_Start_Stop'Access);
Caller.Add_Test (Suite, "Test AWA.Commands.List (tables)",
Test_List_Tables'Access);
Caller.Add_Test (Suite, "Test AWA.Commands.List (users)",
Test_List_Users'Access);
Caller.Add_Test (Suite, "Test AWA.Commands.List (sessions)",
Test_List_Sessions'Access);
Caller.Add_Test (Suite, "Test AWA.Commands.List (jobs)",
Test_List_Jobs'Access);
Caller.Add_Test (Suite, "Test AWA.Commands.Info (secure configuration 1)",
Test_Secure_Configuration'Access);
Caller.Add_Test (Suite, "Test AWA.Commands.Info (secure configuration 2)",
Test_Secure_Configuration_2'Access);
Caller.Add_Test (Suite, "Test AWA.Commands.Info (verbose)",
Test_Verbose_Command'Access);
Caller.Add_Test (Suite, "Test AWA.Commands.User (register)",
Test_User_Command'Access);
end Add_Tests;
-- ------------------------------
-- Execute the command and get the output in a string.
-- ------------------------------
procedure Execute (T : in out Test;
Command : in String;
Input : in String;
Output : in String;
Result : out Ada.Strings.Unbounded.Unbounded_String;
Status : in Natural := 0) is
P : aliased Util.Streams.Pipes.Pipe_Stream;
Buffer : Util.Streams.Buffered.Input_Buffer_Stream;
begin
if Input'Length > 0 then
Log.Info ("Execute: {0} < {1}", Command, Input);
elsif Output'Length > 0 then
Log.Info ("Execute: {0} > {1}", Command, Output);
else
Log.Info ("Execute: {0}", Command);
end if;
P.Set_Input_Stream (Input);
P.Set_Output_Stream (Output);
P.Open (Command, Util.Processes.READ_ALL);
-- Write on the process input stream.
Result := Ada.Strings.Unbounded.Null_Unbounded_String;
Buffer.Initialize (P'Unchecked_Access, 8192);
Buffer.Read (Result);
P.Close;
Ada.Text_IO.Put_Line (Ada.Strings.Unbounded.To_String (Result));
Log.Info ("Command result: {0}", Result);
Util.Tests.Assert_Equals (T, Status, P.Get_Exit_Status, "Command '" & Command & "' failed");
end Execute;
-- ------------------------------
-- Test start and stop command.
-- ------------------------------
procedure Test_Start_Stop (T : in out Test) is
Config : constant String := Util.Tests.Get_Parameter ("test_config_path");
task Start_Server is
entry Start;
entry Wait (Result : out Ada.Strings.Unbounded.Unbounded_String);
end Start_Server;
task body Start_Server is
Output : Ada.Strings.Unbounded.Unbounded_String;
begin
accept Start do
null;
end Start;
begin
T.Execute ("bin/awa_command -c " & Config & " start -m 26123",
"", "", Output, 0);
exception
when others =>
Output := Ada.Strings.Unbounded.To_Unbounded_String ("* exception *");
end;
accept Wait (Result : out Ada.Strings.Unbounded.Unbounded_String) do
Result := Output;
end Wait;
end Start_Server;
Result : Ada.Strings.Unbounded.Unbounded_String;
begin
-- Launch the 'start' command in a separate task because the command will hang.
Start_Server.Start;
delay 5.0;
-- Launch the 'stop' command, this should terminate the 'start' command.
T.Execute ("bin/awa_command -c " & Config & " stop -m 26123",
"", "", Result, 0);
-- Wait for the task result.
Start_Server.Wait (Result);
Util.Tests.Assert_Matches (T, "Starting...", Result, "AWA start command output");
end Test_Start_Stop;
procedure Test_List_Tables (T : in out Test) is
Config : constant String := Util.Tests.Get_Parameter ("test_config_path");
Result : Ada.Strings.Unbounded.Unbounded_String;
begin
T.Execute ("bin/awa_command -c " & Config & " list -t",
"", "", Result, 0);
Util.Tests.Assert_Matches (T, "awa_audit *[0-9]+", Result, "Missing awa_audit");
Util.Tests.Assert_Matches (T, "awa_session *[0-9]+", Result, "Missing awa_session");
Util.Tests.Assert_Matches (T, "entity_type *[0-9]+", Result, "Missing entity_type");
Util.Tests.Assert_Matches (T, "awa_wiki_page *[0-9]+", Result, "Missing awa_wiki_page");
end Test_List_Tables;
-- ------------------------------
-- Test the list -u command.
-- ------------------------------
procedure Test_List_Users (T : in out Test) is
Config : constant String := Util.Tests.Get_Parameter ("test_config_path");
Result : Ada.Strings.Unbounded.Unbounded_String;
begin
T.Execute ("bin/awa_command -c " & Config & " list -u",
"", "", Result, 0);
Util.Tests.Assert_Matches (T, "Joe Pot", Result, "Missing user");
Util.Tests.Assert_Matches (T, "[email protected]", Result, "Missing email");
end Test_List_Users;
-- ------------------------------
-- Test the list -s command.
-- ------------------------------
procedure Test_List_Sessions (T : in out Test) is
Config : constant String := Util.Tests.Get_Parameter ("test_config_path");
Result : Ada.Strings.Unbounded.Unbounded_String;
begin
T.Execute ("bin/awa_command -c " & Config & " list -s",
"", "", Result, 0);
Util.Tests.Assert_Matches (T, "Joe Pot", Result, "Missing user");
end Test_List_Sessions;
-- ------------------------------
-- Test the list -j command.
-- ------------------------------
procedure Test_List_Jobs (T : in out Test) is
Config : constant String := Util.Tests.Get_Parameter ("test_config_path");
Result : Ada.Strings.Unbounded.Unbounded_String;
begin
T.Execute ("bin/awa_command -c " & Config & " list -j",
"", "", Result, 0);
Util.Tests.Assert_Matches (T, "S_FACTORY", Result, "Missing factory");
Util.Tests.Assert_Matches (T, "Joe Pot", Result, "Missing user");
end Test_List_Jobs;
-- ------------------------------
-- Test the command with a secure keystore configuration.
-- ------------------------------
procedure Test_Secure_Configuration (T : in out Test) is
Config : constant String := Util.Tests.Get_Parameter ("test_config_path");
Keystore : constant String := Util.Tests.Get_Parameter ("test_keystore_file");
Result : Ada.Strings.Unbounded.Unbounded_String;
begin
T.Execute ("bin/awa_command -c " & Config & " info --keystore " & Keystore
& " --password=unit-test-password", "", "", Result, 0);
Util.Tests.Assert_Matches (T, "app_name *AWA Secure Demo", Result,
"Secure property not accessed");
end Test_Secure_Configuration;
-- ------------------------------
-- Test the command with a secure keystore configuration.
-- ------------------------------
procedure Test_Secure_Configuration_2 (T : in out Test) is
Config : constant String := Util.Tests.Get_Parameter ("test_secure_config_path");
Result : Ada.Strings.Unbounded.Unbounded_String;
begin
T.Execute ("bin/awa_command -c " & Config & " info", "", "", Result, 0);
Util.Tests.Assert_Matches (T, "app_name *AWA Secure Demo", Result,
"Secure property not accessed");
Util.Tests.Assert_Matches (T, "users.auth_key *auth-", Result,
"Secure property not accessed");
Util.Tests.Assert_Matches (T, "users.server_id *[123]0", Result,
"Secure property not accessed");
end Test_Secure_Configuration_2;
-- ------------------------------
-- Test the command with various logging options.
-- ------------------------------
procedure Test_Verbose_Command (T : in out Test) is
Config : constant String := Util.Tests.Get_Parameter ("test_config_path");
Result : Ada.Strings.Unbounded.Unbounded_String;
begin
T.Execute ("bin/awa_command -v -c " & Config & " info ", "", "", Result, 0);
Util.Tests.Assert_Matches (T, "INFO : Using application search dir:", Result,
"Missing log message");
end Test_Verbose_Command;
-- ------------------------------
-- Test the user command.
-- ------------------------------
procedure Test_User_Command (T : in out Test) is
Email : constant String := "Reg-" & Util.Tests.Get_Uuid & "@register.com";
Config : constant String := Util.Tests.Get_Parameter ("test_config_path");
Result : Ada.Strings.Unbounded.Unbounded_String;
begin
T.Execute ("bin/awa_command -c " & Config & " user " & Email & " --register",
"", "", Result, 0);
Util.Tests.Assert_Matches (T, "User 'Reg-.*@register.com' is now registered", Result,
"Missing notice message");
declare
Principal : AWA.Tests.Helpers.Users.Test_User;
begin
Principal.Email.Set_Email (Email);
AWA.Tests.Helpers.Users.Login (Principal);
T.Assert (False, "Login succeeded with a registered user");
exception
when E : AWA.Users.Services.User_Disabled =>
Util.Tests.Assert_Matches (T, "User account is not validated: Reg-.*",
Ada.Exceptions.Exception_Message (E));
end;
end Test_User_Command;
end AWA.Commands.Tests;
|
-----------------------------------------------------------------------
-- awa-commands-tests -- Test the AWA.Commands
-- Copyright (C) 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.Text_IO;
with Ada.Exceptions;
with Util.Processes;
with Util.Streams.Pipes;
with Util.Streams.Buffered;
with Util.Test_Caller;
with Util.Log.Loggers;
with Security;
with ASF.Tests;
with AWA.Tests.Helpers.Users;
with AWA.Users.Services;
with AWA.Users.Models;
with ASF.Requests.Mockup;
with ASF.Responses.Mockup;
package body AWA.Commands.Tests is
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("AWA.Commands.Tests");
package Caller is new Util.Test_Caller (Test, "Commands");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test AWA.Commands.Start_Stop",
Test_Start_Stop'Access);
Caller.Add_Test (Suite, "Test AWA.Commands.List (tables)",
Test_List_Tables'Access);
Caller.Add_Test (Suite, "Test AWA.Commands.List (users)",
Test_List_Users'Access);
Caller.Add_Test (Suite, "Test AWA.Commands.List (sessions)",
Test_List_Sessions'Access);
Caller.Add_Test (Suite, "Test AWA.Commands.List (jobs)",
Test_List_Jobs'Access);
Caller.Add_Test (Suite, "Test AWA.Commands.Info (secure configuration 1)",
Test_Secure_Configuration'Access);
Caller.Add_Test (Suite, "Test AWA.Commands.Info (secure configuration 2)",
Test_Secure_Configuration_2'Access);
Caller.Add_Test (Suite, "Test AWA.Commands.Info (verbose)",
Test_Verbose_Command'Access);
Caller.Add_Test (Suite, "Test AWA.Commands.User (register)",
Test_User_Command'Access);
end Add_Tests;
-- ------------------------------
-- Execute the command and get the output in a string.
-- ------------------------------
procedure Execute (T : in out Test;
Command : in String;
Input : in String;
Output : in String;
Result : out Ada.Strings.Unbounded.Unbounded_String;
Status : in Natural := 0) is
P : aliased Util.Streams.Pipes.Pipe_Stream;
Buffer : Util.Streams.Buffered.Input_Buffer_Stream;
begin
if Input'Length > 0 then
Log.Info ("Execute: {0} < {1}", Command, Input);
elsif Output'Length > 0 then
Log.Info ("Execute: {0} > {1}", Command, Output);
else
Log.Info ("Execute: {0}", Command);
end if;
P.Set_Input_Stream (Input);
P.Set_Output_Stream (Output);
P.Open (Command, Util.Processes.READ_ALL);
-- Write on the process input stream.
Result := Ada.Strings.Unbounded.Null_Unbounded_String;
Buffer.Initialize (P'Unchecked_Access, 8192);
Buffer.Read (Result);
P.Close;
Ada.Text_IO.Put_Line (Ada.Strings.Unbounded.To_String (Result));
Log.Info ("Command result: {0}", Result);
Util.Tests.Assert_Equals (T, Status, P.Get_Exit_Status, "Command '" & Command & "' failed");
end Execute;
-- ------------------------------
-- Test start and stop command.
-- ------------------------------
procedure Test_Start_Stop (T : in out Test) is
Config : constant String := Util.Tests.Get_Parameter ("test_config_path");
task Start_Server is
entry Start;
entry Wait (Result : out Ada.Strings.Unbounded.Unbounded_String);
end Start_Server;
task body Start_Server is
Output : Ada.Strings.Unbounded.Unbounded_String;
begin
accept Start do
null;
end Start;
begin
T.Execute ("bin/awa_command -c " & Config & " start -m 26123",
"", "", Output, 0);
exception
when others =>
Output := Ada.Strings.Unbounded.To_Unbounded_String ("* exception *");
end;
accept Wait (Result : out Ada.Strings.Unbounded.Unbounded_String) do
Result := Output;
end Wait;
end Start_Server;
Result : Ada.Strings.Unbounded.Unbounded_String;
begin
-- Launch the 'start' command in a separate task because the command will hang.
Start_Server.Start;
delay 5.0;
-- Launch the 'stop' command, this should terminate the 'start' command.
T.Execute ("bin/awa_command -c " & Config & " stop -m 26123",
"", "", Result, 0);
-- Wait for the task result.
Start_Server.Wait (Result);
Util.Tests.Assert_Matches (T, "Starting...", Result, "AWA start command output");
end Test_Start_Stop;
procedure Test_List_Tables (T : in out Test) is
Config : constant String := Util.Tests.Get_Parameter ("test_config_path");
Result : Ada.Strings.Unbounded.Unbounded_String;
begin
T.Execute ("bin/awa_command -c " & Config & " list -t",
"", "", Result, 0);
Util.Tests.Assert_Matches (T, "awa_audit *[0-9]+", Result, "Missing awa_audit");
Util.Tests.Assert_Matches (T, "awa_session *[0-9]+", Result, "Missing awa_session");
Util.Tests.Assert_Matches (T, "entity_type *[0-9]+", Result, "Missing entity_type");
Util.Tests.Assert_Matches (T, "awa_wiki_page *[0-9]+", Result, "Missing awa_wiki_page");
end Test_List_Tables;
-- ------------------------------
-- Test the list -u command.
-- ------------------------------
procedure Test_List_Users (T : in out Test) is
Config : constant String := Util.Tests.Get_Parameter ("test_config_path");
Result : Ada.Strings.Unbounded.Unbounded_String;
begin
T.Execute ("bin/awa_command -c " & Config & " list -u",
"", "", Result, 0);
Util.Tests.Assert_Matches (T, "Joe Pot", Result, "Missing user");
Util.Tests.Assert_Matches (T, "[email protected]", Result, "Missing email");
end Test_List_Users;
-- ------------------------------
-- Test the list -s command.
-- ------------------------------
procedure Test_List_Sessions (T : in out Test) is
Config : constant String := Util.Tests.Get_Parameter ("test_config_path");
Result : Ada.Strings.Unbounded.Unbounded_String;
begin
T.Execute ("bin/awa_command -c " & Config & " list -s",
"", "", Result, 0);
Util.Tests.Assert_Matches (T, "Joe Pot", Result, "Missing user");
end Test_List_Sessions;
-- ------------------------------
-- Test the list -j command.
-- ------------------------------
procedure Test_List_Jobs (T : in out Test) is
Config : constant String := Util.Tests.Get_Parameter ("test_config_path");
Result : Ada.Strings.Unbounded.Unbounded_String;
begin
T.Execute ("bin/awa_command -c " & Config & " list -j",
"", "", Result, 0);
Util.Tests.Assert_Matches (T, "S_FACTORY", Result, "Missing factory");
Util.Tests.Assert_Matches (T, "Joe Pot", Result, "Missing user");
end Test_List_Jobs;
-- ------------------------------
-- Test the command with a secure keystore configuration.
-- ------------------------------
procedure Test_Secure_Configuration (T : in out Test) is
Config : constant String := Util.Tests.Get_Parameter ("test_config_path");
Keystore : constant String := Util.Tests.Get_Parameter ("test_keystore_file");
Result : Ada.Strings.Unbounded.Unbounded_String;
begin
T.Execute ("bin/awa_command -c " & Config & " info --keystore " & Keystore
& " --password=unit-test-password", "", "", Result, 0);
Util.Tests.Assert_Matches (T, "app_name *AWA Secure Demo", Result,
"Secure property not accessed");
end Test_Secure_Configuration;
-- ------------------------------
-- Test the command with a secure keystore configuration.
-- ------------------------------
procedure Test_Secure_Configuration_2 (T : in out Test) is
Config : constant String := Util.Tests.Get_Parameter ("test_secure_config_path");
Result : Ada.Strings.Unbounded.Unbounded_String;
begin
T.Execute ("bin/awa_command -c " & Config & " info", "", "", Result, 0);
Util.Tests.Assert_Matches (T, "app_name *AWA Secure Demo", Result,
"Secure property not accessed");
Util.Tests.Assert_Matches (T, "users.auth_key *auth-", Result,
"Secure property not accessed");
Util.Tests.Assert_Matches (T, "users.server_id *[123]0", Result,
"Secure property not accessed");
end Test_Secure_Configuration_2;
-- ------------------------------
-- Test the command with various logging options.
-- ------------------------------
procedure Test_Verbose_Command (T : in out Test) is
Config : constant String := Util.Tests.Get_Parameter ("test_config_path");
Result : Ada.Strings.Unbounded.Unbounded_String;
begin
T.Execute ("bin/awa_command -v -c " & Config & " info ", "", "", Result, 0);
Util.Tests.Assert_Matches (T, "INFO : Using application search dir:", Result,
"Missing log message");
end Test_Verbose_Command;
-- ------------------------------
-- Test the user command.
-- ------------------------------
procedure Test_User_Command (T : in out Test) is
Email : constant String := "Reg-" & Util.Tests.Get_Uuid & "@register.com";
Config : constant String := Util.Tests.Get_Parameter ("test_config_path");
Result : Ada.Strings.Unbounded.Unbounded_String;
Principal : AWA.Tests.Helpers.Users.Test_User;
Key : AWA.Users.Models.Access_Key_Ref;
begin
T.Execute ("bin/awa_command -c " & Config & " user " & Email & " --register",
"", "", Result, 0);
Util.Tests.Assert_Matches (T, "User 'Reg-.*@register.com' is now registered", Result,
"Missing notice message");
begin
Principal.Email.Set_Email (Email);
AWA.Tests.Helpers.Users.Login (Principal);
T.Assert (False, "Login succeeded with a registered user");
exception
when E : AWA.Users.Services.User_Disabled =>
Util.Tests.Assert_Matches (T, "User account is not validated: Reg-.*",
Ada.Exceptions.Exception_Message (E));
end;
AWA.Tests.Helpers.Users.Find_Access_Key (Principal, Email, Key);
-- Run the verification and get the user and its session
Principal.Manager.Verify_User (Key.Get_Access_Key, "192.168.1.1",
Principal.Principal);
declare
use type Security.Principal_Access;
Request : ASF.Requests.Mockup.Request;
Reply : ASF.Responses.Mockup.Response;
begin
-- Simulate user clicking on the reset password link.
-- This verifies the key, login the user and redirect him to the change-password page
Request.Set_Parameter ("key", Key.Get_Access_Key);
Request.Set_Parameter ("password", "admin");
Request.Set_Parameter ("reset-password", "1");
ASF.Tests.Do_Post (Request, Reply, "/auth/change-password.html", "reset-password-3.html");
if Reply.Get_Status /= ASF.Responses.SC_MOVED_TEMPORARILY then
Log.Error ("Invalid response");
end if;
-- Check that the user is logged and we have a user principal now.
if Request.Get_User_Principal = null then
Log.Error ("A user principal should be defined");
end if;
end;
end Test_User_Command;
end AWA.Commands.Tests;
|
Update the user creation test to check the password creation
|
Update the user creation test to check the password creation
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
d23c72dc62c0ee378106cffc71190229e87b6309
|
src/wiki-render-html.adb
|
src/wiki-render-html.adb
|
-----------------------------------------------------------------------
-- wiki-render-html -- Wiki HTML renderer
-- Copyright (C) 2011, 2012, 2013, 2014, 2015, 2016 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Characters.Conversions;
with Util.Strings;
package body Wiki.Render.Html is
package ACC renames Ada.Characters.Conversions;
-- ------------------------------
-- Set the output stream.
-- ------------------------------
procedure Set_Output_Stream (Engine : in out Html_Renderer;
Stream : in Wiki.Streams.Html.Html_Output_Stream_Access) is
begin
Engine.Output := Stream;
end Set_Output_Stream;
-- ------------------------------
-- Set the link renderer.
-- ------------------------------
procedure Set_Link_Renderer (Document : in out Html_Renderer;
Links : in Link_Renderer_Access) is
begin
Document.Links := Links;
end Set_Link_Renderer;
-- ------------------------------
-- Render the node instance from the document.
-- ------------------------------
overriding
procedure Render (Engine : in out Html_Renderer;
Doc : in Wiki.Nodes.Document;
Node : in Wiki.Nodes.Node_Type) is
use type Wiki.Nodes.Html_Tag_Type;
use type Wiki.Nodes.Node_List_Access;
begin
case Node.Kind is
when Wiki.Nodes.N_HEADER =>
Engine.Add_Header (Header => Node.Header,
Level => Node.Level);
when Wiki.Nodes.N_LINE_BREAK =>
Engine.Output.Start_Element ("br");
Engine.Output.End_Element ("br");
when Wiki.Nodes.N_HORIZONTAL_RULE =>
Engine.Close_Paragraph;
Engine.Add_Blockquote (0);
Engine.Output.Start_Element ("hr");
Engine.Output.End_Element ("hr");
when Wiki.Nodes.N_PARAGRAPH =>
Engine.Close_Paragraph;
Engine.Need_Paragraph := True;
when Wiki.Nodes.N_INDENT =>
-- Engine.Indent_Level := Node.Level;
null;
when Wiki.Nodes.N_TEXT =>
Engine.Add_Text (Text => Node.Text,
Format => Node.Format);
when Wiki.Nodes.N_QUOTE =>
Engine.Open_Paragraph;
Engine.Output.Write (Node.Quote);
when Wiki.Nodes.N_LINK =>
if Node.Image then
Engine.Add_Link (Node.Title, Node.Link_Attr);
else
Engine.Render_Link (Doc, Node.Title, Node.Link_Attr);
end if;
when Wiki.Nodes.N_BLOCKQUOTE =>
Engine.Add_Blockquote (Node.Level);
when Wiki.Nodes.N_TAG_START =>
Engine.Render_Tag (Doc, Node);
end case;
end Render;
procedure Render_Tag (Engine : in out Html_Renderer;
Doc : in Wiki.Nodes.Document;
Node : in Wiki.Nodes.Node_Type) is
use type Wiki.Nodes.Html_Tag_Type;
Name : constant Wiki.Nodes.String_Access := Wiki.Nodes.Get_Tag_Name (Node.Tag_Start);
Iter : Wiki.Attributes.Cursor := Wiki.Attributes.First (Node.Attributes);
begin
if Node.Tag_Start = Wiki.Nodes.P_TAG then
Engine.Has_Paragraph := True;
Engine.Need_Paragraph := False;
end if;
Engine.Output.Start_Element (Name.all);
while Wiki.Attributes.Has_Element (Iter) loop
Engine.Output.Write_Wide_Attribute (Name => Wiki.Attributes.Get_Name (Iter),
Content => Wiki.Attributes.Get_Wide_Value (Iter));
Wiki.Attributes.Next (Iter);
end loop;
Engine.Render (Doc, Node.Children);
if Node.Tag_Start = Wiki.Nodes.P_TAG then
Engine.Has_Paragraph := False;
Engine.Need_Paragraph := True;
end if;
Engine.Output.End_Element (Name.all);
end Render_Tag;
-- ------------------------------
-- Add a section header in the document.
-- ------------------------------
procedure Add_Header (Engine : in out Html_Renderer;
Header : in Wiki.Strings.WString;
Level : in Positive) is
begin
Engine.Close_Paragraph;
Engine.Add_Blockquote (0);
case Level is
when 1 =>
Engine.Output.Write_Wide_Element ("h1", Header);
when 2 =>
Engine.Output.Write_Wide_Element ("h2", Header);
when 3 =>
Engine.Output.Write_Wide_Element ("h3", Header);
when 4 =>
Engine.Output.Write_Wide_Element ("h4", Header);
when 5 =>
Engine.Output.Write_Wide_Element ("h5", Header);
when 6 =>
Engine.Output.Write_Wide_Element ("h6", Header);
when others =>
Engine.Output.Write_Wide_Element ("h3", Header);
end case;
end Add_Header;
-- ------------------------------
-- Add a blockquote (<blockquote>). The level indicates the blockquote nested level.
-- The blockquote must be closed at the next header.
-- ------------------------------
procedure Add_Blockquote (Document : in out Html_Renderer;
Level : in Natural) is
begin
if Document.Quote_Level /= Level then
Document.Close_Paragraph;
Document.Need_Paragraph := True;
end if;
while Document.Quote_Level < Level loop
Document.Output.Start_Element ("blockquote");
Document.Quote_Level := Document.Quote_Level + 1;
end loop;
while Document.Quote_Level > Level loop
Document.Output.End_Element ("blockquote");
Document.Quote_Level := Document.Quote_Level - 1;
end loop;
end Add_Blockquote;
-- ------------------------------
-- Add a list item (<li>). Close the previous paragraph and list item if any.
-- The list item will be closed at the next list item, next paragraph or next header.
-- ------------------------------
procedure Add_List_Item (Document : in out Html_Renderer;
Level : in Positive;
Ordered : in Boolean) is
begin
if Document.Has_Paragraph then
Document.Output.End_Element ("p");
Document.Has_Paragraph := False;
end if;
if Document.Has_Item then
Document.Output.End_Element ("li");
Document.Has_Item := False;
end if;
Document.Need_Paragraph := False;
Document.Open_Paragraph;
while Document.Current_Level < Level loop
if Ordered then
Document.Output.Start_Element ("ol");
else
Document.Output.Start_Element ("ul");
end if;
Document.Current_Level := Document.Current_Level + 1;
Document.List_Styles (Document.Current_Level) := Ordered;
end loop;
end Add_List_Item;
procedure Close_Paragraph (Document : in out Html_Renderer) is
begin
if Document.Html_Level > 0 then
return;
end if;
if Document.Has_Paragraph then
Document.Output.End_Element ("p");
end if;
if Document.Has_Item then
Document.Output.End_Element ("li");
end if;
while Document.Current_Level > 0 loop
if Document.List_Styles (Document.Current_Level) then
Document.Output.End_Element ("ol");
else
Document.Output.End_Element ("ul");
end if;
Document.Current_Level := Document.Current_Level - 1;
end loop;
Document.Has_Paragraph := False;
Document.Has_Item := False;
end Close_Paragraph;
procedure Open_Paragraph (Document : in out Html_Renderer) is
begin
if Document.Html_Level > 0 then
return;
end if;
if Document.Need_Paragraph then
Document.Output.Start_Element ("p");
Document.Has_Paragraph := True;
Document.Need_Paragraph := False;
end if;
if Document.Current_Level > 0 and not Document.Has_Item then
Document.Output.Start_Element ("li");
Document.Has_Item := True;
end if;
end Open_Paragraph;
-- ------------------------------
-- Render a link.
-- ------------------------------
procedure Render_Link (Engine : in out Html_Renderer;
Doc : in Wiki.Nodes.Document;
Title : in Wiki.Strings.WString;
Attr : in Wiki.Attributes.Attribute_List_Type) is
Exists : Boolean;
Link : Unbounded_Wide_Wide_String := Wiki.Attributes.Get_Unbounded_Wide_Value (Attr, "href");
URI : Unbounded_Wide_Wide_String;
begin
Engine.Open_Paragraph;
Engine.Output.Start_Element ("a");
if Length (Title) > 0 then
Document.Output.Write_Wide_Attribute ("title", Title);
end if;
if Length (Language) > 0 then
Document.Output.Write_Wide_Attribute ("lang", Language);
end if;
Engine.Links.Make_Page_Link (Link, URI, Exists);
Engine.Output.Write_Wide_Attribute ("href", URI);
Engine.Output.Write_Wide_Text (Name);
Engine.Output.End_Element ("a");
end Render_Link;
-- ------------------------------
-- Add an image.
-- ------------------------------
procedure Add_Image (Document : in out Html_Renderer;
Link : in Unbounded_Wide_Wide_String;
Alt : in Unbounded_Wide_Wide_String;
Position : in Unbounded_Wide_Wide_String;
Description : in Unbounded_Wide_Wide_String) is
pragma Unreferenced (Position);
URI : Unbounded_Wide_Wide_String;
Width : Natural;
Height : Natural;
begin
Document.Open_Paragraph;
Document.Output.Start_Element ("img");
if Length (Alt) > 0 then
Document.Output.Write_Wide_Attribute ("alt", Alt);
end if;
if Length (Description) > 0 then
Document.Output.Write_Wide_Attribute ("longdesc", Description);
end if;
Document.Links.Make_Image_Link (Link, URI, Width, Height);
Document.Output.Write_Wide_Attribute ("src", URI);
if Width > 0 then
Document.Output.Write_Attribute ("width", Natural'Image (Width));
end if;
if Height > 0 then
Document.Output.Write_Attribute ("height", Natural'Image (Height));
end if;
Document.Output.End_Element ("img");
end Add_Image;
-- ------------------------------
-- Add a quote.
-- ------------------------------
procedure Add_Quote (Document : in out Html_Renderer;
Quote : in Unbounded_Wide_Wide_String;
Link : in Unbounded_Wide_Wide_String;
Language : in Unbounded_Wide_Wide_String) is
begin
Document.Open_Paragraph;
Document.Output.Start_Element ("q");
if Length (Language) > 0 then
Document.Output.Write_Wide_Attribute ("lang", Language);
end if;
if Length (Link) > 0 then
Document.Output.Write_Wide_Attribute ("cite", Link);
end if;
Document.Output.Write_Wide_Text (Quote);
Document.Output.End_Element ("q");
end Add_Quote;
HTML_BOLD : aliased constant String := "b";
HTML_ITALIC : aliased constant String := "i";
HTML_CODE : aliased constant String := "tt";
HTML_SUPERSCRIPT : aliased constant String := "sup";
HTML_SUBSCRIPT : aliased constant String := "sub";
HTML_STRIKEOUT : aliased constant String := "del";
-- HTML_UNDERLINE : aliased constant String := "ins";
HTML_PREFORMAT : aliased constant String := "pre";
type String_Array_Access is array (Documents.Format_Type) of Util.Strings.Name_Access;
HTML_ELEMENT : constant String_Array_Access :=
(Documents.BOLD => HTML_BOLD'Access,
Documents.ITALIC => HTML_ITALIC'Access,
Documents.CODE => HTML_CODE'Access,
Documents.SUPERSCRIPT => HTML_SUPERSCRIPT'Access,
Documents.SUBSCRIPT => HTML_SUBSCRIPT'Access,
Documents.STRIKEOUT => HTML_STRIKEOUT'Access,
Documents.PREFORMAT => HTML_PREFORMAT'Access);
-- ------------------------------
-- Add a text block with the given format.
-- ------------------------------
procedure Add_Text (Engine : in out Html_Renderer;
Text : in Wiki.Strings.WString;
Format : in Wiki.Documents.Format_Map) is
begin
Engine.Open_Paragraph;
for I in Format'Range loop
if Format (I) then
Engine.Output.Start_Element (HTML_ELEMENT (I).all);
end if;
end loop;
Engine.Output.Write_Wide_Text (Text);
for I in reverse Format'Range loop
if Format (I) then
Engine.Output.End_Element (HTML_ELEMENT (I).all);
end if;
end loop;
end Add_Text;
-- ------------------------------
-- Add a text block that is pre-formatted.
-- ------------------------------
procedure Add_Preformatted (Document : in out Html_Renderer;
Text : in Unbounded_Wide_Wide_String;
Format : in Unbounded_Wide_Wide_String) is
begin
Document.Close_Paragraph;
if Format = "html" then
Document.Output.Write (Text);
else
Document.Output.Start_Element ("pre");
-- Document.Output.Write_Wide_Text (Text);
Document.Output.End_Element ("pre");
end if;
end Add_Preformatted;
-- ------------------------------
-- Finish the document after complete wiki text has been parsed.
-- ------------------------------
overriding
procedure Finish (Document : in out Html_Renderer) is
begin
Document.Close_Paragraph;
Document.Add_Blockquote (0);
end Finish;
end Wiki.Render.Html;
|
-----------------------------------------------------------------------
-- wiki-render-html -- Wiki HTML renderer
-- Copyright (C) 2011, 2012, 2013, 2014, 2015, 2016 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Characters.Conversions;
with Util.Strings;
package body Wiki.Render.Html is
package ACC renames Ada.Characters.Conversions;
-- ------------------------------
-- Set the output stream.
-- ------------------------------
procedure Set_Output_Stream (Engine : in out Html_Renderer;
Stream : in Wiki.Streams.Html.Html_Output_Stream_Access) is
begin
Engine.Output := Stream;
end Set_Output_Stream;
-- ------------------------------
-- Set the link renderer.
-- ------------------------------
procedure Set_Link_Renderer (Document : in out Html_Renderer;
Links : in Link_Renderer_Access) is
begin
Document.Links := Links;
end Set_Link_Renderer;
-- ------------------------------
-- Render the node instance from the document.
-- ------------------------------
overriding
procedure Render (Engine : in out Html_Renderer;
Doc : in Wiki.Nodes.Document;
Node : in Wiki.Nodes.Node_Type) is
use type Wiki.Nodes.Html_Tag_Type;
use type Wiki.Nodes.Node_List_Access;
begin
case Node.Kind is
when Wiki.Nodes.N_HEADER =>
Engine.Render_Header (Header => Node.Header,
Level => Node.Level);
when Wiki.Nodes.N_LINE_BREAK =>
Engine.Output.Start_Element ("br");
Engine.Output.End_Element ("br");
when Wiki.Nodes.N_HORIZONTAL_RULE =>
Engine.Close_Paragraph;
Engine.Add_Blockquote (0);
Engine.Output.Start_Element ("hr");
Engine.Output.End_Element ("hr");
when Wiki.Nodes.N_PARAGRAPH =>
Engine.Close_Paragraph;
Engine.Need_Paragraph := True;
when Wiki.Nodes.N_INDENT =>
-- Engine.Indent_Level := Node.Level;
null;
when Wiki.Nodes.N_TEXT =>
Engine.Add_Text (Text => Node.Text,
Format => Node.Format);
when Wiki.Nodes.N_QUOTE =>
Engine.Open_Paragraph;
Engine.Output.Write (Node.Quote);
when Wiki.Nodes.N_LINK =>
if Node.Image then
Engine.Add_Link (Node.Title, Node.Link_Attr);
else
Engine.Render_Link (Doc, Node.Title, Node.Link_Attr);
end if;
when Wiki.Nodes.N_BLOCKQUOTE =>
Engine.Add_Blockquote (Node.Level);
when Wiki.Nodes.N_TAG_START =>
Engine.Render_Tag (Doc, Node);
end case;
end Render;
procedure Render_Tag (Engine : in out Html_Renderer;
Doc : in Wiki.Nodes.Document;
Node : in Wiki.Nodes.Node_Type) is
use type Wiki.Nodes.Html_Tag_Type;
Name : constant Wiki.Nodes.String_Access := Wiki.Nodes.Get_Tag_Name (Node.Tag_Start);
Iter : Wiki.Attributes.Cursor := Wiki.Attributes.First (Node.Attributes);
begin
if Node.Tag_Start = Wiki.Nodes.P_TAG then
Engine.Has_Paragraph := True;
Engine.Need_Paragraph := False;
end if;
Engine.Output.Start_Element (Name.all);
while Wiki.Attributes.Has_Element (Iter) loop
Engine.Output.Write_Wide_Attribute (Name => Wiki.Attributes.Get_Name (Iter),
Content => Wiki.Attributes.Get_Wide_Value (Iter));
Wiki.Attributes.Next (Iter);
end loop;
Engine.Render (Doc, Node.Children);
if Node.Tag_Start = Wiki.Nodes.P_TAG then
Engine.Has_Paragraph := False;
Engine.Need_Paragraph := True;
end if;
Engine.Output.End_Element (Name.all);
end Render_Tag;
-- ------------------------------
-- Render a section header in the document.
-- ------------------------------
procedure Render_Header (Engine : in out Html_Renderer;
Header : in Wiki.Strings.WString;
Level : in Positive) is
begin
Engine.Close_Paragraph;
Engine.Add_Blockquote (0);
case Level is
when 1 =>
Engine.Output.Write_Wide_Element ("h1", Header);
when 2 =>
Engine.Output.Write_Wide_Element ("h2", Header);
when 3 =>
Engine.Output.Write_Wide_Element ("h3", Header);
when 4 =>
Engine.Output.Write_Wide_Element ("h4", Header);
when 5 =>
Engine.Output.Write_Wide_Element ("h5", Header);
when 6 =>
Engine.Output.Write_Wide_Element ("h6", Header);
when others =>
Engine.Output.Write_Wide_Element ("h3", Header);
end case;
end Render_Header;
-- ------------------------------
-- Add a blockquote (<blockquote>). The level indicates the blockquote nested level.
-- The blockquote must be closed at the next header.
-- ------------------------------
procedure Add_Blockquote (Document : in out Html_Renderer;
Level : in Natural) is
begin
if Document.Quote_Level /= Level then
Document.Close_Paragraph;
Document.Need_Paragraph := True;
end if;
while Document.Quote_Level < Level loop
Document.Output.Start_Element ("blockquote");
Document.Quote_Level := Document.Quote_Level + 1;
end loop;
while Document.Quote_Level > Level loop
Document.Output.End_Element ("blockquote");
Document.Quote_Level := Document.Quote_Level - 1;
end loop;
end Add_Blockquote;
-- ------------------------------
-- Add a list item (<li>). Close the previous paragraph and list item if any.
-- The list item will be closed at the next list item, next paragraph or next header.
-- ------------------------------
procedure Add_List_Item (Document : in out Html_Renderer;
Level : in Positive;
Ordered : in Boolean) is
begin
if Document.Has_Paragraph then
Document.Output.End_Element ("p");
Document.Has_Paragraph := False;
end if;
if Document.Has_Item then
Document.Output.End_Element ("li");
Document.Has_Item := False;
end if;
Document.Need_Paragraph := False;
Document.Open_Paragraph;
while Document.Current_Level < Level loop
if Ordered then
Document.Output.Start_Element ("ol");
else
Document.Output.Start_Element ("ul");
end if;
Document.Current_Level := Document.Current_Level + 1;
Document.List_Styles (Document.Current_Level) := Ordered;
end loop;
end Add_List_Item;
procedure Close_Paragraph (Document : in out Html_Renderer) is
begin
if Document.Html_Level > 0 then
return;
end if;
if Document.Has_Paragraph then
Document.Output.End_Element ("p");
end if;
if Document.Has_Item then
Document.Output.End_Element ("li");
end if;
while Document.Current_Level > 0 loop
if Document.List_Styles (Document.Current_Level) then
Document.Output.End_Element ("ol");
else
Document.Output.End_Element ("ul");
end if;
Document.Current_Level := Document.Current_Level - 1;
end loop;
Document.Has_Paragraph := False;
Document.Has_Item := False;
end Close_Paragraph;
procedure Open_Paragraph (Document : in out Html_Renderer) is
begin
if Document.Html_Level > 0 then
return;
end if;
if Document.Need_Paragraph then
Document.Output.Start_Element ("p");
Document.Has_Paragraph := True;
Document.Need_Paragraph := False;
end if;
if Document.Current_Level > 0 and not Document.Has_Item then
Document.Output.Start_Element ("li");
Document.Has_Item := True;
end if;
end Open_Paragraph;
-- ------------------------------
-- Render a link.
-- ------------------------------
procedure Render_Link (Engine : in out Html_Renderer;
Doc : in Wiki.Nodes.Document;
Title : in Wiki.Strings.WString;
Attr : in Wiki.Attributes.Attribute_List_Type) is
Exists : Boolean;
Link : Unbounded_Wide_Wide_String := Wiki.Attributes.Get_Unbounded_Wide_Value (Attr, "href");
URI : Unbounded_Wide_Wide_String;
begin
Engine.Open_Paragraph;
Engine.Output.Start_Element ("a");
if Length (Title) > 0 then
Document.Output.Write_Wide_Attribute ("title", Title);
end if;
if Length (Language) > 0 then
Document.Output.Write_Wide_Attribute ("lang", Language);
end if;
Engine.Links.Make_Page_Link (Link, URI, Exists);
Engine.Output.Write_Wide_Attribute ("href", URI);
Engine.Output.Write_Wide_Text (Name);
Engine.Output.End_Element ("a");
end Render_Link;
-- ------------------------------
-- Add an image.
-- ------------------------------
procedure Add_Image (Document : in out Html_Renderer;
Link : in Unbounded_Wide_Wide_String;
Alt : in Unbounded_Wide_Wide_String;
Position : in Unbounded_Wide_Wide_String;
Description : in Unbounded_Wide_Wide_String) is
pragma Unreferenced (Position);
URI : Unbounded_Wide_Wide_String;
Width : Natural;
Height : Natural;
begin
Document.Open_Paragraph;
Document.Output.Start_Element ("img");
if Length (Alt) > 0 then
Document.Output.Write_Wide_Attribute ("alt", Alt);
end if;
if Length (Description) > 0 then
Document.Output.Write_Wide_Attribute ("longdesc", Description);
end if;
Document.Links.Make_Image_Link (Link, URI, Width, Height);
Document.Output.Write_Wide_Attribute ("src", URI);
if Width > 0 then
Document.Output.Write_Attribute ("width", Natural'Image (Width));
end if;
if Height > 0 then
Document.Output.Write_Attribute ("height", Natural'Image (Height));
end if;
Document.Output.End_Element ("img");
end Add_Image;
-- ------------------------------
-- Add a quote.
-- ------------------------------
procedure Add_Quote (Document : in out Html_Renderer;
Quote : in Unbounded_Wide_Wide_String;
Link : in Unbounded_Wide_Wide_String;
Language : in Unbounded_Wide_Wide_String) is
begin
Document.Open_Paragraph;
Document.Output.Start_Element ("q");
if Length (Language) > 0 then
Document.Output.Write_Wide_Attribute ("lang", Language);
end if;
if Length (Link) > 0 then
Document.Output.Write_Wide_Attribute ("cite", Link);
end if;
Document.Output.Write_Wide_Text (Quote);
Document.Output.End_Element ("q");
end Add_Quote;
HTML_BOLD : aliased constant String := "b";
HTML_ITALIC : aliased constant String := "i";
HTML_CODE : aliased constant String := "tt";
HTML_SUPERSCRIPT : aliased constant String := "sup";
HTML_SUBSCRIPT : aliased constant String := "sub";
HTML_STRIKEOUT : aliased constant String := "del";
-- HTML_UNDERLINE : aliased constant String := "ins";
HTML_PREFORMAT : aliased constant String := "pre";
type String_Array_Access is array (Documents.Format_Type) of Util.Strings.Name_Access;
HTML_ELEMENT : constant String_Array_Access :=
(Documents.BOLD => HTML_BOLD'Access,
Documents.ITALIC => HTML_ITALIC'Access,
Documents.CODE => HTML_CODE'Access,
Documents.SUPERSCRIPT => HTML_SUPERSCRIPT'Access,
Documents.SUBSCRIPT => HTML_SUBSCRIPT'Access,
Documents.STRIKEOUT => HTML_STRIKEOUT'Access,
Documents.PREFORMAT => HTML_PREFORMAT'Access);
-- ------------------------------
-- Add a text block with the given format.
-- ------------------------------
procedure Add_Text (Engine : in out Html_Renderer;
Text : in Wiki.Strings.WString;
Format : in Wiki.Documents.Format_Map) is
begin
Engine.Open_Paragraph;
for I in Format'Range loop
if Format (I) then
Engine.Output.Start_Element (HTML_ELEMENT (I).all);
end if;
end loop;
Engine.Output.Write_Wide_Text (Text);
for I in reverse Format'Range loop
if Format (I) then
Engine.Output.End_Element (HTML_ELEMENT (I).all);
end if;
end loop;
end Add_Text;
-- ------------------------------
-- Add a text block that is pre-formatted.
-- ------------------------------
procedure Add_Preformatted (Document : in out Html_Renderer;
Text : in Unbounded_Wide_Wide_String;
Format : in Unbounded_Wide_Wide_String) is
begin
Document.Close_Paragraph;
if Format = "html" then
Document.Output.Write (Text);
else
Document.Output.Start_Element ("pre");
-- Document.Output.Write_Wide_Text (Text);
Document.Output.End_Element ("pre");
end if;
end Add_Preformatted;
-- ------------------------------
-- Finish the document after complete wiki text has been parsed.
-- ------------------------------
overriding
procedure Finish (Document : in out Html_Renderer) is
begin
Document.Close_Paragraph;
Document.Add_Blockquote (0);
end Finish;
end Wiki.Render.Html;
|
Rename Add_Header into Render_Header
|
Rename Add_Header into Render_Header
|
Ada
|
apache-2.0
|
stcarrez/ada-wiki,stcarrez/ada-wiki
|
a8fa0aeb585bedd51a6208d1c17338e49af81b05
|
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
|
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
|
5146bb85cc34341a711a812bc8f90bb1a37b36e1
|
awa/src/awa-components-wikis.adb
|
awa/src/awa-components-wikis.adb
|
-----------------------------------------------------------------------
-- awa-components-wikis -- Wiki rendering component
-- Copyright (C) 2011, 2012, 2013, 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Strings;
with Ada.Characters.Conversions;
with ASF.Contexts.Writer;
with ASF.Utils;
with Wiki.Render.Html;
with Wiki.Writers;
package body AWA.Components.Wikis is
WIKI_ATTRIBUTE_NAMES : Util.Strings.String_Set.Set;
type Html_Writer_Type is limited new Wiki.Writers.Html_Writer_Type with record
Writer : ASF.Contexts.Writer.Response_Writer_Access;
end record;
overriding
procedure Write (Writer : in out Html_Writer_Type;
Content : in Wide_Wide_String);
-- Write a single character to the string builder.
overriding
procedure Write (Writer : in out Html_Writer_Type;
Char : in Wide_Wide_Character);
overriding
procedure Write (Writer : in out Html_Writer_Type;
Content : in Unbounded_Wide_Wide_String);
-- Write an XML element using the given name and with the content.
-- This is similar to calling <b>Start_Element</b>, <b>Write_Text</b>
-- and <b>End_Element</b>.
overriding
procedure Write_Wide_Element (Writer : in out Html_Writer_Type;
Name : in String;
Content : in Unbounded_Wide_Wide_String);
-- Write an XML attribute within an XML element.
-- The attribute value is escaped according to the XML escape rules.
overriding
procedure Write_Wide_Attribute (Writer : in out Html_Writer_Type;
Name : in String;
Content : in Unbounded_Wide_Wide_String);
-- Start an XML element with the given name.
overriding
procedure Start_Element (Writer : in out Html_Writer_Type;
Name : in String);
-- Closes an XML element of the given name.
overriding
procedure End_Element (Writer : in out Html_Writer_Type;
Name : in String);
-- Write a text escaping any character as necessary.
overriding
procedure Write_Wide_Text (Writer : in out Html_Writer_Type;
Content : in Unbounded_Wide_Wide_String);
overriding
procedure Write (Writer : in out Html_Writer_Type;
Content : in Wide_Wide_String) is
begin
Writer.Writer.Write_Wide_Text (Content);
end Write;
-- ------------------------------
-- Write a single character to the string builder.
-- ------------------------------
overriding
procedure Write (Writer : in out Html_Writer_Type;
Char : in Wide_Wide_Character) is
begin
Writer.Writer.Write_Wide_Char (Char);
end Write;
overriding
procedure Write (Writer : in out Html_Writer_Type;
Content : in Unbounded_Wide_Wide_String) is
begin
Writer.Writer.Write (Content);
end Write;
-- ------------------------------
-- Write an XML element using the given name and with the content.
-- This is similar to calling <b>Start_Element</b>, <b>Write_Text</b>
-- and <b>End_Element</b>.
-- ------------------------------
overriding
procedure Write_Wide_Element (Writer : in out Html_Writer_Type;
Name : in String;
Content : in Unbounded_Wide_Wide_String) is
begin
Writer.Writer.Write_Wide_Element (Name, Content);
end Write_Wide_Element;
-- ------------------------------
-- Write an XML attribute within an XML element.
-- The attribute value is escaped according to the XML escape rules.
-- ------------------------------
overriding
procedure Write_Wide_Attribute (Writer : in out Html_Writer_Type;
Name : in String;
Content : in Unbounded_Wide_Wide_String) is
begin
Writer.Writer.Write_Wide_Attribute (Name, Content);
end Write_Wide_Attribute;
-- ------------------------------
-- Start an XML element with the given name.
-- ------------------------------
overriding
procedure Start_Element (Writer : in out Html_Writer_Type;
Name : in String) is
begin
Writer.Writer.Start_Element (Name);
end Start_Element;
-- ------------------------------
-- Closes an XML element of the given name.
-- ------------------------------
overriding
procedure End_Element (Writer : in out Html_Writer_Type;
Name : in String) is
begin
Writer.Writer.End_Element (Name);
end End_Element;
-- ------------------------------
-- Write a text escaping any character as necessary.
-- ------------------------------
overriding
procedure Write_Wide_Text (Writer : in out Html_Writer_Type;
Content : in Unbounded_Wide_Wide_String) is
begin
Writer.Writer.Write_Wide_Text (Content);
end Write_Wide_Text;
-- ------------------------------
-- Get the wiki format style. The format style is obtained from the <b>format</b>
-- attribute name.
-- ------------------------------
function Get_Wiki_Style (UI : in UIWiki;
Context : in Faces_Context'Class)
return Wiki.Parsers.Wiki_Syntax_Type is
Format : constant String := UI.Get_Attribute (Name => FORMAT_NAME,
Context => Context,
Default => "dotclear");
begin
if Format = "dotclear" then
return Wiki.Parsers.SYNTAX_DOTCLEAR;
elsif Format = "google" then
return Wiki.Parsers.SYNTAX_GOOGLE;
elsif Format = "phpbb" then
return Wiki.Parsers.SYNTAX_PHPBB;
elsif Format = "creole" then
return Wiki.Parsers.SYNTAX_CREOLE;
elsif Format = "mediawiki" then
return Wiki.Parsers.SYNTAX_MEDIA_WIKI;
else
return Wiki.Parsers.SYNTAX_MIX;
end if;
end Get_Wiki_Style;
-- ------------------------------
-- Get the links renderer that must be used to render image and page links.
-- ------------------------------
function Get_Links_Renderer (UI : in UIWiki;
Context : in Faces_Context'Class)
return Wiki.Render.Link_Renderer_Access is
Value : constant Util.Beans.Objects.Object := UI.Get_Attribute (Context, LINKS_NAME);
Bean : constant access Util.Beans.Basic.Readonly_Bean'Class
:= Util.Beans.Objects.To_Bean (Value);
begin
if Bean = null then
return null;
elsif not (Bean.all in Link_Renderer_Bean'Class) then
return null;
else
return Link_Renderer_Bean'Class (Bean.all)'Access;
end if;
end Get_Links_Renderer;
-- ------------------------------
-- Render the wiki text
-- ------------------------------
overriding
procedure Encode_Begin (UI : in UIWiki;
Context : in out Faces_Context'Class) is
use ASF.Contexts.Writer;
use type Wiki.Render.Link_Renderer_Access;
begin
if not UI.Is_Rendered (Context) then
return;
end if;
declare
Writer : constant Response_Writer_Access := Context.Get_Response_Writer;
Html : aliased Html_Writer_Type;
Renderer : aliased Wiki.Render.Html.Html_Renderer;
Format : constant Wiki.Parsers.Wiki_Syntax_Type := UI.Get_Wiki_Style (Context);
Value : constant Util.Beans.Objects.Object := UI.Get_Attribute (Context, VALUE_NAME);
Links : Wiki.Render.Link_Renderer_Access;
begin
Html.Writer := Writer;
Writer.Start_Element ("div");
UI.Render_Attributes (Context, WIKI_ATTRIBUTE_NAMES, Writer);
if not Util.Beans.Objects.Is_Empty (Value) then
Links := UI.Get_Links_Renderer (Context);
if Links /= null then
Renderer.Set_Link_Renderer (Links);
end if;
Renderer.Set_Writer (Html'Unchecked_Access);
Wiki.Parsers.Parse (Renderer'Unchecked_Access,
Util.Beans.Objects.To_Wide_Wide_String (Value),
Format);
end if;
Writer.End_Element ("div");
end;
end Encode_Begin;
-- ------------------------------
-- Get the value identified by the name.
-- ------------------------------
overriding
function Get_Value (From : in Link_Renderer_Bean;
Name : in String) return Util.Beans.Objects.Object is
begin
if Name = IMAGE_PREFIX_ATTR then
return Util.Beans.Objects.To_Object (From.Image_Prefix);
elsif Name = PAGE_PREFIX_ATTR then
return Util.Beans.Objects.To_Object (From.Page_Prefix);
else
return Util.Beans.Objects.Null_Object;
end if;
end Get_Value;
function Starts_With (Content : in Unbounded_Wide_Wide_String;
Item : in String) return Boolean is
use Ada.Characters.Conversions;
Pos : Positive := 1;
begin
if Length (Content) < Item'Length then
return False;
end if;
for I in Item'Range loop
if Item (I) /= To_Character (Element (Content, Pos)) then
return False;
end if;
Pos := Pos + 1;
end loop;
return True;
end Starts_With;
-- ------------------------------
-- Return true if the link is an absolute link.
-- ------------------------------
function Is_Link_Absolute (Renderer : in Link_Renderer_Bean;
Link : in Unbounded_Wide_Wide_String) return Boolean is
begin
return Starts_With (Link, "http://") or Starts_With (Link, "https://");
end Is_Link_Absolute;
procedure Make_Link (Renderer : in Link_Renderer_Bean;
Link : in Unbounded_Wide_Wide_String;
Prefix : in Unbounded_Wide_Wide_String;
URI : out Unbounded_Wide_Wide_String) is
begin
if Renderer.Is_Link_Absolute (Link) then
URI := Link;
else
URI := Prefix & Link;
end if;
end Make_Link;
-- ------------------------------
-- Get the image link that must be rendered from the wiki image link.
-- ------------------------------
overriding
procedure Make_Image_Link (Renderer : in Link_Renderer_Bean;
Link : in Unbounded_Wide_Wide_String;
URI : out Unbounded_Wide_Wide_String;
Width : out Natural;
Height : out Natural) is
begin
Renderer.Make_Link (Link, Renderer.Image_Prefix, URI);
Width := 0;
Height := 0;
end Make_Image_Link;
-- ------------------------------
-- Get the page link that must be rendered from the wiki page link.
-- ------------------------------
overriding
procedure Make_Page_Link (Renderer : in Link_Renderer_Bean;
Link : in Unbounded_Wide_Wide_String;
URI : out Unbounded_Wide_Wide_String;
Exists : out Boolean) is
begin
Renderer.Make_Link (Link, Renderer.Page_Prefix, URI);
Exists := True;
end Make_Page_Link;
begin
ASF.Utils.Set_Text_Attributes (WIKI_ATTRIBUTE_NAMES);
end AWA.Components.Wikis;
|
-----------------------------------------------------------------------
-- awa-components-wikis -- Wiki rendering component
-- Copyright (C) 2011, 2012, 2013, 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Strings;
with Ada.Characters.Conversions;
with ASF.Contexts.Writer;
with ASF.Utils;
with Wiki.Render.Html;
with Wiki.Writers;
package body AWA.Components.Wikis is
WIKI_ATTRIBUTE_NAMES : Util.Strings.String_Set.Set;
type Html_Writer_Type is limited new Wiki.Writers.Html_Writer_Type with record
Writer : ASF.Contexts.Writer.Response_Writer_Access;
end record;
overriding
procedure Write (Writer : in out Html_Writer_Type;
Content : in Wide_Wide_String);
-- Write a single character to the string builder.
overriding
procedure Write (Writer : in out Html_Writer_Type;
Char : in Wide_Wide_Character);
overriding
procedure Write (Writer : in out Html_Writer_Type;
Content : in Unbounded_Wide_Wide_String);
-- Write an XML element using the given name and with the content.
-- This is similar to calling <b>Start_Element</b>, <b>Write_Text</b>
-- and <b>End_Element</b>.
overriding
procedure Write_Wide_Element (Writer : in out Html_Writer_Type;
Name : in String;
Content : in Unbounded_Wide_Wide_String);
-- Write an XML attribute within an XML element.
-- The attribute value is escaped according to the XML escape rules.
overriding
procedure Write_Wide_Attribute (Writer : in out Html_Writer_Type;
Name : in String;
Content : in Unbounded_Wide_Wide_String);
-- Start an XML element with the given name.
overriding
procedure Start_Element (Writer : in out Html_Writer_Type;
Name : in String);
-- Closes an XML element of the given name.
overriding
procedure End_Element (Writer : in out Html_Writer_Type;
Name : in String);
-- Write a text escaping any character as necessary.
overriding
procedure Write_Wide_Text (Writer : in out Html_Writer_Type;
Content : in Unbounded_Wide_Wide_String);
overriding
procedure Write (Writer : in out Html_Writer_Type;
Content : in Wide_Wide_String) is
begin
Writer.Writer.Write_Wide_Text (Content);
end Write;
-- ------------------------------
-- Write a single character to the string builder.
-- ------------------------------
overriding
procedure Write (Writer : in out Html_Writer_Type;
Char : in Wide_Wide_Character) is
begin
Writer.Writer.Write_Wide_Char (Char);
end Write;
overriding
procedure Write (Writer : in out Html_Writer_Type;
Content : in Unbounded_Wide_Wide_String) is
begin
Writer.Writer.Write (Content);
end Write;
-- ------------------------------
-- Write an XML element using the given name and with the content.
-- This is similar to calling <b>Start_Element</b>, <b>Write_Text</b>
-- and <b>End_Element</b>.
-- ------------------------------
overriding
procedure Write_Wide_Element (Writer : in out Html_Writer_Type;
Name : in String;
Content : in Unbounded_Wide_Wide_String) is
begin
Writer.Writer.Write_Wide_Element (Name, Content);
end Write_Wide_Element;
-- ------------------------------
-- Write an XML attribute within an XML element.
-- The attribute value is escaped according to the XML escape rules.
-- ------------------------------
overriding
procedure Write_Wide_Attribute (Writer : in out Html_Writer_Type;
Name : in String;
Content : in Unbounded_Wide_Wide_String) is
begin
Writer.Writer.Write_Wide_Attribute (Name, Content);
end Write_Wide_Attribute;
-- ------------------------------
-- Start an XML element with the given name.
-- ------------------------------
overriding
procedure Start_Element (Writer : in out Html_Writer_Type;
Name : in String) is
begin
Writer.Writer.Start_Element (Name);
end Start_Element;
-- ------------------------------
-- Closes an XML element of the given name.
-- ------------------------------
overriding
procedure End_Element (Writer : in out Html_Writer_Type;
Name : in String) is
begin
Writer.Writer.End_Element (Name);
end End_Element;
-- ------------------------------
-- Write a text escaping any character as necessary.
-- ------------------------------
overriding
procedure Write_Wide_Text (Writer : in out Html_Writer_Type;
Content : in Unbounded_Wide_Wide_String) is
begin
Writer.Writer.Write_Wide_Text (Content);
end Write_Wide_Text;
-- ------------------------------
-- Get the wiki format style. The format style is obtained from the <b>format</b>
-- attribute name.
-- ------------------------------
function Get_Wiki_Style (UI : in UIWiki;
Context : in Faces_Context'Class)
return Wiki.Parsers.Wiki_Syntax_Type is
Format : constant String := UI.Get_Attribute (Name => FORMAT_NAME,
Context => Context,
Default => "dotclear");
begin
if Format = "dotclear" then
return Wiki.Parsers.SYNTAX_DOTCLEAR;
elsif Format = "google" then
return Wiki.Parsers.SYNTAX_GOOGLE;
elsif Format = "phpbb" then
return Wiki.Parsers.SYNTAX_PHPBB;
elsif Format = "creole" then
return Wiki.Parsers.SYNTAX_CREOLE;
elsif Format = "mediawiki" then
return Wiki.Parsers.SYNTAX_MEDIA_WIKI;
else
return Wiki.Parsers.SYNTAX_MIX;
end if;
end Get_Wiki_Style;
-- ------------------------------
-- Get the links renderer that must be used to render image and page links.
-- ------------------------------
function Get_Links_Renderer (UI : in UIWiki;
Context : in Faces_Context'Class)
return Wiki.Render.Link_Renderer_Access is
Value : constant Util.Beans.Objects.Object := UI.Get_Attribute (Context, LINKS_NAME);
Bean : constant access Util.Beans.Basic.Readonly_Bean'Class
:= Util.Beans.Objects.To_Bean (Value);
begin
if Bean = null then
return null;
elsif not (Bean.all in Link_Renderer_Bean'Class) then
return null;
else
return Link_Renderer_Bean'Class (Bean.all)'Access;
end if;
end Get_Links_Renderer;
-- ------------------------------
-- Render the wiki text
-- ------------------------------
overriding
procedure Encode_Begin (UI : in UIWiki;
Context : in out Faces_Context'Class) is
use ASF.Contexts.Writer;
use type Wiki.Render.Link_Renderer_Access;
begin
if not UI.Is_Rendered (Context) then
return;
end if;
declare
Writer : constant Response_Writer_Access := Context.Get_Response_Writer;
Html : aliased Html_Writer_Type;
Renderer : aliased Wiki.Render.Html.Html_Renderer;
Format : constant Wiki.Parsers.Wiki_Syntax_Type := UI.Get_Wiki_Style (Context);
Value : constant Util.Beans.Objects.Object := UI.Get_Attribute (Context, VALUE_NAME);
Links : Wiki.Render.Link_Renderer_Access;
begin
Html.Writer := Writer;
Writer.Start_Element ("div");
UI.Render_Attributes (Context, WIKI_ATTRIBUTE_NAMES, Writer);
if not Util.Beans.Objects.Is_Empty (Value) then
Links := UI.Get_Links_Renderer (Context);
if Links /= null then
Renderer.Set_Link_Renderer (Links);
end if;
Renderer.Set_Writer (Html'Unchecked_Access);
Wiki.Parsers.Parse (Renderer'Unchecked_Access,
Util.Beans.Objects.To_Wide_Wide_String (Value),
Format);
end if;
Writer.End_Element ("div");
end;
end Encode_Begin;
-- ------------------------------
-- Get the value identified by the name.
-- ------------------------------
overriding
function Get_Value (From : in Link_Renderer_Bean;
Name : in String) return Util.Beans.Objects.Object is
begin
if Name = IMAGE_PREFIX_ATTR then
return Util.Beans.Objects.To_Object (From.Image_Prefix);
elsif Name = PAGE_PREFIX_ATTR then
return Util.Beans.Objects.To_Object (From.Page_Prefix);
else
return Util.Beans.Objects.Null_Object;
end if;
end Get_Value;
-- ------------------------------
-- Set the value identified by the name.
-- ------------------------------
overriding
procedure Set_Value (From : in out Link_Renderer_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object) is
begin
if Name = IMAGE_PREFIX_ATTR then
From.Image_Prefix := Util.Beans.Objects.To_Unbounded_Wide_Wide_String (Value);
elsif Name = PAGE_PREFIX_ATTR then
From.Page_Prefix := Util.Beans.Objects.To_Unbounded_Wide_Wide_String (Value);
end if;
end Set_Value;
function Starts_With (Content : in Unbounded_Wide_Wide_String;
Item : in String) return Boolean is
use Ada.Characters.Conversions;
Pos : Positive := 1;
begin
if Length (Content) < Item'Length then
return False;
end if;
for I in Item'Range loop
if Item (I) /= To_Character (Element (Content, Pos)) then
return False;
end if;
Pos := Pos + 1;
end loop;
return True;
end Starts_With;
-- ------------------------------
-- Return true if the link is an absolute link.
-- ------------------------------
function Is_Link_Absolute (Renderer : in Link_Renderer_Bean;
Link : in Unbounded_Wide_Wide_String) return Boolean is
begin
return Starts_With (Link, "http://") or Starts_With (Link, "https://");
end Is_Link_Absolute;
procedure Make_Link (Renderer : in Link_Renderer_Bean;
Link : in Unbounded_Wide_Wide_String;
Prefix : in Unbounded_Wide_Wide_String;
URI : out Unbounded_Wide_Wide_String) is
begin
if Renderer.Is_Link_Absolute (Link) then
URI := Link;
else
URI := Prefix & Link;
end if;
end Make_Link;
-- ------------------------------
-- Get the image link that must be rendered from the wiki image link.
-- ------------------------------
overriding
procedure Make_Image_Link (Renderer : in Link_Renderer_Bean;
Link : in Unbounded_Wide_Wide_String;
URI : out Unbounded_Wide_Wide_String;
Width : out Natural;
Height : out Natural) is
begin
Renderer.Make_Link (Link, Renderer.Image_Prefix, URI);
Width := 0;
Height := 0;
end Make_Image_Link;
-- ------------------------------
-- Get the page link that must be rendered from the wiki page link.
-- ------------------------------
overriding
procedure Make_Page_Link (Renderer : in Link_Renderer_Bean;
Link : in Unbounded_Wide_Wide_String;
URI : out Unbounded_Wide_Wide_String;
Exists : out Boolean) is
begin
Renderer.Make_Link (Link, Renderer.Page_Prefix, URI);
Exists := True;
end Make_Page_Link;
begin
ASF.Utils.Set_Text_Attributes (WIKI_ATTRIBUTE_NAMES);
end AWA.Components.Wikis;
|
Implement the Set_Value procedure to set the image/page prefix from the value
|
Implement the Set_Value procedure to set the image/page prefix from the value
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
978162328802b23a186390cbe19681a76e37a375
|
src/orka/implementation/orka-loops.adb
|
src/orka/implementation/orka-loops.adb
|
-- Copyright (c) 2017 onox <[email protected]>
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
with System;
with Ada.Unchecked_Conversion;
with Ada.Unchecked_Deallocation;
with Ada.Text_IO;
with Ada.Exceptions;
with Orka.Futures;
with Orka.Simulation_Jobs;
package body Orka.Loops is
use Ada.Real_Time;
Render_Job_Start, Render_Job_Finish : Jobs.Job_Ptr := Jobs.Null_Job;
procedure Free is new Ada.Unchecked_Deallocation
(Behaviors.Behavior_Array, Behaviors.Behavior_Array_Access);
function "<" (Left, Right : Behaviors.Behavior_Ptr) return Boolean is
function Convert is new Ada.Unchecked_Conversion
(Source => System.Address, Target => Long_Integer);
begin
return Convert (Left.all'Address) < Convert (Right.all'Address);
end "<";
protected body Handler is
procedure Stop is
begin
Stop_Flag := True;
end Stop;
procedure Set_Frame_Limit (Value : Time_Span) is
begin
Limit := Value;
end Set_Frame_Limit;
function Frame_Limit return Time_Span is
(Limit);
function Should_Stop return Boolean is
(Stop_Flag);
end Handler;
protected body Scene is
procedure Add (Object : Behaviors.Behavior_Ptr) is
begin
Behaviors_Set.Insert (Object);
Modified_Flag := True;
end Add;
procedure Remove (Object : Behaviors.Behavior_Ptr) is
begin
Behaviors_Set.Delete (Object);
Modified_Flag := True;
end Remove;
procedure Replace_Array (Target : in out Behaviors.Behavior_Array_Access) is
Index : Positive := 1;
Count : constant Positive := Positive (Behaviors_Set.Length);
begin
Free (Target);
Target := new Behaviors.Behavior_Array'(1 .. Count => Behaviors.Null_Behavior);
-- Copy the elements from the set to the array
-- for faster iteration by the game loop
for Element of Behaviors_Set loop
Target (Index) := Element;
Index := Index + 1;
end loop;
Modified_Flag := False;
end Replace_Array;
function Modified return Boolean is
(Modified_Flag);
procedure Set_Camera (Camera : Cameras.Camera_Ptr) is
begin
Scene_Camera := Camera;
end Set_Camera;
function Camera return Cameras.Camera_Ptr is
(Scene_Camera);
end Scene;
package SJ renames Simulation_Jobs;
procedure Run_Game_Loop is
Previous_Time : Time := Clock;
Next_Time : Time := Previous_Time;
Lag : Time_Span := Time_Span_Zero;
Scene_Array : Behaviors.Behavior_Array_Access := Behaviors.Empty_Behavior_Array;
Batch_Length : constant := 10;
begin
Scene.Replace_Array (Scene_Array);
-- Based on http://gameprogrammingpatterns.com/game-loop.html
loop
declare
Current_Time : constant Time := Clock;
Elapsed : constant Time_Span := Current_Time - Previous_Time;
begin
Previous_Time := Current_Time;
Lag := Lag + Elapsed;
exit when Handler.Should_Stop;
declare
Iterations : constant Natural := Lag / Time_Step;
begin
Lag := Lag - Iterations * Time_Step;
Scene.Camera.Update (To_Duration (Lag));
declare
Fixed_Update_Job : constant Jobs.Job_Ptr
:= Jobs.Parallelize (SJ.Create_Fixed_Update_Job
(Scene_Array, Time_Step, Iterations), Scene_Array'Length, Batch_Length);
Finished_Job : constant Jobs.Job_Ptr := SJ.Create_Finished_Job
(Scene_Array, Time_Step, Scene.Camera.View_Position, Batch_Length);
Render_Start_Job : constant Jobs.Job_Ptr
:= new Jobs.GPU_Job'Class'(Jobs.GPU_Job'Class (Render_Job_Start.all));
Render_Scene_Job : constant Jobs.Job_Ptr
:= SJ.Create_Scene_Render_Job (Render, Scene_Array, Scene.Camera);
Render_Finish_Job : constant Jobs.Job_Ptr
:= new Jobs.GPU_Job'Class'(Jobs.GPU_Job'Class (Render_Job_Finish.all));
Handle : Futures.Pointers.Mutable_Pointer;
Status : Futures.Status;
begin
Orka.Jobs.Chain
((Render_Start_Job, Fixed_Update_Job, Finished_Job,
Render_Scene_Job, Render_Finish_Job));
Job_Manager.Queue.Enqueue (Render_Start_Job, Handle);
Handle.Get.Wait_Until_Done (Status);
end;
end;
if Scene.Modified then
Scene.Replace_Array (Scene_Array);
end if;
declare
New_Elapsed : constant Time_Span := Clock - Current_Time;
begin
if New_Elapsed > Handler.Frame_Limit then
Next_Time := Current_Time;
else
Next_Time := Next_Time + Handler.Frame_Limit;
delay until Next_Time;
end if;
end;
end;
end loop;
Job_Manager.Shutdown;
exception
when others =>
Job_Manager.Shutdown;
raise;
end Run_Game_Loop;
procedure Stop_Loop is
begin
Handler.Stop;
end Stop_Loop;
procedure Run_Loop is
Fence : aliased SJ.Fences.Buffer_Fence := SJ.Fences.Create_Buffer_Fence;
begin
Render_Job_Start := SJ.Create_Start_Render_Job (Fence'Unchecked_Access, Window);
Render_Job_Finish := SJ.Create_Finish_Render_Job (Fence'Unchecked_Access, Window,
Stop_Loop'Unrestricted_Access);
declare
task Simulation;
use Ada.Exceptions;
task body Simulation is
begin
Run_Game_Loop;
exception
when Error : others =>
Ada.Text_IO.Put_Line ("Exception game loop: " & Exception_Information (Error));
end Simulation;
begin
Job_Manager.Executors.Execute_Jobs
("Renderer", Job_Manager.Queues.GPU, Job_Manager.Queue'Access);
end;
end Run_Loop;
end Orka.Loops;
|
-- Copyright (c) 2017 onox <[email protected]>
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
with System;
with Ada.Unchecked_Conversion;
with Ada.Unchecked_Deallocation;
with Ada.Text_IO;
with Ada.Exceptions;
with Orka.Futures;
with Orka.Simulation_Jobs;
package body Orka.Loops is
use Ada.Real_Time;
procedure Free is new Ada.Unchecked_Deallocation
(Behaviors.Behavior_Array, Behaviors.Behavior_Array_Access);
function "<" (Left, Right : Behaviors.Behavior_Ptr) return Boolean is
function Convert is new Ada.Unchecked_Conversion
(Source => System.Address, Target => Long_Integer);
begin
return Convert (Left.all'Address) < Convert (Right.all'Address);
end "<";
protected body Handler is
procedure Stop is
begin
Stop_Flag := True;
end Stop;
procedure Set_Frame_Limit (Value : Time_Span) is
begin
Limit := Value;
end Set_Frame_Limit;
function Frame_Limit return Time_Span is
(Limit);
function Should_Stop return Boolean is
(Stop_Flag);
end Handler;
protected body Scene is
procedure Add (Object : Behaviors.Behavior_Ptr) is
begin
Behaviors_Set.Insert (Object);
Modified_Flag := True;
end Add;
procedure Remove (Object : Behaviors.Behavior_Ptr) is
begin
Behaviors_Set.Delete (Object);
Modified_Flag := True;
end Remove;
procedure Replace_Array (Target : in out Behaviors.Behavior_Array_Access) is
Index : Positive := 1;
Count : constant Positive := Positive (Behaviors_Set.Length);
begin
Free (Target);
Target := new Behaviors.Behavior_Array'(1 .. Count => Behaviors.Null_Behavior);
-- Copy the elements from the set to the array
-- for faster iteration by the game loop
for Element of Behaviors_Set loop
Target (Index) := Element;
Index := Index + 1;
end loop;
Modified_Flag := False;
end Replace_Array;
function Modified return Boolean is
(Modified_Flag);
procedure Set_Camera (Camera : Cameras.Camera_Ptr) is
begin
Scene_Camera := Camera;
end Set_Camera;
function Camera return Cameras.Camera_Ptr is
(Scene_Camera);
end Scene;
package SJ renames Simulation_Jobs;
procedure Stop_Loop is
begin
Handler.Stop;
end Stop_Loop;
procedure Run_Game_Loop (Fence : not null access SJ.Fences.Buffer_Fence) is
Previous_Time : Time := Clock;
Next_Time : Time := Previous_Time;
Lag : Time_Span := Time_Span_Zero;
Scene_Array : Behaviors.Behavior_Array_Access := Behaviors.Empty_Behavior_Array;
Batch_Length : constant := 10;
begin
Scene.Replace_Array (Scene_Array);
-- Based on http://gameprogrammingpatterns.com/game-loop.html
loop
declare
Current_Time : constant Time := Clock;
Elapsed : constant Time_Span := Current_Time - Previous_Time;
begin
Previous_Time := Current_Time;
Lag := Lag + Elapsed;
exit when Handler.Should_Stop;
declare
Iterations : constant Natural := Lag / Time_Step;
begin
Lag := Lag - Iterations * Time_Step;
Scene.Camera.Update (To_Duration (Lag));
declare
Fixed_Update_Job : constant Jobs.Job_Ptr
:= Jobs.Parallelize (SJ.Create_Fixed_Update_Job
(Scene_Array, Time_Step, Iterations), Scene_Array'Length, Batch_Length);
Finished_Job : constant Jobs.Job_Ptr := SJ.Create_Finished_Job
(Scene_Array, Time_Step, Scene.Camera.View_Position, Batch_Length);
Render_Scene_Job : constant Jobs.Job_Ptr
:= SJ.Create_Scene_Render_Job (Render, Scene_Array, Scene.Camera);
Render_Start_Job : constant Jobs.Job_Ptr
:= SJ.Create_Start_Render_Job (Fence, Window);
Render_Finish_Job : constant Jobs.Job_Ptr
:= SJ.Create_Finish_Render_Job (Fence, Window,
Stop_Loop'Unrestricted_Access);
Handle : Futures.Pointers.Mutable_Pointer;
Status : Futures.Status;
begin
Orka.Jobs.Chain
((Render_Start_Job, Fixed_Update_Job, Finished_Job,
Render_Scene_Job, Render_Finish_Job));
Job_Manager.Queue.Enqueue (Render_Start_Job, Handle);
Handle.Get.Wait_Until_Done (Status);
end;
end;
if Scene.Modified then
Scene.Replace_Array (Scene_Array);
end if;
declare
New_Elapsed : constant Time_Span := Clock - Current_Time;
begin
if New_Elapsed > Handler.Frame_Limit then
Next_Time := Current_Time;
else
Next_Time := Next_Time + Handler.Frame_Limit;
delay until Next_Time;
end if;
end;
end;
end loop;
Job_Manager.Shutdown;
exception
when others =>
Job_Manager.Shutdown;
raise;
end Run_Game_Loop;
procedure Run_Loop is
Fence : aliased SJ.Fences.Buffer_Fence := SJ.Fences.Create_Buffer_Fence;
begin
declare
-- Create a separate task for the game loop. The current task
-- will be used to dequeue and execute GPU jobs.
task Simulation;
use Ada.Exceptions;
task body Simulation is
begin
Run_Game_Loop (Fence'Unchecked_Access);
exception
when Error : others =>
Ada.Text_IO.Put_Line ("Exception game loop: " & Exception_Information (Error));
end Simulation;
begin
-- Execute GPU jobs in the current task
Job_Manager.Executors.Execute_Jobs
("Renderer", Job_Manager.Queues.GPU, Job_Manager.Queue'Access);
end;
end Run_Loop;
end Orka.Loops;
|
Create render jobs instead of copying them
|
orka: Create render jobs instead of copying them
Signed-off-by: onox <[email protected]>
|
Ada
|
apache-2.0
|
onox/orka
|
b8f5162e699fd07e815ef9cdd92cb2749ccf2e93
|
awa/samples/src/atlas-server.adb
|
awa/samples/src/atlas-server.adb
|
-----------------------------------------------------------------------
-- Atlas-server -- Application server
-- Copyright (C) 2011 XXX
-- Written by XXX (XXX)
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR 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 ASF.Server.Web;
with Atlas.Applications;
procedure Atlas.Server is
CONTEXT_PATH : constant String := "/atlas";
App : constant Atlas.Applications.Application_Access := new Atlas.Applications.Application;
WS : ASF.Server.Web.AWS_Container;
begin
Atlas.Applications.Initialize (App);
WS.Register_Application (CONTEXT_PATH, App.all'Access);
WS.Start;
delay 365.0 * 24.0 * 3600.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 Atlas.Server;
|
-----------------------------------------------------------------------
-- Atlas-server -- Application server
-- Copyright (C) 2011 XXX
-- Written by XXX (XXX)
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR 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 ASF.Server.Web;
with Util.Log.Loggers;
with Atlas.Applications;
procedure Atlas.Server is
CONTEXT_PATH : constant String := "/atlas";
App : constant Atlas.Applications.Application_Access := new Atlas.Applications.Application;
Log : Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Atlas.Server");
WS : ASF.Server.Web.AWS_Container;
begin
Atlas.Applications.Initialize (App);
WS.Register_Application (CONTEXT_PATH, App.all'Access);
Log.Info ("Connect you browser to: http://localhost:8080/atlas/index.html");
WS.Start;
delay 365.0 * 24.0 * 3600.0;
App.Close;
exception
when E: others =>
Ada.Text_IO.Put_Line ("Exception in server: " &
Ada.Exceptions.Exception_Name (E) & ": " &
Ada.Exceptions.Exception_Message (E));
end Atlas.Server;
|
Add a log to indicate the main URL to connect to
|
Add a log to indicate the main URL to connect to
|
Ada
|
apache-2.0
|
tectronics/ada-awa,tectronics/ada-awa,Letractively/ada-awa,Letractively/ada-awa,Letractively/ada-awa,tectronics/ada-awa
|
0f2881ff1bd8ac6918dc7dd8773d5fd38792c523
|
examples/MicroBit/src/main.adb
|
examples/MicroBit/src/main.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.GPIO; use nRF51.GPIO;
with nRF51.Device; use nRF51.Device;
procedure Main is
Conf : GPIO_Configuration;
begin
Conf.Mode := Mode_Out;
Conf.Resistors := Pull_Down;
-- Column
P04.Configure_IO (Conf);
P05.Configure_IO (Conf);
P06.Configure_IO (Conf);
P07.Configure_IO (Conf);
P08.Configure_IO (Conf);
P09.Configure_IO (Conf);
P10.Configure_IO (Conf);
P11.Configure_IO (Conf);
P12.Configure_IO (Conf);
-- Row
P13.Configure_IO (Conf);
P14.Configure_IO (Conf);
P15.Configure_IO (Conf);
-- Column sink current
P04.Clear;
P05.Clear;
P06.Clear;
P07.Clear;
P08.Clear;
P09.Clear;
P10.Clear;
P11.Clear;
P12.Clear;
-- Blinky!!!
loop
-- Row source current
P13.Set;
P14.Set;
P15.Set;
for Cnt in 1 .. 100_000 loop
null;
end loop;
P13.Clear;
P14.Clear;
P15.Clear;
for Cnt in 1 .. 100_000 loop
null;
end loop;
end loop;
end Main;
|
------------------------------------------------------------------------------
-- --
-- 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 MicroBit.Display; use MicroBit.Display;
procedure Main is
begin
Initialize;
loop
for X in Coord loop
for Y in Coord loop
Set (X, Y);
for Cnt in 0 .. 100_000 loop
null;
end loop;
Clear (X, Y);
end loop;
end loop;
end loop;
end Main;
|
Update example with Display driver
|
MicroBit: Update example with Display driver
|
Ada
|
bsd-3-clause
|
lambourg/Ada_Drivers_Library,AdaCore/Ada_Drivers_Library,simonjwright/Ada_Drivers_Library,Fabien-Chouteau/Ada_Drivers_Library,ellamosi/Ada_BMP_Library,Fabien-Chouteau/Ada_Drivers_Library,simonjwright/Ada_Drivers_Library,AdaCore/Ada_Drivers_Library
|
ad6ceeb00acb6dd906d8200147fc95edda187064
|
src/gen-artifacts-xmi.ads
|
src/gen-artifacts-xmi.ads
|
-----------------------------------------------------------------------
-- gen-artifacts-xmi -- UML-XMI artifact for Code Generator
-- Copyright (C) 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with DOM.Core;
with Gen.Model.Packages;
with Gen.Model.XMI;
-- The <b>Gen.Artifacts.XMI</b> package is an artifact for the generation of Ada code
-- from an UML XMI description.
package Gen.Artifacts.XMI is
-- ------------------------------
-- UML XMI artifact
-- ------------------------------
type Artifact is new Gen.Artifacts.Artifact with private;
-- After the configuration file is read, processes the node whose root
-- is passed in <b>Node</b> and initializes the <b>Model</b> with the information.
overriding
procedure Initialize (Handler : in out Artifact;
Path : in String;
Node : in DOM.Core.Node;
Model : in out Gen.Model.Packages.Model_Definition'Class;
Context : in out Generator'Class);
-- Prepare the model after all the configuration files have been read and before
-- actually invoking the generation.
overriding
procedure Prepare (Handler : in out Artifact;
Model : in out Gen.Model.Packages.Model_Definition'Class;
Context : in out Generator'Class);
-- Read the UML/XMI model file.
procedure Read_Model (Handler : in out Artifact;
File : in String;
Context : in out Generator'Class);
-- Read the UML configuration files that define the pre-defined types, stereotypes
-- and other components used by a model. These files are XMI files as well.
-- All the XMI files in the UML config directory are read.
procedure Read_UML_Configuration (Handler : in out Artifact;
Context : in out Generator'Class);
private
type Artifact is new Gen.Artifacts.Artifact with record
Nodes : aliased Gen.Model.XMI.UML_Model;
Has_Config : Boolean := False;
-- Stereotype which triggers the generation of database table.
Table_Stereotype : Gen.Model.XMI.Stereotype_Element_Access;
PK_Stereotype : Gen.Model.XMI.Stereotype_Element_Access;
FK_Stereotype : Gen.Model.XMI.Stereotype_Element_Access;
Data_Model_Stereotype : Gen.Model.XMI.Stereotype_Element_Access;
-- Tag definitions which control the generation.
Has_List_Tag : Gen.Model.XMI.Tag_Definition_Element_Access;
-- Stereotype which triggers the generation of AWA bean types.
Bean_Stereotype : Gen.Model.XMI.Stereotype_Element_Access;
end record;
end Gen.Artifacts.XMI;
|
-----------------------------------------------------------------------
-- gen-artifacts-xmi -- UML-XMI artifact for Code Generator
-- Copyright (C) 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with DOM.Core;
with Gen.Model.Packages;
with Gen.Model.XMI;
-- The <b>Gen.Artifacts.XMI</b> package is an artifact for the generation of Ada code
-- from an UML XMI description.
package Gen.Artifacts.XMI is
-- ------------------------------
-- UML XMI artifact
-- ------------------------------
type Artifact is new Gen.Artifacts.Artifact with private;
-- After the configuration file is read, processes the node whose root
-- is passed in <b>Node</b> and initializes the <b>Model</b> with the information.
overriding
procedure Initialize (Handler : in out Artifact;
Path : in String;
Node : in DOM.Core.Node;
Model : in out Gen.Model.Packages.Model_Definition'Class;
Context : in out Generator'Class);
-- Prepare the model after all the configuration files have been read and before
-- actually invoking the generation.
overriding
procedure Prepare (Handler : in out Artifact;
Model : in out Gen.Model.Packages.Model_Definition'Class;
Context : in out Generator'Class);
-- Read the UML/XMI model file.
procedure Read_Model (Handler : in out Artifact;
File : in String;
Context : in out Generator'Class);
-- Read the UML configuration files that define the pre-defined types, stereotypes
-- and other components used by a model. These files are XMI files as well.
-- All the XMI files in the UML config directory are read.
procedure Read_UML_Configuration (Handler : in out Artifact;
Context : in out Generator'Class);
private
type Artifact is new Gen.Artifacts.Artifact with record
Nodes : aliased Gen.Model.XMI.UML_Model;
Has_Config : Boolean := False;
-- Stereotype which triggers the generation of database table.
Table_Stereotype : Gen.Model.XMI.Stereotype_Element_Access;
PK_Stereotype : Gen.Model.XMI.Stereotype_Element_Access;
FK_Stereotype : Gen.Model.XMI.Stereotype_Element_Access;
Data_Model_Stereotype : Gen.Model.XMI.Stereotype_Element_Access;
-- Tag definitions which control the generation.
Has_List_Tag : Gen.Model.XMI.Tag_Definition_Element_Access;
Table_Name_Tag : Gen.Model.XMI.Tag_Definition_Element_Access;
-- Stereotype which triggers the generation of AWA bean types.
Bean_Stereotype : Gen.Model.XMI.Stereotype_Element_Access;
end record;
end Gen.Artifacts.XMI;
|
Add the table name tag definition
|
Add the table name tag definition
|
Ada
|
apache-2.0
|
Letractively/ada-gen,Letractively/ada-gen,Letractively/ada-gen,Letractively/ada-gen
|
ca47a6a697fd21d71b4e45bc11f083132e56ce2c
|
awa/src/awa-helpers-selectors.adb
|
awa/src/awa-helpers-selectors.adb
|
-----------------------------------------------------------------------
-- awa-helpers -- Helpers for AWA applications
-- 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 ADO.Queries.Loaders;
with AWA.Services.Contexts;
package body AWA.Helpers.Selectors is
-- ------------------------------
-- Create a selector list from the definition of a discrete type such as an enum.
-- The select item has the enum value as value and the label is created by
-- localizing the string <b>Prefix</b>_<i>enum name</i>.
-- ------------------------------
function Create_From_Enum (Bundle : in Util.Properties.Bundles.Manager'Class)
return ASF.Models.Selects.Select_Item_List is
Result : ASF.Models.Selects.Select_Item_List;
begin
for I in T'Range loop
declare
Value : constant String := T'Image (I);
Name : constant String := Prefix & "_" & Value;
Label : constant String := Bundle.Get (Name, Name);
begin
Result.Append (ASF.Models.Selects.Create_Select_Item (Label, Value));
end;
end loop;
return Result;
end Create_From_Enum;
-- ------------------------------
-- Append the selector list from the SQL query. The query will be executed.
-- It should return rows with at least two columns. The first column is the
-- selector value and the second column is the selector label.
-- ------------------------------
procedure Append_From_Query (Into : in out ASF.Models.Selects.Select_Item_List;
Query : in out ADO.Statements.Query_Statement'Class) is
begin
Query.Execute;
while Query.Has_Elements loop
declare
Id : constant String := Query.Get_String (1);
Label : constant String := Query.Get_String (2);
begin
Into.Append (ASF.Models.Selects.Create_Select_Item (Id, Label));
end;
Query.Next;
end loop;
end Append_From_Query;
-- ------------------------------
-- Create the selector list from the SQL query. The query will be executed.
-- It should return rows with at least two columns. The first column is the
-- selector value and the second column is the selector label.
-- ------------------------------
function Create_From_Query (Session : in ADO.Sessions.Session'Class;
Query : in ADO.Queries.Context'Class)
return ASF.Models.Selects.Select_Item_List is
Stmt : ADO.Statements.Query_Statement := Session.Create_Statement (Query);
Result : ASF.Models.Selects.Select_Item_List;
begin
Append_From_Query (Result, Stmt);
return Result;
end Create_From_Query;
-- ------------------------------
-- Get the value identified by the name.
-- If the name cannot be found, the method should return the Null object.
-- ------------------------------
function Get_Value (From : in Select_List_Bean;
Name : in String) return Util.Beans.Objects.Object is
begin
if Name = "list" then
return ASF.Models.Selects.To_Object (From.List);
else
return Util.Beans.Objects.Null_Object;
end if;
end Get_Value;
-- ------------------------------
-- 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 Select_List_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object) is
use type AWA.Services.Contexts.Service_Context_Access;
use type ADO.Queries.Query_Definition_Access;
begin
if Name = "query" then
declare
Query_Name : constant String := Util.Beans.Objects.To_String (Value);
Ctx : constant AWA.Services.Contexts.Service_Context_Access
:= AWA.Services.Contexts.Current;
Query_Def : constant ADO.Queries.Query_Definition_Access
:= ADO.Queries.Loaders.Find_Query (Query_Name);
Query : ADO.Queries.Context;
begin
if Ctx = null or Query_Def = null then
return;
end if;
Query.Set_Query (Query_Def);
From.List := Create_From_Query (Session => AWA.Services.Contexts.Get_Session (Ctx),
Query => Query);
end;
end if;
end Set_Value;
-- ------------------------------
-- Create the select list bean instance.
-- ------------------------------
function Create_Select_List_Bean return Util.Beans.Basic.Readonly_Bean_Access is
Result : constant Select_List_Bean_Access := new Select_List_Bean;
begin
return Result.all'Access;
end Create_Select_List_Bean;
end AWA.Helpers.Selectors;
|
-----------------------------------------------------------------------
-- awa-helpers -- Helpers for AWA applications
-- 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 ADO.Queries.Loaders;
with ADO.Schemas;
with Util.Strings;
with Util.Log.Loggers;
with AWA.Services.Contexts;
package body AWA.Helpers.Selectors is
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("AWA.Helpers.Selectors");
-- ------------------------------
-- Create a selector list from the definition of a discrete type such as an enum.
-- The select item has the enum value as value and the label is created by
-- localizing the string <b>Prefix</b>_<i>enum name</i>.
-- ------------------------------
function Create_From_Enum (Bundle : in Util.Properties.Bundles.Manager'Class)
return ASF.Models.Selects.Select_Item_List is
Result : ASF.Models.Selects.Select_Item_List;
begin
for I in T'Range loop
declare
Value : constant String := T'Image (I);
Name : constant String := Prefix & "_" & Value;
Label : constant String := Bundle.Get (Name, Name);
begin
Result.Append (ASF.Models.Selects.Create_Select_Item (Label, Value));
end;
end loop;
return Result;
end Create_From_Enum;
-- ------------------------------
-- Append the selector list from the SQL query. The query will be executed.
-- It should return rows with at least two columns. The first column is the
-- selector value and the second column is the selector label.
-- ------------------------------
procedure Append_From_Query (Into : in out ASF.Models.Selects.Select_Item_List;
Query : in out ADO.Statements.Query_Statement'Class) is
use ADO.Schemas;
Id_Type : ADO.Schemas.Column_Type := T_UNKNOWN;
Label_Type : ADO.Schemas.Column_Type := T_UNKNOWN;
function Get_Column (Id : in Natural;
Of_Type : in ADO.Schemas.Column_Type) return String is
begin
case Of_Type is
when T_CHAR | T_VARCHAR =>
return Query.Get_String (Id);
when T_INTEGER | T_TINYINT | T_SMALLINT | T_ENUM =>
return Util.Strings.Image (Query.Get_Integer (Id));
when T_LONG_INTEGER =>
return Util.Strings.Image (Long_Long_Integer (Query.Get_Int64 (Id)));
when others =>
return "";
end case;
end Get_Column;
begin
Query.Execute;
while Query.Has_Elements loop
if Id_Type = T_UNKNOWN then
Id_Type := Query.Get_Column_Type (0);
Label_Type := Query.Get_Column_Type (1);
end if;
declare
Id : constant String := Get_Column (0, Id_Type);
Label : constant String := Get_Column (1, Label_Type);
begin
Into.Append (ASF.Models.Selects.Create_Select_Item (Label => Label, Value => Id));
end;
Query.Next;
end loop;
end Append_From_Query;
-- ------------------------------
-- Create the selector list from the SQL query. The query will be executed.
-- It should return rows with at least two columns. The first column is the
-- selector value and the second column is the selector label.
-- ------------------------------
function Create_From_Query (Session : in ADO.Sessions.Session'Class;
Query : in ADO.Queries.Context'Class)
return ASF.Models.Selects.Select_Item_List is
Stmt : ADO.Statements.Query_Statement := Session.Create_Statement (Query);
Result : ASF.Models.Selects.Select_Item_List;
begin
Append_From_Query (Result, Stmt);
return Result;
end Create_From_Query;
-- ------------------------------
-- Get the value identified by the name.
-- If the name cannot be found, the method should return the Null object.
-- ------------------------------
function Get_Value (From : in Select_List_Bean;
Name : in String) return Util.Beans.Objects.Object is
begin
if Name = "list" then
return ASF.Models.Selects.To_Object (From.List);
else
return Util.Beans.Objects.Null_Object;
end if;
end Get_Value;
-- ------------------------------
-- 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 Select_List_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object) is
use type AWA.Services.Contexts.Service_Context_Access;
use type ADO.Queries.Query_Definition_Access;
begin
if Name = "query" then
declare
Query_Name : constant String := Util.Beans.Objects.To_String (Value);
Ctx : constant AWA.Services.Contexts.Service_Context_Access
:= AWA.Services.Contexts.Current;
Query_Def : constant ADO.Queries.Query_Definition_Access
:= ADO.Queries.Loaders.Find_Query (Query_Name);
Query : ADO.Queries.Context;
begin
if Ctx = null or Query_Def = null then
return;
end if;
Query.Set_Query (Query_Def);
From.List := Create_From_Query (Session => AWA.Services.Contexts.Get_Session (Ctx),
Query => Query);
end;
end if;
end Set_Value;
-- ------------------------------
-- Create the select list bean instance.
-- ------------------------------
function Create_Select_List_Bean return Util.Beans.Basic.Readonly_Bean_Access is
Result : constant Select_List_Bean_Access := new Select_List_Bean;
begin
return Result.all'Access;
end Create_Select_List_Bean;
end AWA.Helpers.Selectors;
|
Use the column type to decide which column fetch operation must be used
|
Use the column type to decide which column fetch operation must be used
|
Ada
|
apache-2.0
|
Letractively/ada-awa,Letractively/ada-awa,tectronics/ada-awa,Letractively/ada-awa,tectronics/ada-awa,tectronics/ada-awa
|
a11097649e6651cc33424ce3b95c77b307383b23
|
awa/src/awa-services-contexts.adb
|
awa/src/awa-services-contexts.adb
|
-----------------------------------------------------------------------
-- awa-services -- Services
-- 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.Task_Attributes;
with ADO.Databases;
package body AWA.Services.Contexts is
use type ADO.Databases.Connection_Status;
use type AWA.Users.Principals.Principal_Access;
package Task_Context is new Ada.Task_Attributes
(Service_Context_Access, null);
-- ------------------------------
-- Get the application associated with the current service operation.
-- ------------------------------
function Get_Application (Ctx : in Service_Context)
return AWA.Applications.Application_Access is
begin
return Ctx.Application;
end Get_Application;
-- ------------------------------
-- Get the current database connection for reading.
-- ------------------------------
function Get_Session (Ctx : in Service_Context_Access) return ADO.Sessions.Session is
begin
-- If a master database session was created, use it.
if Ctx.Master.Get_Status = ADO.Databases.OPEN then
return ADO.Sessions.Session (Ctx.Master);
elsif Ctx.Slave.Get_Status /= ADO.Databases.OPEN then
Ctx.Slave := Ctx.Application.Get_Session;
end if;
return Ctx.Slave;
end Get_Session;
-- ------------------------------
-- Get the current database connection for reading and writing.
-- ------------------------------
function Get_Master_Session (Ctx : in Service_Context_Access)
return ADO.Sessions.Master_Session is
begin
if Ctx.Master.Get_Status /= ADO.Databases.OPEN then
Ctx.Master := Ctx.Application.Get_Master_Session;
end if;
return Ctx.Master;
end Get_Master_Session;
-- ------------------------------
-- Get the current user invoking the service operation.
-- Returns a null user if there is none.
-- ------------------------------
function Get_User (Ctx : in Service_Context) return AWA.Users.Models.User_Ref is
begin
if Ctx.Principal = null then
return AWA.Users.Models.Null_User;
else
return Ctx.Principal.Get_User;
end if;
end Get_User;
-- ------------------------------
-- Get the current user identifier invoking the service operation.
-- Returns NO_IDENTIFIER if there is none.
-- ------------------------------
function Get_User_Identifier (Ctx : in Service_Context) return ADO.Identifier is
begin
if Ctx.Principal = null then
return ADO.NO_IDENTIFIER;
else
return Ctx.Principal.Get_User_Identifier;
end if;
end Get_User_Identifier;
-- ------------------------------
-- Get the current user session from the user invoking the service operation.
-- Returns a null session if there is none.
-- ------------------------------
function Get_User_Session (Ctx : in Service_Context) return AWA.Users.Models.Session_Ref is
begin
if Ctx.Principal = null then
return AWA.Users.Models.Null_Session;
else
return Ctx.Principal.Get_Session;
end if;
end Get_User_Session;
-- ------------------------------
-- Starts a transaction.
-- ------------------------------
procedure Start (Ctx : in out Service_Context) is
begin
if Ctx.Transaction = 0 and then not Ctx.Active_Transaction then
Ctx.Master.Begin_Transaction;
Ctx.Active_Transaction := True;
end if;
Ctx.Transaction := Ctx.Transaction + 1;
end Start;
-- ------------------------------
-- Commits the current transaction. The database transaction is really committed by the
-- last <b>Commit</b> called.
-- ------------------------------
procedure Commit (Ctx : in out Service_Context) is
begin
Ctx.Transaction := Ctx.Transaction - 1;
if Ctx.Transaction = 0 and then Ctx.Active_Transaction then
Ctx.Master.Commit;
Ctx.Active_Transaction := False;
end if;
end Commit;
-- ------------------------------
-- Rollback the current transaction. The database transaction is rollback at the first
-- call to <b>Rollback</b>.
-- ------------------------------
procedure Rollback (Ctx : in out Service_Context) is
begin
null;
end Rollback;
-- ------------------------------
-- Get the attribute registered under the given name in the HTTP session.
-- ------------------------------
function Get_Session_Attribute (Ctx : in Service_Context;
Name : in String) return Util.Beans.Objects.Object is
pragma Unreferenced (Ctx, Name);
begin
return Util.Beans.Objects.Null_Object;
end Get_Session_Attribute;
-- ------------------------------
-- Set the attribute registered under the given name in the HTTP session.
-- ------------------------------
procedure Set_Session_Attribute (Ctx : in out Service_Context;
Name : in String;
Value : in Util.Beans.Objects.Object) is
begin
null;
end Set_Session_Attribute;
-- ------------------------------
-- Set the current application and user context.
-- ------------------------------
procedure Set_Context (Ctx : in out Service_Context;
Application : in AWA.Applications.Application_Access;
Principal : in AWA.Users.Principals.Principal_Access) is
begin
Ctx.Application := Application;
Ctx.Principal := Principal;
end Set_Context;
-- ------------------------------
-- Initializes the service context.
-- ------------------------------
overriding
procedure Initialize (Ctx : in out Service_Context) is
use type AWA.Applications.Application_Access;
begin
Ctx.Previous := Task_Context.Value;
Task_Context.Set_Value (Ctx'Unchecked_Access);
if Ctx.Previous /= null and then Ctx.Application = null then
Ctx.Application := Ctx.Previous.Application;
end if;
end Initialize;
-- ------------------------------
-- Finalize the service context, rollback non-committed transaction, releases any object.
-- ------------------------------
overriding
procedure Finalize (Ctx : in out Service_Context) is
begin
-- When the service context is released, we must not have any active transaction.
-- This means we are leaving the service in an abnormal way such as when an
-- exception is raised. If this is the case, rollback the transaction.
if Ctx.Active_Transaction then
Ctx.Master.Rollback;
end if;
Task_Context.Set_Value (Ctx.Previous);
end Finalize;
-- ------------------------------
-- Get the current service context.
-- Returns null if the current thread is not associated with any service context.
-- ------------------------------
function Current return Service_Context_Access is
begin
return Task_Context.Value;
end Current;
end AWA.Services.Contexts;
|
-----------------------------------------------------------------------
-- awa-services -- Services
-- 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.Task_Attributes;
with ADO.Databases;
package body AWA.Services.Contexts is
use type ADO.Databases.Connection_Status;
use type AWA.Users.Principals.Principal_Access;
package Task_Context is new Ada.Task_Attributes
(Service_Context_Access, null);
-- ------------------------------
-- Get the application associated with the current service operation.
-- ------------------------------
function Get_Application (Ctx : in Service_Context)
return AWA.Applications.Application_Access is
begin
return Ctx.Application;
end Get_Application;
-- ------------------------------
-- Get the current database connection for reading.
-- ------------------------------
function Get_Session (Ctx : in Service_Context_Access) return ADO.Sessions.Session is
begin
-- If a master database session was created, use it.
if Ctx.Master.Get_Status = ADO.Databases.OPEN then
return ADO.Sessions.Session (Ctx.Master);
elsif Ctx.Slave.Get_Status /= ADO.Databases.OPEN then
Ctx.Slave := Ctx.Application.Get_Session;
end if;
return Ctx.Slave;
end Get_Session;
-- ------------------------------
-- Get the current database connection for reading and writing.
-- ------------------------------
function Get_Master_Session (Ctx : in Service_Context_Access)
return ADO.Sessions.Master_Session is
begin
if Ctx.Master.Get_Status /= ADO.Databases.OPEN then
Ctx.Master := Ctx.Application.Get_Master_Session;
end if;
return Ctx.Master;
end Get_Master_Session;
-- ------------------------------
-- Get the current user invoking the service operation.
-- Returns a null user if there is none.
-- ------------------------------
function Get_User (Ctx : in Service_Context) return AWA.Users.Models.User_Ref is
begin
if Ctx.Principal = null then
return AWA.Users.Models.Null_User;
else
return Ctx.Principal.Get_User;
end if;
end Get_User;
-- ------------------------------
-- Get the current user identifier invoking the service operation.
-- Returns NO_IDENTIFIER if there is none.
-- ------------------------------
function Get_User_Identifier (Ctx : in Service_Context) return ADO.Identifier is
begin
if Ctx.Principal = null then
return ADO.NO_IDENTIFIER;
else
return Ctx.Principal.Get_User_Identifier;
end if;
end Get_User_Identifier;
-- ------------------------------
-- Get the current user session from the user invoking the service operation.
-- Returns a null session if there is none.
-- ------------------------------
function Get_User_Session (Ctx : in Service_Context) return AWA.Users.Models.Session_Ref is
begin
if Ctx.Principal = null then
return AWA.Users.Models.Null_Session;
else
return Ctx.Principal.Get_Session;
end if;
end Get_User_Session;
-- ------------------------------
-- Starts a transaction.
-- ------------------------------
procedure Start (Ctx : in out Service_Context) is
begin
if Ctx.Transaction = 0 and then not Ctx.Active_Transaction then
Ctx.Master.Begin_Transaction;
Ctx.Active_Transaction := True;
end if;
Ctx.Transaction := Ctx.Transaction + 1;
end Start;
-- ------------------------------
-- Commits the current transaction. The database transaction is really committed by the
-- last <b>Commit</b> called.
-- ------------------------------
procedure Commit (Ctx : in out Service_Context) is
begin
Ctx.Transaction := Ctx.Transaction - 1;
if Ctx.Transaction = 0 and then Ctx.Active_Transaction then
Ctx.Master.Commit;
Ctx.Active_Transaction := False;
end if;
end Commit;
-- ------------------------------
-- Rollback the current transaction. The database transaction is rollback at the first
-- call to <b>Rollback</b>.
-- ------------------------------
procedure Rollback (Ctx : in out Service_Context) is
begin
null;
end Rollback;
-- ------------------------------
-- Get the attribute registered under the given name in the HTTP session.
-- ------------------------------
function Get_Session_Attribute (Ctx : in Service_Context;
Name : in String) return Util.Beans.Objects.Object is
pragma Unreferenced (Ctx, Name);
begin
return Util.Beans.Objects.Null_Object;
end Get_Session_Attribute;
-- ------------------------------
-- Set the attribute registered under the given name in the HTTP session.
-- ------------------------------
procedure Set_Session_Attribute (Ctx : in out Service_Context;
Name : in String;
Value : in Util.Beans.Objects.Object) is
begin
null;
end Set_Session_Attribute;
-- ------------------------------
-- Set the current application and user context.
-- ------------------------------
procedure Set_Context (Ctx : in out Service_Context;
Application : in AWA.Applications.Application_Access;
Principal : in AWA.Users.Principals.Principal_Access) is
begin
Ctx.Application := Application;
Ctx.Principal := Principal;
end Set_Context;
-- ------------------------------
-- Initializes the service context.
-- ------------------------------
overriding
procedure Initialize (Ctx : in out Service_Context) is
use type AWA.Applications.Application_Access;
begin
Ctx.Previous := Task_Context.Value;
Task_Context.Set_Value (Ctx'Unchecked_Access);
if Ctx.Previous /= null and then Ctx.Application = null then
Ctx.Application := Ctx.Previous.Application;
end if;
end Initialize;
-- ------------------------------
-- Finalize the service context, rollback non-committed transaction, releases any object.
-- ------------------------------
overriding
procedure Finalize (Ctx : in out Service_Context) is
begin
-- When the service context is released, we must not have any active transaction.
-- This means we are leaving the service in an abnormal way such as when an
-- exception is raised. If this is the case, rollback the transaction.
if Ctx.Active_Transaction then
Ctx.Master.Rollback;
end if;
Task_Context.Set_Value (Ctx.Previous);
end Finalize;
-- ------------------------------
-- Get the current service context.
-- Returns null if the current thread is not associated with any service context.
-- ------------------------------
function Current return Service_Context_Access is
begin
return Task_Context.Value;
end Current;
-- ------------------------------
-- Run the process procedure on behalf of the specific user and session.
-- This operation changes temporarily the identity of the current user principal and
-- executes the <tt>Process</tt> procedure.
-- ------------------------------
procedure Run_As (User : in AWA.Users.Models.User_Ref;
Session : in AWA.Users.Models.Session_Ref) is
Ctx : Service_Context;
Principal : aliased AWA.Users.Principals.Principal
:= AWA.Users.Principals.Create (User, Session);
begin
Ctx.Principal := Principal'Unchecked_Access;
Process;
end Run_As;
end AWA.Services.Contexts;
|
Implement the Run_As by creating a local service context with a user principal and calling the process procedure. When we return (normal return or from an exception), the previous service context is restored
|
Implement the Run_As by creating a local service context with a user
principal and calling the process procedure. When we return (normal
return or from an exception), the previous service context is restored
|
Ada
|
apache-2.0
|
Letractively/ada-awa,tectronics/ada-awa,tectronics/ada-awa,Letractively/ada-awa,Letractively/ada-awa,tectronics/ada-awa
|
093ae9bd6e30f5dc373597e8b6630f0973c7ba6d
|
src/wiki-parsers-html.adb
|
src/wiki-parsers-html.adb
|
-----------------------------------------------------------------------
-- wiki-parsers-html -- Wiki HTML parser
-- Copyright (C) 2015, 2016 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Wiki.Helpers;
with Wiki.Parsers.Html.Entities;
package body Wiki.Parsers.Html is
-- Parse an HTML attribute
procedure Parse_Attribute_Name (P : in out Parser;
Name : in out Wiki.Strings.BString);
-- Parse a HTML/XML comment to strip it.
procedure Parse_Comment (P : in out Parser);
-- Parse a simple DOCTYPE declaration and ignore it.
procedure Parse_Doctype (P : in out Parser);
procedure Collect_Attributes (P : in out Parser);
function Is_Letter (C : in Wiki.Strings.WChar) return Boolean;
procedure Collect_Attribute_Value (P : in out Parser;
Value : in out Wiki.Strings.BString);
function Is_Letter (C : in Wiki.Strings.WChar) return Boolean is
begin
return C > ' ' and C /= ':' and C /= '>' and C /= ''' and C /= '"'
and C /= '/' and C /= '=' and C /= '<';
end Is_Letter;
-- ------------------------------
-- Parse an HTML attribute
-- ------------------------------
procedure Parse_Attribute_Name (P : in out Parser;
Name : in out Wiki.Strings.BString) is
C : Wiki.Strings.WChar;
begin
Skip_Spaces (P);
while not P.Is_Eof loop
Peek (P, C);
if not Is_Letter (C) then
Put_Back (P, C);
return;
end if;
Wiki.Strings.Wide_Wide_Builders.Append (Name, C);
end loop;
end Parse_Attribute_Name;
procedure Collect_Attribute_Value (P : in out Parser;
Value : in out Wiki.Strings.BString) is
C : Wiki.Strings.WChar;
Token : Wiki.Strings.WChar;
begin
-- Value := Wiki.Strings.To_UString ("");
Peek (P, Token);
if Wiki.Helpers.Is_Space (Token) then
return;
elsif Token = '>' then
Put_Back (P, Token);
return;
elsif Token /= ''' and Token /= '"' then
Wiki.Strings.Wide_Wide_Builders.Append (Value, Token);
while not P.Is_Eof loop
Peek (P, C);
if C = ''' or C = '"' or C = ' ' or C = '=' or C = '>' or C = '<' or C = '`' then
Put_Back (P, C);
return;
end if;
Wiki.Strings.Wide_Wide_Builders.Append (Value, C);
end loop;
else
while not P.Is_Eof loop
Peek (P, C);
if C = Token then
return;
end if;
Wiki.Strings.Wide_Wide_Builders.Append (Value, C);
end loop;
end if;
end Collect_Attribute_Value;
-- ------------------------------
-- Parse a list of HTML attributes up to the first '>'.
-- attr-name
-- attr-name=
-- attr-name=value
-- attr-name='value'
-- attr-name="value"
-- <name name='value' ...>
-- ------------------------------
procedure Collect_Attributes (P : in out Parser) is
procedure Append_Attribute (Name : in Wiki.Strings.WString);
C : Wiki.Strings.WChar;
Name : Wiki.Strings.BString (64);
Value : Wiki.Strings.BString (256);
procedure Append_Attribute (Name : in Wiki.Strings.WString) is
procedure Attribute_Value (Value : in Wiki.Strings.WString);
procedure Attribute_Value (Value : in Wiki.Strings.WString) is
begin
Attributes.Append (P.Attributes, Name, Value);
end Attribute_Value;
procedure Attribute_Value is
new Wiki.Strings.Wide_Wide_Builders.Get (Attribute_Value);
pragma Inline (Attribute_Value);
begin
Attribute_Value (Value);
end Append_Attribute;
pragma Inline (Append_Attribute);
procedure Append_Attribute is
new Wiki.Strings.Wide_Wide_Builders.Get (Append_Attribute);
begin
Wiki.Attributes.Clear (P.Attributes);
while not P.Is_Eof loop
Parse_Attribute_Name (P, Name);
Skip_Spaces (P);
Peek (P, C);
if C = '>' or C = '<' or C = '/' then
Put_Back (P, C);
exit;
end if;
if C = '=' then
Collect_Attribute_Value (P, Value);
Append_Attribute (Name);
Wiki.Strings.Wide_Wide_Builders.Clear (Name);
Wiki.Strings.Wide_Wide_Builders.Clear (Value);
elsif Wiki.Strings.Wide_Wide_Builders.Length (Name) > 0 then
Put_Back (P, C);
Append_Attribute (Name);
Wiki.Strings.Wide_Wide_Builders.Clear (Name);
end if;
end loop;
-- Add any pending attribute.
if Wiki.Strings.Wide_Wide_Builders.Length (Name) > 0 then
Append_Attribute (Name);
end if;
end Collect_Attributes;
-- ------------------------------
-- Parse a HTML/XML comment to strip it.
-- ------------------------------
procedure Parse_Comment (P : in out Parser) is
C : Wiki.Strings.WChar;
begin
Peek (P, C);
while not P.Is_Eof loop
Peek (P, C);
if C = '-' then
declare
Count : Natural := 1;
begin
Peek (P, C);
while not P.Is_Eof and C = '-' loop
Peek (P, C);
Count := Count + 1;
end loop;
exit when C = '>' and Count >= 2;
end;
end if;
end loop;
end Parse_Comment;
-- ------------------------------
-- Parse a simple DOCTYPE declaration and ignore it.
-- ------------------------------
procedure Parse_Doctype (P : in out Parser) is
C : Wiki.Strings.WChar;
begin
while not P.Is_Eof loop
Peek (P, C);
exit when C = '>';
end loop;
end Parse_Doctype;
-- ------------------------------
-- Parse a HTML element <XXX attributes>
-- or parse an end of HTML element </XXX>
-- ------------------------------
procedure Parse_Element (P : in out Parser) is
C : Wiki.Strings.WChar;
procedure Add_Element (Token : in Wiki.Strings.WString);
procedure Add_Element (Token : in Wiki.Strings.WString) is
Tag : Wiki.Html_Tag;
begin
Tag := Wiki.Find_Tag (Token);
if C = '/' then
Skip_Spaces (P);
Peek (P, C);
if C /= '>' then
Put_Back (P, C);
end if;
Flush_Text (P);
if Tag = Wiki.UNKNOWN_TAG then
if Token = "noinclude" then
P.Context.Is_Hidden := False;
end if;
else
End_Element (P, Tag);
end if;
else
Collect_Attributes (P);
Peek (P, C);
if C = '/' then
Peek (P, C);
if C = '>' then
Start_Element (P, Tag, P.Attributes);
End_Element (P, Tag);
return;
end if;
elsif C /= '>' then
Put_Back (P, C);
end if;
if Tag = UNKNOWN_TAG then
if Token = "noinclude" then
P.Context.Is_Hidden := True;
end if;
else
Start_Element (P, Tag, P.Attributes);
end if;
end if;
end Add_Element;
pragma Inline (Add_Element);
procedure Add_Element is
new Wiki.Strings.Wide_Wide_Builders.Get (Add_Element);
pragma Inline (Add_Element);
Name : Wiki.Strings.BString (64);
begin
Peek (P, C);
if C = '!' then
Peek (P, C);
if C = '-' then
Parse_Comment (P);
else
Parse_Doctype (P);
end if;
return;
end if;
if C /= '/' then
Put_Back (P, C);
end if;
Parse_Attribute_Name (P, Name);
Add_Element (Name);
end Parse_Element;
-- ------------------------------
-- Parse an HTML entity such as and replace it with the corresponding code.
-- ------------------------------
procedure Parse_Entity (P : in out Parser;
Token : in Wiki.Strings.WChar) is
pragma Unreferenced (Token);
Name : String (1 .. 10);
Len : Natural := 0;
High : Natural := Wiki.Parsers.Html.Entities.Keywords'Last;
Low : Natural := Wiki.Parsers.Html.Entities.Keywords'First;
Pos : Natural;
C : Wiki.Strings.WChar;
begin
while Len < Name'Last loop
Peek (P, C);
exit when C = ';' or else P.Is_Eof;
Len := Len + 1;
Name (Len) := Wiki.Strings.To_Char (C);
end loop;
while Low <= High loop
Pos := (Low + High) / 2;
if Wiki.Parsers.Html.Entities.Keywords (Pos).all = Name (1 .. Len) then
Parse_Text (P, Entities.Mapping (Pos));
return;
elsif Entities.Keywords (Pos).all < Name (1 .. Len) then
Low := Pos + 1;
else
High := Pos - 1;
end if;
end loop;
-- The HTML entity is not recognized: we must treat it as plain wiki text.
Parse_Text (P, '&');
for I in 1 .. Len loop
Parse_Text (P, Wiki.Strings.To_WChar (Name (I)));
end loop;
end Parse_Entity;
end Wiki.Parsers.Html;
|
-----------------------------------------------------------------------
-- wiki-parsers-html -- Wiki HTML parser
-- Copyright (C) 2015, 2016, 2018 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Wiki.Helpers;
with Wiki.Parsers.Html.Entities;
package body Wiki.Parsers.Html is
-- Parse an HTML attribute
procedure Parse_Attribute_Name (P : in out Parser;
Name : in out Wiki.Strings.BString);
-- Parse a HTML/XML comment to strip it.
procedure Parse_Comment (P : in out Parser);
-- Parse a simple DOCTYPE declaration and ignore it.
procedure Parse_Doctype (P : in out Parser);
procedure Collect_Attributes (P : in out Parser);
function Is_Letter (C : in Wiki.Strings.WChar) return Boolean;
procedure Collect_Attribute_Value (P : in out Parser;
Value : in out Wiki.Strings.BString);
function Is_Letter (C : in Wiki.Strings.WChar) return Boolean is
begin
return C > ' ' and C /= ':' and C /= '>' and C /= ''' and C /= '"'
and C /= '/' and C /= '=' and C /= '<';
end Is_Letter;
-- ------------------------------
-- Parse an HTML attribute
-- ------------------------------
procedure Parse_Attribute_Name (P : in out Parser;
Name : in out Wiki.Strings.BString) is
C : Wiki.Strings.WChar;
begin
Skip_Spaces (P);
while not P.Is_Eof loop
Peek (P, C);
if not Is_Letter (C) then
Put_Back (P, C);
return;
end if;
Wiki.Strings.Wide_Wide_Builders.Append (Name, C);
end loop;
end Parse_Attribute_Name;
procedure Collect_Attribute_Value (P : in out Parser;
Value : in out Wiki.Strings.BString) is
C : Wiki.Strings.WChar;
Token : Wiki.Strings.WChar;
begin
-- Value := Wiki.Strings.To_UString ("");
Peek (P, Token);
if Wiki.Helpers.Is_Space (Token) then
return;
elsif Token = '>' then
Put_Back (P, Token);
return;
elsif Token /= ''' and Token /= '"' then
Wiki.Strings.Wide_Wide_Builders.Append (Value, Token);
while not P.Is_Eof loop
Peek (P, C);
if C = ''' or C = '"' or C = ' ' or C = '=' or C = '>' or C = '<' or C = '`' then
Put_Back (P, C);
return;
end if;
Wiki.Strings.Wide_Wide_Builders.Append (Value, C);
end loop;
else
while not P.Is_Eof loop
Peek (P, C);
if C = Token then
return;
end if;
Wiki.Strings.Wide_Wide_Builders.Append (Value, C);
end loop;
end if;
end Collect_Attribute_Value;
-- ------------------------------
-- Parse a list of HTML attributes up to the first '>'.
-- attr-name
-- attr-name=
-- attr-name=value
-- attr-name='value'
-- attr-name="value"
-- <name name='value' ...>
-- ------------------------------
procedure Collect_Attributes (P : in out Parser) is
procedure Append_Attribute (Name : in Wiki.Strings.WString);
C : Wiki.Strings.WChar;
Name : Wiki.Strings.BString (64);
Value : Wiki.Strings.BString (256);
procedure Append_Attribute (Name : in Wiki.Strings.WString) is
procedure Attribute_Value (Value : in Wiki.Strings.WString);
procedure Attribute_Value (Value : in Wiki.Strings.WString) is
begin
Attributes.Append (P.Attributes, Name, Value);
end Attribute_Value;
procedure Attribute_Value is
new Wiki.Strings.Wide_Wide_Builders.Get (Attribute_Value);
pragma Inline (Attribute_Value);
begin
Attribute_Value (Value);
end Append_Attribute;
pragma Inline (Append_Attribute);
procedure Append_Attribute is
new Wiki.Strings.Wide_Wide_Builders.Get (Append_Attribute);
begin
Wiki.Attributes.Clear (P.Attributes);
while not P.Is_Eof loop
Parse_Attribute_Name (P, Name);
Skip_Spaces (P);
Peek (P, C);
if C = '>' or C = '<' or C = '/' then
Put_Back (P, C);
exit;
end if;
if C = '=' then
Collect_Attribute_Value (P, Value);
Append_Attribute (Name);
Wiki.Strings.Wide_Wide_Builders.Clear (Name);
Wiki.Strings.Wide_Wide_Builders.Clear (Value);
elsif Wiki.Strings.Wide_Wide_Builders.Length (Name) > 0 then
Put_Back (P, C);
Append_Attribute (Name);
Wiki.Strings.Wide_Wide_Builders.Clear (Name);
end if;
end loop;
-- Add any pending attribute.
if Wiki.Strings.Wide_Wide_Builders.Length (Name) > 0 then
Append_Attribute (Name);
end if;
end Collect_Attributes;
-- ------------------------------
-- Parse a HTML/XML comment to strip it.
-- ------------------------------
procedure Parse_Comment (P : in out Parser) is
C : Wiki.Strings.WChar;
begin
Peek (P, C);
while not P.Is_Eof loop
Peek (P, C);
if C = '-' then
declare
Count : Natural := 1;
begin
Peek (P, C);
while not P.Is_Eof and C = '-' loop
Peek (P, C);
Count := Count + 1;
end loop;
exit when C = '>' and Count >= 2;
end;
end if;
end loop;
end Parse_Comment;
-- ------------------------------
-- Parse a simple DOCTYPE declaration and ignore it.
-- ------------------------------
procedure Parse_Doctype (P : in out Parser) is
C : Wiki.Strings.WChar;
begin
while not P.Is_Eof loop
Peek (P, C);
exit when C = '>';
end loop;
end Parse_Doctype;
-- ------------------------------
-- Parse a HTML element <XXX attributes>
-- or parse an end of HTML element </XXX>
-- ------------------------------
procedure Parse_Element (P : in out Parser) is
C : Wiki.Strings.WChar;
procedure Add_Element (Token : in Wiki.Strings.WString);
procedure Add_Element (Token : in Wiki.Strings.WString) is
Tag : Wiki.Html_Tag;
begin
Tag := Wiki.Find_Tag (Token);
if C = '/' then
Skip_Spaces (P);
Peek (P, C);
if C /= '>' then
Put_Back (P, C);
end if;
Flush_Text (P);
if Tag = Wiki.UNKNOWN_TAG then
if Token = "noinclude" then
P.Context.Is_Hidden := not P.Context.Is_Included;
elsif Token = "includeonly" then
P.Context.Is_Hidden := P.Context.Is_Included;
end if;
else
End_Element (P, Tag);
end if;
else
Collect_Attributes (P);
Peek (P, C);
if C = '/' then
Peek (P, C);
if C = '>' then
Start_Element (P, Tag, P.Attributes);
End_Element (P, Tag);
return;
end if;
elsif C /= '>' then
Put_Back (P, C);
end if;
if Tag = UNKNOWN_TAG then
if Token = "noinclude" then
P.Context.Is_Hidden := P.Context.Is_Included;
elsif Token = "includeonly" then
P.Context.Is_Hidden := not P.Context.Is_Included;
end if;
else
Start_Element (P, Tag, P.Attributes);
end if;
end if;
end Add_Element;
pragma Inline (Add_Element);
procedure Add_Element is
new Wiki.Strings.Wide_Wide_Builders.Get (Add_Element);
pragma Inline (Add_Element);
Name : Wiki.Strings.BString (64);
begin
Peek (P, C);
if C = '!' then
Peek (P, C);
if C = '-' then
Parse_Comment (P);
else
Parse_Doctype (P);
end if;
return;
end if;
if C /= '/' then
Put_Back (P, C);
end if;
Parse_Attribute_Name (P, Name);
Add_Element (Name);
end Parse_Element;
-- ------------------------------
-- Parse an HTML entity such as and replace it with the corresponding code.
-- ------------------------------
procedure Parse_Entity (P : in out Parser;
Token : in Wiki.Strings.WChar) is
pragma Unreferenced (Token);
Name : String (1 .. 10);
Len : Natural := 0;
High : Natural := Wiki.Parsers.Html.Entities.Keywords'Last;
Low : Natural := Wiki.Parsers.Html.Entities.Keywords'First;
Pos : Natural;
C : Wiki.Strings.WChar;
begin
while Len < Name'Last loop
Peek (P, C);
exit when C = ';' or else P.Is_Eof;
Len := Len + 1;
Name (Len) := Wiki.Strings.To_Char (C);
end loop;
while Low <= High loop
Pos := (Low + High) / 2;
if Wiki.Parsers.Html.Entities.Keywords (Pos).all = Name (1 .. Len) then
Parse_Text (P, Entities.Mapping (Pos));
return;
elsif Entities.Keywords (Pos).all < Name (1 .. Len) then
Low := Pos + 1;
else
High := Pos - 1;
end if;
end loop;
-- The HTML entity is not recognized: we must treat it as plain wiki text.
Parse_Text (P, '&');
for I in 1 .. Len loop
Parse_Text (P, Wiki.Strings.To_WChar (Name (I)));
end loop;
end Parse_Entity;
end Wiki.Parsers.Html;
|
Fix the <noinclude> to take into account the template rendering as a non-inclusion file Add support for <includeonly> in templates
|
Fix the <noinclude> to take into account the template rendering as a non-inclusion file
Add support for <includeonly> in templates
|
Ada
|
apache-2.0
|
stcarrez/ada-wiki,stcarrez/ada-wiki
|
bb2376a77f3a58f047bee0041b6d5d7aa976aafa
|
regtests/util-encoders-tests.adb
|
regtests/util-encoders-tests.adb
|
-----------------------------------------------------------------------
-- util-encodes-tests - Test for encoding
-- 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.Test_Caller;
with Util.Tests;
with Util.Measures;
with Util.Strings.Transforms;
with Ada.Text_IO;
with Util.Encoders.SHA1;
with Util.Encoders.HMAC.SHA1;
-- with Util.Log.Loggers;
package body Util.Encoders.Tests is
use Util.Tests;
-- use Util.Log;
--
-- Log : constant Loggers.Logger := Loggers.Create ("Util.Encoders.Tests");
package Caller is new Util.Test_Caller (Test);
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test Util.Encoders.Base16.Encode",
Test_Hex'Access);
Caller.Add_Test (Suite, "Test Util.Encoders.Base16.Decode",
Test_Hex'Access);
Caller.Add_Test (Suite, "Test Util.Encoders.Base64.Encode",
Test_Base64_Encode'Access);
Caller.Add_Test (Suite, "Test Util.Encoders.Base64.Decode",
Test_Base64_Decode'Access);
Caller.Add_Test (Suite, "Test Util.Encoders.Base64.Benchmark",
Test_Base64_Benchmark'Access);
Caller.Add_Test (Suite, "Test Util.Encoders.SHA1.Encode",
Test_SHA1_Encode'Access);
Caller.Add_Test (Suite, "Test Util.Encoders.SHA1.Benchmark",
Test_SHA1_Benchmark'Access);
Caller.Add_Test (Suite, "Test Util.Encoders.HMAC.SHA1.Sign_SHA1 (RFC2202 test1)",
Test_HMAC_SHA1_RFC2202_T1'Access);
Caller.Add_Test (Suite, "Test Util.Encoders.HMAC.SHA1.Sign_SHA1 (RFC2202 test2)",
Test_HMAC_SHA1_RFC2202_T2'Access);
Caller.Add_Test (Suite, "Test Util.Encoders.HMAC.SHA1.Sign_SHA1 (RFC2202 test3)",
Test_HMAC_SHA1_RFC2202_T3'Access);
Caller.Add_Test (Suite, "Test Util.Encoders.HMAC.SHA1.Sign_SHA1 (RFC2202 test4)",
Test_HMAC_SHA1_RFC2202_T4'Access);
Caller.Add_Test (Suite, "Test Util.Encoders.HMAC.SHA1.Sign_SHA1 (RFC2202 test5)",
Test_HMAC_SHA1_RFC2202_T5'Access);
Caller.Add_Test (Suite, "Test Util.Encoders.HMAC.SHA1.Sign_SHA1 (RFC2202 test6)",
Test_HMAC_SHA1_RFC2202_T6'Access);
Caller.Add_Test (Suite, "Test Util.Encoders.HMAC.SHA1.Sign_SHA1 (RFC2202 test7)",
Test_HMAC_SHA1_RFC2202_T7'Access);
end Add_Tests;
procedure Test_Base64_Encode (T : in out Test) is
C : constant Util.Encoders.Encoder := Create ("base64");
begin
Assert_Equals (T, "YQ==", Util.Encoders.Encode (C, "a"));
Assert_Equals (T, "fA==", Util.Encoders.Encode (C, "|"));
Assert_Equals (T, "fHw=", Util.Encoders.Encode (C, "||"));
Assert_Equals (T, "fH5+", Util.Encoders.Encode (C, "|~~"));
end Test_Base64_Encode;
procedure Test_Base64_Decode (T : in out Test) is
C : Util.Encoders.Encoder := Create ("base64");
begin
Assert_Equals (T, "a", Util.Encoders.Decode (C, "YQ=="));
Assert_Equals (T, "|", Util.Encoders.Decode (C, "fA=="));
Assert_Equals (T, "||", Util.Encoders.Decode (C, "fHw="));
Assert_Equals (T, "|~~", Util.Encoders.Decode (C, "fH5+"));
Test_Encoder (T, C);
end Test_Base64_Decode;
procedure Test_Encoder (T : in out Test;
C : in out Util.Encoders.Encoder) is
begin
for I in 1 .. 334 loop
declare
Pattern : String (1 .. I);
begin
for J in Pattern'Range loop
Pattern (J) := Character'Val (((J + I) mod 63) + 32);
end loop;
declare
E : constant String := Util.Encoders.Encode (C, Pattern);
D : constant String := Util.Encoders.Decode (C, E);
begin
Assert_Equals (T, Pattern, D, "Encoding failed for length "
& Integer'Image (I));
end;
exception
when others =>
Ada.Text_IO.Put_Line ("Error at index " & Integer'Image (I));
raise;
end;
end loop;
end Test_Encoder;
procedure Test_Hex (T : in out Test) is
C : Util.Encoders.Encoder := Create ("hex");
begin
Assert_Equals (T, "41424344", Util.Encoders.Encode(C, "ABCD"));
Assert_Equals (T, "ABCD", Util.Encoders.Decode (C, "41424344"));
Test_Encoder (T, C);
end Test_Hex;
procedure Test_Base64_Benchmark (T : in out Test) is
pragma Unreferenced (T);
C : constant Util.Encoders.Encoder := Create ("base64");
S : constant String (1 .. 1_024) := (others => 'a');
begin
declare
T : Util.Measures.Stamp;
R : constant String := Util.Encoders.Encode (C, S);
pragma Unreferenced (R);
begin
Util.Measures.Report (T, "Base64 encode 1024 bytes");
end;
end Test_Base64_Benchmark;
procedure Test_SHA1_Encode (T : in out Test) is
C : Util.Encoders.SHA1.Context;
Hash : Util.Encoders.SHA1.Digest;
procedure Check_Hash (Value : in String;
Expect : in String) is
J, N : Natural;
Ctx : Util.Encoders.SHA1.Context;
begin
for I in 1 .. Value'Length loop
J := Value'First;
while J <= Value'Last loop
if J + I <= Value'Last then
N := J + I;
else
N := Value'Last;
end if;
Util.Encoders.SHA1.Update (Ctx, Value (J .. N));
J := N + 1;
end loop;
Util.Encoders.SHA1.Finish (Ctx, Hash);
Assert_Equals (T, Expect, Hash, "Invalid hash for: " & Value);
end loop;
end Check_Hash;
begin
Util.Encoders.SHA1.Update (C, "a");
Util.Encoders.SHA1.Finish (C, Hash);
Assert_Equals (T, "86F7E437FAA5A7FCE15D1DDCB9EAEAEA377667B8", Hash,
"Invalid hash for 'a'");
Check_Hash ("ut", "E746699D3947443D84DAD1E0C58BF7AD34712438");
Check_Hash ("Uti", "2C669751BDC4929377245F5EEBEAED1CE4DA8A45");
Check_Hash ("Util", "4C31156EFED35EE7814650F8971C3698059440E3");
Check_Hash ("Util.Encoders", "7DB6007AD8BAEA7C167FF2AE06C9F50A4645F971");
Check_Hash ("e746699d3947443d84dad1e0c58bf7ad347124382C669751BDC492937"
& "7245F5EEBEAED1CE4DA8A45",
"875C9C0DE4CE91ED8F432DD02B5BB40CD35DAACD");
end Test_SHA1_Encode;
-- ------------------------------
-- Benchmark test for SHA1
-- ------------------------------
procedure Test_SHA1_Benchmark (T : in out Test) is
pragma Unreferenced (T);
Hash : Util.Encoders.SHA1.Digest;
Sizes : constant array (1 .. 6) of Positive := (1, 10, 100, 1000, 10000, 100000);
begin
for I in Sizes'Range loop
declare
Size : constant Positive := Sizes (I);
S : constant String (1 .. Size) := (others => '0');
T1 : Util.Measures.Stamp;
C : Util.Encoders.SHA1.Context;
begin
Util.Encoders.SHA1.Update (C, S);
Util.Encoders.SHA1.Finish (C, Hash);
Util.Measures.Report (T1, "Encode SHA1" & Integer'Image (Size) & " bytes");
end;
end loop;
end Test_SHA1_Benchmark;
procedure Check_HMAC (T : in out Test'Class;
Key : in String;
Value : in String;
Expect : in String) is
H : constant String := Util.Encoders.HMAC.SHA1.Sign (Key, Value);
begin
Assert_Equals (T, Expect, Util.Strings.Transforms.To_Lower_Case (H),
"Invalid HMAC-SHA1");
end Check_HMAC;
-- ------------------------------
-- Test HMAC-SHA1
-- ------------------------------
procedure Test_HMAC_SHA1_RFC2202_T1 (T : in out Test) is
Key : constant String (1 .. 20) := (others => Character'Val (16#0b#));
begin
Check_HMAC (T, Key, "Hi There", "b617318655057264e28bc0b6fb378c8ef146be00");
end Test_HMAC_SHA1_RFC2202_T1;
procedure Test_HMAC_SHA1_RFC2202_T2 (T : in out Test) is
begin
Check_HMAC (T, "Jefe", "what do ya want for nothing?",
"effcdf6ae5eb2fa2d27416d5f184df9c259a7c79");
end Test_HMAC_SHA1_RFC2202_T2;
procedure Test_HMAC_SHA1_RFC2202_T3 (T : in out Test) is
Key : constant String (1 .. 20) := (others => Character'Val (16#aa#));
Data : constant String (1 .. 50) := (others => Character'Val (16#dd#));
begin
Check_HMAC (T, Key, Data,
"125d7342b9ac11cd91a39af48aa17b4f63f175d3");
end Test_HMAC_SHA1_RFC2202_T3;
procedure Test_HMAC_SHA1_RFC2202_T4 (T : in out Test) is
C : constant Util.Encoders.Encoder := Create ("hex");
Key : constant String := Util.Encoders.Decode (C, "0102030405060708090a0b0c0d0e0f10111213141516171819");
Data : constant String (1 .. 50) := (others => Character'Val (16#cd#));
begin
Check_HMAC (T, Key, Data,
"4c9007f4026250c6bc8414f9bf50c86c2d7235da");
end Test_HMAC_SHA1_RFC2202_T4;
procedure Test_HMAC_SHA1_RFC2202_T5 (T : in out Test) is
Key : constant String (1 .. 20) := (others => Character'Val (16#0c#));
begin
-- RFC2202 test case 5 but without truncation...
Check_HMAC (T, Key, "Test With Truncation",
"4c1a03424b55e07fe7f27be1d58bb9324a9a5a04");
end Test_HMAC_SHA1_RFC2202_T5;
procedure Test_HMAC_SHA1_RFC2202_T6 (T : in out Test) is
Key : constant String (1 .. 80) := (others => Character'Val (16#aa#));
begin
Check_HMAC (T, Key, "Test Using Larger Than Block-Size Key - Hash Key First",
"aa4ae5e15272d00e95705637ce8a3b55ed402112");
end Test_HMAC_SHA1_RFC2202_T6;
procedure Test_HMAC_SHA1_RFC2202_T7 (T : in out Test) is
Key : constant String (1 .. 80) := (others => Character'Val (16#Aa#));
begin
Check_HMAC (T, Key, "Test Using Larger Than Block-Size Key and Larger "
& "Than One Block-Size Data",
"e8e99d0f45237d786d6bbaa7965c7808bbff1a91");
end Test_HMAC_SHA1_RFC2202_T7;
end Util.Encoders.Tests;
|
-----------------------------------------------------------------------
-- util-encodes-tests - Test for encoding
-- 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 Util.Strings.Transforms;
with Ada.Text_IO;
with Util.Encoders.SHA1;
with Util.Encoders.HMAC.SHA1;
package body Util.Encoders.Tests is
use Util.Tests;
-- use Util.Log;
--
-- Log : constant Loggers.Logger := Loggers.Create ("Util.Encoders.Tests");
procedure Check_HMAC (T : in out Test'Class;
Key : in String;
Value : in String;
Expect : in String);
package Caller is new Util.Test_Caller (Test, "Encoders");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test Util.Encoders.Base16.Encode",
Test_Hex'Access);
Caller.Add_Test (Suite, "Test Util.Encoders.Base16.Decode",
Test_Hex'Access);
Caller.Add_Test (Suite, "Test Util.Encoders.Base64.Encode",
Test_Base64_Encode'Access);
Caller.Add_Test (Suite, "Test Util.Encoders.Base64.Decode",
Test_Base64_Decode'Access);
Caller.Add_Test (Suite, "Test Util.Encoders.Base64.Benchmark",
Test_Base64_Benchmark'Access);
Caller.Add_Test (Suite, "Test Util.Encoders.SHA1.Encode",
Test_SHA1_Encode'Access);
Caller.Add_Test (Suite, "Test Util.Encoders.SHA1.Benchmark",
Test_SHA1_Benchmark'Access);
Caller.Add_Test (Suite, "Test Util.Encoders.HMAC.SHA1.Sign_SHA1 (RFC2202 test1)",
Test_HMAC_SHA1_RFC2202_T1'Access);
Caller.Add_Test (Suite, "Test Util.Encoders.HMAC.SHA1.Sign_SHA1 (RFC2202 test2)",
Test_HMAC_SHA1_RFC2202_T2'Access);
Caller.Add_Test (Suite, "Test Util.Encoders.HMAC.SHA1.Sign_SHA1 (RFC2202 test3)",
Test_HMAC_SHA1_RFC2202_T3'Access);
Caller.Add_Test (Suite, "Test Util.Encoders.HMAC.SHA1.Sign_SHA1 (RFC2202 test4)",
Test_HMAC_SHA1_RFC2202_T4'Access);
Caller.Add_Test (Suite, "Test Util.Encoders.HMAC.SHA1.Sign_SHA1 (RFC2202 test5)",
Test_HMAC_SHA1_RFC2202_T5'Access);
Caller.Add_Test (Suite, "Test Util.Encoders.HMAC.SHA1.Sign_SHA1 (RFC2202 test6)",
Test_HMAC_SHA1_RFC2202_T6'Access);
Caller.Add_Test (Suite, "Test Util.Encoders.HMAC.SHA1.Sign_SHA1 (RFC2202 test7)",
Test_HMAC_SHA1_RFC2202_T7'Access);
end Add_Tests;
procedure Test_Base64_Encode (T : in out Test) is
C : constant Util.Encoders.Encoder := Create ("base64");
begin
Assert_Equals (T, "YQ==", Util.Encoders.Encode (C, "a"));
Assert_Equals (T, "fA==", Util.Encoders.Encode (C, "|"));
Assert_Equals (T, "fHw=", Util.Encoders.Encode (C, "||"));
Assert_Equals (T, "fH5+", Util.Encoders.Encode (C, "|~~"));
end Test_Base64_Encode;
procedure Test_Base64_Decode (T : in out Test) is
C : Util.Encoders.Encoder := Create ("base64");
begin
Assert_Equals (T, "a", Util.Encoders.Decode (C, "YQ=="));
Assert_Equals (T, "|", Util.Encoders.Decode (C, "fA=="));
Assert_Equals (T, "||", Util.Encoders.Decode (C, "fHw="));
Assert_Equals (T, "|~~", Util.Encoders.Decode (C, "fH5+"));
Test_Encoder (T, C);
end Test_Base64_Decode;
procedure Test_Encoder (T : in out Test;
C : in out Util.Encoders.Encoder) is
begin
for I in 1 .. 334 loop
declare
Pattern : String (1 .. I);
begin
for J in Pattern'Range loop
Pattern (J) := Character'Val (((J + I) mod 63) + 32);
end loop;
declare
E : constant String := Util.Encoders.Encode (C, Pattern);
D : constant String := Util.Encoders.Decode (C, E);
begin
Assert_Equals (T, Pattern, D, "Encoding failed for length "
& Integer'Image (I));
end;
exception
when others =>
Ada.Text_IO.Put_Line ("Error at index " & Integer'Image (I));
raise;
end;
end loop;
end Test_Encoder;
procedure Test_Hex (T : in out Test) is
C : Util.Encoders.Encoder := Create ("hex");
begin
Assert_Equals (T, "41424344", Util.Encoders.Encode (C, "ABCD"));
Assert_Equals (T, "ABCD", Util.Encoders.Decode (C, "41424344"));
Test_Encoder (T, C);
end Test_Hex;
procedure Test_Base64_Benchmark (T : in out Test) is
pragma Unreferenced (T);
C : constant Util.Encoders.Encoder := Create ("base64");
S : constant String (1 .. 1_024) := (others => 'a');
begin
declare
T : Util.Measures.Stamp;
R : constant String := Util.Encoders.Encode (C, S);
pragma Unreferenced (R);
begin
Util.Measures.Report (T, "Base64 encode 1024 bytes");
end;
end Test_Base64_Benchmark;
procedure Test_SHA1_Encode (T : in out Test) is
procedure Check_Hash (Value : in String;
Expect : in String);
C : Util.Encoders.SHA1.Context;
Hash : Util.Encoders.SHA1.Digest;
procedure Check_Hash (Value : in String;
Expect : in String) is
J, N : Natural;
Ctx : Util.Encoders.SHA1.Context;
begin
for I in 1 .. Value'Length loop
J := Value'First;
while J <= Value'Last loop
if J + I <= Value'Last then
N := J + I;
else
N := Value'Last;
end if;
Util.Encoders.SHA1.Update (Ctx, Value (J .. N));
J := N + 1;
end loop;
Util.Encoders.SHA1.Finish (Ctx, Hash);
Assert_Equals (T, Expect, Hash, "Invalid hash for: " & Value);
end loop;
end Check_Hash;
begin
Util.Encoders.SHA1.Update (C, "a");
Util.Encoders.SHA1.Finish (C, Hash);
Assert_Equals (T, "86F7E437FAA5A7FCE15D1DDCB9EAEAEA377667B8", Hash,
"Invalid hash for 'a'");
Check_Hash ("ut", "E746699D3947443D84DAD1E0C58BF7AD34712438");
Check_Hash ("Uti", "2C669751BDC4929377245F5EEBEAED1CE4DA8A45");
Check_Hash ("Util", "4C31156EFED35EE7814650F8971C3698059440E3");
Check_Hash ("Util.Encoders", "7DB6007AD8BAEA7C167FF2AE06C9F50A4645F971");
Check_Hash ("e746699d3947443d84dad1e0c58bf7ad347124382C669751BDC492937"
& "7245F5EEBEAED1CE4DA8A45",
"875C9C0DE4CE91ED8F432DD02B5BB40CD35DAACD");
end Test_SHA1_Encode;
-- ------------------------------
-- Benchmark test for SHA1
-- ------------------------------
procedure Test_SHA1_Benchmark (T : in out Test) is
pragma Unreferenced (T);
Hash : Util.Encoders.SHA1.Digest;
Sizes : constant array (1 .. 6) of Positive := (1, 10, 100, 1000, 10000, 100000);
begin
for I in Sizes'Range loop
declare
Size : constant Positive := Sizes (I);
S : constant String (1 .. Size) := (others => '0');
T1 : Util.Measures.Stamp;
C : Util.Encoders.SHA1.Context;
begin
Util.Encoders.SHA1.Update (C, S);
Util.Encoders.SHA1.Finish (C, Hash);
Util.Measures.Report (T1, "Encode SHA1" & Integer'Image (Size) & " bytes");
end;
end loop;
end Test_SHA1_Benchmark;
procedure Check_HMAC (T : in out Test'Class;
Key : in String;
Value : in String;
Expect : in String) is
H : constant String := Util.Encoders.HMAC.SHA1.Sign (Key, Value);
begin
Assert_Equals (T, Expect, Util.Strings.Transforms.To_Lower_Case (H),
"Invalid HMAC-SHA1");
end Check_HMAC;
-- ------------------------------
-- Test HMAC-SHA1
-- ------------------------------
procedure Test_HMAC_SHA1_RFC2202_T1 (T : in out Test) is
Key : constant String (1 .. 20) := (others => Character'Val (16#0b#));
begin
Check_HMAC (T, Key, "Hi There", "b617318655057264e28bc0b6fb378c8ef146be00");
end Test_HMAC_SHA1_RFC2202_T1;
procedure Test_HMAC_SHA1_RFC2202_T2 (T : in out Test) is
begin
Check_HMAC (T, "Jefe", "what do ya want for nothing?",
"effcdf6ae5eb2fa2d27416d5f184df9c259a7c79");
end Test_HMAC_SHA1_RFC2202_T2;
procedure Test_HMAC_SHA1_RFC2202_T3 (T : in out Test) is
Key : constant String (1 .. 20) := (others => Character'Val (16#aa#));
Data : constant String (1 .. 50) := (others => Character'Val (16#dd#));
begin
Check_HMAC (T, Key, Data,
"125d7342b9ac11cd91a39af48aa17b4f63f175d3");
end Test_HMAC_SHA1_RFC2202_T3;
procedure Test_HMAC_SHA1_RFC2202_T4 (T : in out Test) is
C : constant Util.Encoders.Encoder := Create ("hex");
Key : constant String := Util.Encoders.Decode (C, "0102030405060708090a0b0c0d0e0f"
& "10111213141516171819");
Data : constant String (1 .. 50) := (others => Character'Val (16#cd#));
begin
Check_HMAC (T, Key, Data,
"4c9007f4026250c6bc8414f9bf50c86c2d7235da");
end Test_HMAC_SHA1_RFC2202_T4;
procedure Test_HMAC_SHA1_RFC2202_T5 (T : in out Test) is
Key : constant String (1 .. 20) := (others => Character'Val (16#0c#));
begin
-- RFC2202 test case 5 but without truncation...
Check_HMAC (T, Key, "Test With Truncation",
"4c1a03424b55e07fe7f27be1d58bb9324a9a5a04");
end Test_HMAC_SHA1_RFC2202_T5;
procedure Test_HMAC_SHA1_RFC2202_T6 (T : in out Test) is
Key : constant String (1 .. 80) := (others => Character'Val (16#aa#));
begin
Check_HMAC (T, Key, "Test Using Larger Than Block-Size Key - Hash Key First",
"aa4ae5e15272d00e95705637ce8a3b55ed402112");
end Test_HMAC_SHA1_RFC2202_T6;
procedure Test_HMAC_SHA1_RFC2202_T7 (T : in out Test) is
Key : constant String (1 .. 80) := (others => Character'Val (16#Aa#));
begin
Check_HMAC (T, Key, "Test Using Larger Than Block-Size Key and Larger "
& "Than One Block-Size Data",
"e8e99d0f45237d786d6bbaa7965c7808bbff1a91");
end Test_HMAC_SHA1_RFC2202_T7;
end Util.Encoders.Tests;
|
Fix compilation warnings
|
Fix compilation warnings
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
ffb2ce090790fed0057c943b9b26a0bfa484bb9d
|
src/os-linux/util-systems-os.ads
|
src/os-linux/util-systems-os.ads
|
-----------------------------------------------------------------------
-- util-system-os -- Unix system operations
-- 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 System;
with Interfaces.C;
with Interfaces.C.Strings;
with Util.Processes;
with Util.Systems.Constants;
-- 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");
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, "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;
|
Define the Sys_Stat and Sys_Fstat operations
|
Define the Sys_Stat and Sys_Fstat operations
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
8732909b8754c900f97482c80b16a38bfd895d3e
|
regtests/ado-sequences-tests.adb
|
regtests/ado-sequences-tests.adb
|
-----------------------------------------------------------------------
-- ado-sequences-tests -- Test sequences factories
-- Copyright (C) 2011, 2012, 2015, 2017, 2018 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Test_Caller;
with ADO.Drivers;
with ADO.Sessions;
with ADO.SQL;
with ADO.Statements;
with Regtests.Simple.Model;
with ADO.Sequences.Hilo;
with ADO.Sessions.Sources;
with ADO.Sessions.Factory;
with ADO.Schemas;
package body ADO.Sequences.Tests is
type Test_Impl is
new ADO.Objects.Object_Record (Key_Type => ADO.Objects.KEY_INTEGER,
Of_Class => Regtests.Simple.Model.ALLOCATE_TABLE)
with record
Version : Integer;
Value : ADO.Identifier;
Name : Ada.Strings.Unbounded.Unbounded_String;
Select_Name : Ada.Strings.Unbounded.Unbounded_String;
end record;
overriding
procedure Destroy (Object : access Test_Impl);
overriding
procedure Find (Object : in out Test_Impl;
Session : in out ADO.Sessions.Session'Class;
Query : in ADO.SQL.Query'Class;
Found : out Boolean);
overriding
procedure Load (Object : in out Test_Impl;
Session : in out ADO.Sessions.Session'Class);
overriding
procedure Save (Object : in out Test_Impl;
Session : in out ADO.Sessions.Master_Session'Class);
overriding
procedure Delete (Object : in out Test_Impl;
Session : in out ADO.Sessions.Master_Session'Class);
overriding
procedure Create (Object : in out Test_Impl;
Session : in out ADO.Sessions.Master_Session'Class);
package Caller is new Util.Test_Caller (Test, "ADO.Sequences");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test ADO.Sequences.Create",
Test_Create_Factory'Access);
end Add_Tests;
SEQUENCE_NAME : aliased constant String := "sequence";
Sequence_Table : aliased ADO.Schemas.Class_Mapping
:= ADO.Schemas.Class_Mapping '(Count => 0, Table => SEQUENCE_NAME'Access, Members => <>);
-- Test creation of the sequence factory.
-- This test revealed a memory leak if we failed to create a database connection.
procedure Test_Create_Factory (T : in out Test) is
Seq_Factory : ADO.Sequences.Factory;
Obj : Test_Impl;
Factory : aliased ADO.Sessions.Factory.Session_Factory;
Controller : aliased ADO.Sessions.Sources.Data_Source;
Prev_Id : Identifier := ADO.NO_IDENTIFIER;
begin
Seq_Factory.Set_Default_Generator (ADO.Sequences.Hilo.Create_HiLo_Generator'Access,
Factory'Unchecked_Access);
begin
Seq_Factory.Allocate (Obj);
T.Assert (False, "No exception raised.");
exception
when ADO.Sessions.Connection_Error =>
null; -- Good! An exception is expected because the session factory is empty.
end;
-- Make a real connection.
Controller.Set_Connection (ADO.Drivers.Get_Config ("test.database"));
Factory.Create (Controller);
for I in 1 .. 1_000 loop
Seq_Factory.Allocate (Obj);
T.Assert (Obj.Get_Key_Value /= Prev_Id, "Invalid id was allocated");
Prev_Id := Obj.Get_Key_Value;
end loop;
-- Erase the sequence entry used for the allocate entity table.
declare
S : ADO.Sessions.Master_Session := Regtests.Get_Master_Database;
D : ADO.Statements.Delete_Statement := S.Create_Statement (Sequence_Table'Access);
begin
D.Set_Filter ("name = :name");
D.Bind_Param ("name", String '("allocate"));
D.Execute;
-- Also delete all allocate items.
D := S.Create_Statement (Regtests.Simple.Model.ALLOCATE_TABLE);
D.Execute;
end;
-- Create new objects. This forces the creation of a new entry in the sequence table.
for I in 1 .. 1_00 loop
Seq_Factory.Allocate (Obj);
T.Assert (Obj.Get_Key_Value /= Prev_Id, "Invalid id was allocated");
Prev_Id := Obj.Get_Key_Value;
end loop;
end Test_Create_Factory;
overriding
procedure Destroy (Object : access Test_Impl) is
begin
null;
end Destroy;
overriding
procedure Find (Object : in out Test_Impl;
Session : in out ADO.Sessions.Session'Class;
Query : in ADO.SQL.Query'Class;
Found : out Boolean) is
pragma Unreferenced (Object, Session, Query);
begin
Found := False;
end Find;
overriding
procedure Load (Object : in out Test_Impl;
Session : in out ADO.Sessions.Session'Class) is
begin
null;
end Load;
overriding
procedure Save (Object : in out Test_Impl;
Session : in out ADO.Sessions.Master_Session'Class) is
begin
null;
end Save;
overriding
procedure Delete (Object : in out Test_Impl;
Session : in out ADO.Sessions.Master_Session'Class) is
begin
null;
end Delete;
overriding
procedure Create (Object : in out Test_Impl;
Session : in out ADO.Sessions.Master_Session'Class) is
begin
null;
end Create;
end ADO.Sequences.Tests;
|
-----------------------------------------------------------------------
-- ado-sequences-tests -- Test sequences factories
-- Copyright (C) 2011, 2012, 2015, 2017, 2018 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Test_Caller;
with ADO.Drivers;
with ADO.Sessions;
with ADO.SQL;
with ADO.Statements;
with Regtests.Simple.Model;
with ADO.Sequences.Hilo;
with ADO.Sessions.Sources;
with ADO.Sessions.Factory;
with ADO.Schemas;
package body ADO.Sequences.Tests is
type Test_Impl is
new ADO.Objects.Object_Record (Key_Type => ADO.Objects.KEY_INTEGER,
Of_Class => Regtests.Simple.Model.ALLOCATE_TABLE)
with record
Version : Integer;
Value : ADO.Identifier;
Name : Ada.Strings.Unbounded.Unbounded_String;
Select_Name : Ada.Strings.Unbounded.Unbounded_String;
end record;
overriding
procedure Destroy (Object : access Test_Impl);
overriding
procedure Find (Object : in out Test_Impl;
Session : in out ADO.Sessions.Session'Class;
Query : in ADO.SQL.Query'Class;
Found : out Boolean);
overriding
procedure Load (Object : in out Test_Impl;
Session : in out ADO.Sessions.Session'Class);
overriding
procedure Save (Object : in out Test_Impl;
Session : in out ADO.Sessions.Master_Session'Class);
overriding
procedure Delete (Object : in out Test_Impl;
Session : in out ADO.Sessions.Master_Session'Class);
overriding
procedure Create (Object : in out Test_Impl;
Session : in out ADO.Sessions.Master_Session'Class);
package Caller is new Util.Test_Caller (Test, "ADO.Sequences");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test ADO.Sequences.Create",
Test_Create_Factory'Access);
end Add_Tests;
SEQUENCE_NAME : aliased constant String := "sequence";
Sequence_Table : aliased ADO.Schemas.Class_Mapping
:= ADO.Schemas.Class_Mapping '(Count => 0, Table => SEQUENCE_NAME'Access, Members => <>);
-- Test creation of the sequence factory.
-- This test revealed a memory leak if we failed to create a database connection.
procedure Test_Create_Factory (T : in out Test) is
Seq_Factory : ADO.Sequences.Factory;
Obj : Test_Impl;
Factory : aliased ADO.Sessions.Factory.Session_Factory;
Controller : aliased ADO.Sessions.Sources.Data_Source;
Prev_Id : Identifier := ADO.NO_IDENTIFIER;
begin
Seq_Factory.Set_Default_Generator (ADO.Sequences.Hilo.Create_HiLo_Generator'Access,
Factory'Unchecked_Access);
begin
Seq_Factory.Allocate (Obj);
T.Assert (False, "No exception raised.");
exception
when ADO.Sessions.Connection_Error =>
null; -- Good! An exception is expected because the session factory is empty.
end;
-- Make a real connection.
Controller.Set_Connection (ADO.Drivers.Get_Config ("test.database"));
Factory.Create (Controller);
for I in 1 .. 1_000 loop
Seq_Factory.Allocate (Obj);
T.Assert (Obj.Get_Key_Value /= Prev_Id, "Invalid id was allocated");
Prev_Id := Obj.Get_Key_Value;
end loop;
-- Erase the sequence entry used for the allocate entity table.
declare
S : constant ADO.Sessions.Master_Session := Regtests.Get_Master_Database;
D : ADO.Statements.Delete_Statement := S.Create_Statement (Sequence_Table'Access);
begin
D.Set_Filter ("name = :name");
D.Bind_Param ("name", String '("allocate"));
D.Execute;
-- Also delete all allocate items.
D := S.Create_Statement (Regtests.Simple.Model.ALLOCATE_TABLE);
D.Execute;
end;
-- Create new objects. This forces the creation of a new entry in the sequence table.
for I in 1 .. 1_00 loop
Seq_Factory.Allocate (Obj);
T.Assert (Obj.Get_Key_Value /= Prev_Id, "Invalid id was allocated");
Prev_Id := Obj.Get_Key_Value;
end loop;
end Test_Create_Factory;
overriding
procedure Destroy (Object : access Test_Impl) is
begin
null;
end Destroy;
overriding
procedure Find (Object : in out Test_Impl;
Session : in out ADO.Sessions.Session'Class;
Query : in ADO.SQL.Query'Class;
Found : out Boolean) is
pragma Unreferenced (Object, Session, Query);
begin
Found := False;
end Find;
overriding
procedure Load (Object : in out Test_Impl;
Session : in out ADO.Sessions.Session'Class) is
begin
null;
end Load;
overriding
procedure Save (Object : in out Test_Impl;
Session : in out ADO.Sessions.Master_Session'Class) is
begin
null;
end Save;
overriding
procedure Delete (Object : in out Test_Impl;
Session : in out ADO.Sessions.Master_Session'Class) is
begin
null;
end Delete;
overriding
procedure Create (Object : in out Test_Impl;
Session : in out ADO.Sessions.Master_Session'Class) is
begin
null;
end Create;
end ADO.Sequences.Tests;
|
Fix compilation warning
|
Fix compilation warning
|
Ada
|
apache-2.0
|
stcarrez/ada-ado
|
67c3d03971a425bdf4d98521d046764c351d6a65
|
awa/src/awa-commands-info.adb
|
awa/src/awa-commands-info.adb
|
-----------------------------------------------------------------------
-- akt-commands-info -- Info command to describe the current configuration
-- Copyright (C) 2020 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
package body AWA.Commands.Info is
use type AWA.Modules.Module_Access;
-- ------------------------------
-- Print the configuration identified by the given name.
-- ------------------------------
procedure Print (Command : in out Command_Type;
Name : in String;
Value : in String;
Default : in String;
Context : in out Context_Type) is
pragma Unreferenced (Default);
Pos : Natural;
begin
Context.Console.Start_Row;
Context.Console.Print_Field (1, Name);
Pos := Value'First;
while Pos <= Value'Last loop
if Value'Last - Pos > Command.Value_Length then
Context.Console.Print_Field (2, Value (Pos .. Pos + Command.Value_Length - 1));
Pos := Pos + Command.Value_Length;
Context.Console.End_Row;
Context.Console.Start_Row;
Context.Console.Print_Field (1, "");
else
Context.Console.Print_Field (2, Value (Pos .. Value'Last));
Pos := Pos + Value'Length;
end if;
end loop;
Context.Console.End_Row;
end Print;
procedure Print (Command : in out Command_Type;
Application : in out AWA.Applications.Application'Class;
Name : in String;
Default : in String;
Context : in out Context_Type) is
Value : constant String := Application.Get_Init_Parameter (Name, Default);
begin
Command.Print (Name, Value, Default, Context);
end Print;
procedure Print (Command : in out Command_Type;
Module : in AWA.Modules.Module'Class;
Name : in String;
Default : in String;
Context : in out Context_Type) is
Value : constant String := Module.Get_Config (Name, Default);
begin
Command.Print (Module.Get_Name & "." & Name, Value, Default, Context);
end Print;
-- ------------------------------
-- Print the configuration about the application.
-- ------------------------------
overriding
procedure Execute (Command : in out Command_Type;
Application : in out AWA.Applications.Application'Class;
Args : in Argument_List'Class;
Context : in out Context_Type) is
pragma Unreferenced (Args);
Module : AWA.Modules.Module_Access;
begin
if Command.Long_List then
Command.Value_Length := Natural'Last;
end if;
Application.Load_Bundle (Name => "commands",
Locale => "en",
Bundle => Command.Bundle);
Context.Console.Start_Title;
Context.Console.Print_Title (1, "", 30);
Context.Console.Print_Title (2, "", Command.Value_Length);
Context.Console.End_Title;
Context.Console.Notice (N_INFO, "Database configuration");
Context.Console.Notice (N_INFO, "----------------------");
Command.Print (Application, "database", "", Context);
Command.Print (Application, "ado.queries.paths", "", Context);
Command.Print (Application, "ado.queries.load", "", Context);
Command.Print (Application, "ado.drivers.load", "", Context);
Context.Console.Start_Title;
Context.Console.Print_Title (1, "", 30);
Context.Console.Print_Title (2, "", Command.Value_Length);
Context.Console.End_Title;
Context.Console.Notice (N_INFO, "Server faces configuration");
Context.Console.Notice (N_INFO, "--------------------------");
Command.Print (Application, "view.dir",
ASF.Applications.DEF_VIEW_DIR, Context);
Command.Print (Application, "view.escape_unknown_tags",
ASF.Applications.DEF_ESCAPE_UNKNOWN_TAGS, Context);
Command.Print (Application, "view.ext",
ASF.Applications.DEF_VIEW_EXT, Context);
Command.Print (Application, "view.file_ext",
ASF.Applications.DEF_VIEW_FILE_EXT, Context);
Command.Print (Application, "view.ignore_spaces",
ASF.Applications.DEF_IGNORE_WHITE_SPACES, Context);
Command.Print (Application, "view.ignore_empty_lines",
ASF.Applications.DEF_IGNORE_EMPTY_LINES, Context);
Command.Print (Application, "view.static.dir",
ASF.Applications.DEF_STATIC_DIR, Context);
Command.Print (Application, "bundle.dir", "bundles", Context);
Context.Console.Start_Title;
Context.Console.Print_Title (1, "", 30);
Context.Console.Print_Title (2, "", Command.Value_Length);
Context.Console.End_Title;
Context.Console.Notice (N_INFO, "AWA Application");
Context.Console.Notice (N_INFO, "--------------------------");
Command.Print (Application, "app_name", "", Context);
Command.Print (Application, "app_search_dirs", ".", Context);
Command.Print (Application, "app.modules.dir", "", Context);
Command.Print (Application, "app_url_base", "", Context);
Command.Print (Application, "awa_url_host", "", Context);
Command.Print (Application, "awa_url_port", "", Context);
Command.Print (Application, "awa_url_scheme", "", Context);
Command.Print (Application, "app.config", "awa.xml", Context);
Command.Print (Application, "app.config.plugins", "", Context);
Command.Print (Application, "contextPath", "", Context);
Command.Print (Application, "awa_dispatcher_count", "", Context);
Command.Print (Application, "awa_dispatcher_priority", "", Context);
Context.Console.Start_Title;
Context.Console.Print_Title (1, "", 30);
Context.Console.Print_Title (2, "", Command.Value_Length);
Context.Console.End_Title;
Context.Console.Notice (N_INFO, "Users Module");
Context.Console.Notice (N_INFO, "------------");
Command.Print (Application, "openid.realm", "", Context);
Command.Print (Application, "openid.callback_url", "", Context);
Command.Print (Application, "openid.success_url", "", Context);
Command.Print (Application, "auth.url.orange", "", Context);
Command.Print (Application, "auth.provider.orange", "", Context);
Command.Print (Application, "auth.url.yahoo", "", Context);
Command.Print (Application, "auth.provider.yahoo", "", Context);
Command.Print (Application, "auth.url.google", "", Context);
Command.Print (Application, "auth.provider.google", "", Context);
Command.Print (Application, "auth.url.facebook", "", Context);
Command.Print (Application, "auth.provider.facebook", "", Context);
Command.Print (Application, "auth.url.google-plus", "", Context);
Command.Print (Application, "auth.provider.google-plus", "", Context);
Command.Print (Application, "facebook.callback_url", "", Context);
Command.Print (Application, "facebook.request_url", "", Context);
Command.Print (Application, "facebook.scope", "", Context);
Command.Print (Application, "facebook.client_id", "", Context);
Command.Print (Application, "facebook.secret", "", Context);
Command.Print (Application, "google-plus.issuer", "", Context);
Command.Print (Application, "google-plus.callback_url", "", Context);
Command.Print (Application, "google-plus.request_url", "", Context);
Command.Print (Application, "google-plus.scope", "", Context);
Command.Print (Application, "google-plus.client_id", "", Context);
Command.Print (Application, "google-plus.secret", "", Context);
Command.Print (Application, "auth-filter.redirect", "", Context);
Command.Print (Application, "verify-filter.redirect", "", Context);
Context.Console.Start_Title;
Context.Console.Print_Title (1, "", 30);
Context.Console.Print_Title (2, "", Command.Value_Length);
Context.Console.End_Title;
Context.Console.Notice (N_INFO, "Mail Module");
Context.Console.Notice (N_INFO, "-----------");
Command.Print (Application, "mail.smtp.host", "", Context);
Command.Print (Application, "mail.smtp.port", "", Context);
Command.Print (Application, "mail.smtp.enable", "true", Context);
Command.Print (Application, "mail.mailer", "smtp", Context);
Command.Print (Application, "mail.file.maildir", "mail", Context);
Command.Print (Application, "app_mail_name", "", Context);
Command.Print (Application, "app_mail_from", "", Context);
Module := Application.Find_Module ("workspaces");
if Module /= null then
Context.Console.Start_Title;
Context.Console.Print_Title (1, "", 30);
Context.Console.Print_Title (2, "", Command.Value_Length);
Context.Console.End_Title;
Context.Console.Notice (N_INFO, "Workspace Module");
Context.Console.Notice (N_INFO, "----------------");
Command.Print (Module.all, "permissions_list", "", Context);
Command.Print (Module.all, "allow_workspace_create", "", Context);
end if;
Module := Application.Find_Module ("storages");
if Module /= null then
Context.Console.Start_Title;
Context.Console.Print_Title (1, "", 30);
Context.Console.Print_Title (2, "", Command.Value_Length);
Context.Console.End_Title;
Context.Console.Notice (N_INFO, "Storage Module");
Context.Console.Notice (N_INFO, "--------------------------");
Command.Print (Module.all, "database_max_size", "100000", Context);
Command.Print (Module.all, "storage_root", "storage", Context);
Command.Print (Module.all, "tmp_storage_root", "tmp", Context);
Module := Application.Find_Module ("images");
if Module /= null then
Command.Print (Module.all, "thumbnail_command", "", Context);
end if;
end if;
Module := Application.Find_Module ("wikis");
if Module /= null then
Context.Console.Start_Title;
Context.Console.Print_Title (1, "", 30);
Context.Console.Print_Title (2, "", Command.Value_Length);
Context.Console.End_Title;
Context.Console.Notice (N_INFO, "Wiki Module");
Context.Console.Notice (N_INFO, "-----------");
Command.Print (Module.all, "image_prefix", "", Context);
Command.Print (Module.all, "page_prefix", "", Context);
Command.Print (Module.all, "wiki_copy_list", "", Context);
Module := Application.Find_Module ("wiki_previews");
if Module /= null then
Command.Print (Module.all, "wiki_preview_tmp", "tmp", Context);
Command.Print (Module.all, "wiki_preview_dir", "web/preview", Context);
Command.Print (Module.all, "wiki_preview_template", "", Context);
Command.Print (Module.all, "wiki_preview_html", "", Context);
Command.Print (Module.all, "wiki_preview_command", "", Context);
end if;
end if;
Module := Application.Find_Module ("counters");
if Module /= null then
Context.Console.Start_Title;
Context.Console.Print_Title (1, "", 30);
Context.Console.Print_Title (2, "", Command.Value_Length);
Context.Console.End_Title;
Context.Console.Notice (N_INFO, "Counter Module");
Context.Console.Notice (N_INFO, "--------------");
Command.Print (Module.all, "counter_age_limit", "300", Context);
Command.Print (Module.all, "counter_limit", "1000", Context);
end if;
end Execute;
-- ------------------------------
-- Setup the command before parsing the arguments and executing it.
-- ------------------------------
overriding
procedure Setup (Command : in out Command_Type;
Config : in out GNAT.Command_Line.Command_Line_Configuration;
Context : in out Context_Type) is
begin
GC.Set_Usage (Config => Config,
Usage => Command.Get_Name & " [arguments]",
Help => Command.Get_Description);
Command_Drivers.Application_Command_Type (Command).Setup (Config, Context);
GC.Define_Switch (Config => Config,
Output => Command.Long_List'Access,
Switch => "-l",
Long_Switch => "--long-lines",
Help => -("Use long lines to print configuration values"));
end Setup;
-- ------------------------------
-- Write the help associated with the command.
-- ------------------------------
overriding
procedure Help (Command : in out Command_Type;
Name : in String;
Context : in out Context_Type) is
pragma Unreferenced (Command, Context);
begin
null;
end Help;
begin
Command_Drivers.Driver.Add_Command ("info",
-("report configuration information"),
Command'Access);
end AWA.Commands.Info;
|
-----------------------------------------------------------------------
-- akt-commands-info -- Info command to describe the current configuration
-- Copyright (C) 2020 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
package body AWA.Commands.Info is
use type AWA.Modules.Module_Access;
-- ------------------------------
-- Print the configuration identified by the given name.
-- ------------------------------
procedure Print (Command : in out Command_Type;
Name : in String;
Value : in String;
Default : in String;
Context : in out Context_Type) is
pragma Unreferenced (Default);
Pos : Natural;
begin
Context.Console.Start_Row;
Context.Console.Print_Field (1, Name);
Pos := Value'First;
while Pos <= Value'Last loop
if Value'Last - Pos > Command.Value_Length then
Context.Console.Print_Field (2, Value (Pos .. Pos + Command.Value_Length - 1));
Pos := Pos + Command.Value_Length;
Context.Console.End_Row;
Context.Console.Start_Row;
Context.Console.Print_Field (1, "");
else
Context.Console.Print_Field (2, Value (Pos .. Value'Last));
Pos := Pos + Value'Length;
end if;
end loop;
Context.Console.End_Row;
end Print;
procedure Print (Command : in out Command_Type;
Application : in out AWA.Applications.Application'Class;
Name : in String;
Default : in String;
Context : in out Context_Type) is
Value : constant String := Application.Get_Init_Parameter (Name, Default);
begin
Command.Print (Name, Value, Default, Context);
end Print;
procedure Print (Command : in out Command_Type;
Module : in AWA.Modules.Module'Class;
Name : in String;
Default : in String;
Context : in out Context_Type) is
Value : constant String := Module.Get_Config (Name, Default);
begin
Command.Print (Module.Get_Name & "." & Name, Value, Default, Context);
end Print;
-- ------------------------------
-- Print the configuration about the application.
-- ------------------------------
overriding
procedure Execute (Command : in out Command_Type;
Application : in out AWA.Applications.Application'Class;
Args : in Argument_List'Class;
Context : in out Context_Type) is
pragma Unreferenced (Args);
Module : AWA.Modules.Module_Access;
begin
if Command.Long_List then
Command.Value_Length := Natural'Last;
end if;
Application.Load_Bundle (Name => "commands",
Locale => "en",
Bundle => Command.Bundle);
Context.Console.Start_Title;
Context.Console.Print_Title (1, "", 30);
Context.Console.Print_Title (2, "", Command.Value_Length);
Context.Console.End_Title;
Context.Console.Notice (N_INFO, "Database configuration");
Context.Console.Notice (N_INFO, "----------------------");
Command.Print (Application, "database", "", Context);
Command.Print (Application, "ado.queries.paths", "", Context);
Command.Print (Application, "ado.queries.load", "", Context);
Command.Print (Application, "ado.drivers.load", "", Context);
Context.Console.Start_Title;
Context.Console.Print_Title (1, "", 30);
Context.Console.Print_Title (2, "", Command.Value_Length);
Context.Console.End_Title;
Context.Console.Notice (N_INFO, "Server faces configuration");
Context.Console.Notice (N_INFO, "--------------------------");
Command.Print (Application, "view.dir",
ASF.Applications.DEF_VIEW_DIR, Context);
Command.Print (Application, "view.escape_unknown_tags",
ASF.Applications.DEF_ESCAPE_UNKNOWN_TAGS, Context);
Command.Print (Application, "view.ext",
ASF.Applications.DEF_VIEW_EXT, Context);
Command.Print (Application, "view.file_ext",
ASF.Applications.DEF_VIEW_FILE_EXT, Context);
Command.Print (Application, "view.ignore_spaces",
ASF.Applications.DEF_IGNORE_WHITE_SPACES, Context);
Command.Print (Application, "view.ignore_empty_lines",
ASF.Applications.DEF_IGNORE_EMPTY_LINES, Context);
Command.Print (Application, "view.static.dir",
ASF.Applications.DEF_STATIC_DIR, Context);
Command.Print (Application, "bundle.dir", "bundles", Context);
Context.Console.Start_Title;
Context.Console.Print_Title (1, "", 30);
Context.Console.Print_Title (2, "", Command.Value_Length);
Context.Console.End_Title;
Context.Console.Notice (N_INFO, "AWA Application");
Context.Console.Notice (N_INFO, "--------------------------");
Command.Print (Application, "app_name", "", Context);
Command.Print (Application, "app_search_dirs", ".", Context);
Command.Print (Application, "app.modules.dir", "", Context);
Command.Print (Application, "app_url_base", "", Context);
Command.Print (Application, "awa_url_host", "", Context);
Command.Print (Application, "awa_url_port", "", Context);
Command.Print (Application, "awa_url_scheme", "", Context);
Command.Print (Application, "app.config", "awa.xml", Context);
Command.Print (Application, "app.config.plugins", "", Context);
Command.Print (Application, "contextPath", "", Context);
Command.Print (Application, "awa_dispatcher_count", "", Context);
Command.Print (Application, "awa_dispatcher_priority", "", Context);
Module := Application.Find_Module ("users");
if Module /= null then
Context.Console.Start_Title;
Context.Console.Print_Title (1, "", 30);
Context.Console.Print_Title (2, "", Command.Value_Length);
Context.Console.End_Title;
Context.Console.Notice (N_INFO, "Users Module");
Context.Console.Notice (N_INFO, "------------");
Command.Print (Application, "openid.realm", "", Context);
Command.Print (Application, "openid.callback_url", "", Context);
Command.Print (Application, "openid.success_url", "", Context);
Command.Print (Application, "auth.url.orange", "", Context);
Command.Print (Application, "auth.provider.orange", "", Context);
Command.Print (Application, "auth.url.yahoo", "", Context);
Command.Print (Application, "auth.provider.yahoo", "", Context);
Command.Print (Application, "auth.url.google", "", Context);
Command.Print (Application, "auth.provider.google", "", Context);
Command.Print (Application, "auth.url.facebook", "", Context);
Command.Print (Application, "auth.provider.facebook", "", Context);
Command.Print (Application, "auth.url.google-plus", "", Context);
Command.Print (Application, "auth.provider.google-plus", "", Context);
Command.Print (Application, "facebook.callback_url", "", Context);
Command.Print (Application, "facebook.request_url", "", Context);
Command.Print (Application, "facebook.scope", "", Context);
Command.Print (Application, "facebook.client_id", "", Context);
Command.Print (Application, "facebook.secret", "", Context);
Command.Print (Application, "google-plus.issuer", "", Context);
Command.Print (Application, "google-plus.callback_url", "", Context);
Command.Print (Application, "google-plus.request_url", "", Context);
Command.Print (Application, "google-plus.scope", "", Context);
Command.Print (Application, "google-plus.client_id", "", Context);
Command.Print (Application, "google-plus.secret", "", Context);
Command.Print (Application, "auth-filter.redirect", "", Context);
Command.Print (Application, "verify-filter.redirect", "", Context);
end if;
Module := Application.Find_Module ("mail");
if Module /= null then
Context.Console.Start_Title;
Context.Console.Print_Title (1, "", 30);
Context.Console.Print_Title (2, "", Command.Value_Length);
Context.Console.End_Title;
Context.Console.Notice (N_INFO, "Mail Module");
Context.Console.Notice (N_INFO, "-----------");
Command.Print (Application, "mail.smtp.host", "", Context);
Command.Print (Application, "mail.smtp.port", "", Context);
Command.Print (Application, "mail.smtp.enable", "true", Context);
Command.Print (Application, "mail.mailer", "smtp", Context);
Command.Print (Application, "mail.file.maildir", "mail", Context);
Command.Print (Application, "app_mail_name", "", Context);
Command.Print (Application, "app_mail_from", "", Context);
end if;
Module := Application.Find_Module ("workspaces");
if Module /= null then
Context.Console.Start_Title;
Context.Console.Print_Title (1, "", 30);
Context.Console.Print_Title (2, "", Command.Value_Length);
Context.Console.End_Title;
Context.Console.Notice (N_INFO, "Workspace Module");
Context.Console.Notice (N_INFO, "----------------");
Command.Print (Module.all, "permissions_list", "", Context);
Command.Print (Module.all, "allow_workspace_create", "", Context);
end if;
Module := Application.Find_Module ("storages");
if Module /= null then
Context.Console.Start_Title;
Context.Console.Print_Title (1, "", 30);
Context.Console.Print_Title (2, "", Command.Value_Length);
Context.Console.End_Title;
Context.Console.Notice (N_INFO, "Storage Module");
Context.Console.Notice (N_INFO, "--------------------------");
Command.Print (Module.all, "database_max_size", "100000", Context);
Command.Print (Module.all, "storage_root", "storage", Context);
Command.Print (Module.all, "tmp_storage_root", "tmp", Context);
Module := Application.Find_Module ("images");
if Module /= null then
Command.Print (Module.all, "thumbnail_command", "", Context);
end if;
end if;
Module := Application.Find_Module ("wikis");
if Module /= null then
Context.Console.Start_Title;
Context.Console.Print_Title (1, "", 30);
Context.Console.Print_Title (2, "", Command.Value_Length);
Context.Console.End_Title;
Context.Console.Notice (N_INFO, "Wiki Module");
Context.Console.Notice (N_INFO, "-----------");
Command.Print (Module.all, "image_prefix", "", Context);
Command.Print (Module.all, "page_prefix", "", Context);
Command.Print (Module.all, "wiki_copy_list", "", Context);
Module := Application.Find_Module ("wiki_previews");
if Module /= null then
Command.Print (Module.all, "wiki_preview_tmp", "tmp", Context);
Command.Print (Module.all, "wiki_preview_dir", "web/preview", Context);
Command.Print (Module.all, "wiki_preview_template", "", Context);
Command.Print (Module.all, "wiki_preview_html", "", Context);
Command.Print (Module.all, "wiki_preview_command", "", Context);
end if;
end if;
Module := Application.Find_Module ("counters");
if Module /= null then
Context.Console.Start_Title;
Context.Console.Print_Title (1, "", 30);
Context.Console.Print_Title (2, "", Command.Value_Length);
Context.Console.End_Title;
Context.Console.Notice (N_INFO, "Counter Module");
Context.Console.Notice (N_INFO, "--------------");
Command.Print (Module.all, "counter_age_limit", "300", Context);
Command.Print (Module.all, "counter_limit", "1000", Context);
end if;
end Execute;
-- ------------------------------
-- Setup the command before parsing the arguments and executing it.
-- ------------------------------
overriding
procedure Setup (Command : in out Command_Type;
Config : in out GNAT.Command_Line.Command_Line_Configuration;
Context : in out Context_Type) is
begin
GC.Set_Usage (Config => Config,
Usage => Command.Get_Name & " [arguments]",
Help => Command.Get_Description);
Command_Drivers.Application_Command_Type (Command).Setup (Config, Context);
GC.Define_Switch (Config => Config,
Output => Command.Long_List'Access,
Switch => "-l",
Long_Switch => "--long-lines",
Help => -("Use long lines to print configuration values"));
end Setup;
-- ------------------------------
-- Write the help associated with the command.
-- ------------------------------
overriding
procedure Help (Command : in out Command_Type;
Name : in String;
Context : in out Context_Type) is
pragma Unreferenced (Command, Context);
begin
null;
end Help;
begin
Command_Drivers.Driver.Add_Command ("info",
-("report configuration information"),
Command'Access);
end AWA.Commands.Info;
|
Update the info command to avoid printing the mail, user configurations if these modules are not active
|
Update the info command to avoid printing the mail, user configurations if these modules are not active
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
d6a0367e14553b9bdacb0685cfb62549f371e634
|
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.
--
-- @include security-permissions.ads
-- @include security-openid.ads
-- @include security-oauth.ads
-- @include security-contexts.ads
-- @include security-controllers.ads
package Security is
-- ------------------------------
-- Principal
-- ------------------------------
type Principal is limited interface;
type Principal_Access is access all Principal'Class;
-- Get the principal name.
function Get_Name (From : in Principal) return String is abstract;
end Security;
|
-----------------------------------------------------------------------
-- security -- Security
-- Copyright (C) 2010, 2011, 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
-- == Introduction ==
-- The <tt>Security</tt> package provides a security framework that allows
-- an application to use OpenID or OAuth security frameworks. This security
-- framework was first developed within the Ada Server Faces project.
-- This package defines abstractions that are close or similar to Java
-- security package.
--
-- The security framework uses the following abstractions:
--
-- === Policy and policy manager ===
-- The <tt>Policy</tt> defines and implements the set of security rules that specify how to
-- protect the system or resources. The <tt>Policy_Manager</tt> maintains the security policies.
--
-- === Principal ===
-- The <tt>Principal</tt> is the entity that can be authenticated. A principal is obtained
-- after successful authentication of a user or of a system through an authorization process.
-- The OpenID or OAuth authentication processes generate such security principal.
--
-- === Permission ===
-- The <tt>Permission</tt> represents an access to a system or application resource.
-- A permission is checked by using the security policy manager. The policy manager uses a
-- security controller to enforce the permission.
--
-- === Security Context ===
-- The <tt>Security_Context</tt> holds the contextual information that the security controller
-- can use to verify the permission. The security context is associated with a principal and
-- a set of policy context.
--
-- == Overview ==
-- An application will create a security policy manager and register one or several security
-- policies. The framework defines a simple role based security policy and an URL security
-- policy intended to provide security in web applications. The security policy manager reads
-- some security policy configuration file which allows the security policies to configure
-- and create the security controllers. These controllers will enforce the security according
-- to the application security rules. All these components (yellow) are built only once when
-- an application starts.
--
-- A user is authenticated through an authentication system which creates a <tt>Principal</tt>
-- instance that identifies the user (green). The security framework provides two authentication
-- systems: OpenID and OAuth.
--
-- [http://ada-security.googlecode.com/svn/wiki/ModelOverview.png]
--
-- When a permission must be enforced, a security context is created and linked to the
-- <tt>Principal</tt> instance. Additional security policy context can be added depending on
-- the application context. To check the permission, the security policy manager is called
-- and it will ask a security controller to verify the permission.
--
-- The framework allows an application to plug its own security policy, its own policy context,
-- its own principal and authentication mechanism.
--
-- @include security-permissions.ads
-- @include security-openid.ads
-- @include security-oauth.ads
-- @include security-contexts.ads
-- @include security-controllers.ads
package Security is
-- ------------------------------
-- Principal
-- ------------------------------
type Principal is limited interface;
type Principal_Access is access all Principal'Class;
-- Get the principal name.
function Get_Name (From : in Principal) return String is abstract;
end Security;
|
Update the documentation
|
Update the documentation
|
Ada
|
apache-2.0
|
stcarrez/ada-security
|
12b8af6e055640218d488a0a435f2b8d9e0c93b2
|
regtests/util-dates-formats-tests.adb
|
regtests/util-dates-formats-tests.adb
|
-----------------------------------------------------------------------
-- util-dates-formats-tests - Test for date formats
-- 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.Calendar.Formatting;
with Util.Test_Caller;
with Util.Assertions;
with Util.Properties.Bundles;
with Util.Log.Loggers;
package body Util.Dates.Formats.Tests is
use Util.Tests;
use Ada.Strings.Unbounded;
-- The logger
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Util.Dates.Formats.Tests");
package Caller is new Util.Test_Caller (Test, "Dates");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test Util.Dates.Split",
Test_Split'Access);
Caller.Add_Test (Suite, "Test Util.Dates.Formats.Format",
Test_Format'Access);
Caller.Add_Test (Suite, "Test Util.Dates.Get_Day_Start",
Test_Get_Day_Start'Access);
Caller.Add_Test (Suite, "Test Util.Dates.Get_Week_Start",
Test_Get_Week_Start'Access);
Caller.Add_Test (Suite, "Test Util.Dates.Get_Month_Start",
Test_Get_Month_Start'Access);
Caller.Add_Test (Suite, "Test Util.Dates.Get_Day_End",
Test_Get_Day_End'Access);
Caller.Add_Test (Suite, "Test Util.Dates.Get_Week_End",
Test_Get_Week_End'Access);
Caller.Add_Test (Suite, "Test Util.Dates.Get_Month_End",
Test_Get_Month_End'Access);
end Add_Tests;
procedure Test_Format (T : in out Test) is
Bundle : Util.Properties.Bundles.Manager;
procedure Check (Pattern : in String;
Date : in Ada.Calendar.Time;
Expect : in String);
procedure Check (Pattern : in String;
Date : in Ada.Calendar.Time;
Expect : in String) is
Result : Ada.Strings.Unbounded.Unbounded_String;
begin
Util.Dates.Formats.Format (Pattern => Pattern,
Date => Date,
Bundle => Bundle,
Into => Result);
Util.Tests.Assert_Equals (T, Expect, To_String (Result),
"Invalid result for: " & Pattern);
end Check;
T1 : constant Ada.Calendar.Time := Ada.Calendar.Formatting.Time_Of (1980, 1, 2, 10, 30, 23);
T2 : constant Ada.Calendar.Time := Ada.Calendar.Formatting.Time_Of (2011, 11, 19, 0, 0, 0);
T3 : constant Ada.Calendar.Time := Ada.Calendar.Formatting.Time_Of (2011, 11, 19, 23, 0, 0);
begin
Check ("%H", T1, "10");
Check ("%H", T2, "00");
Check ("%I", T3, "11");
Check ("%k", T2, " 0");
Check ("%k", T3, "23");
Check ("%l", T2, " 0");
Check ("%l", T3, "11");
Check ("%r", T3, "11:00:00 PM");
Check ("%r", T2, "00:00:00 AM");
Check ("%R:%S", T3, "23:00:00");
Check ("%y-%Y %m/%d %T", T1, "80-1980 01/02 10:30:23");
Check ("%C %d %D", T1, "19 02 01/02/80");
Check ("%e", T1, " 1");
Check ("%F", T1, "1980-01-02");
Check ("%G", T1, "1980W01");
Check ("%g", T1, "80W01");
end Test_Format;
procedure Check (T : in out Test'Class;
Year : in Ada.Calendar.Year_Number;
Month : in Ada.Calendar.Month_Number;
Day : in Ada.Calendar.Day_Number;
Expect_Day : in Ada.Calendar.Day_Number;
Message : in String;
Is_End : in Boolean;
Operation : access function (D : in Ada.Calendar.Time)
return Ada.Calendar.Time) is
use type Ada.Calendar.Time;
Date : Ada.Calendar.Time := Ada.Calendar.Formatting.Time_Of (Year, Month, Day,
0, 0, 0);
begin
for I in 1 .. 47 loop
declare
R : constant Ada.Calendar.Time := Operation (Date);
D : Date_Record;
begin
Split (D, R);
Log.Info ("{0} ({1}) => {2}",
Ada.Calendar.Formatting.Image (Date),
Message, Ada.Calendar.Formatting.Image (R));
Util.Tests.Assert_Equals (T, Natural (Year), Natural (D.Year),
"Invalid year " & Message);
Util.Tests.Assert_Equals (T, Natural (Month), Natural (D.Month),
"Invalid month " & Message);
Util.Tests.Assert_Equals (T, Natural (Expect_Day), Natural (D.Month_Day),
"Invalid day " & Message);
if Is_End then
Util.Tests.Assert_Equals (T, 23, Natural (D.Hour),
"Invalid hour " & Message);
Util.Tests.Assert_Equals (T, 59, Natural (D.Minute),
"Invalid minute " & Message);
Util.Tests.Assert_Equals (T, 59, Natural (D.Second),
"Invalid second " & Message);
else
Util.Tests.Assert_Equals (T, 0, Natural (D.Hour),
"Invalid hour " & Message);
Util.Tests.Assert_Equals (T, 0, Natural (D.Minute),
"Invalid minute " & Message);
Util.Tests.Assert_Equals (T, 0, Natural (D.Second),
"Invalid second " & Message);
end if;
end;
Date := Date + 1800.0;
end loop;
end Check;
-- ------------------------------
-- Test the Get_Day_Start operation.
-- ------------------------------
procedure Test_Get_Day_Start (T : in out Test) is
begin
Check (T, 2013, 6, 04, 04, "Get_Day_Start", False, Get_Day_Start'Access);
Check (T, 2010, 2, 14, 14, "Get_Day_Start", False, Get_Day_Start'Access);
end Test_Get_Day_Start;
-- ------------------------------
-- Test the Get_Week_Start operation.
-- ------------------------------
procedure Test_Get_Week_Start (T : in out Test) is
begin
Check (T, 2013, 6, 04, 03, "Get_Week_Start", False, Get_Week_Start'Access);
Check (T, 2013, 6, 03, 03, "Get_Week_Start", False, Get_Week_Start'Access);
Check (T, 2013, 6, 05, 03, "Get_Week_Start", False, Get_Week_Start'Access);
Check (T, 2013, 6, 08, 03, "Get_Week_Start", False, Get_Week_Start'Access);
Check (T, 2010, 2, 14, 08, "Get_Week_Start", False, Get_Week_Start'Access);
Check (T, 2010, 2, 13, 08, "Get_Week_Start", False, Get_Week_Start'Access);
Check (T, 2010, 2, 10, 08, "Get_Week_Start", False, Get_Week_Start'Access);
Check (T, 2010, 2, 15, 15, "Get_Week_Start", False, Get_Week_Start'Access);
end Test_Get_Week_Start;
-- ------------------------------
-- Test the Get_Month_Start operation.
-- ------------------------------
procedure Test_Get_Month_Start (T : in out Test) is
begin
Check (T, 2013, 6, 04, 01, "Get_Month_Start", False, Get_Month_Start'Access);
Check (T, 2010, 2, 14, 01, "Get_Month_Start", False, Get_Month_Start'Access);
end Test_Get_Month_Start;
-- ------------------------------
-- Test the Get_Day_End operation.
-- ------------------------------
procedure Test_Get_Day_End (T : in out Test) is
begin
Check (T, 2013, 6, 04, 04, "Get_Day_Start", True, Get_Day_End'Access);
Check (T, 2010, 2, 14, 14, "Get_Day_Start", True, Get_Day_End'Access);
end Test_Get_Day_End;
-- ------------------------------
-- Test the Get_Week_End operation.
-- ------------------------------
procedure Test_Get_Week_End (T : in out Test) is
begin
Check (T, 2013, 6, 04, 09, "Get_Week_End", True, Get_Week_End'Access);
Check (T, 2013, 6, 03, 09, "Get_Week_End", True, Get_Week_End'Access);
Check (T, 2013, 6, 05, 09, "Get_Week_End", True, Get_Week_End'Access);
Check (T, 2013, 6, 08, 09, "Get_Week_End", True, Get_Week_End'Access);
Check (T, 2010, 2, 14, 14, "Get_Week_End", True, Get_Week_End'Access);
Check (T, 2010, 2, 13, 14, "Get_Week_End", True, Get_Week_End'Access);
Check (T, 2010, 2, 10, 14, "Get_Week_End", True, Get_Week_End'Access);
Check (T, 2010, 2, 15, 21, "Get_Week_End", True, Get_Week_End'Access);
end Test_Get_Week_End;
-- ------------------------------
-- Test the Get_Month_End operation.
-- ------------------------------
procedure Test_Get_Month_End (T : in out Test) is
begin
Check (T, 2013, 6, 04, 30, "Get_Month_End", True, Get_Month_End'Access);
Check (T, 2010, 2, 14, 28, "Get_Month_End", True, Get_Month_End'Access);
Check (T, 2000, 2, 14, 29, "Get_Month_End", True, Get_Month_End'Access);
end Test_Get_Month_End;
-- ------------------------------
-- Test the Split operation.
-- ------------------------------
procedure Test_Split (T : in out Test) is
procedure Assert_Equals is
new Util.Assertions.Assert_Equals_T (Ada.Calendar.Formatting.Day_Name);
Date : constant Ada.Calendar.Time := Ada.Calendar.Formatting.Time_Of (2014, 11, 12,
23, 30, 0);
D : Date_Record;
begin
Split (D, Date);
Util.Tests.Assert_Equals (T, 2014, Natural (D.Year), "Invalid year ");
Util.Tests.Assert_Equals (T, 11, Natural (D.Month), "Invalid month ");
Util.Tests.Assert_Equals (T, 12, Natural (D.Month_Day), "Invalid day ");
Util.Tests.Assert_Equals (T, 23, Natural (D.Hour), "Invalid hour ");
Util.Tests.Assert_Equals (T, 30, Natural (D.Minute), "Invalid minute ");
Assert_Equals (T, Ada.Calendar.Formatting.Wednesday, D.Day, "Invalid day ");
end Test_Split;
end Util.Dates.Formats.Tests;
|
-----------------------------------------------------------------------
-- util-dates-formats-tests - Test for date formats
-- 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.Calendar.Formatting;
with Util.Test_Caller;
with Util.Assertions;
with Util.Properties.Bundles;
with Util.Log.Loggers;
with Util.Dates.RFC7231;
package body Util.Dates.Formats.Tests is
use Util.Tests;
use Ada.Strings.Unbounded;
-- The logger
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Util.Dates.Formats.Tests");
package Caller is new Util.Test_Caller (Test, "Dates");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test Util.Dates.Split",
Test_Split'Access);
Caller.Add_Test (Suite, "Test Util.Dates.Formats.Format",
Test_Format'Access);
Caller.Add_Test (Suite, "Test Util.Dates.Get_Day_Start",
Test_Get_Day_Start'Access);
Caller.Add_Test (Suite, "Test Util.Dates.Get_Week_Start",
Test_Get_Week_Start'Access);
Caller.Add_Test (Suite, "Test Util.Dates.Get_Month_Start",
Test_Get_Month_Start'Access);
Caller.Add_Test (Suite, "Test Util.Dates.Get_Day_End",
Test_Get_Day_End'Access);
Caller.Add_Test (Suite, "Test Util.Dates.Get_Week_End",
Test_Get_Week_End'Access);
Caller.Add_Test (Suite, "Test Util.Dates.Get_Month_End",
Test_Get_Month_End'Access);
Caller.Add_Test (Suite, "Test Util.Dates.RFC7231.Append_Date",
Test_Append_Date'Access);
end Add_Tests;
procedure Test_Format (T : in out Test) is
Bundle : Util.Properties.Bundles.Manager;
procedure Check (Pattern : in String;
Date : in Ada.Calendar.Time;
Expect : in String);
procedure Check (Pattern : in String;
Date : in Ada.Calendar.Time;
Expect : in String) is
Result : Ada.Strings.Unbounded.Unbounded_String;
begin
Util.Dates.Formats.Format (Pattern => Pattern,
Date => Date,
Bundle => Bundle,
Into => Result);
Util.Tests.Assert_Equals (T, Expect, To_String (Result),
"Invalid result for: " & Pattern);
end Check;
T1 : constant Ada.Calendar.Time := Ada.Calendar.Formatting.Time_Of (1980, 1, 2, 10, 30, 23);
T2 : constant Ada.Calendar.Time := Ada.Calendar.Formatting.Time_Of (2011, 11, 19, 0, 0, 0);
T3 : constant Ada.Calendar.Time := Ada.Calendar.Formatting.Time_Of (2011, 11, 19, 23, 0, 0);
begin
Check ("%H", T1, "10");
Check ("%H", T2, "00");
Check ("%I", T3, "11");
Check ("%k", T2, " 0");
Check ("%k", T3, "23");
Check ("%l", T2, " 0");
Check ("%l", T3, "11");
Check ("%r", T3, "11:00:00 PM");
Check ("%r", T2, "00:00:00 AM");
Check ("%R:%S", T3, "23:00:00");
Check ("%y-%Y %m/%d %T", T1, "80-1980 01/02 10:30:23");
Check ("%C %d %D", T1, "19 02 01/02/80");
Check ("%e", T1, " 1");
Check ("%F", T1, "1980-01-02");
Check ("%G", T1, "1980W01");
Check ("%g", T1, "80W01");
end Test_Format;
procedure Check (T : in out Test'Class;
Year : in Ada.Calendar.Year_Number;
Month : in Ada.Calendar.Month_Number;
Day : in Ada.Calendar.Day_Number;
Expect_Day : in Ada.Calendar.Day_Number;
Message : in String;
Is_End : in Boolean;
Operation : access function (D : in Ada.Calendar.Time)
return Ada.Calendar.Time) is
use type Ada.Calendar.Time;
Date : Ada.Calendar.Time := Ada.Calendar.Formatting.Time_Of (Year, Month, Day,
0, 0, 0);
begin
for I in 1 .. 47 loop
declare
R : constant Ada.Calendar.Time := Operation (Date);
D : Date_Record;
begin
Split (D, R);
Log.Info ("{0} ({1}) => {2}",
Ada.Calendar.Formatting.Image (Date),
Message, Ada.Calendar.Formatting.Image (R));
Util.Tests.Assert_Equals (T, Natural (Year), Natural (D.Year),
"Invalid year " & Message);
Util.Tests.Assert_Equals (T, Natural (Month), Natural (D.Month),
"Invalid month " & Message);
Util.Tests.Assert_Equals (T, Natural (Expect_Day), Natural (D.Month_Day),
"Invalid day " & Message);
if Is_End then
Util.Tests.Assert_Equals (T, 23, Natural (D.Hour),
"Invalid hour " & Message);
Util.Tests.Assert_Equals (T, 59, Natural (D.Minute),
"Invalid minute " & Message);
Util.Tests.Assert_Equals (T, 59, Natural (D.Second),
"Invalid second " & Message);
else
Util.Tests.Assert_Equals (T, 0, Natural (D.Hour),
"Invalid hour " & Message);
Util.Tests.Assert_Equals (T, 0, Natural (D.Minute),
"Invalid minute " & Message);
Util.Tests.Assert_Equals (T, 0, Natural (D.Second),
"Invalid second " & Message);
end if;
end;
Date := Date + 1800.0;
end loop;
end Check;
-- ------------------------------
-- Test the Get_Day_Start operation.
-- ------------------------------
procedure Test_Get_Day_Start (T : in out Test) is
begin
Check (T, 2013, 6, 04, 04, "Get_Day_Start", False, Get_Day_Start'Access);
Check (T, 2010, 2, 14, 14, "Get_Day_Start", False, Get_Day_Start'Access);
end Test_Get_Day_Start;
-- ------------------------------
-- Test the Get_Week_Start operation.
-- ------------------------------
procedure Test_Get_Week_Start (T : in out Test) is
begin
Check (T, 2013, 6, 04, 03, "Get_Week_Start", False, Get_Week_Start'Access);
Check (T, 2013, 6, 03, 03, "Get_Week_Start", False, Get_Week_Start'Access);
Check (T, 2013, 6, 05, 03, "Get_Week_Start", False, Get_Week_Start'Access);
Check (T, 2013, 6, 08, 03, "Get_Week_Start", False, Get_Week_Start'Access);
Check (T, 2010, 2, 14, 08, "Get_Week_Start", False, Get_Week_Start'Access);
Check (T, 2010, 2, 13, 08, "Get_Week_Start", False, Get_Week_Start'Access);
Check (T, 2010, 2, 10, 08, "Get_Week_Start", False, Get_Week_Start'Access);
Check (T, 2010, 2, 15, 15, "Get_Week_Start", False, Get_Week_Start'Access);
end Test_Get_Week_Start;
-- ------------------------------
-- Test the Get_Month_Start operation.
-- ------------------------------
procedure Test_Get_Month_Start (T : in out Test) is
begin
Check (T, 2013, 6, 04, 01, "Get_Month_Start", False, Get_Month_Start'Access);
Check (T, 2010, 2, 14, 01, "Get_Month_Start", False, Get_Month_Start'Access);
end Test_Get_Month_Start;
-- ------------------------------
-- Test the Get_Day_End operation.
-- ------------------------------
procedure Test_Get_Day_End (T : in out Test) is
begin
Check (T, 2013, 6, 04, 04, "Get_Day_Start", True, Get_Day_End'Access);
Check (T, 2010, 2, 14, 14, "Get_Day_Start", True, Get_Day_End'Access);
end Test_Get_Day_End;
-- ------------------------------
-- Test the Get_Week_End operation.
-- ------------------------------
procedure Test_Get_Week_End (T : in out Test) is
begin
Check (T, 2013, 6, 04, 09, "Get_Week_End", True, Get_Week_End'Access);
Check (T, 2013, 6, 03, 09, "Get_Week_End", True, Get_Week_End'Access);
Check (T, 2013, 6, 05, 09, "Get_Week_End", True, Get_Week_End'Access);
Check (T, 2013, 6, 08, 09, "Get_Week_End", True, Get_Week_End'Access);
Check (T, 2010, 2, 14, 14, "Get_Week_End", True, Get_Week_End'Access);
Check (T, 2010, 2, 13, 14, "Get_Week_End", True, Get_Week_End'Access);
Check (T, 2010, 2, 10, 14, "Get_Week_End", True, Get_Week_End'Access);
Check (T, 2010, 2, 15, 21, "Get_Week_End", True, Get_Week_End'Access);
end Test_Get_Week_End;
-- ------------------------------
-- Test the Get_Month_End operation.
-- ------------------------------
procedure Test_Get_Month_End (T : in out Test) is
begin
Check (T, 2013, 6, 04, 30, "Get_Month_End", True, Get_Month_End'Access);
Check (T, 2010, 2, 14, 28, "Get_Month_End", True, Get_Month_End'Access);
Check (T, 2000, 2, 14, 29, "Get_Month_End", True, Get_Month_End'Access);
end Test_Get_Month_End;
-- ------------------------------
-- Test the Split operation.
-- ------------------------------
procedure Test_Split (T : in out Test) is
procedure Assert_Equals is
new Util.Assertions.Assert_Equals_T (Ada.Calendar.Formatting.Day_Name);
Date : constant Ada.Calendar.Time := Ada.Calendar.Formatting.Time_Of (2014, 11, 12,
23, 30, 0);
D : Date_Record;
begin
Split (D, Date);
Util.Tests.Assert_Equals (T, 2014, Natural (D.Year), "Invalid year ");
Util.Tests.Assert_Equals (T, 11, Natural (D.Month), "Invalid month ");
Util.Tests.Assert_Equals (T, 12, Natural (D.Month_Day), "Invalid day ");
Util.Tests.Assert_Equals (T, 23, Natural (D.Hour), "Invalid hour ");
Util.Tests.Assert_Equals (T, 30, Natural (D.Minute), "Invalid minute ");
Assert_Equals (T, Ada.Calendar.Formatting.Wednesday, D.Day, "Invalid day ");
end Test_Split;
procedure Check (T : in out Test;
Date : in String) is
D : constant Ada.Calendar.Time := Util.Dates.RFC7231.Value (Date);
F : constant String := Util.Dates.RFC7231.Image (D);
begin
Util.Tests.Assert_Equals (T, Date, F, "Invalid date conversion");
end Check;
-- ------------------------------
-- Test the Append_Date as well as the Image operation
-- ------------------------------
procedure Test_Append_Date (T : in out Test) is
begin
Check (T, "Mon, 26 Mar 2012 19:43:47 GMT");
Check (T, "Tue, 02 Feb 2016 15:18:35 GMT");
Check (T, "Wed, 07 Oct 2015 03:41:11 GMT");
Check (T, "Thu, 17 Sep 2015 10:07:02 GMT");
Check (T, "Sat, 03 Oct 2015 17:09:58 GMT");
Check (T, "Fri, 17 Jul 2015 16:07:54 GMT");
Check (T, "Sun, 04 Oct 2015 15:10:44 GMT");
end Test_Append_Date;
end Util.Dates.Formats.Tests;
|
Add a new test Test_Append_Date to verify several HTTP date parsing and formatting
|
Add a new test Test_Append_Date to verify several HTTP date parsing and formatting
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
6d74f0154cd45a6d6a7bb9b3b635e25c4c3fd365
|
awa/plugins/awa-counters/regtests/awa-counters-modules-tests.adb
|
awa/plugins/awa-counters/regtests/awa-counters-modules-tests.adb
|
-----------------------------------------------------------------------
-- awa-wikis-modules-tests -- Unit tests for wikis service
-- Copyright (C) 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Measures;
with Util.Test_Caller;
with AWA.Tests.Helpers;
with AWA.Tests.Helpers.Users;
with AWA.Services.Contexts;
with AWA.Counters.Definition;
with AWA.Users.Models;
with Security.Contexts;
package body AWA.Counters.Modules.Tests is
package User_Counter is
new AWA.Counters.Definition (AWA.Users.Models.USER_TABLE);
package Session_Counter is
new AWA.Counters.Definition (AWA.Users.Models.SESSION_TABLE);
package Global_Counter is
new AWA.Counters.Definition (null, "count");
package Caller is new Util.Test_Caller (Test, "Counters.Modules");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test AWA.Counters.Modules.Increment",
Test_Increment'Access);
Caller.Add_Test (Suite, "Test AWA.Counters.Modules.Increment (global counter)",
Test_Global_Counter'Access);
end Add_Tests;
-- ------------------------------
-- Test incrementing counters and flushing.
-- ------------------------------
procedure Test_Increment (T : in out Test) is
Sec_Ctx : Security.Contexts.Security_Context;
Context : AWA.Services.Contexts.Service_Context;
Before : Integer;
After : Integer;
begin
AWA.Tests.Helpers.Users.Login (Context, Sec_Ctx, "[email protected]");
T.Manager := AWA.Counters.Modules.Get_Counter_Module;
T.Assert (T.Manager /= null, "There is no counter plugin");
T.Manager.Get_Counter (User_Counter.Index, Context.Get_User, Before);
AWA.Counters.Increment (User_Counter.Index, Context.Get_User);
T.Manager.Flush;
T.Manager.Get_Counter (User_Counter.Index, Context.Get_User, After);
Util.Tests.Assert_Equals (T, Before + 1, After, "The counter must have been incremented");
declare
S : Util.Measures.Stamp;
begin
for I in 1 .. 1_000 loop
AWA.Counters.Increment (User_Counter.Index, Context.Get_User);
end loop;
Util.Measures.Report (S, "AWA.Counters.Increment", 1000);
end;
AWA.Counters.Increment (User_Counter.Index, Context.Get_User);
declare
S : Util.Measures.Stamp;
begin
T.Manager.Flush;
Util.Measures.Report (S, "AWA.Counters.Flush");
end;
T.Manager.Get_Counter (User_Counter.Index, Context.Get_User, After);
Util.Tests.Assert_Equals (T, Before + 2 + 1_000, After,
"The counter must have been incremented");
end Test_Increment;
-- ------------------------------
-- Test creation of a wiki page.
-- ------------------------------
-- Test incrementing a global counter.
procedure Test_Global_Counter (T : in out Test) is
Sec_Ctx : Security.Contexts.Security_Context;
Context : AWA.Services.Contexts.Service_Context;
begin
AWA.Tests.Helpers.Users.Login (Context, Sec_Ctx, "[email protected]");
T.Manager := AWA.Counters.Modules.Get_Counter_Module;
T.Assert (T.Manager /= null, "There is no counter plugin");
-- T.Manager.Get_Counter (Global_Counter.Index, Before);
AWA.Counters.Increment (Global_Counter.Index);
T.Manager.Flush;
end Test_Global_Counter;
end AWA.Counters.Modules.Tests;
|
-----------------------------------------------------------------------
-- awa-wikis-modules-tests -- Unit tests for wikis service
-- Copyright (C) 2015, 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.Measures;
with Util.Test_Caller;
with AWA.Tests.Helpers;
with AWA.Tests.Helpers.Users;
with AWA.Services.Contexts;
with AWA.Counters.Definition;
with AWA.Users.Models;
with Security.Contexts;
package body AWA.Counters.Modules.Tests is
package User_Counter is
new AWA.Counters.Definition (AWA.Users.Models.USER_TABLE);
package Session_Counter is
new AWA.Counters.Definition (AWA.Users.Models.SESSION_TABLE);
package Global_Counter is
new AWA.Counters.Definition (null, "count");
package Caller is new Util.Test_Caller (Test, "Counters.Modules");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test AWA.Counters.Modules.Increment",
Test_Increment'Access);
Caller.Add_Test (Suite, "Test AWA.Counters.Modules.Increment (global counter)",
Test_Global_Counter'Access);
end Add_Tests;
-- ------------------------------
-- Test incrementing counters and flushing.
-- ------------------------------
procedure Test_Increment (T : in out Test) is
Sec_Ctx : Security.Contexts.Security_Context;
Context : AWA.Services.Contexts.Service_Context;
Before : Integer;
After : Integer;
begin
AWA.Tests.Helpers.Users.Login (Context, Sec_Ctx, "[email protected]");
T.Manager := AWA.Counters.Modules.Get_Counter_Module;
T.Assert (T.Manager /= null, "There is no counter plugin");
T.Manager.Get_Counter (User_Counter.Index, Context.Get_User, Before);
AWA.Counters.Increment (User_Counter.Index, Context.Get_User);
T.Manager.Flush;
T.Manager.Get_Counter (User_Counter.Index, Context.Get_User, After);
Util.Tests.Assert_Equals (T, Before + 1, After, "The counter must have been incremented");
declare
S : Util.Measures.Stamp;
begin
for I in 1 .. 1_000 loop
AWA.Counters.Increment (User_Counter.Index, Context.Get_User);
end loop;
Util.Measures.Report (S, "AWA.Counters.Increment", 1000);
end;
declare
S : Util.Measures.Stamp;
begin
for I in 1 .. 1_000 loop
AWA.Counters.Increment (Session_Counter.Index, Context.Get_User_Session);
end loop;
Util.Measures.Report (S, "AWA.Counters.Increment", 1000);
end;
AWA.Counters.Increment (User_Counter.Index, Context.Get_User);
declare
S : Util.Measures.Stamp;
begin
T.Manager.Flush;
Util.Measures.Report (S, "AWA.Counters.Flush");
end;
T.Manager.Get_Counter (User_Counter.Index, Context.Get_User, After);
Util.Tests.Assert_Equals (T, Before + 2 + 1_000, After,
"The counter must have been incremented");
end Test_Increment;
-- ------------------------------
-- Test creation of a wiki page.
-- ------------------------------
-- Test incrementing a global counter.
procedure Test_Global_Counter (T : in out Test) is
Sec_Ctx : Security.Contexts.Security_Context;
Context : AWA.Services.Contexts.Service_Context;
begin
AWA.Tests.Helpers.Users.Login (Context, Sec_Ctx, "[email protected]");
T.Manager := AWA.Counters.Modules.Get_Counter_Module;
T.Assert (T.Manager /= null, "There is no counter plugin");
-- T.Manager.Get_Counter (Global_Counter.Index, Before);
AWA.Counters.Increment (Global_Counter.Index);
T.Manager.Flush;
end Test_Global_Counter;
end AWA.Counters.Modules.Tests;
|
Fix compilation warning
|
Fix compilation warning
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
e0c07972cbf9623fb5ee49b3100694eea3dbf1f8
|
src/babel-files.adb
|
src/babel-files.adb
|
-- bkp-files -- File and directories
-----------------------------------------------------------------------
-- Copyright (C) 2014 Stephane.Carrez
-- Written by Stephane.Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Log.Loggers;
with Util.Files;
with Util.Encoders.Base16;
package body Babel.Files is
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Bkp.Files");
Hex_Encoder : Util.Encoders.Base16.Encoder;
-- ------------------------------
-- Compare two files on their name and directory.
-- ------------------------------
function "<" (Left, Right : in File_Type) return Boolean is
use type Ada.Strings.Unbounded.Unbounded_String;
begin
if Left = NO_FILE then
return False;
elsif Right = NO_FILE then
return True;
elsif Left.Dir = Right.Dir then
return Left.Name < Right.Name;
elsif Left.Dir = NO_DIRECTORY then
return True;
elsif Right.Dir = NO_DIRECTORY then
return False;
else
return Left.Dir.Path < Right.Dir.Path;
end if;
end "<";
-- ------------------------------
-- Allocate a File_Type entry with the given name for the directory.
-- ------------------------------
function Allocate (Name : in String;
Dir : in Directory_Type) return File_Type is
use Ada.Strings.Unbounded;
Result : constant File_Type := new File '(Len => Name'Length,
Id => NO_IDENTIFIER,
Dir => Dir,
Name => Name,
others => <>);
begin
return Result;
end Allocate;
-- ------------------------------
-- Allocate a Directory_Type entry with the given name for the directory.
-- ------------------------------
function Allocate (Name : in String;
Dir : in Directory_Type) return Directory_Type is
use Ada.Strings.Unbounded;
Result : constant Directory_Type := new Directory '(Len => Name'Length,
Id => NO_IDENTIFIER,
Parent => Dir,
Name => Name,
others => <>);
begin
if Dir /= null then
Result.Path := To_Unbounded_String
(Util.Files.Compose (To_String (Dir.Path), Name));
else
Result.Path := To_Unbounded_String (Name);
end if;
return Result;
end Allocate;
-- ------------------------------
-- Return true if the file was modified and need a backup.
-- ------------------------------
function Is_Modified (Element : in File_Type) return Boolean is
use type ADO.Identifier;
begin
if Element.Id = NO_IDENTIFIER then
return True;
elsif (Element.Status and FILE_MODIFIED) /= 0 then
return True;
else
return False;
end if;
end Is_Modified;
-- ------------------------------
-- Return true if the file is a new file.
-- ------------------------------
function Is_New (Element : in File_Type) return Boolean is
use type ADO.Identifier;
begin
return Element.Id = NO_IDENTIFIER;
end Is_New;
-- ------------------------------
-- Set the file as modified.
-- ------------------------------
procedure Set_Modified (Element : in File_Type) is
begin
Element.Status := Element.Status or FILE_MODIFIED;
end Set_Modified;
-- ------------------------------
-- Set the SHA1 signature that was computed for this file.
-- If the computed signature is different from the current signature,
-- the FILE_MODIFIED flag is set on the file. The FILE_HAS_SHA1 flag
-- is set on the file.
-- ------------------------------
procedure Set_Signature (Element : in File_Type;
Signature : in Util.Encoders.SHA1.Hash_Array) is
use type Util.Encoders.SHA1.Hash_Array;
begin
if (Element.Status and FILE_HAS_SHA1) /= 0 and then Element.SHA1 /= Signature then
Element.Status := Element.Status or FILE_MODIFIED;
end if;
Element.Status := Element.Status or FILE_HAS_SHA1;
Element.SHA1 := Signature;
end Set_Signature;
-- ------------------------------
-- Set the file size. If the new size is different, the FILE_MODIFIED
-- flag is set on the file.
-- ------------------------------
procedure Set_Size (Element : in File_Type;
Size : in File_Size) is
begin
if Element.Size /= Size then
Element.Size := Size;
Element.Status := Element.Status or FILE_MODIFIED;
end if;
end Set_Size;
-- ------------------------------
-- Return the path for the file.
-- ------------------------------
function Get_Path (Element : in File_Type) return String is
begin
if Element.Dir = null then
return Element.Name;
else
return Util.Files.Compose (Get_Path (Element.Dir), Element.Name);
end if;
end Get_Path;
-- ------------------------------
-- Return the path for the directory.
-- ------------------------------
function Get_Path (Element : in Directory_Type) return String is
begin
return Ada.Strings.Unbounded.To_String (Element.Path);
end Get_Path;
-- ------------------------------
-- Return the SHA1 signature computed for the file.
-- ------------------------------
function Get_SHA1 (Element : in File_Type) return String is
begin
return Hex_Encoder.Transform (Element.SHA1);
end Get_SHA1;
-- ------------------------------
-- Return the file size.
-- ------------------------------
function Get_Size (Element : in File_Type) return File_Size is
begin
return Element.Size;
end Get_Size;
-- ------------------------------
-- Add the file with the given name in the container.
-- ------------------------------
overriding
procedure Add_File (Into : in out Default_Container;
Element : in File_Type) is
begin
Into.Files.Append (Element);
end Add_File;
-- ------------------------------
-- Add the directory with the given name in the container.
-- ------------------------------
overriding
procedure Add_Directory (Into : in out Default_Container;
Element : in Directory_Type) is
begin
Into.Dirs.Append (Element);
end Add_Directory;
-- ------------------------------
-- Create a new file instance with the given name in the container.
-- ------------------------------
overriding
function Create (Into : in Default_Container;
Name : in String) return File_Type is
begin
return Allocate (Name => Name,
Dir => Into.Current);
end Create;
-- ------------------------------
-- Create a new directory instance with the given name in the container.
-- ------------------------------
overriding
function Create (Into : in Default_Container;
Name : in String) return Directory_Type is
begin
return Allocate (Name => Name,
Dir => Into.Current);
end Create;
-- ------------------------------
-- Find the file with the given name in this file container.
-- Returns NO_FILE if the file was not found.
-- ------------------------------
overriding
function Find (From : in Default_Container;
Name : in String) return File_Type is
pragma Unreferenced (From, Name);
begin
return NO_FILE;
end Find;
-- ------------------------------
-- Find the directory with the given name in this file container.
-- Returns NO_DIRECTORY if the directory was not found.
-- ------------------------------
overriding
function Find (From : in Default_Container;
Name : in String) return Directory_Type is
pragma Unreferenced (From, Name);
begin
return NO_DIRECTORY;
end Find;
-- ------------------------------
-- Set the directory object associated with the container.
-- ------------------------------
procedure Set_Directory (Into : in out Default_Container;
Directory : in Directory_Type) is
begin
Into.Current := Directory;
Into.Files.Clear;
Into.Dirs.Clear;
end Set_Directory;
-- ------------------------------
-- Execute the Process procedure on each directory found in the container.
-- ------------------------------
overriding
procedure Each_Directory (Container : in Default_Container;
Process : not null access
procedure (Dir : in Directory_Type)) is
Iter : Directory_Vectors.Cursor := Container.Dirs.First;
begin
while Directory_Vectors.Has_Element (Iter) loop
Process (Directory_Vectors.Element (Iter));
Directory_Vectors.Next (Iter);
end loop;
end Each_Directory;
-- ------------------------------
-- Execute the Process procedure on each file found in the container.
-- ------------------------------
overriding
procedure Each_File (Container : in Default_Container;
Process : not null access
procedure (F : in File_Type)) is
Iter : File_Vectors.Cursor := Container.Files.First;
begin
while File_Vectors.Has_Element (Iter) loop
Process (File_Vectors.Element (Iter));
File_Vectors.Next (Iter);
end loop;
end Each_File;
end Babel.Files;
|
-- bkp-files -- File and directories
-----------------------------------------------------------------------
-- Copyright (C) 2014 Stephane.Carrez
-- Written by Stephane.Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Log.Loggers;
with Util.Files;
with Util.Encoders.Base16;
package body Babel.Files is
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Bkp.Files");
Hex_Encoder : Util.Encoders.Base16.Encoder;
-- ------------------------------
-- Compare two files on their name and directory.
-- ------------------------------
function "<" (Left, Right : in File_Type) return Boolean is
use type Ada.Strings.Unbounded.Unbounded_String;
begin
if Left = NO_FILE then
return False;
elsif Right = NO_FILE then
return True;
elsif Left.Dir = Right.Dir then
return Left.Name < Right.Name;
elsif Left.Dir = NO_DIRECTORY then
return True;
elsif Right.Dir = NO_DIRECTORY then
return False;
else
return Left.Dir.Path < Right.Dir.Path;
end if;
end "<";
-- ------------------------------
-- Allocate a File_Type entry with the given name for the directory.
-- ------------------------------
function Allocate (Name : in String;
Dir : in Directory_Type) return File_Type is
use Ada.Strings.Unbounded;
Result : constant File_Type := new File '(Len => Name'Length,
Id => NO_IDENTIFIER,
Dir => Dir,
Name => Name,
others => <>);
begin
return Result;
end Allocate;
-- ------------------------------
-- Allocate a Directory_Type entry with the given name for the directory.
-- ------------------------------
function Allocate (Name : in String;
Dir : in Directory_Type) return Directory_Type is
use Ada.Strings.Unbounded;
Result : constant Directory_Type := new Directory '(Len => Name'Length,
Id => NO_IDENTIFIER,
Parent => Dir,
Name => Name,
others => <>);
begin
if Dir /= null then
Result.Path := To_Unbounded_String
(Util.Files.Compose (To_String (Dir.Path), Name));
else
Result.Path := To_Unbounded_String (Name);
end if;
return Result;
end Allocate;
-- ------------------------------
-- Return true if the file was modified and need a backup.
-- ------------------------------
function Is_Modified (Element : in File_Type) return Boolean is
use type ADO.Identifier;
begin
if Element.Id = NO_IDENTIFIER then
return True;
elsif (Element.Status and FILE_MODIFIED) /= 0 then
return True;
else
return False;
end if;
end Is_Modified;
-- ------------------------------
-- Return true if the file is a new file.
-- ------------------------------
function Is_New (Element : in File_Type) return Boolean is
use type ADO.Identifier;
begin
return Element.Id = NO_IDENTIFIER;
end Is_New;
-- ------------------------------
-- Set the file as modified.
-- ------------------------------
procedure Set_Modified (Element : in File_Type) is
begin
Element.Status := Element.Status or FILE_MODIFIED;
end Set_Modified;
-- ------------------------------
-- Set the SHA1 signature that was computed for this file.
-- If the computed signature is different from the current signature,
-- the FILE_MODIFIED flag is set on the file. The FILE_HAS_SHA1 flag
-- is set on the file.
-- ------------------------------
procedure Set_Signature (Element : in File_Type;
Signature : in Util.Encoders.SHA1.Hash_Array) is
use type Util.Encoders.SHA1.Hash_Array;
begin
if (Element.Status and FILE_HAS_SHA1) /= 0 and then Element.SHA1 /= Signature then
Element.Status := Element.Status or FILE_MODIFIED;
end if;
Element.Status := Element.Status or FILE_HAS_SHA1;
Element.SHA1 := Signature;
end Set_Signature;
-- ------------------------------
-- Set the file size. If the new size is different, the FILE_MODIFIED
-- flag is set on the file.
-- ------------------------------
procedure Set_Size (Element : in File_Type;
Size : in File_Size) is
begin
if Element.Size /= Size then
Element.Size := Size;
Element.Status := Element.Status or FILE_MODIFIED;
end if;
end Set_Size;
-- ------------------------------
-- Return the path for the file.
-- ------------------------------
function Get_Path (Element : in File_Type) return String is
begin
if Element.Dir = null then
return Element.Name;
else
return Util.Files.Compose (Get_Path (Element.Dir), Element.Name);
end if;
end Get_Path;
-- ------------------------------
-- Return the path for the directory.
-- ------------------------------
function Get_Path (Element : in Directory_Type) return String is
begin
return Ada.Strings.Unbounded.To_String (Element.Path);
end Get_Path;
-- ------------------------------
-- Return the SHA1 signature computed for the file.
-- ------------------------------
function Get_SHA1 (Element : in File_Type) return String is
begin
return Hex_Encoder.Transform (Element.SHA1);
end Get_SHA1;
-- ------------------------------
-- Return the file size.
-- ------------------------------
function Get_Size (Element : in File_Type) return File_Size is
begin
return Element.Size;
end Get_Size;
-- ------------------------------
-- Return the file modification date.
-- ------------------------------
function Get_Date (Element : in File_Type) return Ada.Calendar.Time is
begin
return Element.Date;
end Get_Date;
-- ------------------------------
-- Add the file with the given name in the container.
-- ------------------------------
overriding
procedure Add_File (Into : in out Default_Container;
Element : in File_Type) is
begin
Into.Files.Append (Element);
end Add_File;
-- ------------------------------
-- Add the directory with the given name in the container.
-- ------------------------------
overriding
procedure Add_Directory (Into : in out Default_Container;
Element : in Directory_Type) is
begin
Into.Dirs.Append (Element);
end Add_Directory;
-- ------------------------------
-- Create a new file instance with the given name in the container.
-- ------------------------------
overriding
function Create (Into : in Default_Container;
Name : in String) return File_Type is
begin
return Allocate (Name => Name,
Dir => Into.Current);
end Create;
-- ------------------------------
-- Create a new directory instance with the given name in the container.
-- ------------------------------
overriding
function Create (Into : in Default_Container;
Name : in String) return Directory_Type is
begin
return Allocate (Name => Name,
Dir => Into.Current);
end Create;
-- ------------------------------
-- Find the file with the given name in this file container.
-- Returns NO_FILE if the file was not found.
-- ------------------------------
overriding
function Find (From : in Default_Container;
Name : in String) return File_Type is
pragma Unreferenced (From, Name);
begin
return NO_FILE;
end Find;
-- ------------------------------
-- Find the directory with the given name in this file container.
-- Returns NO_DIRECTORY if the directory was not found.
-- ------------------------------
overriding
function Find (From : in Default_Container;
Name : in String) return Directory_Type is
pragma Unreferenced (From, Name);
begin
return NO_DIRECTORY;
end Find;
-- ------------------------------
-- Set the directory object associated with the container.
-- ------------------------------
procedure Set_Directory (Into : in out Default_Container;
Directory : in Directory_Type) is
begin
Into.Current := Directory;
Into.Files.Clear;
Into.Dirs.Clear;
end Set_Directory;
-- ------------------------------
-- Execute the Process procedure on each directory found in the container.
-- ------------------------------
overriding
procedure Each_Directory (Container : in Default_Container;
Process : not null access
procedure (Dir : in Directory_Type)) is
Iter : Directory_Vectors.Cursor := Container.Dirs.First;
begin
while Directory_Vectors.Has_Element (Iter) loop
Process (Directory_Vectors.Element (Iter));
Directory_Vectors.Next (Iter);
end loop;
end Each_Directory;
-- ------------------------------
-- Execute the Process procedure on each file found in the container.
-- ------------------------------
overriding
procedure Each_File (Container : in Default_Container;
Process : not null access
procedure (F : in File_Type)) is
Iter : File_Vectors.Cursor := Container.Files.First;
begin
while File_Vectors.Has_Element (Iter) loop
Process (File_Vectors.Element (Iter));
File_Vectors.Next (Iter);
end loop;
end Each_File;
end Babel.Files;
|
Implement the Get_Date operation
|
Implement the Get_Date operation
|
Ada
|
apache-2.0
|
stcarrez/babel
|
80e1147ea315d765113401fd586623d9a46df25e
|
mat/src/symbols/mat-symbols-targets.adb
|
mat/src/symbols/mat-symbols-targets.adb
|
-----------------------------------------------------------------------
-- mat-symbols-targets - Symbol files management
-- Copyright (C) 2014 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
package body MAT.Symbols.Targets is
-- ------------------------------
-- Open the binary and load the symbols from that file.
-- ------------------------------
procedure Open (Symbols : in out Target_Symbols;
Path : in String) is
begin
Bfd.Files.Open (Symbols.File, Path, "");
if Bfd.Files.Check_Format (Symbols.File, Bfd.Files.OBJECT) then
Bfd.Symbols.Read_Symbols (Symbols.File, Symbols.Symbols);
end if;
end Open;
end MAT.Symbols.Targets;
|
-----------------------------------------------------------------------
-- mat-symbols-targets - Symbol files management
-- Copyright (C) 2014 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Bfd.Sections;
package body MAT.Symbols.Targets is
-- ------------------------------
-- Open the binary and load the symbols from that file.
-- ------------------------------
procedure Open (Symbols : in out Target_Symbols;
Path : in String) is
begin
Bfd.Files.Open (Symbols.File, Path, "");
if Bfd.Files.Check_Format (Symbols.File, Bfd.Files.OBJECT) then
Bfd.Symbols.Read_Symbols (Symbols.File, Symbols.Symbols);
end if;
end Open;
-- ------------------------------
-- Find the nearest source file and line for the given address.
-- ------------------------------
procedure Find_Nearest_Line (Symbols : in Target_Symbols;
Addr : in MAT.Types.Target_Addr;
Name : out Ada.Strings.Unbounded.Unbounded_String;
Func : out Ada.Strings.Unbounded.Unbounded_String;
Line : out Natural) is
Text_Section : Bfd.Sections.Section;
begin
Line := 0;
if Bfd.Files.Is_Open (Symbols.File) then
Text_Section := Bfd.Sections.Find_Section (Symbols.File, ".text");
Bfd.Symbols.Find_Nearest_Line (File => Symbols.File,
Sec => Text_Section,
Symbols => Symbols.Symbols,
Addr => Bfd.Vma_Type (Addr),
Name => Name,
Func => Func,
Line => Line);
else
Line := 0;
Name := Ada.Strings.Unbounded.To_Unbounded_String ("");
Func := Ada.Strings.Unbounded.To_Unbounded_String ("");
end if;
exception
when Bfd.NOT_FOUND =>
Line := 0;
Name := Ada.Strings.Unbounded.To_Unbounded_String ("");
Func := Ada.Strings.Unbounded.To_Unbounded_String ("");
end Find_Nearest_Line;
end MAT.Symbols.Targets;
|
Implement Find_Nearest_Line by using Bfd library
|
Implement Find_Nearest_Line by using Bfd library
|
Ada
|
apache-2.0
|
stcarrez/mat,stcarrez/mat,stcarrez/mat
|
38b919bcc880d50c4b4457ead00e68ec82d0db49
|
src/sys/measures/util-measures.adb
|
src/sys/measures/util-measures.adb
|
-----------------------------------------------------------------------
-- measure -- Benchmark tools
-- Copyright (C) 2008, 2009, 2010, 2011, 2012, 2013, 2015, 2017, 2018 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Task_Attributes;
with Ada.Strings.Hash;
with Ada.Unchecked_Deallocation;
with GNAT.Calendar.Time_IO;
with Util.Streams.Buffered;
with Util.Streams.Texts.TR;
package body Util.Measures is
ISO_DATE_TIME : constant GNAT.Calendar.Time_IO.Picture_String := "%Y-%m-%d %H:%M:%S";
procedure Free is
new Ada.Unchecked_Deallocation (Buckets_Type, Buckets_Access);
procedure Free is
new Ada.Unchecked_Deallocation (Measure, Measure_Access);
procedure Free is
new Ada.Unchecked_Deallocation (String, String_Access);
package Task_Context is new Ada.Task_Attributes
(Measure_Set_Access, null);
function Format (D : in Duration) return String;
-- Format the duration in a time in 'ns', 'us', 'ms' or seconds.
function Format (D : in Duration;
Unit : in Unit_Type) return String;
-- ------------------------------
-- Disable collecting measures on the measure set.
-- ------------------------------
procedure Disable (Measures : in out Measure_Set) is
begin
Measures.Enabled := False;
end Disable;
-- ------------------------------
-- Enable collecting measures on the measure set.
-- ------------------------------
procedure Enable (Measures : in out Measure_Set) is
begin
Measures.Enabled := True;
end Enable;
-- ------------------------------
-- Set the per-thread measure set.
-- ------------------------------
procedure Set_Current (Measures : in Measure_Set_Access) is
begin
Task_Context.Set_Value (Measures);
end Set_Current;
-- ------------------------------
-- Get the per-thread measure set.
-- ------------------------------
function Get_Current return Measure_Set_Access is
begin
return Task_Context.Value;
end Get_Current;
-- ------------------------------
-- Dump an XML result with the measures collected by the measure set.
-- When writing the measures, the measure set is cleared. It is safe
-- to write measures while other measures are being collected.
-- ------------------------------
procedure Write (Measures : in out Measure_Set;
Title : in String;
Stream : in out Util.Streams.Texts.Print_Stream'Class) is
procedure Dump_XML (Item : in Measure_Access);
procedure Dump_XML (Item : in Measure_Access) is
Total : constant String := Format (Item.Time);
Time : constant String := Format (Item.Time / Item.Count);
begin
Stream.Write ("<time count=""");
Stream.Write (Item.Count);
Stream.Write (""" time=""");
Stream.Write (Time (Time'First + 1 .. Time'Last));
if Item.Count > 1 then
Stream.Write (""" total=""");
Stream.Write (Total (Total'First + 1 .. Total'Last));
end if;
Stream.Write (""" title=""");
Util.Streams.Texts.TR.Escape_Java_Script (Into => Stream,
Content => Item.Name.all);
Stream.Write ("""/>");
Stream.Write (ASCII.LF);
end Dump_XML;
Buckets : Buckets_Access;
TS, TE : Ada.Calendar.Time;
begin
Measures.Data.Steal_Map (Buckets, TS, TE);
Stream.Write ("<measures title=""");
Util.Streams.Texts.TR.Escape_Java_Script (Into => Stream,
Content => Title);
Stream.Write (""" start=""");
Stream.Write (TS, ISO_DATE_TIME);
Stream.Write (""" end=""");
Stream.Write (TE, ISO_DATE_TIME);
Stream.Write (""">");
if Buckets /= null then
Stream.Write (ASCII.LF);
begin
for I in Buckets'Range loop
declare
Next : Measure_Access;
Node : Measure_Access := Buckets (I);
begin
while Node /= null loop
Dump_XML (Node);
Free (Node.Name);
Next := Node.Next;
Free (Node);
Node := Next;
end loop;
end;
end loop;
exception
when others =>
Free (Buckets);
raise;
end;
Free (Buckets);
end if;
Stream.Write ("</measures>");
end Write;
-- ------------------------------
-- Dump an XML result with the measures collected by the measure set.
-- ------------------------------
procedure Write (Measures : in out Measure_Set;
Title : in String;
Stream : in Ada.Text_IO.File_Type) is
Buffer : aliased Util.Streams.Buffered.Output_Buffer_Stream;
Output : Util.Streams.Texts.Print_Stream;
begin
Buffer.Initialize (Size => 128 * 1024);
Output.Initialize (To => Buffer'Unchecked_Access);
Write (Measures, Title, Output);
Output.Flush;
Ada.Text_IO.Put_Line (Stream, Util.Streams.Texts.To_String (Buffer));
end Write;
-- ------------------------------
-- Dump an XML result with the measures in a file.
-- ------------------------------
procedure Write (Measures : in out Measure_Set;
Title : in String;
Path : in String) is
File : Ada.Text_IO.File_Type;
begin
Ada.Text_IO.Create (File => File, Name => Path);
Write (Measures, Title, File);
Ada.Text_IO.Close (File);
exception
when others =>
if Ada.Text_IO.Is_Open (File) then
Ada.Text_IO.Close (File);
end if;
raise;
end Write;
-- ------------------------------
-- Report the time spent between the stamp creation and this method call.
-- Collect the result in the per-thread measure set under the given measure
-- title.
-- ------------------------------
procedure Report (S : in out Stamp;
Title : in String;
Count : in Positive := 1) is
Measures : constant Measure_Set_Access := Task_Context.Value;
begin
if Measures /= null and then Measures.Enabled then
Report (Measures.all, S, Title, Count);
end if;
end Report;
-- ------------------------------
-- Report the time spent between the stamp creation and this method call.
-- Collect the result in the measure set under the given measure title.
-- ------------------------------
procedure Report (Measures : in out Measure_Set;
S : in out Stamp;
Title : in String;
Count : in Positive := 1) is
use Ada.Calendar;
begin
if Measures.Enabled then
declare
D : constant Duration := Ada.Calendar.Clock - S.Start;
begin
Measures.Data.Add (Title, D, Count);
end;
S.Start := Ada.Calendar.Clock;
end if;
end Report;
-- ------------------------------
-- Report the time spent between the stamp creation and this method call.
-- The report is written in the file with the given title. The duration is
-- expressed in the unit defined in <tt>Unit</tt>.
-- ------------------------------
procedure Report (S : in out Stamp;
File : in out Ada.Text_IO.File_Type;
Title : in String;
Unit : in Unit_Type := Microseconds) is
use Ada.Calendar;
D : constant Duration := Ada.Calendar.Clock - S.Start;
begin
Ada.Text_IO.Put (File, Title);
Ada.Text_IO.Put (File, Format (D, Unit));
S.Start := Ada.Calendar.Clock;
end Report;
protected body Measure_Data is
-- ------------------------------
-- Get the measures and clear to start a new set of measures.
-- Return in <b>Time_Start</b> and <b>Time_End</b> the period of time.
-- ------------------------------
procedure Steal_Map (Result : out Buckets_Access;
Time_Start : out Ada.Calendar.Time;
Time_End : out Ada.Calendar.Time) is
begin
Result := Buckets;
Time_Start := Start;
Start := Ada.Calendar.Clock;
Time_End := Start;
Buckets := null;
end Steal_Map;
-- ------------------------------
-- Add the measure
-- ------------------------------
procedure Add (Title : in String;
D : in Duration;
Count : in Positive := 1) is
use Ada.Containers;
Pos : Hash_Type;
Node : Measure_Access;
begin
if Buckets = null then
Buckets := new Buckets_Type (0 .. 256);
end if;
Pos := Ada.Strings.Hash (Title) mod Buckets'Length;
Node := Buckets (Pos);
while Node /= null loop
if Node.Name'Length = Title'Length
and then Node.Name.all = Title
then
Node.Count := Node.Count + Count;
Node.Time := Node.Time + D;
return;
end if;
Node := Node.Next;
end loop;
Buckets (Pos) := new Measure '(Name => new String '(Title),
Time => D,
Count => Count,
Next => Buckets (Pos));
end Add;
end Measure_Data;
-- ------------------------------
-- Format the duration in a time in 'ns', 'us', 'ms' or seconds.
-- ------------------------------
function Format (D : in Duration) return String is
begin
if D < 0.000_001 then
return Duration'Image (D * 1_000_000_000) (1 .. 6) & " ns";
elsif D < 0.001 then
return Duration'Image (D * 1_000_000) (1 .. 6) & " us";
elsif D < 1.0 then
return Duration'Image (D * 1_000) (1 .. 6) & " ms";
else
return Duration'Image (D) (1 .. 6) & " s";
end if;
end Format;
-- ------------------------------
-- Format the duration in a time in 'ns', 'us', 'ms' or seconds.
-- ------------------------------
function Format (D : in Duration;
Unit : in Unit_Type) return String is
begin
case Unit is
when Seconds =>
return Duration'Image (D);
when Milliseconds =>
return Duration'Image (D * 1_000);
when Microseconds =>
return Duration'Image (D * 1_000_000);
when Nanoseconds =>
return Duration'Image (D * 1_000_000_000);
end case;
end Format;
-- ------------------------------
-- Finalize the measures and release the storage.
-- ------------------------------
overriding
procedure Finalize (Measures : in out Measure_Set) is
Buckets : Buckets_Access;
TS, TE : Ada.Calendar.Time;
begin
-- When deleting the measure set, we have to release the buckets and measures
-- that were allocated. We could call <b>Write</b> but we don't know where
-- the measures have to be written.
Measures.Data.Steal_Map (Buckets, TS, TE);
if Buckets /= null then
for I in Buckets'Range loop
declare
Next : Measure_Access;
Node : Measure_Access := Buckets (I);
begin
while Node /= null loop
Free (Node.Name);
Next := Node.Next;
Free (Node);
Node := Next;
end loop;
end;
end loop;
Free (Buckets);
end if;
end Finalize;
end Util.Measures;
|
-----------------------------------------------------------------------
-- measure -- Benchmark tools
-- Copyright (C) 2008 - 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.Task_Attributes;
with Ada.Strings.Hash;
with Ada.Unchecked_Deallocation;
with GNAT.Calendar.Time_IO;
with Util.Streams.Buffered;
with Util.Streams.Texts.TR;
package body Util.Measures is
ISO_DATE_TIME : constant GNAT.Calendar.Time_IO.Picture_String := "%Y-%m-%d %H:%M:%S";
procedure Free is
new Ada.Unchecked_Deallocation (Buckets_Type, Buckets_Access);
procedure Free is
new Ada.Unchecked_Deallocation (Measure, Measure_Access);
procedure Free is
new Ada.Unchecked_Deallocation (String, String_Access);
package Task_Context is new Ada.Task_Attributes
(Measure_Set_Access, null);
function Format (D : in Duration) return String;
-- Format the duration in a time in 'ns', 'us', 'ms' or seconds.
function Format (D : in Duration;
Unit : in Unit_Type) return String;
-- ------------------------------
-- Disable collecting measures on the measure set.
-- ------------------------------
procedure Disable (Measures : in out Measure_Set) is
begin
Measures.Enabled := False;
end Disable;
-- ------------------------------
-- Enable collecting measures on the measure set.
-- ------------------------------
procedure Enable (Measures : in out Measure_Set) is
begin
Measures.Enabled := True;
end Enable;
-- ------------------------------
-- Set the per-thread measure set.
-- ------------------------------
procedure Set_Current (Measures : in Measure_Set_Access) is
begin
Task_Context.Set_Value (Measures);
end Set_Current;
-- ------------------------------
-- Get the per-thread measure set.
-- ------------------------------
function Get_Current return Measure_Set_Access is
begin
return Task_Context.Value;
end Get_Current;
-- ------------------------------
-- Dump an XML result with the measures collected by the measure set.
-- When writing the measures, the measure set is cleared. It is safe
-- to write measures while other measures are being collected.
-- ------------------------------
procedure Write (Measures : in out Measure_Set;
Title : in String;
Stream : in out Util.Streams.Texts.Print_Stream'Class) is
procedure Dump_XML (Item : in Measure_Access);
procedure Dump_XML (Item : in Measure_Access) is
Total : constant String := Format (Item.Time);
Time : constant String := Format (Item.Time / Item.Count);
begin
Stream.Write ("<time count=""");
Stream.Write (Item.Count);
Stream.Write (""" time=""");
Stream.Write (Time (Time'First + 1 .. Time'Last));
if Item.Count > 1 then
Stream.Write (""" total=""");
Stream.Write (Total (Total'First + 1 .. Total'Last));
end if;
Stream.Write (""" title=""");
Util.Streams.Texts.TR.Escape_Java_Script (Into => Stream,
Content => Item.Name.all);
Stream.Write ("""/>");
Stream.Write (ASCII.LF);
end Dump_XML;
Buckets : Buckets_Access;
TS, TE : Ada.Calendar.Time;
begin
Measures.Data.Steal_Map (Buckets, TS, TE);
Stream.Write ("<measures title=""");
Util.Streams.Texts.TR.Escape_Java_Script (Into => Stream,
Content => Title);
Stream.Write (""" start=""");
Stream.Write (TS, ISO_DATE_TIME);
Stream.Write (""" end=""");
Stream.Write (TE, ISO_DATE_TIME);
Stream.Write (""">");
if Buckets /= null then
Stream.Write (ASCII.LF);
begin
for I in Buckets'Range loop
declare
Next : Measure_Access;
Node : Measure_Access := Buckets (I);
begin
while Node /= null loop
Dump_XML (Node);
Free (Node.Name);
Next := Node.Next;
Free (Node);
Node := Next;
end loop;
end;
end loop;
exception
when others =>
Free (Buckets);
raise;
end;
Free (Buckets);
end if;
Stream.Write ("</measures>");
end Write;
-- ------------------------------
-- Dump an XML result with the measures collected by the measure set.
-- ------------------------------
procedure Write (Measures : in out Measure_Set;
Title : in String;
Stream : in Ada.Text_IO.File_Type) is
Buffer : aliased Util.Streams.Buffered.Output_Buffer_Stream;
Output : Util.Streams.Texts.Print_Stream;
begin
Buffer.Initialize (Size => 128 * 1024);
Output.Initialize (To => Buffer'Access);
Write (Measures, Title, Output);
Output.Flush;
Ada.Text_IO.Put_Line (Stream, Util.Streams.Texts.To_String (Buffer));
end Write;
-- ------------------------------
-- Dump an XML result with the measures in a file.
-- ------------------------------
procedure Write (Measures : in out Measure_Set;
Title : in String;
Path : in String) is
File : Ada.Text_IO.File_Type;
begin
Ada.Text_IO.Create (File => File, Name => Path);
Write (Measures, Title, File);
Ada.Text_IO.Close (File);
exception
when others =>
if Ada.Text_IO.Is_Open (File) then
Ada.Text_IO.Close (File);
end if;
raise;
end Write;
-- ------------------------------
-- Report the time spent between the stamp creation and this method call.
-- Collect the result in the per-thread measure set under the given measure
-- title.
-- ------------------------------
procedure Report (S : in out Stamp;
Title : in String;
Count : in Positive := 1) is
Measures : constant Measure_Set_Access := Task_Context.Value;
begin
if Measures /= null and then Measures.Enabled then
Report (Measures.all, S, Title, Count);
end if;
end Report;
-- ------------------------------
-- Report the time spent between the stamp creation and this method call.
-- Collect the result in the measure set under the given measure title.
-- ------------------------------
procedure Report (Measures : in out Measure_Set;
S : in out Stamp;
Title : in String;
Count : in Positive := 1) is
use Ada.Calendar;
begin
if Measures.Enabled then
declare
D : constant Duration := Ada.Calendar.Clock - S.Start;
begin
Measures.Data.Add (Title, D, Count);
end;
S.Start := Ada.Calendar.Clock;
end if;
end Report;
-- ------------------------------
-- Report the time spent between the stamp creation and this method call.
-- The report is written in the file with the given title. The duration is
-- expressed in the unit defined in <tt>Unit</tt>.
-- ------------------------------
procedure Report (S : in out Stamp;
File : in out Ada.Text_IO.File_Type;
Title : in String;
Unit : in Unit_Type := Microseconds) is
use Ada.Calendar;
D : constant Duration := Ada.Calendar.Clock - S.Start;
begin
Ada.Text_IO.Put (File, Title);
Ada.Text_IO.Put (File, Format (D, Unit));
S.Start := Ada.Calendar.Clock;
end Report;
protected body Measure_Data is
-- ------------------------------
-- Get the measures and clear to start a new set of measures.
-- Return in <b>Time_Start</b> and <b>Time_End</b> the period of time.
-- ------------------------------
procedure Steal_Map (Result : out Buckets_Access;
Time_Start : out Ada.Calendar.Time;
Time_End : out Ada.Calendar.Time) is
begin
Result := Buckets;
Time_Start := Start;
Start := Ada.Calendar.Clock;
Time_End := Start;
Buckets := null;
end Steal_Map;
-- ------------------------------
-- Add the measure
-- ------------------------------
procedure Add (Title : in String;
D : in Duration;
Count : in Positive := 1) is
use Ada.Containers;
Pos : Hash_Type;
Node : Measure_Access;
begin
if Buckets = null then
Buckets := new Buckets_Type (0 .. 256);
end if;
Pos := Ada.Strings.Hash (Title) mod Buckets'Length;
Node := Buckets (Pos);
while Node /= null loop
if Node.Name'Length = Title'Length
and then Node.Name.all = Title
then
Node.Count := Node.Count + Count;
Node.Time := Node.Time + D;
return;
end if;
Node := Node.Next;
end loop;
Buckets (Pos) := new Measure '(Name => new String '(Title),
Time => D,
Count => Count,
Next => Buckets (Pos));
end Add;
end Measure_Data;
-- ------------------------------
-- Format the duration in a time in 'ns', 'us', 'ms' or seconds.
-- ------------------------------
function Format (D : in Duration) return String is
begin
if D < 0.000_001 then
return Duration'Image (D * 1_000_000_000) (1 .. 6) & " ns";
elsif D < 0.001 then
return Duration'Image (D * 1_000_000) (1 .. 6) & " us";
elsif D < 1.0 then
return Duration'Image (D * 1_000) (1 .. 6) & " ms";
else
return Duration'Image (D) (1 .. 6) & " s";
end if;
end Format;
-- ------------------------------
-- Format the duration in a time in 'ns', 'us', 'ms' or seconds.
-- ------------------------------
function Format (D : in Duration;
Unit : in Unit_Type) return String is
begin
case Unit is
when Seconds =>
return Duration'Image (D);
when Milliseconds =>
return Duration'Image (D * 1_000);
when Microseconds =>
return Duration'Image (D * 1_000_000);
when Nanoseconds =>
return Duration'Image (D * 1_000_000_000);
end case;
end Format;
-- ------------------------------
-- Finalize the measures and release the storage.
-- ------------------------------
overriding
procedure Finalize (Measures : in out Measure_Set) is
Buckets : Buckets_Access;
TS, TE : Ada.Calendar.Time;
begin
-- When deleting the measure set, we have to release the buckets and measures
-- that were allocated. We could call <b>Write</b> but we don't know where
-- the measures have to be written.
Measures.Data.Steal_Map (Buckets, TS, TE);
if Buckets /= null then
for I in Buckets'Range loop
declare
Next : Measure_Access;
Node : Measure_Access := Buckets (I);
begin
while Node /= null loop
Free (Node.Name);
Next := Node.Next;
Free (Node);
Node := Next;
end loop;
end;
end loop;
Free (Buckets);
end if;
end Finalize;
end Util.Measures;
|
Replace an Unchecked_Access by an Access
|
Replace an Unchecked_Access by an Access
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
c1e299983a99865d31265ff7257b707bc8c1d141
|
src/util-streams-pipes.ads
|
src/util-streams-pipes.ads
|
-----------------------------------------------------------------------
-- util-streams-pipes -- Pipe stream to or from a process
-- Copyright (C) 2011, 2013, 2015, 2016 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Finalization;
with Util.Processes;
-- The <b>Util.Streams.Pipes</b> package defines a pipe stream to or from a process.
-- The process is created and launched by the <b>Open</b> operation. The pipe allows
-- to read or write to the process through the <b>Read</b> and <b>Write</b> operation.
package Util.Streams.Pipes is
use Util.Processes;
subtype Pipe_Mode is Util.Processes.Pipe_Mode range READ .. READ_WRITE;
-- -----------------------
-- Pipe stream
-- -----------------------
-- The <b>Pipe_Stream</b> is an output/input stream that reads or writes
-- to or from a process.
type Pipe_Stream is limited new Output_Stream and Input_Stream with private;
-- Set the shell executable path to use to launch a command. The default on Unix is
-- the /bin/sh command. Argument splitting is done by the /bin/sh -c command.
-- When setting an empty shell command, the argument splitting is done by the
-- <tt>Spawn</tt> procedure.
procedure Set_Shell (Stream : in out Pipe_Stream;
Shell : in String);
-- Open a pipe to read or write to an external process. The pipe is created and the
-- command is executed with the input and output streams redirected through the pipe.
procedure Open (Stream : in out Pipe_Stream;
Command : in String;
Mode : in Pipe_Mode := READ);
-- Close the pipe and wait for the external process to terminate.
overriding
procedure Close (Stream : in out Pipe_Stream);
-- Get the process exit status.
function Get_Exit_Status (Stream : in Pipe_Stream) return Integer;
-- Returns True if the process is running.
function Is_Running (Stream : in Pipe_Stream) return Boolean;
-- Write the buffer array to the output stream.
overriding
procedure Write (Stream : in out Pipe_Stream;
Buffer : in Ada.Streams.Stream_Element_Array);
-- Read into the buffer as many bytes as possible and return in
-- <b>last</b> the position of the last byte read.
overriding
procedure Read (Stream : in out Pipe_Stream;
Into : out Ada.Streams.Stream_Element_Array;
Last : out Ada.Streams.Stream_Element_Offset);
private
use Ada.Streams;
type Pipe_Stream is limited new Ada.Finalization.Limited_Controlled
and Output_Stream and Input_Stream with record
Proc : Util.Processes.Process;
end record;
-- Flush the stream and release the buffer.
overriding
procedure Finalize (Object : in out Pipe_Stream);
end Util.Streams.Pipes;
|
-----------------------------------------------------------------------
-- util-streams-pipes -- Pipe stream to or from a process
-- Copyright (C) 2011, 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 Ada.Finalization;
with Util.Processes;
-- The <b>Util.Streams.Pipes</b> package defines a pipe stream to or from a process.
-- The process is created and launched by the <b>Open</b> operation. The pipe allows
-- to read or write to the process through the <b>Read</b> and <b>Write</b> operation.
package Util.Streams.Pipes is
use Util.Processes;
subtype Pipe_Mode is Util.Processes.Pipe_Mode range READ .. READ_WRITE;
-- -----------------------
-- Pipe stream
-- -----------------------
-- The <b>Pipe_Stream</b> is an output/input stream that reads or writes
-- to or from a process.
type Pipe_Stream is limited new Output_Stream and Input_Stream with private;
-- Set the shell executable path to use to launch a command. The default on Unix is
-- the /bin/sh command. Argument splitting is done by the /bin/sh -c command.
-- When setting an empty shell command, the argument splitting is done by the
-- <tt>Spawn</tt> procedure.
procedure Set_Shell (Stream : in out Pipe_Stream;
Shell : in String);
-- Before launching the process, redirect the input stream of the process
-- to the specified file.
-- Raises <b>Invalid_State</b> if the process is running.
procedure Set_Input_Stream (Stream : in out Pipe_Stream;
File : in String);
-- Set the output stream of the process.
-- Raises <b>Invalid_State</b> if the process is running.
procedure Set_Output_Stream (Stream : in out Pipe_Stream;
File : in String;
Append : in Boolean := False);
-- Set the error stream of the process.
-- Raises <b>Invalid_State</b> if the process is running.
procedure Set_Error_Stream (Stream : in out Pipe_Stream;
File : in String;
Append : in Boolean := False);
-- Set the working directory that the process will use once it is created.
-- The directory must exist or the <b>Invalid_Directory</b> exception will be raised.
procedure Set_Working_Directory (Stream : in out Pipe_Stream;
Path : in String);
-- Open a pipe to read or write to an external process. The pipe is created and the
-- command is executed with the input and output streams redirected through the pipe.
procedure Open (Stream : in out Pipe_Stream;
Command : in String;
Mode : in Pipe_Mode := READ);
-- Close the pipe and wait for the external process to terminate.
overriding
procedure Close (Stream : in out Pipe_Stream);
-- Get the process exit status.
function Get_Exit_Status (Stream : in Pipe_Stream) return Integer;
-- Returns True if the process is running.
function Is_Running (Stream : in Pipe_Stream) return Boolean;
-- Write the buffer array to the output stream.
overriding
procedure Write (Stream : in out Pipe_Stream;
Buffer : in Ada.Streams.Stream_Element_Array);
-- Read into the buffer as many bytes as possible and return in
-- <b>last</b> the position of the last byte read.
overriding
procedure Read (Stream : in out Pipe_Stream;
Into : out Ada.Streams.Stream_Element_Array;
Last : out Ada.Streams.Stream_Element_Offset);
private
use Ada.Streams;
type Pipe_Stream is limited new Ada.Finalization.Limited_Controlled
and Output_Stream and Input_Stream with record
Proc : Util.Processes.Process;
end record;
-- Flush the stream and release the buffer.
overriding
procedure Finalize (Object : in out Pipe_Stream);
end Util.Streams.Pipes;
|
Declare Set_Input_Stream, Set_Output_Stream, Set_Error_Stream, Set_Working_Directory procedures to allow a better control of the underlying process that will be started by the Open call
|
Declare Set_Input_Stream, Set_Output_Stream, Set_Error_Stream, Set_Working_Directory procedures
to allow a better control of the underlying process that will be started by the Open call
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
9cb79ad70940a505dec5c70d43b7afeff37d64c7
|
src/util-streams-pipes.ads
|
src/util-streams-pipes.ads
|
-----------------------------------------------------------------------
-- util-streams-pipes -- Pipe stream to or from a process
-- Copyright (C) 2011, 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 Ada.Finalization;
with Util.Processes;
-- == Pipes ==
-- The `Util.Streams.Pipes` package defines a pipe stream to or from a process.
-- It allows to launch an external program while getting the program standard output or
-- providing the program standard input. The `Pipe_Stream` type represents the input or
-- output stream for the external program. This is a portable interface that works on
-- Unix and Windows.
--
-- The process is created and launched by the `Open` operation. The pipe allows
-- to read or write to the process through the `Read` and `Write` operation.
-- It is very close to the *popen* operation provided by the C stdio library.
-- First, create the pipe instance:
--
-- with Util.Streams.Pipes;
-- ...
-- Pipe : aliased Util.Streams.Pipes.Pipe_Stream;
--
-- The pipe instance can be associated with only one process at a time.
-- The process is launched by using the `Open` command and by specifying the command
-- to execute as well as the pipe redirection mode:
--
-- * `READ` to read the process standard output,
-- * `WRITE` to write the process standard input.
--
-- For example to run the `ls -l` command and read its output, we could run it by using:
--
-- Pipe.Open (Command => "ls -l", Mode => Util.Processes.READ);
--
-- The `Pipe_Stream` is not buffered and a buffer can be configured easily by using the
-- `Input_Buffer_Stream` type and connecting the buffer to the pipe so that it reads
-- the pipe to fill the buffer. The initialization of the buffer is the following:
--
-- with Util.Streams.Buffered;
-- ...
-- Buffer : Util.Streams.Buffered.Input_Buffer_Stream;
-- ...
-- Buffer.Initialize (Input => Pipe'Unchecked_Access, Size => 1024);
--
-- And to read the process output, one can use the following:
--
-- Content : Ada.Strings.Unbounded.Unbounded_String;
-- ...
-- Buffer.Read (Into => Content);
--
-- The pipe object should be closed when reading or writing to it is finished.
-- By closing the pipe, the caller will wait for the termination of the process.
-- The process exit status can be obtained by using the `Get_Exit_Status` function.
--
-- Pipe.Close;
-- if Pipe.Get_Exit_Status /= 0 then
-- Ada.Text_IO.Put_Line ("Command exited with status "
-- & Integer'Image (Pipe.Get_Exit_Status));
-- end if;
--
-- You will note that the `Pipe_Stream` is a limited type and thus cannot be copied.
-- When leaving the scope of the `Pipe_Stream` instance, the application will wait for
-- the process to terminate.
--
-- Before opening the pipe, it is possible to have some control on the process that
-- will be created to configure:
--
-- * The shell that will be used to launch the process,
-- * The process working directory,
-- * Redirect the process output to a file,
-- * Redirect the process error to a file,
-- * Redirect the process input from a file.
--
-- All these operations must be made before calling the `Open` procedure.
package Util.Streams.Pipes is
use Util.Processes;
subtype Pipe_Mode is Util.Processes.Pipe_Mode range READ .. READ_WRITE;
-- -----------------------
-- Pipe stream
-- -----------------------
-- The <b>Pipe_Stream</b> is an output/input stream that reads or writes
-- to or from a process.
type Pipe_Stream is limited new Output_Stream and Input_Stream with private;
-- Set the shell executable path to use to launch a command. The default on Unix is
-- the /bin/sh command. Argument splitting is done by the /bin/sh -c command.
-- When setting an empty shell command, the argument splitting is done by the
-- <tt>Spawn</tt> procedure.
procedure Set_Shell (Stream : in out Pipe_Stream;
Shell : in String);
-- Before launching the process, redirect the input stream of the process
-- to the specified file.
-- Raises <b>Invalid_State</b> if the process is running.
procedure Set_Input_Stream (Stream : in out Pipe_Stream;
File : in String);
-- Set the output stream of the process.
-- Raises <b>Invalid_State</b> if the process is running.
procedure Set_Output_Stream (Stream : in out Pipe_Stream;
File : in String;
Append : in Boolean := False);
-- Set the error stream of the process.
-- Raises <b>Invalid_State</b> if the process is running.
procedure Set_Error_Stream (Stream : in out Pipe_Stream;
File : in String;
Append : in Boolean := False);
-- Set the working directory that the process will use once it is created.
-- The directory must exist or the <b>Invalid_Directory</b> exception will be raised.
procedure Set_Working_Directory (Stream : in out Pipe_Stream;
Path : in String);
-- Open a pipe to read or write to an external process. The pipe is created and the
-- command is executed with the input and output streams redirected through the pipe.
procedure Open (Stream : in out Pipe_Stream;
Command : in String;
Mode : in Pipe_Mode := READ);
-- Close the pipe and wait for the external process to terminate.
overriding
procedure Close (Stream : in out Pipe_Stream);
-- Get the process exit status.
function Get_Exit_Status (Stream : in Pipe_Stream) return Integer;
-- Returns True if the process is running.
function Is_Running (Stream : in Pipe_Stream) return Boolean;
-- Write the buffer array to the output stream.
overriding
procedure Write (Stream : in out Pipe_Stream;
Buffer : in Ada.Streams.Stream_Element_Array);
-- Read into the buffer as many bytes as possible and return in
-- <b>last</b> the position of the last byte read.
overriding
procedure Read (Stream : in out Pipe_Stream;
Into : out Ada.Streams.Stream_Element_Array;
Last : out Ada.Streams.Stream_Element_Offset);
private
use Ada.Streams;
type Pipe_Stream is limited new Ada.Finalization.Limited_Controlled
and Output_Stream and Input_Stream with record
Proc : Util.Processes.Process;
end record;
-- Flush the stream and release the buffer.
overriding
procedure Finalize (Object : in out Pipe_Stream);
end Util.Streams.Pipes;
|
-----------------------------------------------------------------------
-- util-streams-pipes -- Pipe stream to or from a process
-- Copyright (C) 2011, 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 Ada.Finalization;
with Util.Processes;
-- == Pipes ==
-- The `Util.Streams.Pipes` package defines a pipe stream to or from a process.
-- It allows to launch an external program while getting the program standard output or
-- providing the program standard input. The `Pipe_Stream` type represents the input or
-- output stream for the external program. This is a portable interface that works on
-- Unix and Windows.
--
-- The process is created and launched by the `Open` operation. The pipe allows
-- to read or write to the process through the `Read` and `Write` operation.
-- It is very close to the *popen* operation provided by the C stdio library.
-- First, create the pipe instance:
--
-- with Util.Streams.Pipes;
-- ...
-- Pipe : aliased Util.Streams.Pipes.Pipe_Stream;
--
-- The pipe instance can be associated with only one process at a time.
-- The process is launched by using the `Open` command and by specifying the command
-- to execute as well as the pipe redirection mode:
--
-- * `READ` to read the process standard output,
-- * `WRITE` to write the process standard input.
--
-- For example to run the `ls -l` command and read its output, we could run it by using:
--
-- Pipe.Open (Command => "ls -l", Mode => Util.Processes.READ);
--
-- The `Pipe_Stream` is not buffered and a buffer can be configured easily by using the
-- `Input_Buffer_Stream` type and connecting the buffer to the pipe so that it reads
-- the pipe to fill the buffer. The initialization of the buffer is the following:
--
-- with Util.Streams.Buffered;
-- ...
-- Buffer : Util.Streams.Buffered.Input_Buffer_Stream;
-- ...
-- Buffer.Initialize (Input => Pipe'Unchecked_Access, Size => 1024);
--
-- And to read the process output, one can use the following:
--
-- Content : Ada.Strings.Unbounded.Unbounded_String;
-- ...
-- Buffer.Read (Into => Content);
--
-- The pipe object should be closed when reading or writing to it is finished.
-- By closing the pipe, the caller will wait for the termination of the process.
-- The process exit status can be obtained by using the `Get_Exit_Status` function.
--
-- Pipe.Close;
-- if Pipe.Get_Exit_Status /= 0 then
-- Ada.Text_IO.Put_Line ("Command exited with status "
-- & Integer'Image (Pipe.Get_Exit_Status));
-- end if;
--
-- You will note that the `Pipe_Stream` is a limited type and thus cannot be copied.
-- When leaving the scope of the `Pipe_Stream` instance, the application will wait for
-- the process to terminate.
--
-- Before opening the pipe, it is possible to have some control on the process that
-- will be created to configure:
--
-- * The shell that will be used to launch the process,
-- * The process working directory,
-- * Redirect the process output to a file,
-- * Redirect the process error to a file,
-- * Redirect the process input from a file.
--
-- All these operations must be made before calling the `Open` procedure.
package Util.Streams.Pipes is
use Util.Processes;
subtype Pipe_Mode is Util.Processes.Pipe_Mode range READ .. READ_WRITE;
-- -----------------------
-- Pipe stream
-- -----------------------
-- The <b>Pipe_Stream</b> is an output/input stream that reads or writes
-- to or from a process.
type Pipe_Stream is limited new Output_Stream and Input_Stream with private;
-- Set the shell executable path to use to launch a command. The default on Unix is
-- the /bin/sh command. Argument splitting is done by the /bin/sh -c command.
-- When setting an empty shell command, the argument splitting is done by the
-- <tt>Spawn</tt> procedure.
procedure Set_Shell (Stream : in out Pipe_Stream;
Shell : in String);
-- Before launching the process, redirect the input stream of the process
-- to the specified file.
-- Raises <b>Invalid_State</b> if the process is running.
procedure Set_Input_Stream (Stream : in out Pipe_Stream;
File : in String);
-- Set the output stream of the process.
-- Raises <b>Invalid_State</b> if the process is running.
procedure Set_Output_Stream (Stream : in out Pipe_Stream;
File : in String;
Append : in Boolean := False);
-- Set the error stream of the process.
-- Raises <b>Invalid_State</b> if the process is running.
procedure Set_Error_Stream (Stream : in out Pipe_Stream;
File : in String;
Append : in Boolean := False);
-- Set the working directory that the process will use once it is created.
-- The directory must exist or the <b>Invalid_Directory</b> exception will be raised.
procedure Set_Working_Directory (Stream : in out Pipe_Stream;
Path : in String);
-- Closes the given file descriptor in the child process before executing the command.
procedure Add_Close (Stream : in out Pipe_Stream;
Fd : in Util.Processes.File_Type);
-- Open a pipe to read or write to an external process. The pipe is created and the
-- command is executed with the input and output streams redirected through the pipe.
procedure Open (Stream : in out Pipe_Stream;
Command : in String;
Mode : in Pipe_Mode := READ);
-- Close the pipe and wait for the external process to terminate.
overriding
procedure Close (Stream : in out Pipe_Stream);
-- Get the process exit status.
function Get_Exit_Status (Stream : in Pipe_Stream) return Integer;
-- Returns True if the process is running.
function Is_Running (Stream : in Pipe_Stream) return Boolean;
-- Write the buffer array to the output stream.
overriding
procedure Write (Stream : in out Pipe_Stream;
Buffer : in Ada.Streams.Stream_Element_Array);
-- Read into the buffer as many bytes as possible and return in
-- <b>last</b> the position of the last byte read.
overriding
procedure Read (Stream : in out Pipe_Stream;
Into : out Ada.Streams.Stream_Element_Array;
Last : out Ada.Streams.Stream_Element_Offset);
private
use Ada.Streams;
type Pipe_Stream is limited new Ada.Finalization.Limited_Controlled
and Output_Stream and Input_Stream with record
Proc : Util.Processes.Process;
end record;
-- Flush the stream and release the buffer.
overriding
procedure Finalize (Object : in out Pipe_Stream);
end Util.Streams.Pipes;
|
Declare the Add_Close procedure
|
Declare the Add_Close procedure
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
40bb91ac7115b14ab74873cdb934cfc7695f801b
|
src/gen-model-mappings.ads
|
src/gen-model-mappings.ads
|
-----------------------------------------------------------------------
-- gen-model-mappings -- Type mappings for Code Generator
-- Copyright (C) 2011, 2012, 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Ada.Containers.Hashed_Maps;
with Ada.Strings.Unbounded.Hash;
with Util.Beans.Objects;
-- The <b>Gen.Model.Mappings</b> package controls the mappings to convert an XML
-- type into the Ada type.
package Gen.Model.Mappings is
ADA_MAPPING : constant String := "Ada05";
MySQL_MAPPING : constant String := "MySQL";
SQLite_MAPPING : constant String := "SQLite";
type Basic_Type is (T_BOOLEAN, T_INTEGER, T_DATE, T_ENUM, T_IDENTIFIER, T_STRING, T_BLOB,
T_BEAN, T_TABLE);
-- ------------------------------
-- Mapping Definition
-- ------------------------------
type Mapping_Definition;
type Mapping_Definition_Access is access all Mapping_Definition'Class;
type Mapping_Definition is new Definition with record
Target : Ada.Strings.Unbounded.Unbounded_String;
Kind : Basic_Type := T_INTEGER;
Allow_Null : Mapping_Definition_Access;
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 : Mapping_Definition;
Name : String) return Util.Beans.Objects.Object;
-- Find the mapping for the given type name.
function Find_Type (Name : in Ada.Strings.Unbounded.Unbounded_String;
Allow_Null : in Boolean)
return Mapping_Definition_Access;
procedure Register_Type (Name : in String;
Mapping : in Mapping_Definition_Access;
Kind : in Basic_Type);
-- Register a type mapping <b>From</b> that is mapped to <b>Target</b>.
procedure Register_Type (Target : in String;
From : in String;
Kind : in Basic_Type;
Allow_Null : in Boolean);
-- Setup the type mapping for the language identified by the given name.
procedure Set_Mapping_Name (Name : in String);
package Mapping_Maps is
new Ada.Containers.Hashed_Maps (Key_Type => Ada.Strings.Unbounded.Unbounded_String,
Element_Type => Mapping_Definition_Access,
Hash => Ada.Strings.Unbounded.Hash,
Equivalent_Keys => Ada.Strings.Unbounded."=");
subtype Map is Mapping_Maps.Map;
subtype Cursor is Mapping_Maps.Cursor;
end Gen.Model.Mappings;
|
-----------------------------------------------------------------------
-- gen-model-mappings -- Type mappings for Code Generator
-- Copyright (C) 2011, 2012, 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Ada.Containers.Hashed_Maps;
with Ada.Strings.Unbounded.Hash;
with Util.Beans.Objects;
-- The <b>Gen.Model.Mappings</b> package controls the mappings to convert an XML
-- type into the Ada type.
package Gen.Model.Mappings is
ADA_MAPPING : constant String := "Ada05";
MySQL_MAPPING : constant String := "MySQL";
SQLite_MAPPING : constant String := "SQLite";
type Basic_Type is (T_BOOLEAN, T_INTEGER, T_DATE, T_ENUM, T_IDENTIFIER, T_STRING, T_BLOB,
T_BEAN, T_TABLE);
-- ------------------------------
-- Mapping Definition
-- ------------------------------
type Mapping_Definition;
type Mapping_Definition_Access is access all Mapping_Definition'Class;
type Mapping_Definition is new Definition with record
Target : Ada.Strings.Unbounded.Unbounded_String;
Kind : Basic_Type := T_INTEGER;
Allow_Null : Mapping_Definition_Access;
Nullable : Boolean := False;
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 : Mapping_Definition;
Name : String) return Util.Beans.Objects.Object;
-- Find the mapping for the given type name.
function Find_Type (Name : in Ada.Strings.Unbounded.Unbounded_String;
Allow_Null : in Boolean)
return Mapping_Definition_Access;
procedure Register_Type (Name : in String;
Mapping : in Mapping_Definition_Access;
Kind : in Basic_Type);
-- Register a type mapping <b>From</b> that is mapped to <b>Target</b>.
procedure Register_Type (Target : in String;
From : in String;
Kind : in Basic_Type;
Allow_Null : in Boolean);
-- Setup the type mapping for the language identified by the given name.
procedure Set_Mapping_Name (Name : in String);
package Mapping_Maps is
new Ada.Containers.Hashed_Maps (Key_Type => Ada.Strings.Unbounded.Unbounded_String,
Element_Type => Mapping_Definition_Access,
Hash => Ada.Strings.Unbounded.Hash,
Equivalent_Keys => Ada.Strings.Unbounded."=");
subtype Map is Mapping_Maps.Map;
subtype Cursor is Mapping_Maps.Cursor;
end Gen.Model.Mappings;
|
Add Nullable boolean value to the Mapping_Definition
|
Add Nullable boolean value to the Mapping_Definition
|
Ada
|
apache-2.0
|
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
|
f56154e456ab53c1ebbba5c2f81acd1840e79d91
|
mat/src/mat-expressions.ads
|
mat/src/mat-expressions.ads
|
-----------------------------------------------------------------------
-- mat-expressions -- Expressions for memory slot selection
-- Copyright (C) 2014 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
private with Util.Concurrent.Counters;
with MAT.Types;
with MAT.Memory;
package MAT.Expressions is
type Context_Type is record
Addr : MAT.Types.Target_Addr;
Allocation : MAT.Memory.Allocation;
end record;
type Inside_Type is (INSIDE_FILE, INSIDE_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 String;
Kind : in Inside_Type) return Expression_Type;
-- Create an size range expression node.
function Create_Size (Min : in MAT.Types.Target_Size;
Max : in MAT.Types.Target_Size) return Expression_Type;
-- Create an addr range expression node.
function Create_Addr (Min : in MAT.Types.Target_Addr;
Max : in MAT.Types.Target_Addr) return Expression_Type;
-- Create an time range expression node.
function Create_Time (Min : in MAT.Types.Target_Tick_Ref;
Max : in MAT.Types.Target_Tick_Ref) return Expression_Type;
-- Evaluate the expression to check if the memory slot described by the
-- context is selected. Returns True if the memory slot is selected.
function Is_Selected (Node : in Expression_Type;
Addr : in MAT.Types.Target_Addr;
Allocation : in MAT.Memory.Allocation) return Boolean;
private
type Kind_Type is (N_NOT, N_OR, N_AND, N_TRUE, N_FALSE,
N_IN_FILE, N_IN_FILE_DIRECT, N_INSIDE,
N_CALL_ADDR, N_CALL_ADDR_DIRECT,
N_IN_FUNC, N_IN_FUNC_DIRECT,
N_RANGE_SIZE, N_RANGE_ADDR,
N_RANGE_TIME,
N_CONDITION, N_THREAD);
type Node_Type;
type Node_Type_Access is access all Node_Type;
type Node_Type (Kind : Kind_Type) is record
Ref_Counter : Util.Concurrent.Counters.Counter;
case Kind is
when N_NOT =>
Expr : Node_Type_Access;
when N_OR | N_AND =>
Left, Right : Node_Type_Access;
when N_INSIDE | N_IN_FILE | N_IN_FILE_DIRECT | N_IN_FUNC | N_IN_FUNC_DIRECT =>
Name : Ada.Strings.Unbounded.Unbounded_String;
Inside : Inside_Type;
when N_RANGE_SIZE =>
Min_Size : MAT.Types.Target_Size;
Max_Size : MAT.Types.Target_Size;
when N_RANGE_ADDR | N_CALL_ADDR | N_CALL_ADDR_DIRECT =>
Min_Addr : MAT.Types.Target_Addr;
Max_Addr : MAT.Types.Target_Addr;
when N_RANGE_TIME =>
Min_Time : MAT.Types.Target_Tick_Ref;
Max_Time : MAT.Types.Target_Tick_Ref;
when N_THREAD =>
Thread : MAT.Types.Target_Thread_Ref;
when others =>
null;
end case;
end record;
-- Evaluate the node against the context. Returns True if the node expression
-- selects the memory slot defined by the context.
function Is_Selected (Node : in Node_Type;
Addr : in MAT.Types.Target_Addr;
Allocation : in MAT.Memory.Allocation) return Boolean;
type Expression_Type is tagged record
Node : Node_Type_Access;
end record;
end MAT.Expressions;
|
-----------------------------------------------------------------------
-- mat-expressions -- Expressions for memory slot selection
-- Copyright (C) 2014 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
private with Util.Concurrent.Counters;
with MAT.Types;
with MAT.Memory;
package MAT.Expressions is
type Context_Type is record
Addr : MAT.Types.Target_Addr;
Allocation : MAT.Memory.Allocation;
end record;
type Inside_Type is (INSIDE_FILE, INSIDE_FUNCTION);
type Expression_Type is tagged private;
-- Create a NOT expression node.
function Create_Not (Expr : in Expression_Type) return Expression_Type;
-- Create a AND expression node.
function Create_And (Left : in Expression_Type;
Right : in Expression_Type) return Expression_Type;
-- Create a OR expression node.
function Create_Or (Left : in Expression_Type;
Right : in Expression_Type) return Expression_Type;
-- Create an INSIDE expression node.
function Create_Inside (Name : in Ada.Strings.Unbounded.Unbounded_String;
Kind : in Inside_Type) return Expression_Type;
-- Create an size range expression node.
function Create_Size (Min : in MAT.Types.Target_Size;
Max : in MAT.Types.Target_Size) return Expression_Type;
-- Create an addr range expression node.
function Create_Addr (Min : in MAT.Types.Target_Addr;
Max : in MAT.Types.Target_Addr) return Expression_Type;
-- Create an time range expression node.
function Create_Time (Min : in MAT.Types.Target_Tick_Ref;
Max : in MAT.Types.Target_Tick_Ref) return Expression_Type;
-- Evaluate the expression to check if the memory slot described by the
-- context is selected. Returns True if the memory slot is selected.
function Is_Selected (Node : in Expression_Type;
Addr : in MAT.Types.Target_Addr;
Allocation : in MAT.Memory.Allocation) return Boolean;
private
type Kind_Type is (N_NOT, N_OR, N_AND, N_TRUE, N_FALSE,
N_IN_FILE, N_IN_FILE_DIRECT, N_INSIDE,
N_CALL_ADDR, N_CALL_ADDR_DIRECT,
N_IN_FUNC, N_IN_FUNC_DIRECT,
N_RANGE_SIZE, N_RANGE_ADDR,
N_RANGE_TIME,
N_CONDITION, N_THREAD);
type Node_Type;
type Node_Type_Access is access all Node_Type;
type Node_Type (Kind : Kind_Type) is record
Ref_Counter : Util.Concurrent.Counters.Counter;
case Kind is
when N_NOT =>
Expr : Node_Type_Access;
when N_OR | N_AND =>
Left, Right : Node_Type_Access;
when N_INSIDE | N_IN_FILE | N_IN_FILE_DIRECT | N_IN_FUNC | N_IN_FUNC_DIRECT =>
Name : Ada.Strings.Unbounded.Unbounded_String;
Inside : Inside_Type;
when N_RANGE_SIZE =>
Min_Size : MAT.Types.Target_Size;
Max_Size : MAT.Types.Target_Size;
when N_RANGE_ADDR | N_CALL_ADDR | N_CALL_ADDR_DIRECT =>
Min_Addr : MAT.Types.Target_Addr;
Max_Addr : MAT.Types.Target_Addr;
when N_RANGE_TIME =>
Min_Time : MAT.Types.Target_Tick_Ref;
Max_Time : MAT.Types.Target_Tick_Ref;
when N_THREAD =>
Thread : MAT.Types.Target_Thread_Ref;
when others =>
null;
end case;
end record;
-- Evaluate the node against the context. Returns True if the node expression
-- selects the memory slot defined by the context.
function Is_Selected (Node : in Node_Type;
Addr : in MAT.Types.Target_Addr;
Allocation : in MAT.Memory.Allocation) return Boolean;
type Expression_Type is tagged record
Node : Node_Type_Access;
end record;
end MAT.Expressions;
|
Change Create_Inside to use an Ada.Strings.Unbounded.Unbounded_String type
|
Change Create_Inside to use an Ada.Strings.Unbounded.Unbounded_String type
|
Ada
|
apache-2.0
|
stcarrez/mat,stcarrez/mat,stcarrez/mat
|
fd33bc6313a9eafb096f60c6cc0d7a4bcf459cce
|
regtests/ado-schemas-tests.adb
|
regtests/ado-schemas-tests.adb
|
-----------------------------------------------------------------------
-- schemas Tests -- Test loading of database schema
-- Copyright (C) 2009, 2010, 2011, 2012, 2015, 2017, 2018 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Test_Caller;
with Util.Strings.Vectors;
with Util.Strings.Transforms;
with ADO.Configs;
with ADO.Schemas.Databases;
with ADO.Sessions.Sources;
with ADO.Schemas.Entities;
with Regtests;
with Regtests.Simple.Model;
package body ADO.Schemas.Tests is
use Util.Tests;
function To_Lower_Case (S : in String) return String
renames Util.Strings.Transforms.To_Lower_Case;
package Caller is new Util.Test_Caller (Test, "ADO.Schemas");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test ADO.Schemas.Entities.Find_Entity_Type",
Test_Find_Entity_Type'Access);
Caller.Add_Test (Suite, "Test ADO.Schemas.Entities.Find_Entity_Type (error)",
Test_Find_Entity_Type_Error'Access);
Caller.Add_Test (Suite, "Test ADO.Sessions.Load_Schema",
Test_Load_Schema'Access);
Caller.Add_Test (Suite, "Test ADO.Schemas.Get_Table",
Test_Table_Iterator'Access);
Caller.Add_Test (Suite, "Test ADO.Schemas.Get_Table (Empty schema)",
Test_Empty_Schema'Access);
Caller.Add_Test (Suite, "Test ADO.Schemas.Databases.Create_Database",
Test_Create_Schema'Access);
end Add_Tests;
-- ------------------------------
-- Test reading the entity cache and the Find_Entity_Type operation
-- ------------------------------
procedure Test_Find_Entity_Type (T : in out Test) is
S : ADO.Sessions.Session := Regtests.Get_Database;
C : ADO.Schemas.Entities.Entity_Cache;
begin
ADO.Schemas.Entities.Initialize (Cache => C,
Session => S);
declare
-- T1 : constant ADO.Model.Entity_Type_Ref
-- := Entities.Find_Entity_Type (Cache => C,
-- Table => Regtests.Simple.Model.USER_TABLE'Access);
-- T2 : constant ADO.Model.Entity_Type_Ref
-- := Entities.Find_Entity_Type (Cache => C,
-- Table => Regtests.Simple.Model.ALLOCATE_TABLE'Access);
T4 : constant ADO.Entity_Type
:= Entities.Find_Entity_Type (Cache => C,
Table => Regtests.Simple.Model.ALLOCATE_TABLE);
T5 : constant ADO.Entity_Type
:= Entities.Find_Entity_Type (Cache => C,
Table => Regtests.Simple.Model.USER_TABLE);
begin
-- T.Assert (not ADO.Objects.Is_Null (T1), "Find_Entity_Type returned a null value");
-- T.Assert (not ADO.Objects.Is_Null (T2), "Find_Entity_Type returned a null value");
T.Assert (T4 /= T5, "Two distinct tables have different entity types");
T.Assert (T4 > 0, "T1.Id must be positive");
T.Assert (T5 > 0, "T2.Id must be positive");
-- T.Assert (T1.Get_Id /= T2.Get_Id, "Two distinct tables have different ids");
--
-- Assert_Equals (T, Integer (T2.Get_Id), Integer (T4),
-- "Invalid entity type for allocate_table");
-- Assert_Equals (T, Integer (T1.Get_Id), Integer (T5),
-- "Invalid entity type for user_table");
end;
end Test_Find_Entity_Type;
-- ------------------------------
-- Test calling Find_Entity_Type with an invalid table.
-- ------------------------------
procedure Test_Find_Entity_Type_Error (T : in out Test) is
C : ADO.Schemas.Entities.Entity_Cache;
begin
declare
R : ADO.Entity_Type;
pragma Unreferenced (R);
begin
R := Entities.Find_Entity_Type (Cache => C,
Table => Regtests.Simple.Model.USER_TABLE);
T.Assert (False, "Find_Entity_Type did not raise the No_Entity_Type exception");
exception
when ADO.Schemas.Entities.No_Entity_Type =>
null;
end;
end Test_Find_Entity_Type_Error;
-- ------------------------------
-- Test the Load_Schema operation and check the result schema.
-- ------------------------------
procedure Test_Load_Schema (T : in out Test) is
S : constant ADO.Sessions.Session := Regtests.Get_Database;
Schema : Schema_Definition;
Table : Table_Definition;
begin
S.Load_Schema (Schema);
Table := ADO.Schemas.Find_Table (Schema, "allocate");
T.Assert (Table /= null, "Table schema for test_allocate not found");
Assert_Equals (T, "allocate", Get_Name (Table));
declare
C : Column_Cursor := Get_Columns (Table);
Nb_Columns : Integer := 0;
begin
while Has_Element (C) loop
Nb_Columns := Nb_Columns + 1;
Next (C);
end loop;
Assert_Equals (T, 3, Nb_Columns, "Invalid number of columns");
end;
declare
C : constant Column_Definition := Find_Column (Table, "ID");
begin
T.Assert (C /= null, "Cannot find column 'id' in table schema");
Assert_Equals (T, "id", To_Lower_Case (Get_Name (C)), "Invalid column name");
T.Assert (Get_Type (C) = T_LONG_INTEGER, "Invalid column type");
T.Assert (not Is_Null (C), "Column is null");
end;
declare
C : constant Column_Definition := Find_Column (Table, "NAME");
begin
T.Assert (C /= null, "Cannot find column 'NAME' in table schema");
Assert_Equals (T, "name", To_Lower_Case (Get_Name (C)), "Invalid column name");
T.Assert (Get_Type (C) = T_VARCHAR, "Invalid column type");
T.Assert (Is_Null (C), "Column is null");
end;
declare
C : constant Column_Definition := Find_Column (Table, "version");
begin
T.Assert (C /= null, "Cannot find column 'version' in table schema");
Assert_Equals (T, "version", To_Lower_Case (Get_Name (C)), "Invalid column name");
T.Assert (Get_Type (C) = T_INTEGER, "Invalid column type");
T.Assert (not Is_Null (C), "Column is null");
end;
declare
C : constant Column_Definition := Find_Column (Table, "this_column_does_not_exist");
begin
T.Assert (C = null, "Find_Column must return null for an unknown column");
end;
end Test_Load_Schema;
-- ------------------------------
-- Test the Table_Cursor operations and check the result schema.
-- ------------------------------
procedure Test_Table_Iterator (T : in out Test) is
S : constant ADO.Sessions.Session := Regtests.Get_Database;
Schema : Schema_Definition;
Table : Table_Definition;
Driver : constant String := S.Get_Driver.Get_Driver_Name;
begin
S.Load_Schema (Schema);
declare
Iter : Table_Cursor := Schema.Get_Tables;
Count : Natural := 0;
begin
T.Assert (Has_Element (Iter), "The Get_Tables returns an empty iterator");
while Has_Element (Iter) loop
Table := Element (Iter);
T.Assert (Table /= null, "Element function must not return null");
declare
Col_Iter : Column_Cursor := Get_Columns (Table);
begin
-- T.Assert (Has_Element (Col_Iter), "Table has a column");
while Has_Element (Col_Iter) loop
T.Assert (Element (Col_Iter) /= null, "Element function must not return null");
Next (Col_Iter);
end loop;
end;
Count := Count + 1;
Next (Iter);
end loop;
if Driver = "sqlite" then
Util.Tests.Assert_Equals (T, 15, Count,
"Invalid number of tables found in the schema");
elsif Driver = "mysql" then
Util.Tests.Assert_Equals (T, 8, Count,
"Invalid number of tables found in the schema");
elsif Driver = "postgresql" then
Util.Tests.Assert_Equals (T, 8, Count,
"Invalid number of tables found in the schema");
end if;
end;
end Test_Table_Iterator;
-- ------------------------------
-- Test the Table_Cursor operations on an empty schema.
-- ------------------------------
procedure Test_Empty_Schema (T : in out Test) is
Schema : Schema_Definition;
Iter : constant Table_Cursor := Schema.Get_Tables;
begin
T.Assert (not Has_Element (Iter), "The Get_Tables must return an empty iterator");
T.Assert (Schema.Find_Table ("test") = null, "The Find_Table must return null");
end Test_Empty_Schema;
-- ------------------------------
-- Test the creation of database.
-- ------------------------------
procedure Test_Create_Schema (T : in out Test) is
use ADO.Sessions.Sources;
Msg : Util.Strings.Vectors.Vector;
Cfg : Data_Source := Data_Source (Regtests.Get_Controller);
Path : constant String :=
"db/regtests/" & Cfg.Get_Driver & "/create-ado-" & Cfg.Get_Driver & ".sql";
begin
Cfg.Set_Database (Cfg.Get_Database & ".test");
ADO.Schemas.Databases.Create_Database (Admin => Cfg,
Config => Cfg,
Schema_Path => Path,
Messages => Msg);
end Test_Create_Schema;
end ADO.Schemas.Tests;
|
-----------------------------------------------------------------------
-- schemas Tests -- Test loading of database schema
-- Copyright (C) 2009, 2010, 2011, 2012, 2015, 2017, 2018 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Test_Caller;
with Util.Strings.Vectors;
with Util.Strings.Transforms;
with ADO.Schemas.Databases;
with ADO.Sessions.Sources;
with ADO.Schemas.Entities;
with Regtests;
with Regtests.Simple.Model;
package body ADO.Schemas.Tests is
use Util.Tests;
function To_Lower_Case (S : in String) return String
renames Util.Strings.Transforms.To_Lower_Case;
package Caller is new Util.Test_Caller (Test, "ADO.Schemas");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test ADO.Schemas.Entities.Find_Entity_Type",
Test_Find_Entity_Type'Access);
Caller.Add_Test (Suite, "Test ADO.Schemas.Entities.Find_Entity_Type (error)",
Test_Find_Entity_Type_Error'Access);
Caller.Add_Test (Suite, "Test ADO.Sessions.Load_Schema",
Test_Load_Schema'Access);
Caller.Add_Test (Suite, "Test ADO.Schemas.Get_Table",
Test_Table_Iterator'Access);
Caller.Add_Test (Suite, "Test ADO.Schemas.Get_Table (Empty schema)",
Test_Empty_Schema'Access);
Caller.Add_Test (Suite, "Test ADO.Schemas.Databases.Create_Database",
Test_Create_Schema'Access);
end Add_Tests;
-- ------------------------------
-- Test reading the entity cache and the Find_Entity_Type operation
-- ------------------------------
procedure Test_Find_Entity_Type (T : in out Test) is
S : ADO.Sessions.Session := Regtests.Get_Database;
C : ADO.Schemas.Entities.Entity_Cache;
begin
ADO.Schemas.Entities.Initialize (Cache => C,
Session => S);
declare
-- T1 : constant ADO.Model.Entity_Type_Ref
-- := Entities.Find_Entity_Type (Cache => C,
-- Table => Regtests.Simple.Model.USER_TABLE'Access);
-- T2 : constant ADO.Model.Entity_Type_Ref
-- := Entities.Find_Entity_Type (Cache => C,
-- Table => Regtests.Simple.Model.ALLOCATE_TABLE'Access);
T4 : constant ADO.Entity_Type
:= Entities.Find_Entity_Type (Cache => C,
Table => Regtests.Simple.Model.ALLOCATE_TABLE);
T5 : constant ADO.Entity_Type
:= Entities.Find_Entity_Type (Cache => C,
Table => Regtests.Simple.Model.USER_TABLE);
begin
-- T.Assert (not ADO.Objects.Is_Null (T1), "Find_Entity_Type returned a null value");
-- T.Assert (not ADO.Objects.Is_Null (T2), "Find_Entity_Type returned a null value");
T.Assert (T4 /= T5, "Two distinct tables have different entity types");
T.Assert (T4 > 0, "T1.Id must be positive");
T.Assert (T5 > 0, "T2.Id must be positive");
-- T.Assert (T1.Get_Id /= T2.Get_Id, "Two distinct tables have different ids");
--
-- Assert_Equals (T, Integer (T2.Get_Id), Integer (T4),
-- "Invalid entity type for allocate_table");
-- Assert_Equals (T, Integer (T1.Get_Id), Integer (T5),
-- "Invalid entity type for user_table");
end;
end Test_Find_Entity_Type;
-- ------------------------------
-- Test calling Find_Entity_Type with an invalid table.
-- ------------------------------
procedure Test_Find_Entity_Type_Error (T : in out Test) is
C : ADO.Schemas.Entities.Entity_Cache;
begin
declare
R : ADO.Entity_Type;
pragma Unreferenced (R);
begin
R := Entities.Find_Entity_Type (Cache => C,
Table => Regtests.Simple.Model.USER_TABLE);
T.Assert (False, "Find_Entity_Type did not raise the No_Entity_Type exception");
exception
when ADO.Schemas.Entities.No_Entity_Type =>
null;
end;
end Test_Find_Entity_Type_Error;
-- ------------------------------
-- Test the Load_Schema operation and check the result schema.
-- ------------------------------
procedure Test_Load_Schema (T : in out Test) is
S : constant ADO.Sessions.Session := Regtests.Get_Database;
Schema : Schema_Definition;
Table : Table_Definition;
begin
S.Load_Schema (Schema);
Table := ADO.Schemas.Find_Table (Schema, "allocate");
T.Assert (Table /= null, "Table schema for test_allocate not found");
Assert_Equals (T, "allocate", Get_Name (Table));
declare
C : Column_Cursor := Get_Columns (Table);
Nb_Columns : Integer := 0;
begin
while Has_Element (C) loop
Nb_Columns := Nb_Columns + 1;
Next (C);
end loop;
Assert_Equals (T, 3, Nb_Columns, "Invalid number of columns");
end;
declare
C : constant Column_Definition := Find_Column (Table, "ID");
begin
T.Assert (C /= null, "Cannot find column 'id' in table schema");
Assert_Equals (T, "id", To_Lower_Case (Get_Name (C)), "Invalid column name");
T.Assert (Get_Type (C) = T_LONG_INTEGER, "Invalid column type");
T.Assert (not Is_Null (C), "Column is null");
end;
declare
C : constant Column_Definition := Find_Column (Table, "NAME");
begin
T.Assert (C /= null, "Cannot find column 'NAME' in table schema");
Assert_Equals (T, "name", To_Lower_Case (Get_Name (C)), "Invalid column name");
T.Assert (Get_Type (C) = T_VARCHAR, "Invalid column type");
T.Assert (Is_Null (C), "Column is null");
end;
declare
C : constant Column_Definition := Find_Column (Table, "version");
begin
T.Assert (C /= null, "Cannot find column 'version' in table schema");
Assert_Equals (T, "version", To_Lower_Case (Get_Name (C)), "Invalid column name");
T.Assert (Get_Type (C) = T_INTEGER, "Invalid column type");
T.Assert (not Is_Null (C), "Column is null");
end;
declare
C : constant Column_Definition := Find_Column (Table, "this_column_does_not_exist");
begin
T.Assert (C = null, "Find_Column must return null for an unknown column");
end;
end Test_Load_Schema;
-- ------------------------------
-- Test the Table_Cursor operations and check the result schema.
-- ------------------------------
procedure Test_Table_Iterator (T : in out Test) is
S : constant ADO.Sessions.Session := Regtests.Get_Database;
Schema : Schema_Definition;
Table : Table_Definition;
Driver : constant String := S.Get_Driver.Get_Driver_Name;
begin
S.Load_Schema (Schema);
declare
Iter : Table_Cursor := Schema.Get_Tables;
Count : Natural := 0;
begin
T.Assert (Has_Element (Iter), "The Get_Tables returns an empty iterator");
while Has_Element (Iter) loop
Table := Element (Iter);
T.Assert (Table /= null, "Element function must not return null");
declare
Col_Iter : Column_Cursor := Get_Columns (Table);
begin
-- T.Assert (Has_Element (Col_Iter), "Table has a column");
while Has_Element (Col_Iter) loop
T.Assert (Element (Col_Iter) /= null, "Element function must not return null");
Next (Col_Iter);
end loop;
end;
Count := Count + 1;
Next (Iter);
end loop;
if Driver = "sqlite" then
Util.Tests.Assert_Equals (T, 15, Count,
"Invalid number of tables found in the schema");
elsif Driver = "mysql" then
Util.Tests.Assert_Equals (T, 8, Count,
"Invalid number of tables found in the schema");
elsif Driver = "postgresql" then
Util.Tests.Assert_Equals (T, 8, Count,
"Invalid number of tables found in the schema");
end if;
end;
end Test_Table_Iterator;
-- ------------------------------
-- Test the Table_Cursor operations on an empty schema.
-- ------------------------------
procedure Test_Empty_Schema (T : in out Test) is
Schema : Schema_Definition;
Iter : constant Table_Cursor := Schema.Get_Tables;
begin
T.Assert (not Has_Element (Iter), "The Get_Tables must return an empty iterator");
T.Assert (Schema.Find_Table ("test") = null, "The Find_Table must return null");
end Test_Empty_Schema;
-- ------------------------------
-- Test the creation of database.
-- ------------------------------
procedure Test_Create_Schema (T : in out Test) is
use ADO.Sessions.Sources;
Msg : Util.Strings.Vectors.Vector;
Cfg : Data_Source := Data_Source (Regtests.Get_Controller);
Path : constant String :=
"db/regtests/" & Cfg.Get_Driver & "/create-ado-" & Cfg.Get_Driver & ".sql";
pragma Unreferenced (T, Msg);
begin
Cfg.Set_Database (Cfg.Get_Database & ".test");
ADO.Schemas.Databases.Create_Database (Admin => Cfg,
Config => Cfg,
Schema_Path => Path,
Messages => Msg);
end Test_Create_Schema;
end ADO.Schemas.Tests;
|
Fix compilation warnings
|
Fix compilation warnings
|
Ada
|
apache-2.0
|
stcarrez/ada-ado
|
ee209a391c4829f918c315179d01e778235a93c1
|
regtests/ado-schemas-tests.ads
|
regtests/ado-schemas-tests.ads
|
-----------------------------------------------------------------------
-- schemas Tests -- Test loading of database schema
-- Copyright (C) 2009, 2010, 2011, 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Tests;
package ADO.Schemas.Tests is
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite);
type Test is new Util.Tests.Test with null record;
-- Test reading the entity cache and the Find_Entity_Type operation
procedure Test_Find_Entity_Type (T : in out Test);
-- Test calling Find_Entity_Type with an invalid table.
procedure Test_Find_Entity_Type_Error (T : in out Test);
-- Test the Load_Schema operation and check the result schema.
procedure Test_Load_Schema (T : in out Test);
end ADO.Schemas.Tests;
|
-----------------------------------------------------------------------
-- schemas Tests -- Test loading of database schema
-- Copyright (C) 2009, 2010, 2011, 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Tests;
package ADO.Schemas.Tests is
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite);
type Test is new Util.Tests.Test with null record;
-- Test reading the entity cache and the Find_Entity_Type operation
procedure Test_Find_Entity_Type (T : in out Test);
-- Test calling Find_Entity_Type with an invalid table.
procedure Test_Find_Entity_Type_Error (T : in out Test);
-- Test the Load_Schema operation and check the result schema.
procedure Test_Load_Schema (T : in out Test);
-- Test the Table_Cursor operations and check the result schema.
procedure Test_Table_Iterator (T : in out Test);
end ADO.Schemas.Tests;
|
Declare Test_Table_Iterator procedure to test the table iterator
|
Declare Test_Table_Iterator procedure to test the table iterator
|
Ada
|
apache-2.0
|
stcarrez/ada-ado
|
70cd0a67a88ed5c0df7181adfb28e0e72ef6d338
|
src/ado-sessions.adb
|
src/ado-sessions.adb
|
-----------------------------------------------------------------------
-- ADO Sessions -- Sessions Management
-- Copyright (C) 2009, 2010, 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 Util.Log;
with Util.Log.Loggers;
with Ada.Unchecked_Deallocation;
with ADO.Drivers;
with ADO.Sequences;
with ADO.Statements.Create;
package body ADO.Sessions is
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("ADO.Sessions");
procedure Check_Session (Database : in Session'Class;
Message : in String := "") is
begin
if Database.Impl = null then
Log.Error ("Session is closed or not initialized");
raise NOT_OPEN;
end if;
if Message'Length > 0 then
Log.Info (Message, Database.Impl.Database.Value.Ident);
end if;
end Check_Session;
-- ---------
-- Session
-- ---------
-- ------------------------------
-- Get the session status.
-- ------------------------------
function Get_Status (Database : in Session) return Connection_Status is
begin
if Database.Impl = null or else Database.Impl.Database.Is_Null then
return CLOSED;
else
return OPEN;
end if;
end Get_Status;
-- ------------------------------
-- Get the database driver which manages this connection.
-- ------------------------------
function Get_Driver (Database : in Session) return ADO.Drivers.Connections.Driver_Access is
begin
if Database.Impl = null or else Database.Impl.Database.Is_Null then
return null;
else
return Database.Impl.Database.Value.Get_Driver;
end if;
end Get_Driver;
-- ------------------------------
-- Close the session.
-- ------------------------------
procedure Close (Database : in out Session) is
procedure Free is new
Ada.Unchecked_Deallocation (Object => Session_Record,
Name => Session_Record_Access);
Is_Zero : Boolean;
begin
Log.Info ("Closing session");
if Database.Impl /= null then
ADO.Objects.Release_Proxy (Database.Impl.Proxy);
Database.Impl.Database.Value.Close;
Util.Concurrent.Counters.Decrement (Database.Impl.Counter, Is_Zero);
if Is_Zero then
Free (Database.Impl);
end if;
Database.Impl := null;
end if;
end Close;
-- ------------------------------
-- Insert a new cache in the manager. The cache is identified by the given name.
-- ------------------------------
procedure Add_Cache (Database : in out Session;
Name : in String;
Cache : in ADO.Caches.Cache_Type_Access) is
begin
Check_Session (Database);
Database.Impl.Values.Add_Cache (Name, Cache);
end Add_Cache;
-- ------------------------------
-- Attach the object to the session.
-- ------------------------------
procedure Attach (Database : in out Session;
Object : in ADO.Objects.Object_Ref'Class) is
pragma Unreferenced (Object);
begin
Check_Session (Database);
end Attach;
-- ------------------------------
-- Check if the session contains the object identified by the given key.
-- ------------------------------
function Contains (Database : in Session;
Item : in ADO.Objects.Object_Key) return Boolean is
begin
Check_Session (Database);
return ADO.Objects.Cache.Contains (Database.Impl.Cache, Item);
end Contains;
-- ------------------------------
-- Remove the object from the session cache.
-- ------------------------------
procedure Evict (Database : in out Session;
Item : in ADO.Objects.Object_Key) is
begin
Check_Session (Database);
ADO.Objects.Cache.Remove (Database.Impl.Cache, Item);
end Evict;
-- ------------------------------
-- Create a query statement. The statement is not prepared
-- ------------------------------
function Create_Statement (Database : in Session;
Table : in ADO.Schemas.Class_Mapping_Access)
return Query_Statement is
begin
Check_Session (Database);
declare
Query : constant Query_Statement_Access := Database.Impl.Database.Value.all.Create_Statement (Table);
begin
return ADO.Statements.Create.Create_Statement (Query, Database.Impl.Values.all'Access);
end;
end Create_Statement;
-- ------------------------------
-- Create a query statement. The statement is not prepared
-- ------------------------------
function Create_Statement (Database : in Session;
Query : in String)
return Query_Statement is
begin
Check_Session (Database);
declare
Stmt : constant Query_Statement_Access := Database.Impl.Database.Value.all.Create_Statement (Query);
begin
return ADO.Statements.Create.Create_Statement (Stmt, Database.Impl.Values.all'Access);
end;
end Create_Statement;
-- ------------------------------
-- Create a query statement. The statement is not prepared
-- ------------------------------
function Create_Statement (Database : in Session;
Query : in ADO.Queries.Context'Class)
return Query_Statement is
begin
Check_Session (Database);
declare
SQL : constant String := Query.Get_SQL (Database.Impl.Queries);
Stmt : Query_Statement := Database.Create_Statement (SQL);
begin
Stmt.Set_Parameters (Query);
return Stmt;
end;
end Create_Statement;
-- ------------------------------
-- Create a query statement and initialize the SQL statement with the query definition.
-- ------------------------------
function Create_Statement (Database : in Session;
Query : in ADO.Queries.Query_Definition_Access)
return Query_Statement is
begin
Check_Session (Database);
declare
SQL : constant String := ADO.Queries.Get_SQL (Query, Database.Impl.Queries, False);
begin
return Database.Create_Statement (SQL);
end;
end Create_Statement;
-- ------------------------------
-- Create a query statement. The statement is not prepared
-- ------------------------------
function Create_Statement (Database : in Session;
Query : in ADO.SQL.Query'Class;
Table : in ADO.Schemas.Class_Mapping_Access)
return Query_Statement is
begin
Check_Session (Database);
declare
Stmt : Query_Statement := Database.Create_Statement (Table);
begin
if Query in ADO.Queries.Context'Class then
declare
SQL : constant String
:= ADO.Queries.Context'Class (Query).Get_SQL (Database.Impl.Queries);
begin
ADO.SQL.Append (Stmt.Get_Query.SQL, SQL);
end;
end if;
Stmt.Set_Parameters (Query);
return Stmt;
end;
end Create_Statement;
-- ------------------------------
-- Load the database schema definition for the current database.
-- ------------------------------
procedure Load_Schema (Database : in Session;
Schema : out ADO.Schemas.Schema_Definition) is
begin
Check_Session (Database, "Loading schema {0}");
Database.Impl.Database.Value.Load_Schema (Schema);
end Load_Schema;
-- ---------
-- Master Session
-- ---------
-- ------------------------------
-- Start a transaction.
-- ------------------------------
procedure Begin_Transaction (Database : in out Master_Session) is
begin
Check_Session (Database, "Begin transaction {0}");
Database.Impl.Database.Value.Begin_Transaction;
end Begin_Transaction;
-- ------------------------------
-- Commit the current transaction.
-- ------------------------------
procedure Commit (Database : in out Master_Session) is
begin
Check_Session (Database, "Commit transaction {0}");
Database.Impl.Database.Value.Commit;
end Commit;
-- ------------------------------
-- Rollback the current transaction.
-- ------------------------------
procedure Rollback (Database : in out Master_Session) is
begin
Check_Session (Database, "Rollback transaction {0}");
Database.Impl.Database.Value.Rollback;
end Rollback;
-- ------------------------------
-- Allocate an identifier for the table.
-- ------------------------------
procedure Allocate (Database : in out Master_Session;
Id : in out ADO.Objects.Object_Record'Class) is
begin
Check_Session (Database);
ADO.Sequences.Allocate (Database.Sequences.all, Id);
end Allocate;
-- ------------------------------
-- Flush the objects that were modified.
-- ------------------------------
procedure Flush (Database : in out Master_Session) is
begin
Check_Session (Database);
end Flush;
overriding
procedure Adjust (Object : in out Session) is
begin
if Object.Impl /= null then
Util.Concurrent.Counters.Increment (Object.Impl.Counter);
end if;
end Adjust;
overriding
procedure Finalize (Object : in out Session) is
procedure Free is
new Ada.Unchecked_Deallocation (Object => Session_Record,
Name => Session_Record_Access);
Is_Zero : Boolean;
begin
if Object.Impl /= null then
Util.Concurrent.Counters.Decrement (Object.Impl.Counter, Is_Zero);
if Is_Zero then
ADO.Objects.Release_Proxy (Object.Impl.Proxy, Detach => True);
if not Object.Impl.Database.Is_Null then
Object.Impl.Database.Value.Close;
end if;
Free (Object.Impl);
end if;
Object.Impl := null;
end if;
end Finalize;
-- ------------------------------
-- Create a delete statement
-- ------------------------------
function Create_Statement (Database : in Master_Session;
Table : in ADO.Schemas.Class_Mapping_Access)
return Delete_Statement is
begin
Check_Session (Database);
declare
Stmt : constant Delete_Statement_Access := Database.Impl.Database.Value.all.Create_Statement (Table);
begin
return ADO.Statements.Create.Create_Statement (Stmt.all'Access, Database.Impl.Values.all'Access);
end;
end Create_Statement;
-- ------------------------------
-- Create an update statement
-- ------------------------------
function Create_Statement (Database : in Master_Session;
Table : in ADO.Schemas.Class_Mapping_Access)
return Update_Statement is
begin
Check_Session (Database);
declare
Stmt : constant Update_Statement_Access := Database.Impl.Database.Value.all.Create_Statement (Table);
begin
return ADO.Statements.Create.Create_Statement (Stmt.all'Access, Database.Impl.Values.all'Access);
end;
end Create_Statement;
-- ------------------------------
-- Create an insert statement
-- ------------------------------
function Create_Statement (Database : in Master_Session;
Table : in ADO.Schemas.Class_Mapping_Access)
return Insert_Statement is
begin
Check_Session (Database);
declare
Stmt : constant Insert_Statement_Access := Database.Impl.Database.Value.all.Create_Statement (Table);
begin
return ADO.Statements.Create.Create_Statement (Stmt.all'Access, Database.Impl.Values.all'Access);
end;
end Create_Statement;
-- ------------------------------
-- Internal method to get the session proxy associated with the given database session.
-- The session proxy is associated with some ADO objects to be able to retrieve the database
-- session for the implementation of lazy loading. The session proxy is kept until the
-- session exist and at least one ADO object is refering to it.
-- ------------------------------
function Get_Session_Proxy (Database : in Session) return ADO.Objects.Session_Proxy_Access is
use type ADO.Objects.Session_Proxy_Access;
begin
Check_Session (Database);
if Database.Impl.Proxy = null then
Database.Impl.Proxy := ADO.Objects.Create_Session_Proxy (Database.Impl);
end if;
return Database.Impl.Proxy;
end Get_Session_Proxy;
end ADO.Sessions;
|
-----------------------------------------------------------------------
-- ADO Sessions -- Sessions Management
-- Copyright (C) 2009, 2010, 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 Util.Log;
with Util.Log.Loggers;
with Ada.Unchecked_Deallocation;
with ADO.Drivers;
with ADO.Sequences;
with ADO.Statements.Create;
package body ADO.Sessions is
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("ADO.Sessions");
procedure Check_Session (Database : in Session'Class;
Message : in String := "") is
begin
if Database.Impl = null then
Log.Error ("Session is closed or not initialized");
raise NOT_OPEN;
end if;
if Message'Length > 0 then
Log.Info (Message, Database.Impl.Database.Value.Ident);
end if;
end Check_Session;
-- ---------
-- Session
-- ---------
-- ------------------------------
-- Get the session status.
-- ------------------------------
function Get_Status (Database : in Session) return Connection_Status is
begin
if Database.Impl = null or else Database.Impl.Database.Is_Null then
return CLOSED;
else
return OPEN;
end if;
end Get_Status;
-- ------------------------------
-- Get the database driver which manages this connection.
-- ------------------------------
function Get_Driver (Database : in Session) return ADO.Drivers.Connections.Driver_Access is
begin
if Database.Impl = null or else Database.Impl.Database.Is_Null then
return null;
else
return Database.Impl.Database.Value.Get_Driver;
end if;
end Get_Driver;
-- ------------------------------
-- Close the session.
-- ------------------------------
procedure Close (Database : in out Session) is
procedure Free is new
Ada.Unchecked_Deallocation (Object => Session_Record,
Name => Session_Record_Access);
Is_Zero : Boolean;
begin
Log.Info ("Closing session");
if Database.Impl /= null then
ADO.Objects.Release_Proxy (Database.Impl.Proxy);
Database.Impl.Database.Value.Close;
Util.Concurrent.Counters.Decrement (Database.Impl.Counter, Is_Zero);
if Is_Zero then
Free (Database.Impl);
end if;
Database.Impl := null;
end if;
end Close;
-- ------------------------------
-- Insert a new cache in the manager. The cache is identified by the given name.
-- ------------------------------
procedure Add_Cache (Database : in out Session;
Name : in String;
Cache : in ADO.Caches.Cache_Type_Access) is
begin
Check_Session (Database);
Database.Impl.Values.Add_Cache (Name, Cache);
end Add_Cache;
-- ------------------------------
-- Attach the object to the session.
-- ------------------------------
procedure Attach (Database : in out Session;
Object : in ADO.Objects.Object_Ref'Class) is
pragma Unreferenced (Object);
begin
Check_Session (Database);
end Attach;
-- ------------------------------
-- Check if the session contains the object identified by the given key.
-- ------------------------------
function Contains (Database : in Session;
Item : in ADO.Objects.Object_Key) return Boolean is
begin
Check_Session (Database);
return ADO.Objects.Cache.Contains (Database.Impl.Cache, Item);
end Contains;
-- ------------------------------
-- Remove the object from the session cache.
-- ------------------------------
procedure Evict (Database : in out Session;
Item : in ADO.Objects.Object_Key) is
begin
Check_Session (Database);
ADO.Objects.Cache.Remove (Database.Impl.Cache, Item);
end Evict;
-- ------------------------------
-- Create a query statement. The statement is not prepared
-- ------------------------------
function Create_Statement (Database : in Session;
Table : in ADO.Schemas.Class_Mapping_Access)
return Query_Statement is
begin
Check_Session (Database);
declare
Query : constant Query_Statement_Access := Database.Impl.Database.Value.all.Create_Statement (Table);
begin
return ADO.Statements.Create.Create_Statement (Query, Database.Impl.Values.all'Access);
end;
end Create_Statement;
-- ------------------------------
-- Create a query statement. The statement is not prepared
-- ------------------------------
function Create_Statement (Database : in Session;
Query : in String)
return Query_Statement is
begin
Check_Session (Database);
declare
Stmt : constant Query_Statement_Access := Database.Impl.Database.Value.all.Create_Statement (Query);
begin
return ADO.Statements.Create.Create_Statement (Stmt, Database.Impl.Values.all'Access);
end;
end Create_Statement;
-- ------------------------------
-- Create a query statement. The statement is not prepared
-- ------------------------------
function Create_Statement (Database : in Session;
Query : in ADO.Queries.Context'Class)
return Query_Statement is
begin
Check_Session (Database);
declare
SQL : constant String := Query.Get_SQL (Database.Impl.Queries.all);
Stmt : Query_Statement := Database.Create_Statement (SQL);
begin
Stmt.Set_Parameters (Query);
return Stmt;
end;
end Create_Statement;
-- ------------------------------
-- Create a query statement and initialize the SQL statement with the query definition.
-- ------------------------------
function Create_Statement (Database : in Session;
Query : in ADO.Queries.Query_Definition_Access)
return Query_Statement is
begin
Check_Session (Database);
declare
SQL : constant String := ADO.Queries.Get_SQL (Query, Database.Impl.Queries.all, False);
begin
return Database.Create_Statement (SQL);
end;
end Create_Statement;
-- ------------------------------
-- Create a query statement. The statement is not prepared
-- ------------------------------
function Create_Statement (Database : in Session;
Query : in ADO.SQL.Query'Class;
Table : in ADO.Schemas.Class_Mapping_Access)
return Query_Statement is
begin
Check_Session (Database);
declare
Stmt : Query_Statement := Database.Create_Statement (Table);
begin
if Query in ADO.Queries.Context'Class then
declare
SQL : constant String
:= ADO.Queries.Context'Class (Query).Get_SQL (Database.Impl.Queries.all);
begin
ADO.SQL.Append (Stmt.Get_Query.SQL, SQL);
end;
end if;
Stmt.Set_Parameters (Query);
return Stmt;
end;
end Create_Statement;
-- ------------------------------
-- Load the database schema definition for the current database.
-- ------------------------------
procedure Load_Schema (Database : in Session;
Schema : out ADO.Schemas.Schema_Definition) is
begin
Check_Session (Database, "Loading schema {0}");
Database.Impl.Database.Value.Load_Schema (Schema);
end Load_Schema;
-- ---------
-- Master Session
-- ---------
-- ------------------------------
-- Start a transaction.
-- ------------------------------
procedure Begin_Transaction (Database : in out Master_Session) is
begin
Check_Session (Database, "Begin transaction {0}");
Database.Impl.Database.Value.Begin_Transaction;
end Begin_Transaction;
-- ------------------------------
-- Commit the current transaction.
-- ------------------------------
procedure Commit (Database : in out Master_Session) is
begin
Check_Session (Database, "Commit transaction {0}");
Database.Impl.Database.Value.Commit;
end Commit;
-- ------------------------------
-- Rollback the current transaction.
-- ------------------------------
procedure Rollback (Database : in out Master_Session) is
begin
Check_Session (Database, "Rollback transaction {0}");
Database.Impl.Database.Value.Rollback;
end Rollback;
-- ------------------------------
-- Allocate an identifier for the table.
-- ------------------------------
procedure Allocate (Database : in out Master_Session;
Id : in out ADO.Objects.Object_Record'Class) is
begin
Check_Session (Database);
ADO.Sequences.Allocate (Database.Sequences.all, Id);
end Allocate;
-- ------------------------------
-- Flush the objects that were modified.
-- ------------------------------
procedure Flush (Database : in out Master_Session) is
begin
Check_Session (Database);
end Flush;
overriding
procedure Adjust (Object : in out Session) is
begin
if Object.Impl /= null then
Util.Concurrent.Counters.Increment (Object.Impl.Counter);
end if;
end Adjust;
overriding
procedure Finalize (Object : in out Session) is
procedure Free is
new Ada.Unchecked_Deallocation (Object => Session_Record,
Name => Session_Record_Access);
Is_Zero : Boolean;
begin
if Object.Impl /= null then
Util.Concurrent.Counters.Decrement (Object.Impl.Counter, Is_Zero);
if Is_Zero then
ADO.Objects.Release_Proxy (Object.Impl.Proxy, Detach => True);
if not Object.Impl.Database.Is_Null then
Object.Impl.Database.Value.Close;
end if;
Free (Object.Impl);
end if;
Object.Impl := null;
end if;
end Finalize;
-- ------------------------------
-- Create a delete statement
-- ------------------------------
function Create_Statement (Database : in Master_Session;
Table : in ADO.Schemas.Class_Mapping_Access)
return Delete_Statement is
begin
Check_Session (Database);
declare
Stmt : constant Delete_Statement_Access := Database.Impl.Database.Value.all.Create_Statement (Table);
begin
return ADO.Statements.Create.Create_Statement (Stmt.all'Access, Database.Impl.Values.all'Access);
end;
end Create_Statement;
-- ------------------------------
-- Create an update statement
-- ------------------------------
function Create_Statement (Database : in Master_Session;
Table : in ADO.Schemas.Class_Mapping_Access)
return Update_Statement is
begin
Check_Session (Database);
declare
Stmt : constant Update_Statement_Access := Database.Impl.Database.Value.all.Create_Statement (Table);
begin
return ADO.Statements.Create.Create_Statement (Stmt.all'Access, Database.Impl.Values.all'Access);
end;
end Create_Statement;
-- ------------------------------
-- Create an insert statement
-- ------------------------------
function Create_Statement (Database : in Master_Session;
Table : in ADO.Schemas.Class_Mapping_Access)
return Insert_Statement is
begin
Check_Session (Database);
declare
Stmt : constant Insert_Statement_Access := Database.Impl.Database.Value.all.Create_Statement (Table);
begin
return ADO.Statements.Create.Create_Statement (Stmt.all'Access, Database.Impl.Values.all'Access);
end;
end Create_Statement;
-- ------------------------------
-- Internal method to get the session proxy associated with the given database session.
-- The session proxy is associated with some ADO objects to be able to retrieve the database
-- session for the implementation of lazy loading. The session proxy is kept until the
-- session exist and at least one ADO object is refering to it.
-- ------------------------------
function Get_Session_Proxy (Database : in Session) return ADO.Objects.Session_Proxy_Access is
use type ADO.Objects.Session_Proxy_Access;
begin
Check_Session (Database);
if Database.Impl.Proxy = null then
Database.Impl.Proxy := ADO.Objects.Create_Session_Proxy (Database.Impl);
end if;
return Database.Impl.Proxy;
end Get_Session_Proxy;
end ADO.Sessions;
|
Update to take into account the change in Get_SQL operation
|
Update to take into account the change in Get_SQL operation
|
Ada
|
apache-2.0
|
stcarrez/ada-ado
|
ce0281f49c4ba2ddb05804df0431a5489107284d
|
src/asf-streams-json.adb
|
src/asf-streams-json.adb
|
-----------------------------------------------------------------------
-- asf-streams-json -- JSON Print streams for servlets
-- Copyright (C) 2016 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Serialize.IO.JSON;
package body ASF.Streams.JSON is
-- ------------------------------
-- Initialize the stream
-- ------------------------------
procedure Initialize (Stream : in out Print_Stream;
To : in ASF.Streams.Print_Stream'Class) is
begin
Stream.Initialize (To.Target);
end Initialize;
end ASF.Streams.JSON;
|
-----------------------------------------------------------------------
-- asf-streams-json -- JSON Print streams for servlets
-- Copyright (C) 2016, 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
package body ASF.Streams.JSON is
-- ------------------------------
-- Initialize the stream
-- ------------------------------
procedure Initialize (Stream : in out Print_Stream;
To : in ASF.Streams.Print_Stream'Class) is
begin
Stream.Initialize (To.Target);
end Initialize;
end ASF.Streams.JSON;
|
Remove unused with clause Util.Serialize.IO.JSON
|
Remove unused with clause Util.Serialize.IO.JSON
|
Ada
|
apache-2.0
|
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
|
bbed357141765fcd75e71383433d78526532c2b2
|
awa/regtests/awa-jobs-services-tests.adb
|
awa/regtests/awa-jobs-services-tests.adb
|
-----------------------------------------------------------------------
-- jobs-tests -- Unit tests for AWA jobs
-- 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 AWA.Tests;
with AWA.Jobs.Modules;
with AWA.Services.Contexts;
package body AWA.Jobs.Services.Tests is
package Caller is new Util.Test_Caller (Test, "Jobs.Services");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test AWA.Jobs.Modules.Register",
Test_Job_Schedule'Access);
end Add_Tests;
procedure Work_1 (Job : in out AWA.Jobs.Services.Abstract_Job_Type'Class) is
begin
null;
end Work_1;
procedure Work_2 (Job : in out AWA.Jobs.Services.Abstract_Job_Type'Class) is
begin
null;
end Work_2;
-- Test the job factory.
procedure Test_Job_Schedule (T : in out Test) is
Context : AWA.Services.Contexts.Service_Context;
J : AWA.Jobs.Services.Job_Type;
begin
Context.Set_Context (AWA.Tests.Get_Application, null);
J.Set_Parameter ("count", "1");
J.Set_Parameter ("message", "Hello");
J.Schedule (Work_1_Definition.Factory);
end Test_Job_Schedule;
-- Execute the job. This operation must be implemented and should perform the work
-- represented by the job. It should use the <tt>Get_Parameter</tt> function to retrieve
-- the job parameter and it can use the <tt>Set_Result</tt> operation to save the result.
overriding
procedure Execute (Job : in out Test_Job) is
begin
null;
end Execute;
end AWA.Jobs.Services.Tests;
|
-----------------------------------------------------------------------
-- jobs-tests -- Unit tests for AWA jobs
-- 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.Test_Caller;
with Util.Log.Loggers;
with AWA.Jobs.Modules;
with AWA.Services.Contexts;
package body AWA.Jobs.Services.Tests is
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("AWA.Jobs.Services.Tests");
package Caller is new Util.Test_Caller (Test, "Jobs.Services");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test AWA.Jobs.Modules.Register",
Test_Job_Schedule'Access);
end Add_Tests;
procedure Work_1 (Job : in out AWA.Jobs.Services.Abstract_Job_Type'Class) is
Msg : constant String := Job.Get_Parameter ("message");
Cnt : constant Natural := Job.Get_Parameter ("count", 0);
begin
Log.Info ("Execute work_1 {0}, count {1}", Msg, Natural'Image (Cnt));
end Work_1;
procedure Work_2 (Job : in out AWA.Jobs.Services.Abstract_Job_Type'Class) is
begin
null;
end Work_2;
-- ------------------------------
-- Test the job factory.
-- ------------------------------
procedure Test_Job_Schedule (T : in out Test) is
use type AWA.Jobs.Models.Job_Status_Type;
Context : AWA.Services.Contexts.Service_Context;
J : AWA.Jobs.Services.Job_Type;
begin
Context.Set_Context (AWA.Tests.Get_Application, null);
J.Set_Parameter ("count", 1);
Util.Tests.Assert_Equals (T, 1, J.Get_Parameter ("count", 0), "Invalid count param");
J.Set_Parameter ("message", "Hello");
Util.Tests.Assert_Equals (T, "Hello", J.Get_Parameter ("message"), "Invalid message param");
J.Schedule (Work_1_Definition.Factory);
T.Assert (J.Get_Status = AWA.Jobs.Models.SCHEDULED, "Job is not scheduled");
--
for I in 1 .. 10 loop
delay 0.1;
end loop;
end Test_Job_Schedule;
-- Execute the job. This operation must be implemented and should perform the work
-- represented by the job. It should use the <tt>Get_Parameter</tt> function to retrieve
-- the job parameter and it can use the <tt>Set_Result</tt> operation to save the result.
overriding
procedure Execute (Job : in out Test_Job) is
begin
null;
end Execute;
end AWA.Jobs.Services.Tests;
|
Update the job unit tests to verify some parameters
|
Update the job unit tests to verify some parameters
|
Ada
|
apache-2.0
|
tectronics/ada-awa,Letractively/ada-awa,tectronics/ada-awa,Letractively/ada-awa,Letractively/ada-awa,tectronics/ada-awa
|
989e36c0a1719eb377aaf71e08f06da77aff02b6
|
mat/src/gtk/mat-callbacks.ads
|
mat/src/gtk/mat-callbacks.ads
|
-----------------------------------------------------------------------
-- mat-callbacks - Callbacks for Gtk
-- 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.Types;
with Gtkada.Builder;
package MAT.Callbacks is
-- Callback executed when the "quit" action is executed from the menu.
procedure On_Menu_Quit (Object : access Gtkada.Builder.Gtkada_Builder_Record'Class);
-- Callback executed when the "about" action is executed from the menu.
procedure On_Menu_About (Object : access Gtkada.Builder.Gtkada_Builder_Record'Class);
-- Callback executed when the "close-about" action is executed from the about box.
procedure On_Close_About (Object : access Gtkada.Builder.Gtkada_Builder_Record'Class);
end MAT.Callbacks;
|
-----------------------------------------------------------------------
-- mat-callbacks - Callbacks for Gtk
-- 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.Types;
with Gtkada.Builder;
package MAT.Callbacks is
-- Initialize and register the callbacks.
procedure Initialize (Builder : in Gtkada.Builder.Gtkada_Builder);
-- Callback executed when the "quit" action is executed from the menu.
procedure On_Menu_Quit (Object : access Gtkada.Builder.Gtkada_Builder_Record'Class);
-- Callback executed when the "about" action is executed from the menu.
procedure On_Menu_About (Object : access Gtkada.Builder.Gtkada_Builder_Record'Class);
-- Callback executed when the "close-about" action is executed from the about box.
procedure On_Close_About (Object : access Gtkada.Builder.Gtkada_Builder_Record'Class);
end MAT.Callbacks;
|
Define the Initialize procedure
|
Define the Initialize procedure
|
Ada
|
apache-2.0
|
stcarrez/mat,stcarrez/mat,stcarrez/mat
|
9aeae40e1b703901a0d35ed095d8cadfd8e5b7a0
|
boards/OpenMV2/src/openmv-lcd_shield.adb
|
boards/OpenMV2/src/openmv-lcd_shield.adb
|
------------------------------------------------------------------------------
-- --
-- Copyright (C) 2015-2016, AdaCore --
-- --
-- Redistribution and use in source and binary forms, with or without --
-- modification, are permitted provided that the following conditions are --
-- met: --
-- 1. Redistributions of source code must retain the above copyright --
-- notice, this list of conditions and the following disclaimer. --
-- 2. Redistributions in binary form must reproduce the above copyright --
-- notice, this list of conditions and the following disclaimer in --
-- the documentation and/or other materials provided with the --
-- distribution. --
-- 3. Neither the name of the copyright holder nor the names of its --
-- contributors may be used to endorse or promote products derived --
-- from this software without specific prior written permission. --
-- --
-- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS --
-- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT --
-- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR --
-- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT --
-- HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, --
-- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT --
-- LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, --
-- DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY --
-- THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT --
-- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE --
-- OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. --
-- --
------------------------------------------------------------------------------
with STM32.GPIO;
with STM32.Device;
with OpenMV;
with ST7735R; use ST7735R;
with ST7735R.RAM_Framebuffer; use ST7735R.RAM_Framebuffer;
with Ravenscar_Time;
package body OpenMV.LCD_Shield is
LCD_RST : STM32.GPIO.GPIO_Point renames Shield_PWM1;
LCD_RS : STM32.GPIO.GPIO_Point renames Shield_PWM2;
LCD_CS : STM32.GPIO.GPIO_Point renames Shield_SEL;
All_Points : constant STM32.GPIO.GPIO_Points := (LCD_RS, LCD_CS, LCD_RST);
LCD_Driver : ST7735R_RAM_Framebuffer_Device (Shield_SPI'Access,
LCD_CS'Access,
LCD_RS'Access,
LCD_RST'Access,
Ravenscar_Time.Delays);
Is_Initialized : Boolean := False;
-----------------
-- Initialized --
-----------------
function Initialized return Boolean is (Is_Initialized);
----------------
-- Initialize --
----------------
procedure Initialize is
GPIO_Conf : STM32.GPIO.GPIO_Port_Configuration;
begin
-- Initalize shield SPI port
Initialize_Shield_SPI;
STM32.Device.Enable_Clock (All_Points);
GPIO_Conf.Mode := STM32.GPIO.Mode_Out;
GPIO_Conf.Output_Type := STM32.GPIO.Push_Pull;
GPIO_Conf.Speed := STM32.GPIO.Speed_100MHz;
GPIO_Conf.Resistors := STM32.GPIO.Floating;
STM32.GPIO.Configure_IO (All_Points, GPIO_Conf);
Initialize (LCD_Driver);
Set_Memory_Data_Access
(LCD => LCD_Driver,
Color_Order => RGB_Order,
Vertical => Vertical_Refresh_Top_Bottom,
Horizontal => Horizontal_Refresh_Left_Right,
Row_Addr_Order => Row_Address_Bottom_Top,
Column_Addr_Order => Column_Address_Right_Left,
Row_Column_Exchange => False);
Set_Pixel_Format (LCD_Driver, Pixel_16bits);
Set_Frame_Rate_Normal (LCD_Driver,
RTN => 16#01#,
Front_Porch => 16#2C#,
Back_Porch => 16#2D#);
Set_Frame_Rate_Idle (LCD_Driver,
RTN => 16#01#,
Front_Porch => 16#2C#,
Back_Porch => 16#2D#);
Set_Frame_Rate_Partial_Full (LCD_Driver,
RTN_Part => 16#01#,
Front_Porch_Part => 16#2C#,
Back_Porch_Part => 16#2D#,
RTN_Full => 16#01#,
Front_Porch_Full => 16#2C#,
Back_Porch_Full => 16#2D#);
Set_Inversion_Control (LCD_Driver,
Normal => Line_Inversion,
Idle => Line_Inversion,
Full_Partial => Line_Inversion);
Set_Power_Control_1 (LCD_Driver,
AVDD => 2#101#, -- 5
VRHP => 2#0_0010#, -- 4.6
VRHN => 2#0_0010#, -- -4.6
MODE => 2#10#); -- AUTO
Set_Power_Control_2 (LCD_Driver,
VGH25 => 2#11#, -- 2.4
VGSEL => 2#01#, -- 3*AVDD
VGHBT => 2#01#); -- -10
Set_Power_Control_3 (LCD_Driver, 16#0A#, 16#00#);
Set_Power_Control_4 (LCD_Driver, 16#8A#, 16#2A#);
Set_Power_Control_5 (LCD_Driver, 16#8A#, 16#EE#);
Set_Vcom (LCD_Driver, 16#E#);
Set_Address (LCD_Driver,
X_Start => 0,
X_End => 127,
Y_Start => 0,
Y_End => 159);
Turn_On (LCD_Driver);
LCD_Driver.Initialize_Layer (Layer => 1,
Mode => HAL.Bitmap.RGB_565,
X => 0,
Y => 0,
Width => Image_Width,
Height => Image_Height);
Is_Initialized := True;
end Initialize;
----------------
-- Get_Bitmap --
----------------
function Get_Bitmap return not null HAL.Bitmap.Any_Bitmap_Buffer is
begin
return LCD_Driver.Hidden_Buffer (1);
end Get_Bitmap;
----------------------
-- Rotate_Screen_90 --
----------------------
procedure Rotate_Screen_90 is
begin
Set_Memory_Data_Access
(LCD => LCD_Driver,
Color_Order => RGB_Order,
Vertical => Vertical_Refresh_Top_Bottom,
Horizontal => Horizontal_Refresh_Left_Right,
Row_Addr_Order => Row_Address_Top_Bottom,
Column_Addr_Order => Column_Address_Left_Right,
Row_Column_Exchange => False);
end Rotate_Screen_90;
---------------------
-- Rotate_Screen_0 --
---------------------
procedure Rotate_Screen_0 is
begin
Set_Memory_Data_Access
(LCD => LCD_Driver,
Color_Order => RGB_Order,
Vertical => Vertical_Refresh_Top_Bottom,
Horizontal => Horizontal_Refresh_Left_Right,
Row_Addr_Order => Row_Address_Bottom_Top,
Column_Addr_Order => Column_Address_Right_Left,
Row_Column_Exchange => False);
end Rotate_Screen_0;
-------------
-- Display --
-------------
procedure Display is
begin
LCD_Driver.Update_Layer (1);
end Display;
end OpenMV.LCD_Shield;
|
------------------------------------------------------------------------------
-- --
-- Copyright (C) 2015-2016, AdaCore --
-- --
-- Redistribution and use in source and binary forms, with or without --
-- modification, are permitted provided that the following conditions are --
-- met: --
-- 1. Redistributions of source code must retain the above copyright --
-- notice, this list of conditions and the following disclaimer. --
-- 2. Redistributions in binary form must reproduce the above copyright --
-- notice, this list of conditions and the following disclaimer in --
-- the documentation and/or other materials provided with the --
-- distribution. --
-- 3. Neither the name of the copyright holder nor the names of its --
-- contributors may be used to endorse or promote products derived --
-- from this software without specific prior written permission. --
-- --
-- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS --
-- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT --
-- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR --
-- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT --
-- HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, --
-- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT --
-- LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, --
-- DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY --
-- THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT --
-- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE --
-- OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. --
-- --
------------------------------------------------------------------------------
with STM32.GPIO;
with STM32.Device;
with OpenMV;
with ST7735R; use ST7735R;
with ST7735R.RAM_Framebuffer; use ST7735R.RAM_Framebuffer;
with Ravenscar_Time;
package body OpenMV.LCD_Shield is
LCD_RST : STM32.GPIO.GPIO_Point renames Shield_PWM1;
LCD_RS : STM32.GPIO.GPIO_Point renames Shield_PWM2;
LCD_CS : STM32.GPIO.GPIO_Point renames Shield_SEL;
All_Points : constant STM32.GPIO.GPIO_Points := (LCD_RS, LCD_CS, LCD_RST);
LCD_Driver : ST7735R_RAM_Framebuffer_Screen (Shield_SPI'Access,
LCD_CS'Access,
LCD_RS'Access,
LCD_RST'Access,
Ravenscar_Time.Delays);
Is_Initialized : Boolean := False;
-----------------
-- Initialized --
-----------------
function Initialized return Boolean is (Is_Initialized);
----------------
-- Initialize --
----------------
procedure Initialize is
GPIO_Conf : STM32.GPIO.GPIO_Port_Configuration;
begin
-- Initalize shield SPI port
Initialize_Shield_SPI;
STM32.Device.Enable_Clock (All_Points);
GPIO_Conf.Mode := STM32.GPIO.Mode_Out;
GPIO_Conf.Output_Type := STM32.GPIO.Push_Pull;
GPIO_Conf.Speed := STM32.GPIO.Speed_100MHz;
GPIO_Conf.Resistors := STM32.GPIO.Floating;
STM32.GPIO.Configure_IO (All_Points, GPIO_Conf);
Initialize (LCD_Driver);
Set_Memory_Data_Access
(LCD => LCD_Driver,
Color_Order => RGB_Order,
Vertical => Vertical_Refresh_Top_Bottom,
Horizontal => Horizontal_Refresh_Left_Right,
Row_Addr_Order => Row_Address_Bottom_Top,
Column_Addr_Order => Column_Address_Right_Left,
Row_Column_Exchange => False);
Set_Pixel_Format (LCD_Driver, Pixel_16bits);
Set_Frame_Rate_Normal (LCD_Driver,
RTN => 16#01#,
Front_Porch => 16#2C#,
Back_Porch => 16#2D#);
Set_Frame_Rate_Idle (LCD_Driver,
RTN => 16#01#,
Front_Porch => 16#2C#,
Back_Porch => 16#2D#);
Set_Frame_Rate_Partial_Full (LCD_Driver,
RTN_Part => 16#01#,
Front_Porch_Part => 16#2C#,
Back_Porch_Part => 16#2D#,
RTN_Full => 16#01#,
Front_Porch_Full => 16#2C#,
Back_Porch_Full => 16#2D#);
Set_Inversion_Control (LCD_Driver,
Normal => Line_Inversion,
Idle => Line_Inversion,
Full_Partial => Line_Inversion);
Set_Power_Control_1 (LCD_Driver,
AVDD => 2#101#, -- 5
VRHP => 2#0_0010#, -- 4.6
VRHN => 2#0_0010#, -- -4.6
MODE => 2#10#); -- AUTO
Set_Power_Control_2 (LCD_Driver,
VGH25 => 2#11#, -- 2.4
VGSEL => 2#01#, -- 3*AVDD
VGHBT => 2#01#); -- -10
Set_Power_Control_3 (LCD_Driver, 16#0A#, 16#00#);
Set_Power_Control_4 (LCD_Driver, 16#8A#, 16#2A#);
Set_Power_Control_5 (LCD_Driver, 16#8A#, 16#EE#);
Set_Vcom (LCD_Driver, 16#E#);
Set_Address (LCD_Driver,
X_Start => 0,
X_End => 127,
Y_Start => 0,
Y_End => 159);
Turn_On (LCD_Driver);
LCD_Driver.Initialize_Layer (Layer => 1,
Mode => HAL.Bitmap.RGB_565,
X => 0,
Y => 0,
Width => Image_Width,
Height => Image_Height);
Is_Initialized := True;
end Initialize;
----------------
-- Get_Bitmap --
----------------
function Get_Bitmap return not null HAL.Bitmap.Any_Bitmap_Buffer is
begin
return LCD_Driver.Hidden_Buffer (1);
end Get_Bitmap;
----------------------
-- Rotate_Screen_90 --
----------------------
procedure Rotate_Screen_90 is
begin
Set_Memory_Data_Access
(LCD => LCD_Driver,
Color_Order => RGB_Order,
Vertical => Vertical_Refresh_Top_Bottom,
Horizontal => Horizontal_Refresh_Left_Right,
Row_Addr_Order => Row_Address_Top_Bottom,
Column_Addr_Order => Column_Address_Left_Right,
Row_Column_Exchange => False);
end Rotate_Screen_90;
---------------------
-- Rotate_Screen_0 --
---------------------
procedure Rotate_Screen_0 is
begin
Set_Memory_Data_Access
(LCD => LCD_Driver,
Color_Order => RGB_Order,
Vertical => Vertical_Refresh_Top_Bottom,
Horizontal => Horizontal_Refresh_Left_Right,
Row_Addr_Order => Row_Address_Bottom_Top,
Column_Addr_Order => Column_Address_Right_Left,
Row_Column_Exchange => False);
end Rotate_Screen_0;
-------------
-- Display --
-------------
procedure Display is
begin
LCD_Driver.Update_Layer (1);
end Display;
end OpenMV.LCD_Shield;
|
Fix screen type name
|
OpenMV: Fix screen type name
|
Ada
|
bsd-3-clause
|
AdaCore/Ada_Drivers_Library,simonjwright/Ada_Drivers_Library,ellamosi/Ada_BMP_Library,Fabien-Chouteau/Ada_Drivers_Library,Fabien-Chouteau/Ada_Drivers_Library,AdaCore/Ada_Drivers_Library,simonjwright/Ada_Drivers_Library
|
f355f02264d1f9a3ff156f91ab40cf6755c30900
|
src/asf-components-holders.ads
|
src/asf-components-holders.ads
|
-----------------------------------------------------------------------
-- components-holders -- Value holder interfaces
-- Copyright (C) 2009, 2010, 2011, 2013 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
-- The <bASF.Components.Holders</b> defines the value holder interfaces
-- which allow to plug a converter and one or several validators.
-- These interfaces must be implemented by UIOutput component and UIInput
-- component to participate in the JSF/ASF lifecycle (validation phase).
with EL.Objects;
with ASF.Converters;
with ASF.Validators;
package ASF.Components.Holders is
-- ------------------------------
-- Value Holder
-- ------------------------------
type Value_Holder is limited interface;
-- Get the local value of the component without evaluating
-- the associated Value_Expression.
function Get_Local_Value (Holder : in Value_Holder) return EL.Objects.Object is abstract;
-- Get the value of the component. If the component has a local
-- value which is not null, returns it. Otherwise, if we have a Value_Expression
-- evaluate and returns the value.
function Get_Value (Holder : in Value_Holder) return EL.Objects.Object is abstract;
-- Set the value of the component.
procedure Set_Value (Holder : in out Value_Holder;
Value : in EL.Objects.Object) is abstract;
-- Get the converter that is registered on the component.
function Get_Converter (Holder : in Value_Holder)
return ASF.Converters.Converter_Access is abstract;
-- Set the converter to be used on the component.
procedure Set_Converter (Holder : in out Value_Holder;
Converter : in ASF.Converters.Converter_Access) is abstract;
-- ------------------------------
-- Editable Value Holder
-- ------------------------------
-- The <b>Editable_Value_Holder</b> extends the <b>Value_Holder</b> to provide
-- operations used when a value can be modified.
type Editable_Value_Holder is limited interface and Value_Holder;
-- Add the validator to be used on the component. The ASF implementation limits
-- to 5 the number of validators that can be set on a component (See UIInput).
-- The validator instance will be freed when the editable value holder is deleted
-- unless <b>Shared</b> is true.
procedure Add_Validator (Holder : in out Editable_Value_Holder;
Validator : in ASF.Validators.Validator_Access;
Shared : in Boolean := False) is abstract;
-- ------------------------------
-- List Holder
-- ------------------------------
-- The <b>List_Holder</b> is an interface used by the data scroller to get some information
-- about how a list is displayed.
type List_Holder is limited interface;
type List_Holder_Access is access all List_Holder'Class;
-- Get the number of rows in the list.
function Get_Row_Count (List : in List_Holder) return Natural is abstract;
-- Get the number of rows per page.
function Get_Row_Per_Page (List : in List_Holder) return Positive is abstract;
-- Get the current page.
function Get_Current_Page (List : in List_Holder) return Positive is abstract;
-- Set the current page number.
procedure Set_Current_Page (List : in out List_Holder;
Page : in Positive) is abstract;
end ASF.Components.Holders;
|
-----------------------------------------------------------------------
-- components-holders -- Value holder interfaces
-- Copyright (C) 2009, 2010, 2011, 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.
-----------------------------------------------------------------------
-- The <bASF.Components.Holders</b> defines the value holder interfaces
-- which allow to plug a converter and one or several validators.
-- These interfaces must be implemented by UIOutput component and UIInput
-- component to participate in the JSF/ASF lifecycle (validation phase).
with EL.Objects;
with ASF.Converters;
with ASF.Validators;
package ASF.Components.Holders is
-- ------------------------------
-- Value Holder
-- ------------------------------
type Value_Holder is limited interface;
-- Get the local value of the component without evaluating
-- the associated Value_Expression.
function Get_Local_Value (Holder : in Value_Holder) return EL.Objects.Object is abstract;
-- Get the value of the component. If the component has a local
-- value which is not null, returns it. Otherwise, if we have a Value_Expression
-- evaluate and returns the value.
function Get_Value (Holder : in Value_Holder) return EL.Objects.Object is abstract;
-- Set the value of the component.
procedure Set_Value (Holder : in out Value_Holder;
Value : in EL.Objects.Object) is abstract;
-- Get the converter that is registered on the component.
function Get_Converter (Holder : in Value_Holder)
return ASF.Converters.Converter_Access is abstract;
-- Set the converter to be used on the component.
procedure Set_Converter (Holder : in out Value_Holder;
Converter : in ASF.Converters.Converter_Access;
Release : in Boolean := False) is abstract;
-- ------------------------------
-- Editable Value Holder
-- ------------------------------
-- The <b>Editable_Value_Holder</b> extends the <b>Value_Holder</b> to provide
-- operations used when a value can be modified.
type Editable_Value_Holder is limited interface and Value_Holder;
-- Add the validator to be used on the component. The ASF implementation limits
-- to 5 the number of validators that can be set on a component (See UIInput).
-- The validator instance will be freed when the editable value holder is deleted
-- unless <b>Shared</b> is true.
procedure Add_Validator (Holder : in out Editable_Value_Holder;
Validator : in ASF.Validators.Validator_Access;
Shared : in Boolean := False) is abstract;
-- ------------------------------
-- List Holder
-- ------------------------------
-- The <b>List_Holder</b> is an interface used by the data scroller to get some information
-- about how a list is displayed.
type List_Holder is limited interface;
type List_Holder_Access is access all List_Holder'Class;
-- Get the number of rows in the list.
function Get_Row_Count (List : in List_Holder) return Natural is abstract;
-- Get the number of rows per page.
function Get_Row_Per_Page (List : in List_Holder) return Positive is abstract;
-- Get the current page.
function Get_Current_Page (List : in List_Holder) return Positive is abstract;
-- Set the current page number.
procedure Set_Current_Page (List : in out List_Holder;
Page : in Positive) is abstract;
end ASF.Components.Holders;
|
Add a Release parameter to the Set_Converter procedure
|
Add a Release parameter to the Set_Converter procedure
|
Ada
|
apache-2.0
|
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
|
30c13260e82cfa97b062bc4726028334eea37314
|
src/el-expressions.ads
|
src/el-expressions.ads
|
-----------------------------------------------------------------------
-- EL.Expressions -- Expression Language
-- Copyright (C) 2009, 2010, 2011, 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
--
-- First, create the expression object:
--
-- E : constant Expression := EL.Expressions.Create_Expression ("obj.count + 3");
--
-- The expression must be evaluated against an expression context.
-- The expression context will resolve variables whose values can change depending
-- on the evaluation context. In the example, ''obj'' is the variable name
-- and ''count'' is the property associated with that variable.
--
-- Value : constant Object := E.Get_Value (Context);
--
-- The ''Value'' holds the result which can be a boolean, an integer, a date,
-- a float number or a string. The value can be converted as follows:
--
-- N : Integer := To_Integer (Value);
--
with EL.Objects;
with Ada.Finalization;
with Ada.Strings.Unbounded;
limited private with EL.Expressions.Nodes;
with EL.Contexts;
with Util.Beans.Methods;
with Util.Beans.Basic;
package EL.Expressions is
pragma Preelaborate;
use EL.Objects;
use EL.Contexts;
-- Exception raised when parsing an invalid expression.
Invalid_Expression : exception;
-- Exception raised when a variable cannot be resolved.
Invalid_Variable : exception;
-- Exception raised when a method cannot be found.
Invalid_Method : exception;
-- A parameter is missing in a function call.
Missing_Argument : exception;
-- ------------------------------
-- Expression
-- ------------------------------
type Expression is new Ada.Finalization.Controlled with private;
type Expression_Access is access all Expression'Class;
-- Check whether the expression is a holds a constant value.
function Is_Constant (Expr : Expression'Class) return Boolean;
-- Returns True if the expression is empty (no constant value and no expression).
function Is_Null (Expr : in Expression'Class) return Boolean;
-- Get the value of the expression using the given expression context.
-- Returns an object that holds a typed result.
function Get_Value (Expr : Expression;
Context : ELContext'Class) return Object;
-- Get the expression string that was parsed.
function Get_Expression (Expr : in Expression) return String;
-- Parse an expression and return its representation ready for evaluation.
-- The context is used to resolve the functions. Variables will be
-- resolved during evaluation of the expression.
-- Raises <b>Invalid_Expression</b> if the expression is invalid.
function Create_Expression (Expr : String;
Context : ELContext'Class)
return Expression;
-- Reduce the expression by eliminating known variables and computing
-- constant expressions. The result expression is either another
-- expression or a computed constant value.
function Reduce_Expression (Expr : Expression;
Context : ELContext'Class)
return Expression;
-- Create an EL expression from an object.
function Create_Expression (Bean : in EL.Objects.Object)
return Expression;
-- ------------------------------
-- ValueExpression
-- ------------------------------ --
type Value_Expression is new Expression with private;
type Value_Expression_Access is access all Value_Expression'Class;
-- Set the value of the expression to the given object value.
procedure Set_Value (Expr : in Value_Expression;
Context : in ELContext'Class;
Value : in Object);
-- Returns true if the expression is read-only.
function Is_Readonly (Expr : in Value_Expression;
Context : in ELContext'Class) return Boolean;
overriding
function Reduce_Expression (Expr : Value_Expression;
Context : ELContext'Class)
return Value_Expression;
-- Parse an expression and return its representation ready for evaluation.
function Create_Expression (Expr : String;
Context : ELContext'Class)
return Value_Expression;
function Create_ValueExpression (Bean : EL.Objects.Object)
return Value_Expression;
-- Create a Value_Expression from an expression.
-- Raises Invalid_Expression if the expression in not an lvalue.
function Create_Expression (Expr : Expression'Class)
return Value_Expression;
-- ------------------------------
-- Method Expression
-- ------------------------------
-- A <b>Method_Expression</b> is an expression that refers to a method.
-- Information about the object and method is retrieved by using
-- the <b>Get_Method_Info</b> operation.
type Method_Expression is new EL.Expressions.Expression with private;
type Method_Info is record
Object : access Util.Beans.Basic.Readonly_Bean'Class;
Binding : Util.Beans.Methods.Method_Binding_Access;
end record;
-- Evaluate the method expression and return the object and method
-- binding to execute the method. The result contains a pointer
-- to the bean object and a method binding. The method binding
-- contains the information to invoke the method
-- (such as an access to the function or procedure).
-- Raises the <b>Invalid_Method</b> exception if the method
-- cannot be resolved.
function Get_Method_Info (Expr : Method_Expression;
Context : ELContext'Class)
return Method_Info;
-- Parse an expression and return its representation ready for evaluation.
-- The context is used to resolve the functions. Variables will be
-- resolved during evaluation of the expression.
-- Raises <b>Invalid_Expression</b> if the expression is invalid.
overriding
function Create_Expression (Expr : String;
Context : EL.Contexts.ELContext'Class)
return Method_Expression;
-- Reduce the expression by eliminating known variables and computing
-- constant expressions. The result expression is either another
-- expression or a computed constant value.
overriding
function Reduce_Expression (Expr : Method_Expression;
Context : EL.Contexts.ELContext'Class)
return Method_Expression;
-- Create a Method_Expression from an expression.
-- Raises Invalid_Expression if the expression in not an lvalue.
function Create_Expression (Expr : Expression'Class)
return Method_Expression;
private
overriding
procedure Adjust (Object : in out Expression);
overriding
procedure Finalize (Object : in out Expression);
type Expression is new Ada.Finalization.Controlled with record
Node : access EL.Expressions.Nodes.ELNode'Class := null;
Value : EL.Objects.Object := EL.Objects.Null_Object;
Expr : Ada.Strings.Unbounded.Unbounded_String;
end record;
type Value_Expression is new Expression with null record;
type Method_Expression is new EL.Expressions.Expression with null record;
end EL.Expressions;
|
-----------------------------------------------------------------------
-- EL.Expressions -- Expression Language
-- Copyright (C) 2009, 2010, 2011, 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.
-----------------------------------------------------------------------
--
-- First, create the expression object:
--
-- E : constant Expression := EL.Expressions.Create_Expression ("obj.count + 3");
--
-- The expression must be evaluated against an expression context.
-- The expression context will resolve variables whose values can change depending
-- on the evaluation context. In the example, ''obj'' is the variable name
-- and ''count'' is the property associated with that variable.
--
-- Value : constant Object := E.Get_Value (Context);
--
-- The ''Value'' holds the result which can be a boolean, an integer, a date,
-- a float number or a string. The value can be converted as follows:
--
-- N : Integer := To_Integer (Value);
--
with EL.Objects;
with Ada.Finalization;
with Ada.Strings.Unbounded;
limited private with EL.Expressions.Nodes;
with EL.Contexts;
with Util.Beans.Methods;
package EL.Expressions is
pragma Preelaborate;
use EL.Objects;
use EL.Contexts;
-- Exception raised when parsing an invalid expression.
Invalid_Expression : exception;
-- Exception raised when a variable cannot be resolved.
Invalid_Variable : exception;
-- Exception raised when a method cannot be found.
Invalid_Method : exception;
-- A parameter is missing in a function call.
Missing_Argument : exception;
-- ------------------------------
-- Expression
-- ------------------------------
type Expression is new Ada.Finalization.Controlled with private;
type Expression_Access is access all Expression'Class;
-- Check whether the expression is a holds a constant value.
function Is_Constant (Expr : Expression'Class) return Boolean;
-- Returns True if the expression is empty (no constant value and no expression).
function Is_Null (Expr : in Expression'Class) return Boolean;
-- Get the value of the expression using the given expression context.
-- Returns an object that holds a typed result.
function Get_Value (Expr : Expression;
Context : ELContext'Class) return Object;
-- Get the expression string that was parsed.
function Get_Expression (Expr : in Expression) return String;
-- Parse an expression and return its representation ready for evaluation.
-- The context is used to resolve the functions. Variables will be
-- resolved during evaluation of the expression.
-- Raises <b>Invalid_Expression</b> if the expression is invalid.
function Create_Expression (Expr : String;
Context : ELContext'Class)
return Expression;
-- Reduce the expression by eliminating known variables and computing
-- constant expressions. The result expression is either another
-- expression or a computed constant value.
function Reduce_Expression (Expr : Expression;
Context : ELContext'Class)
return Expression;
-- Create an EL expression from an object.
function Create_Expression (Bean : in EL.Objects.Object)
return Expression;
-- ------------------------------
-- ValueExpression
-- ------------------------------ --
type Value_Expression is new Expression with private;
type Value_Expression_Access is access all Value_Expression'Class;
-- Set the value of the expression to the given object value.
procedure Set_Value (Expr : in Value_Expression;
Context : in ELContext'Class;
Value : in Object);
-- Returns true if the expression is read-only.
function Is_Readonly (Expr : in Value_Expression;
Context : in ELContext'Class) return Boolean;
overriding
function Reduce_Expression (Expr : Value_Expression;
Context : ELContext'Class)
return Value_Expression;
-- Parse an expression and return its representation ready for evaluation.
function Create_Expression (Expr : String;
Context : ELContext'Class)
return Value_Expression;
function Create_ValueExpression (Bean : EL.Objects.Object)
return Value_Expression;
-- Create a Value_Expression from an expression.
-- Raises Invalid_Expression if the expression in not an lvalue.
function Create_Expression (Expr : Expression'Class)
return Value_Expression;
-- ------------------------------
-- Method Expression
-- ------------------------------
-- A <b>Method_Expression</b> is an expression that refers to a method.
-- Information about the object and method is retrieved by using
-- the <b>Get_Method_Info</b> operation.
type Method_Expression is new EL.Expressions.Expression with private;
type Method_Info is record
Object : EL.Objects.Object;
Binding : Util.Beans.Methods.Method_Binding_Access;
end record;
-- Evaluate the method expression and return the object and method
-- binding to execute the method. The result contains a pointer
-- to the bean object and a method binding. The method binding
-- contains the information to invoke the method
-- (such as an access to the function or procedure).
-- Raises the <b>Invalid_Method</b> exception if the method
-- cannot be resolved.
function Get_Method_Info (Expr : Method_Expression;
Context : ELContext'Class)
return Method_Info;
-- Parse an expression and return its representation ready for evaluation.
-- The context is used to resolve the functions. Variables will be
-- resolved during evaluation of the expression.
-- Raises <b>Invalid_Expression</b> if the expression is invalid.
overriding
function Create_Expression (Expr : String;
Context : EL.Contexts.ELContext'Class)
return Method_Expression;
-- Reduce the expression by eliminating known variables and computing
-- constant expressions. The result expression is either another
-- expression or a computed constant value.
overriding
function Reduce_Expression (Expr : Method_Expression;
Context : EL.Contexts.ELContext'Class)
return Method_Expression;
-- Create a Method_Expression from an expression.
-- Raises Invalid_Expression if the expression in not an lvalue.
function Create_Expression (Expr : Expression'Class)
return Method_Expression;
private
overriding
procedure Adjust (Object : in out Expression);
overriding
procedure Finalize (Object : in out Expression);
type Expression is new Ada.Finalization.Controlled with record
Node : access EL.Expressions.Nodes.ELNode'Class := null;
Value : EL.Objects.Object := EL.Objects.Null_Object;
Expr : Ada.Strings.Unbounded.Unbounded_String;
end record;
type Value_Expression is new Expression with null record;
type Method_Expression is new EL.Expressions.Expression with null record;
end EL.Expressions;
|
Change Method_Info to use an Object to hold the object pointer instead of the access to the Bean instance because GNAT 2020 will generate a Program_Error exception when the object access was assigned
|
Change Method_Info to use an Object to hold the object pointer instead of the access to the Bean instance
because GNAT 2020 will generate a Program_Error exception when the object access was assigned
|
Ada
|
apache-2.0
|
stcarrez/ada-el
|
c92983b349bc4359fddedc499514561aa9e5e316
|
src/security-oauth-clients.ads
|
src/security-oauth-clients.ads
|
-----------------------------------------------------------------------
-- security-oauth -- OAuth Security
-- Copyright (C) 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Security.Permissions;
-- The <b>Security.OAuth.Clients</b> package implements the client OAuth 2.0 authorization.
--
-- Note: OAuth 1.0 could be implemented but since it's being deprecated it's not worth doing it.
package Security.OAuth.Clients is
-- ------------------------------
-- Access Token
-- ------------------------------
-- Access tokens are credentials used to access protected resources.
-- The access token is represented as a <b>Principal</b>. This is an opaque
-- value for an application.
type Access_Token (Len : Natural) is new Security.Permissions.Principal with private;
type Access_Token_Access is access all Access_Token'Class;
-- Returns true if the given role is stored in the user principal.
function Has_Role (User : in Access_Token;
Role : in Permissions.Role_Type) return Boolean;
-- Get the principal name. This is the OAuth access token.
function Get_Name (From : in Access_Token) return String;
-- ------------------------------
-- Application
-- ------------------------------
-- The <b>Application</b> holds the necessary information to let a user
-- grant access to its protected resources on the resource server. It contains
-- information that allows the OAuth authorization server to identify the
-- application (client id and secret key).
type Application is tagged private;
-- Set the application identifier used by the OAuth authorization server
-- to identify the application (for example, the App ID in Facebook).
procedure Set_Application_Identifier (App : in out Application;
Client : in String);
-- Set the application secret defined in the OAuth authorization server
-- for the application (for example, the App Secret in Facebook).
procedure Set_Application_Secret (App : in out Application;
Secret : in String);
-- Set the redirection callback that will be used to redirect the user
-- back to the application after the OAuth authorization is finished.
procedure Set_Application_Callback (App : in out Application;
URI : in String);
-- Set the OAuth authorization server URI that the application must use
-- to exchange the OAuth code into an access token.
procedure Set_Provider_URI (App : in out Application;
URI : in String);
-- OAuth 2.0 Section 4.1.1 Authorization Request
-- Build a unique opaque value used to prevent cross-site request forgery.
-- The <b>Nonce</b> parameters is an optional but recommended unique value
-- used only once. The state value will be returned back by the OAuth provider.
-- This protects the <tt>client_id</tt> and <tt>redirect_uri</tt> parameters.
function Get_State (App : in Application;
Nonce : in String) return String;
-- Get the authenticate parameters to build the URI to redirect the user to
-- the OAuth authorization form.
function Get_Auth_Params (App : in Application;
State : in String;
Scope : in String := "") return String;
-- OAuth 2.0 Section 4.1.2 Authorization Response
-- Verify that the <b>State</b> opaque value was created by the <b>Get_State</b>
-- operation with the given client and redirect URL.
function Is_Valid_State (App : in Application;
Nonce : in String;
State : in String) return Boolean;
-- OAuth 2.0 Section 4.1.3. Access Token Request
-- Section 4.1.4. Access Token Response
-- Exchange the OAuth code into an access token.
function Request_Access_Token (App : in Application;
Code : in String) return Access_Token_Access;
-- Create the access token
function Create_Access_Token (App : in Application;
Token : in String;
Expires : in Natural) return Access_Token_Access;
private
type Access_Token (Len : Natural) is new Security.Permissions.Principal with record
Access_Id : String (1 .. Len);
end record;
type Application is tagged record
Client_Id : Ada.Strings.Unbounded.Unbounded_String;
Secret : Ada.Strings.Unbounded.Unbounded_String;
Callback : Ada.Strings.Unbounded.Unbounded_String;
Request_URI : Ada.Strings.Unbounded.Unbounded_String;
Protect : Ada.Strings.Unbounded.Unbounded_String;
Key : Ada.Strings.Unbounded.Unbounded_String;
end record;
end Security.OAuth.Clients;
|
-----------------------------------------------------------------------
-- security-oauth -- OAuth Security
-- Copyright (C) 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Security.Permissions;
-- The <b>Security.OAuth.Clients</b> package implements the client OAuth 2.0 authorization.
--
-- Note: OAuth 1.0 could be implemented but since it's being deprecated it's not worth doing it.
package Security.OAuth.Clients is
-- ------------------------------
-- Access Token
-- ------------------------------
-- Access tokens are credentials used to access protected resources.
-- The access token is represented as a <b>Principal</b>. This is an opaque
-- value for an application.
type Access_Token (Len : Natural) is new Security.Principal with private;
type Access_Token_Access is access all Access_Token'Class;
-- Get the principal name. This is the OAuth access token.
function Get_Name (From : in Access_Token) return String;
-- ------------------------------
-- Application
-- ------------------------------
-- The <b>Application</b> holds the necessary information to let a user
-- grant access to its protected resources on the resource server. It contains
-- information that allows the OAuth authorization server to identify the
-- application (client id and secret key).
type Application is tagged private;
-- Set the application identifier used by the OAuth authorization server
-- to identify the application (for example, the App ID in Facebook).
procedure Set_Application_Identifier (App : in out Application;
Client : in String);
-- Set the application secret defined in the OAuth authorization server
-- for the application (for example, the App Secret in Facebook).
procedure Set_Application_Secret (App : in out Application;
Secret : in String);
-- Set the redirection callback that will be used to redirect the user
-- back to the application after the OAuth authorization is finished.
procedure Set_Application_Callback (App : in out Application;
URI : in String);
-- Set the OAuth authorization server URI that the application must use
-- to exchange the OAuth code into an access token.
procedure Set_Provider_URI (App : in out Application;
URI : in String);
-- OAuth 2.0 Section 4.1.1 Authorization Request
-- Build a unique opaque value used to prevent cross-site request forgery.
-- The <b>Nonce</b> parameters is an optional but recommended unique value
-- used only once. The state value will be returned back by the OAuth provider.
-- This protects the <tt>client_id</tt> and <tt>redirect_uri</tt> parameters.
function Get_State (App : in Application;
Nonce : in String) return String;
-- Get the authenticate parameters to build the URI to redirect the user to
-- the OAuth authorization form.
function Get_Auth_Params (App : in Application;
State : in String;
Scope : in String := "") return String;
-- OAuth 2.0 Section 4.1.2 Authorization Response
-- Verify that the <b>State</b> opaque value was created by the <b>Get_State</b>
-- operation with the given client and redirect URL.
function Is_Valid_State (App : in Application;
Nonce : in String;
State : in String) return Boolean;
-- OAuth 2.0 Section 4.1.3. Access Token Request
-- Section 4.1.4. Access Token Response
-- Exchange the OAuth code into an access token.
function Request_Access_Token (App : in Application;
Code : in String) return Access_Token_Access;
-- Create the access token
function Create_Access_Token (App : in Application;
Token : in String;
Expires : in Natural) return Access_Token_Access;
private
type Access_Token (Len : Natural) is new Security.Principal with record
Access_Id : String (1 .. Len);
end record;
type Application is tagged record
Client_Id : Ada.Strings.Unbounded.Unbounded_String;
Secret : Ada.Strings.Unbounded.Unbounded_String;
Callback : Ada.Strings.Unbounded.Unbounded_String;
Request_URI : Ada.Strings.Unbounded.Unbounded_String;
Protect : Ada.Strings.Unbounded.Unbounded_String;
Key : Ada.Strings.Unbounded.Unbounded_String;
end record;
end Security.OAuth.Clients;
|
Remove the Has_Role operation
|
Remove the Has_Role operation
|
Ada
|
apache-2.0
|
stcarrez/ada-security
|
38a5deee30e6b21b4b0620b4696f0c150c68c7fe
|
orka/src/orka/interface/orka-strings.ads
|
orka/src/orka/interface/orka-strings.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.Strings.Unbounded;
private package Orka.Strings is
pragma Preelaborate;
function Trim (Value : String) return String;
-- Return value with whitespace removed from both the start and end
function Strip_Line_Term (Value : String) return String;
-- Return the value without any LF and CR characters at the end
function Lines (Value : String) return Positive;
-- Return the number of lines that the string contains
package SU renames Ada.Strings.Unbounded;
function "+" (Value : String) return SU.Unbounded_String renames SU.To_Unbounded_String;
function "+" (Value : SU.Unbounded_String) return String renames SU.To_String;
type String_List is array (Positive range <>) of SU.Unbounded_String;
function Split
(Value : String;
Separator : String := " ";
Maximum : Natural := 0) return String_List;
function Join (List : String_List; Separator : String) return String;
end Orka.Strings;
|
-- 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.Strings.Unbounded;
package Orka.Strings is
pragma Preelaborate;
function Trim (Value : String) return String;
-- Return value with whitespace removed from both the start and end
function Strip_Line_Term (Value : String) return String;
-- Return the value without any LF and CR characters at the end
function Lines (Value : String) return Positive;
-- Return the number of lines that the string contains
package SU renames Ada.Strings.Unbounded;
function "+" (Value : String) return SU.Unbounded_String renames SU.To_Unbounded_String;
function "+" (Value : SU.Unbounded_String) return String renames SU.To_String;
type String_List is array (Positive range <>) of SU.Unbounded_String;
function Split
(Value : String;
Separator : String := " ";
Maximum : Natural := 0) return String_List;
function Join (List : String_List; Separator : String) return String;
end Orka.Strings;
|
Make package Orka.Strings public
|
orka: Make package Orka.Strings public
Signed-off-by: onox <[email protected]>
|
Ada
|
apache-2.0
|
onox/orka
|
0321a4d6b3a34662af447b9d284401b6f4035bd9
|
awa/src/awa-wikis-writers-html.adb
|
awa/src/awa-wikis-writers-html.adb
|
-----------------------------------------------------------------------
-- awa-wikis-writers -- Wiki HTML writer
-- Copyright (C) 2011, 2012, 2013, 2014, 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Strings;
package body AWA.Wikis.Writers.Html is
use AWA.Wikis.Documents;
-- ------------------------------
-- Wiki to HTML writer
-- ------------------------------
-- Set the output writer.
-- ------------------------------
procedure Set_Writer (Document : in out Html_Writer;
Writer : in ASF.Contexts.Writer.Response_Writer_Access) is
begin
Document.Writer := Writer;
end Set_Writer;
-- ------------------------------
-- Add a section header in the document.
-- ------------------------------
overriding
procedure Add_Header (Document : in out Html_Writer;
Header : in Unbounded_Wide_Wide_String;
Level : in Positive) is
begin
Document.Close_Paragraph;
Document.Add_Blockquote (0);
case Level is
when 1 =>
Document.Writer.Write_Wide_Element ("h1", Header);
when 2 =>
Document.Writer.Write_Wide_Element ("h2", Header);
when 3 =>
Document.Writer.Write_Wide_Element ("h3", Header);
when 4 =>
Document.Writer.Write_Wide_Element ("h4", Header);
when 5 =>
Document.Writer.Write_Wide_Element ("h5", Header);
when 6 =>
Document.Writer.Write_Wide_Element ("h6", Header);
when others =>
Document.Writer.Write_Wide_Element ("h3", Header);
end case;
end Add_Header;
-- ------------------------------
-- Add a line break (<br>).
-- ------------------------------
overriding
procedure Add_Line_Break (Document : in out Html_Writer) is
begin
Document.Writer.Start_Element ("br");
Document.Writer.End_Element ("br");
end Add_Line_Break;
-- ------------------------------
-- Add a paragraph (<p>). Close the previous paragraph if any.
-- The paragraph must be closed at the next paragraph or next header.
-- ------------------------------
overriding
procedure Add_Paragraph (Document : in out Html_Writer) is
begin
Document.Close_Paragraph;
Document.Need_Paragraph := True;
end Add_Paragraph;
-- ------------------------------
-- Add a blockquote (<blockquote>). The level indicates the blockquote nested level.
-- The blockquote must be closed at the next header.
-- ------------------------------
overriding
procedure Add_Blockquote (Document : in out Html_Writer;
Level : in Natural) is
begin
if Document.Quote_Level /= Level then
Document.Close_Paragraph;
Document.Need_Paragraph := True;
end if;
while Document.Quote_Level < Level loop
Document.Writer.Start_Element ("blockquote");
Document.Quote_Level := Document.Quote_Level + 1;
end loop;
while Document.Quote_Level > Level loop
Document.Writer.End_Element ("blockquote");
Document.Quote_Level := Document.Quote_Level - 1;
end loop;
end Add_Blockquote;
-- ------------------------------
-- Add a list item (<li>). Close the previous paragraph and list item if any.
-- The list item will be closed at the next list item, next paragraph or next header.
-- ------------------------------
overriding
procedure Add_List_Item (Document : in out Html_Writer;
Level : in Positive;
Ordered : in Boolean) is
begin
if Document.Has_Paragraph then
Document.Writer.End_Element ("p");
Document.Has_Paragraph := False;
end if;
if Document.Has_Item then
Document.Writer.End_Element ("li");
Document.Has_Item := False;
end if;
Document.Need_Paragraph := False;
Document.Open_Paragraph;
while Document.Current_Level < Level loop
if Ordered then
Document.Writer.Start_Element ("ol");
else
Document.Writer.Start_Element ("ul");
end if;
Document.Current_Level := Document.Current_Level + 1;
Document.List_Styles (Document.Current_Level) := Ordered;
end loop;
end Add_List_Item;
procedure Close_Paragraph (Document : in out Html_Writer) is
begin
if Document.Has_Paragraph then
Document.Writer.End_Element ("p");
end if;
if Document.Has_Item then
Document.Writer.End_Element ("li");
end if;
while Document.Current_Level > 0 loop
if Document.List_Styles (Document.Current_Level) then
Document.Writer.End_Element ("ol");
else
Document.Writer.End_Element ("ul");
end if;
Document.Current_Level := Document.Current_Level - 1;
end loop;
Document.Has_Paragraph := False;
Document.Has_Item := False;
end Close_Paragraph;
procedure Open_Paragraph (Document : in out Html_Writer) is
begin
if Document.Need_Paragraph then
Document.Writer.Start_Element ("p");
Document.Has_Paragraph := True;
Document.Need_Paragraph := False;
end if;
if Document.Current_Level > 0 and not Document.Has_Item then
Document.Writer.Start_Element ("li");
Document.Has_Item := True;
end if;
end Open_Paragraph;
-- ------------------------------
-- Add an horizontal rule (<hr>).
-- ------------------------------
overriding
procedure Add_Horizontal_Rule (Document : in out Html_Writer) is
begin
Document.Close_Paragraph;
Document.Add_Blockquote (0);
Document.Writer.Start_Element ("hr");
Document.Writer.End_Element ("hr");
end Add_Horizontal_Rule;
-- ------------------------------
-- Add a link.
-- ------------------------------
overriding
procedure Add_Link (Document : in out Html_Writer;
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
begin
Document.Open_Paragraph;
Document.Writer.Start_Element ("a");
if Length (Title) > 0 then
Document.Writer.Write_Wide_Attribute ("title", Title);
end if;
if Length (Language) > 0 then
Document.Writer.Write_Wide_Attribute ("lang", Language);
end if;
Document.Writer.Write_Wide_Attribute ("href", Link);
Document.Writer.Write_Wide_Text (Name);
Document.Writer.End_Element ("a");
end Add_Link;
-- ------------------------------
-- Add an image.
-- ------------------------------
overriding
procedure Add_Image (Document : in out Html_Writer;
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;
Document.Writer.Start_Element ("img");
if Length (Alt) > 0 then
Document.Writer.Write_Wide_Attribute ("alt", Alt);
end if;
if Length (Description) > 0 then
Document.Writer.Write_Wide_Attribute ("longdesc", Description);
end if;
Document.Writer.Write_Wide_Attribute ("src", Link);
Document.Writer.End_Element ("img");
end Add_Image;
-- ------------------------------
-- Add a quote.
-- ------------------------------
overriding
procedure Add_Quote (Document : in out Html_Writer;
Quote : in Unbounded_Wide_Wide_String;
Link : in Unbounded_Wide_Wide_String;
Language : in Unbounded_Wide_Wide_String) is
begin
Document.Open_Paragraph;
Document.Writer.Start_Element ("q");
if Length (Language) > 0 then
Document.Writer.Write_Wide_Attribute ("lang", Language);
end if;
if Length (Link) > 0 then
Document.Writer.Write_Wide_Attribute ("cite", Link);
end if;
Document.Writer.Write_Wide_Text (Quote);
Document.Writer.End_Element ("q");
end Add_Quote;
HTML_BOLD : aliased constant String := "b";
HTML_ITALIC : aliased constant String := "i";
HTML_CODE : aliased constant String := "tt";
HTML_SUPERSCRIPT : aliased constant String := "sup";
HTML_SUBSCRIPT : aliased constant String := "sub";
HTML_STRIKEOUT : aliased constant String := "del";
-- HTML_UNDERLINE : aliased constant String := "ins";
HTML_PREFORMAT : aliased constant String := "pre";
type String_Array_Access is array (Documents.Format_Type) of Util.Strings.Name_Access;
HTML_ELEMENT : constant String_Array_Access :=
(BOLD => HTML_BOLD'Access,
ITALIC => HTML_ITALIC'Access,
CODE => HTML_CODE'Access,
SUPERSCRIPT => HTML_SUPERSCRIPT'Access,
SUBSCRIPT => HTML_SUBSCRIPT'Access,
STRIKEOUT => HTML_STRIKEOUT'Access,
PREFORMAT => HTML_PREFORMAT'Access);
-- ------------------------------
-- Add a text block with the given format.
-- ------------------------------
overriding
procedure Add_Text (Document : in out Html_Writer;
Text : in Unbounded_Wide_Wide_String;
Format : in AWA.Wikis.Documents.Format_Map) is
begin
Document.Open_Paragraph;
for I in Format'Range loop
if Format (I) then
Document.Writer.Start_Element (HTML_ELEMENT (I).all);
end if;
end loop;
Document.Writer.Write_Wide_Text (Text);
for I in reverse Format'Range loop
if Format (I) then
Document.Writer.End_Element (HTML_ELEMENT (I).all);
end if;
end loop;
end Add_Text;
-- ------------------------------
-- Add a text block that is pre-formatted.
-- ------------------------------
procedure Add_Preformatted (Document : in out Html_Writer;
Text : in Unbounded_Wide_Wide_String;
Format : in Unbounded_Wide_Wide_String) is
begin
Document.Close_Paragraph;
if Format = "html" then
Document.Writer.Write (Text);
else
Document.Writer.Start_Element ("pre");
Document.Writer.Write_Wide_Text (Text);
Document.Writer.End_Element ("pre");
end if;
end Add_Preformatted;
-- ------------------------------
-- Finish the document after complete wiki text has been parsed.
-- ------------------------------
overriding
procedure Finish (Document : in out Html_Writer) is
begin
Document.Close_Paragraph;
Document.Add_Blockquote (0);
end Finish;
end AWA.Wikis.Writers.Html;
|
-----------------------------------------------------------------------
-- awa-wikis-writers -- Wiki HTML writer
-- Copyright (C) 2011, 2012, 2013, 2014, 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Strings;
package body AWA.Wikis.Writers.Html is
use AWA.Wikis.Documents;
-- ------------------------------
-- Wiki to HTML writer
-- ------------------------------
-- Set the output writer.
-- ------------------------------
procedure Set_Writer (Document : in out Html_Writer;
Writer : in ASF.Contexts.Writer.Response_Writer_Access) is
begin
Document.Writer := Writer;
end Set_Writer;
-- ------------------------------
-- Add a section header in the document.
-- ------------------------------
overriding
procedure Add_Header (Document : in out Html_Writer;
Header : in Unbounded_Wide_Wide_String;
Level : in Positive) is
begin
Document.Close_Paragraph;
Document.Add_Blockquote (0);
case Level is
when 1 =>
Document.Writer.Write_Wide_Element ("h1", Header);
when 2 =>
Document.Writer.Write_Wide_Element ("h2", Header);
when 3 =>
Document.Writer.Write_Wide_Element ("h3", Header);
when 4 =>
Document.Writer.Write_Wide_Element ("h4", Header);
when 5 =>
Document.Writer.Write_Wide_Element ("h5", Header);
when 6 =>
Document.Writer.Write_Wide_Element ("h6", Header);
when others =>
Document.Writer.Write_Wide_Element ("h3", Header);
end case;
end Add_Header;
-- ------------------------------
-- Add a line break (<br>).
-- ------------------------------
overriding
procedure Add_Line_Break (Document : in out Html_Writer) is
begin
Document.Writer.Write_Raw ("<br />");
end Add_Line_Break;
-- ------------------------------
-- Add a paragraph (<p>). Close the previous paragraph if any.
-- The paragraph must be closed at the next paragraph or next header.
-- ------------------------------
overriding
procedure Add_Paragraph (Document : in out Html_Writer) is
begin
Document.Close_Paragraph;
Document.Need_Paragraph := True;
end Add_Paragraph;
-- ------------------------------
-- Add a blockquote (<blockquote>). The level indicates the blockquote nested level.
-- The blockquote must be closed at the next header.
-- ------------------------------
overriding
procedure Add_Blockquote (Document : in out Html_Writer;
Level : in Natural) is
begin
if Document.Quote_Level /= Level then
Document.Close_Paragraph;
Document.Need_Paragraph := True;
end if;
while Document.Quote_Level < Level loop
Document.Writer.Start_Element ("blockquote");
Document.Quote_Level := Document.Quote_Level + 1;
end loop;
while Document.Quote_Level > Level loop
Document.Writer.End_Element ("blockquote");
Document.Quote_Level := Document.Quote_Level - 1;
end loop;
end Add_Blockquote;
-- ------------------------------
-- Add a list item (<li>). Close the previous paragraph and list item if any.
-- The list item will be closed at the next list item, next paragraph or next header.
-- ------------------------------
overriding
procedure Add_List_Item (Document : in out Html_Writer;
Level : in Positive;
Ordered : in Boolean) is
begin
if Document.Has_Paragraph then
Document.Writer.End_Element ("p");
Document.Has_Paragraph := False;
end if;
if Document.Has_Item then
Document.Writer.End_Element ("li");
Document.Has_Item := False;
end if;
Document.Need_Paragraph := False;
Document.Open_Paragraph;
while Document.Current_Level < Level loop
if Ordered then
Document.Writer.Start_Element ("ol");
else
Document.Writer.Start_Element ("ul");
end if;
Document.Current_Level := Document.Current_Level + 1;
Document.List_Styles (Document.Current_Level) := Ordered;
end loop;
end Add_List_Item;
procedure Close_Paragraph (Document : in out Html_Writer) is
begin
if Document.Has_Paragraph then
Document.Writer.End_Element ("p");
end if;
if Document.Has_Item then
Document.Writer.End_Element ("li");
end if;
while Document.Current_Level > 0 loop
if Document.List_Styles (Document.Current_Level) then
Document.Writer.End_Element ("ol");
else
Document.Writer.End_Element ("ul");
end if;
Document.Current_Level := Document.Current_Level - 1;
end loop;
Document.Has_Paragraph := False;
Document.Has_Item := False;
end Close_Paragraph;
procedure Open_Paragraph (Document : in out Html_Writer) is
begin
if Document.Need_Paragraph then
Document.Writer.Start_Element ("p");
Document.Has_Paragraph := True;
Document.Need_Paragraph := False;
end if;
if Document.Current_Level > 0 and not Document.Has_Item then
Document.Writer.Start_Element ("li");
Document.Has_Item := True;
end if;
end Open_Paragraph;
-- ------------------------------
-- Add an horizontal rule (<hr>).
-- ------------------------------
overriding
procedure Add_Horizontal_Rule (Document : in out Html_Writer) is
begin
Document.Close_Paragraph;
Document.Add_Blockquote (0);
Document.Writer.Start_Element ("hr");
Document.Writer.End_Element ("hr");
end Add_Horizontal_Rule;
-- ------------------------------
-- Add a link.
-- ------------------------------
overriding
procedure Add_Link (Document : in out Html_Writer;
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
begin
Document.Open_Paragraph;
Document.Writer.Start_Element ("a");
if Length (Title) > 0 then
Document.Writer.Write_Wide_Attribute ("title", Title);
end if;
if Length (Language) > 0 then
Document.Writer.Write_Wide_Attribute ("lang", Language);
end if;
Document.Writer.Write_Wide_Attribute ("href", Link);
Document.Writer.Write_Wide_Text (Name);
Document.Writer.End_Element ("a");
end Add_Link;
-- ------------------------------
-- Add an image.
-- ------------------------------
overriding
procedure Add_Image (Document : in out Html_Writer;
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;
Document.Writer.Start_Element ("img");
if Length (Alt) > 0 then
Document.Writer.Write_Wide_Attribute ("alt", Alt);
end if;
if Length (Description) > 0 then
Document.Writer.Write_Wide_Attribute ("longdesc", Description);
end if;
Document.Writer.Write_Wide_Attribute ("src", Link);
Document.Writer.End_Element ("img");
end Add_Image;
-- ------------------------------
-- Add a quote.
-- ------------------------------
overriding
procedure Add_Quote (Document : in out Html_Writer;
Quote : in Unbounded_Wide_Wide_String;
Link : in Unbounded_Wide_Wide_String;
Language : in Unbounded_Wide_Wide_String) is
begin
Document.Open_Paragraph;
Document.Writer.Start_Element ("q");
if Length (Language) > 0 then
Document.Writer.Write_Wide_Attribute ("lang", Language);
end if;
if Length (Link) > 0 then
Document.Writer.Write_Wide_Attribute ("cite", Link);
end if;
Document.Writer.Write_Wide_Text (Quote);
Document.Writer.End_Element ("q");
end Add_Quote;
HTML_BOLD : aliased constant String := "b";
HTML_ITALIC : aliased constant String := "i";
HTML_CODE : aliased constant String := "tt";
HTML_SUPERSCRIPT : aliased constant String := "sup";
HTML_SUBSCRIPT : aliased constant String := "sub";
HTML_STRIKEOUT : aliased constant String := "del";
-- HTML_UNDERLINE : aliased constant String := "ins";
HTML_PREFORMAT : aliased constant String := "pre";
type String_Array_Access is array (Documents.Format_Type) of Util.Strings.Name_Access;
HTML_ELEMENT : constant String_Array_Access :=
(BOLD => HTML_BOLD'Access,
ITALIC => HTML_ITALIC'Access,
CODE => HTML_CODE'Access,
SUPERSCRIPT => HTML_SUPERSCRIPT'Access,
SUBSCRIPT => HTML_SUBSCRIPT'Access,
STRIKEOUT => HTML_STRIKEOUT'Access,
PREFORMAT => HTML_PREFORMAT'Access);
-- ------------------------------
-- Add a text block with the given format.
-- ------------------------------
overriding
procedure Add_Text (Document : in out Html_Writer;
Text : in Unbounded_Wide_Wide_String;
Format : in AWA.Wikis.Documents.Format_Map) is
begin
Document.Open_Paragraph;
for I in Format'Range loop
if Format (I) then
Document.Writer.Start_Element (HTML_ELEMENT (I).all);
end if;
end loop;
Document.Writer.Write_Wide_Text (Text);
for I in reverse Format'Range loop
if Format (I) then
Document.Writer.End_Element (HTML_ELEMENT (I).all);
end if;
end loop;
end Add_Text;
-- ------------------------------
-- Add a text block that is pre-formatted.
-- ------------------------------
procedure Add_Preformatted (Document : in out Html_Writer;
Text : in Unbounded_Wide_Wide_String;
Format : in Unbounded_Wide_Wide_String) is
begin
Document.Close_Paragraph;
if Format = "html" then
Document.Writer.Write (Text);
else
Document.Writer.Start_Element ("pre");
Document.Writer.Write_Wide_Text (Text);
Document.Writer.End_Element ("pre");
end if;
end Add_Preformatted;
-- ------------------------------
-- Finish the document after complete wiki text has been parsed.
-- ------------------------------
overriding
procedure Finish (Document : in out Html_Writer) is
begin
Document.Close_Paragraph;
Document.Add_Blockquote (0);
end Finish;
end AWA.Wikis.Writers.Html;
|
Write the line break using <br /> instead of <br></br>
|
Write the line break using <br /> instead of <br></br>
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
adb34ce53897ecf4274d81706cf883b3dfcdadee
|
src/tests/aunit/util-xunit.ads
|
src/tests/aunit/util-xunit.ads
|
-----------------------------------------------------------------------
-- util-xunit - Unit tests on top of AUnit
-- Copyright (C) 2009, 2010, 2011, 2019 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with AUnit;
with AUnit.Simple_Test_Cases;
with AUnit.Test_Suites;
with AUnit.Test_Fixtures;
with Ada.Strings.Unbounded;
with GNAT.Source_Info;
-- The <b>Util.XUnit</b> package exposes a common package definition used by the Ada testutil
-- library. It is intended to hide the details of the AUnit implementation.
-- A quite identical package exist for Ahven implementation.
package Util.XUnit is
use Ada.Strings.Unbounded;
use AUnit.Test_Suites;
subtype Status is AUnit.Status;
Success : constant Status := AUnit.Success;
Failure : constant Status := AUnit.Failure;
subtype Message_String is AUnit.Message_String;
subtype Test_Suite is AUnit.Test_Suites.Test_Suite;
subtype Access_Test_Suite is AUnit.Test_Suites.Access_Test_Suite;
function Format (S : in String) return Message_String renames AUnit.Format;
type Test_Case is abstract new AUnit.Simple_Test_Cases.Test_Case with null record;
-- maybe_overriding
procedure Assert (T : in Test_Case;
Condition : in Boolean;
Message : in String := "Test failed";
Source : in String := GNAT.Source_Info.File;
Line : in Natural := GNAT.Source_Info.Line);
type Test is abstract new AUnit.Test_Fixtures.Test_Fixture with null record;
-- maybe_overriding
procedure Assert (T : in Test;
Condition : in Boolean;
Message : in String := "Test failed";
Source : in String := GNAT.Source_Info.File;
Line : in Natural := GNAT.Source_Info.Line);
-- The main testsuite program. This launches the tests, collects the
-- results, create performance logs and set the program exit status
-- according to the testsuite execution status.
generic
with function Suite return Access_Test_Suite;
procedure Harness (Output : in String;
XML : in Boolean;
Label : in String;
Result : out Status);
end Util.XUnit;
|
-----------------------------------------------------------------------
-- util-xunit - Unit tests on top of AUnit
-- Copyright (C) 2009, 2010, 2011, 2019 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with AUnit;
with AUnit.Assertions;
with AUnit.Simple_Test_Cases;
with AUnit.Test_Suites;
with AUnit.Test_Fixtures;
with Ada.Strings.Unbounded;
with GNAT.Source_Info;
-- The <b>Util.XUnit</b> package exposes a common package definition used by the Ada testutil
-- library. It is intended to hide the details of the AUnit implementation.
-- A quite identical package exist for Ahven implementation.
package Util.XUnit is
use Ada.Strings.Unbounded;
use AUnit.Test_Suites;
subtype Status is AUnit.Status;
Success : constant Status := AUnit.Success;
Failure : constant Status := AUnit.Failure;
subtype Message_String is AUnit.Message_String;
subtype Test_Suite is AUnit.Test_Suites.Test_Suite;
subtype Access_Test_Suite is AUnit.Test_Suites.Access_Test_Suite;
Assertion_Error : exception renames AUnit.Assertions.Assertion_Error;
function Format (S : in String) return Message_String renames AUnit.Format;
type Test_Case is abstract new AUnit.Simple_Test_Cases.Test_Case with null record;
-- maybe_overriding
procedure Assert (T : in Test_Case;
Condition : in Boolean;
Message : in String := "Test failed";
Source : in String := GNAT.Source_Info.File;
Line : in Natural := GNAT.Source_Info.Line);
type Test is abstract new AUnit.Test_Fixtures.Test_Fixture with null record;
-- maybe_overriding
procedure Assert (T : in Test;
Condition : in Boolean;
Message : in String := "Test failed";
Source : in String := GNAT.Source_Info.File;
Line : in Natural := GNAT.Source_Info.Line);
-- The main testsuite program. This launches the tests, collects the
-- results, create performance logs and set the program exit status
-- according to the testsuite execution status.
generic
with function Suite return Access_Test_Suite;
procedure Harness (Output : in String;
XML : in Boolean;
Label : in String;
Result : out Status);
end Util.XUnit;
|
Declare the Assertion_Error exception
|
Declare the Assertion_Error exception
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
d59b5a3ef506846713d7545af90a9ada0f6471d4
|
src/xml/util-serialize-io-xml.ads
|
src/xml/util-serialize-io-xml.ads
|
-----------------------------------------------------------------------
-- util-serialize-io-xml -- XML Serialization Driver
-- 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 Sax.Exceptions;
with Sax.Locators;
with Sax.Readers;
with Sax.Attributes;
with Unicode.CES;
with Input_Sources;
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.Buffered_Stream'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
new Util.Streams.Texts.Print_Stream and Util.Serialize.IO.Output_Stream with private;
-- 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_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 a XML name/value attribute.
procedure Write_Attribute (Stream : in out Output_Stream;
Name : in String;
Value : in Util.Beans.Objects.Object);
-- Write a XML name/value entity (see Write_Attribute).
procedure Write_Entity (Stream : in out Output_Stream;
Name : in String;
Value : in Util.Beans.Objects.Object);
-- Starts a XML array.
procedure Start_Array (Stream : in out Output_Stream;
Length : in Ada.Containers.Count_Type);
-- Terminates a XML array.
procedure End_Array (Stream : in out Output_Stream);
-- 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;
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
new Util.Streams.Texts.Print_Stream and Util.Serialize.IO.Output_Stream with record
Close_Start : Boolean := False;
end record;
end Util.Serialize.IO.XML;
|
-----------------------------------------------------------------------
-- util-serialize-io-xml -- XML Serialization Driver
-- Copyright (C) 2011, 2012, 2016 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Sax.Exceptions;
with Sax.Locators;
with Sax.Readers;
with Sax.Attributes;
with Unicode.CES;
with Input_Sources;
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.Buffered_Stream'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
new Util.Streams.Texts.Print_Stream and Util.Serialize.IO.Output_Stream with private;
-- 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 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_Long_Entity (Stream : in out Output_Stream;
Name : in String;
Value : in Long_Long_Integer);
-- Write a XML name/value entity (see Write_Attribute).
procedure Write_Entity (Stream : in out Output_Stream;
Name : in String;
Value : in Util.Beans.Objects.Object);
-- Starts a XML array.
procedure Start_Array (Stream : in out Output_Stream;
Length : in Ada.Containers.Count_Type);
-- Terminates a XML array.
procedure End_Array (Stream : in out Output_Stream);
-- 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;
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
new Util.Streams.Texts.Print_Stream and Util.Serialize.IO.Output_Stream with record
Close_Start : Boolean := False;
end record;
end Util.Serialize.IO.XML;
|
Declare the Write_Escape procedure Override the Write_Attribute, Write_Entity procedures for XML serialization
|
Declare the Write_Escape procedure
Override the Write_Attribute, Write_Entity procedures for XML serialization
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
0c0b37314a3548142c291e9b665b70be9e309197
|
awa/src/awa-permissions.adb
|
awa/src/awa-permissions.adb
|
-----------------------------------------------------------------------
-- awa-permissions -- Permissions module
-- Copyright (C) 2011 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Log.Loggers;
with Util.Beans.Objects;
with Util.Serialize.Mappers.Record_Mapper;
with ADO.Schemas.Entities;
with ADO.Sessions.Entities;
with Security.Contexts;
with AWA.Services.Contexts;
with AWA.Permissions.Controllers;
package body AWA.Permissions is
use Util.Log;
Log : constant Loggers.Logger := Loggers.Create ("AWA.Permissions");
-- ------------------------------
-- Verify that the permission represented by <b>Permission</b> is granted.
-- ------------------------------
procedure Check (Permission : in Security.Permissions.Permission_Index) is
begin
if not (Security.Contexts.Has_Permission (Permission)) then
raise NO_PERMISSION;
end if;
end Check;
-- ------------------------------
-- Verify that the permission represented by <b>Permission</b> is granted to access the
-- database entity represented by <b>Entity</b>.
-- ------------------------------
procedure Check (Permission : in Security.Permissions.Permission_Index;
Entity : in ADO.Identifier) is
use type Security.Contexts.Security_Context_Access;
Context : constant Security.Contexts.Security_Context_Access := Security.Contexts.Current;
Perm : Entity_Permission (Permission);
Result : Boolean;
begin
if Context = null then
Log.Debug ("There is no security context, permission denied");
raise NO_PERMISSION;
end if;
Perm.Entity := Entity;
Context.Has_Permission (Perm, Result);
if not Result then
Log.Debug ("Permission is refused");
raise NO_PERMISSION;
end if;
end Check;
type Controller_Config is record
Name : Util.Beans.Objects.Object;
SQL : Util.Beans.Objects.Object;
Entity : ADO.Entity_Type := 0;
Count : Natural := 0;
Manager : Entity_Policy_Access;
Session : ADO.Sessions.Session;
end record;
type Config_Fields is (FIELD_NAME, FIELD_ENTITY_TYPE, FIELD_ENTITY_PERMISSION, FIELD_SQL);
type Controller_Config_Access is access all Controller_Config;
procedure Set_Member (Into : in out Controller_Config;
Field : in Config_Fields;
Value : in Util.Beans.Objects.Object);
-- ------------------------------
-- Called while parsing the XML policy file when the <name>, <entity-type>, <sql> and
-- <entity-permission> XML entities are found. Create the new permission when the complete
-- permission definition has been parsed and save the permission in the security manager.
-- ------------------------------
procedure Set_Member (Into : in out Controller_Config;
Field : in Config_Fields;
Value : in Util.Beans.Objects.Object) is
use AWA.Permissions.Controllers;
use type ADO.Entity_Type;
begin
case Field is
when FIELD_NAME =>
Into.Name := Value;
when FIELD_SQL =>
Into.SQL := Value;
when FIELD_ENTITY_TYPE =>
declare
Name : constant String := Util.Beans.Objects.To_String (Value);
begin
Into.Entity := ADO.Sessions.Entities.Find_Entity_Type (Into.Session, Name);
exception
when ADO.Schemas.Entities.No_Entity_Type =>
raise Util.Serialize.Mappers.Field_Error with "Invalid entity type: " & Name;
end;
when FIELD_ENTITY_PERMISSION =>
declare
Name : constant String := Util.Beans.Objects.To_String (Into.Name);
begin
if Into.Entity = 0 then
raise Util.Serialize.Mappers.Field_Error
with "Permission '" & Name & "' ignored: missing entity type";
end if;
declare
SQL : constant String := Util.Beans.Objects.To_String (Into.SQL);
Perm : constant Entity_Controller_Access
:= new Entity_Controller '(Len => SQL'Length,
SQL => SQL,
Entity => Into.Entity);
begin
Into.Manager.Add_Permission (Name, Perm.all'Access);
Into.Count := 0;
Into.Entity := 0;
end;
end;
end case;
end Set_Member;
package Config_Mapper is
new Util.Serialize.Mappers.Record_Mapper (Element_Type => Controller_Config,
Element_Type_Access => Controller_Config_Access,
Fields => Config_Fields,
Set_Member => Set_Member);
Mapper : aliased Config_Mapper.Mapper;
-- ------------------------------
-- Setup the XML parser to read the <b>entity-permission</b> description. For example:
--
-- <entity-permission>
-- <name>create-workspace</name>
-- <entity-type>WORKSPACE</entity-type>
-- <sql>select acl.id from acl where ...</sql>
-- </entity-permission>
--
-- This defines a permission <b>create-workspace</b> that will be granted if the
-- SQL statement returns a non empty list.
-- ------------------------------
-- ------------------------------
-- Get the policy name.
-- ------------------------------
overriding
function Get_Name (From : in Entity_Policy) return String is
begin
return NAME;
end Get_Name;
-- ------------------------------
-- Setup the XML parser to read the <b>policy</b> description.
-- ------------------------------
overriding
procedure Prepare_Config (Policy : in out Entity_Policy;
Reader : in out Util.Serialize.IO.XML.Parser) is
Config : Controller_Config_Access := new Controller_Config;
begin
Reader.Add_Mapping ("policy-rules", Mapper'Access);
Reader.Add_Mapping ("module", Mapper'Access);
Config.Manager := Policy'Unchecked_Access;
Config.Session := AWA.Services.Contexts.Get_Session (AWA.Services.Contexts.Current);
Config_Mapper.Set_Context (Reader, Config);
end Prepare_Config;
begin
Mapper.Add_Mapping ("entity-permission", FIELD_ENTITY_PERMISSION);
Mapper.Add_Mapping ("entity-permission/name", FIELD_NAME);
Mapper.Add_Mapping ("entity-permission/entity-type", FIELD_ENTITY_TYPE);
Mapper.Add_Mapping ("entity-permission/sql", FIELD_SQL);
end AWA.Permissions;
|
-----------------------------------------------------------------------
-- awa-permissions -- Permissions module
-- Copyright (C) 2011 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Log.Loggers;
with Util.Beans.Objects;
with Util.Serialize.Mappers.Record_Mapper;
with ADO.Schemas.Entities;
with ADO.Sessions.Entities;
with Security.Contexts;
with AWA.Services.Contexts;
with AWA.Permissions.Controllers;
package body AWA.Permissions is
use Util.Log;
Log : constant Loggers.Logger := Loggers.Create ("AWA.Permissions");
-- ------------------------------
-- Verify that the permission represented by <b>Permission</b> is granted.
-- ------------------------------
procedure Check (Permission : in Security.Permissions.Permission_Index) is
begin
if not (Security.Contexts.Has_Permission (Permission)) then
raise NO_PERMISSION;
end if;
end Check;
-- ------------------------------
-- Verify that the permission represented by <b>Permission</b> is granted to access the
-- database entity represented by <b>Entity</b>.
-- ------------------------------
procedure Check (Permission : in Security.Permissions.Permission_Index;
Entity : in ADO.Identifier) is
use type Security.Contexts.Security_Context_Access;
Context : constant Security.Contexts.Security_Context_Access := Security.Contexts.Current;
Perm : Entity_Permission (Permission);
begin
if Context = null then
Log.Debug ("There is no security context, permission denied");
raise NO_PERMISSION;
end if;
Perm.Entity := Entity;
if not Context.Has_Permission (Perm) then
Log.Debug ("Permission is refused");
raise NO_PERMISSION;
end if;
end Check;
type Controller_Config is record
Name : Util.Beans.Objects.Object;
SQL : Util.Beans.Objects.Object;
Entity : ADO.Entity_Type := 0;
Count : Natural := 0;
Manager : Entity_Policy_Access;
Session : ADO.Sessions.Session;
end record;
type Config_Fields is (FIELD_NAME, FIELD_ENTITY_TYPE, FIELD_ENTITY_PERMISSION, FIELD_SQL);
type Controller_Config_Access is access all Controller_Config;
procedure Set_Member (Into : in out Controller_Config;
Field : in Config_Fields;
Value : in Util.Beans.Objects.Object);
-- ------------------------------
-- Called while parsing the XML policy file when the <name>, <entity-type>, <sql> and
-- <entity-permission> XML entities are found. Create the new permission when the complete
-- permission definition has been parsed and save the permission in the security manager.
-- ------------------------------
procedure Set_Member (Into : in out Controller_Config;
Field : in Config_Fields;
Value : in Util.Beans.Objects.Object) is
use AWA.Permissions.Controllers;
use type ADO.Entity_Type;
begin
case Field is
when FIELD_NAME =>
Into.Name := Value;
when FIELD_SQL =>
Into.SQL := Value;
when FIELD_ENTITY_TYPE =>
declare
Name : constant String := Util.Beans.Objects.To_String (Value);
begin
Into.Entity := ADO.Sessions.Entities.Find_Entity_Type (Into.Session, Name);
exception
when ADO.Schemas.Entities.No_Entity_Type =>
raise Util.Serialize.Mappers.Field_Error with "Invalid entity type: " & Name;
end;
when FIELD_ENTITY_PERMISSION =>
declare
Name : constant String := Util.Beans.Objects.To_String (Into.Name);
begin
if Into.Entity = 0 then
raise Util.Serialize.Mappers.Field_Error
with "Permission '" & Name & "' ignored: missing entity type";
end if;
declare
SQL : constant String := Util.Beans.Objects.To_String (Into.SQL);
Perm : constant Entity_Controller_Access
:= new Entity_Controller '(Len => SQL'Length,
SQL => SQL,
Entity => Into.Entity);
begin
Into.Manager.Add_Permission (Name, Perm.all'Access);
Into.Count := 0;
Into.Entity := 0;
end;
end;
end case;
end Set_Member;
package Config_Mapper is
new Util.Serialize.Mappers.Record_Mapper (Element_Type => Controller_Config,
Element_Type_Access => Controller_Config_Access,
Fields => Config_Fields,
Set_Member => Set_Member);
Mapper : aliased Config_Mapper.Mapper;
-- ------------------------------
-- Setup the XML parser to read the <b>entity-permission</b> description. For example:
--
-- <entity-permission>
-- <name>create-workspace</name>
-- <entity-type>WORKSPACE</entity-type>
-- <sql>select acl.id from acl where ...</sql>
-- </entity-permission>
--
-- This defines a permission <b>create-workspace</b> that will be granted if the
-- SQL statement returns a non empty list.
-- ------------------------------
-- ------------------------------
-- Get the policy name.
-- ------------------------------
overriding
function Get_Name (From : in Entity_Policy) return String is
begin
return NAME;
end Get_Name;
-- ------------------------------
-- Setup the XML parser to read the <b>policy</b> description.
-- ------------------------------
overriding
procedure Prepare_Config (Policy : in out Entity_Policy;
Reader : in out Util.Serialize.IO.XML.Parser) is
Config : Controller_Config_Access := new Controller_Config;
begin
Reader.Add_Mapping ("policy-rules", Mapper'Access);
Reader.Add_Mapping ("module", Mapper'Access);
Config.Manager := Policy'Unchecked_Access;
Config.Session := AWA.Services.Contexts.Get_Session (AWA.Services.Contexts.Current);
Config_Mapper.Set_Context (Reader, Config);
end Prepare_Config;
begin
Mapper.Add_Mapping ("entity-permission", FIELD_ENTITY_PERMISSION);
Mapper.Add_Mapping ("entity-permission/name", FIELD_NAME);
Mapper.Add_Mapping ("entity-permission/entity-type", FIELD_ENTITY_TYPE);
Mapper.Add_Mapping ("entity-permission/sql", FIELD_SQL);
end AWA.Permissions;
|
Fix compilation after changes in Ada Security packages
|
Fix compilation after changes in Ada Security packages
|
Ada
|
apache-2.0
|
tectronics/ada-awa,Letractively/ada-awa,Letractively/ada-awa,tectronics/ada-awa,tectronics/ada-awa,Letractively/ada-awa
|
62081e230c8727a40a61c883a4fe4873e71f98d0
|
src/asf-contexts-exceptions-iterator.adb
|
src/asf-contexts-exceptions-iterator.adb
|
-----------------------------------------------------------------------
-- asf-contexts-exceptions-iterator -- Exception handlers in faces context
-- Copyright (C) 2011, 2021 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Unchecked_Deallocation;
-- ------------------------------
-- Iterate over the exception events which are in the queue and execute the given procedure.
-- The procedure should return True in <b>Remove</b> to indicate that the exception has been
-- processed.
--
-- Notes: this procedure should not be called directly (use ASF.Contexts.Faces.Iterate).
-- This procedure is separate to avoid circular dependency.
-- ------------------------------
package body ASF.Contexts.Exceptions.Iterator is
procedure Iterate
(Queue : in out Exception_Queue;
Context : in out ASF.Contexts.Faces.Faces_Context'Class;
Process : not null
access procedure (Event : in ASF.Events.Exceptions.Exception_Event'Class;
Remove : out Boolean;
Context : in out Contexts.Faces.Faces_Context'Class)) is
procedure Free is
new Ada.Unchecked_Deallocation (Object => ASF.Events.Exceptions.Exception_Event'Class,
Name => ASF.Events.Exceptions.Exception_Event_Access);
Event : ASF.Events.Exceptions.Exception_Event_Access;
Remove : Boolean := False;
Pos : Natural := 1;
Len : Natural := Natural (Queue.Unhandled_Events.Length);
begin
while Pos <= Len loop
Event := Queue.Unhandled_Events.Element (Pos);
Process (Event.all, Remove, Context);
if Remove then
ASF.Events.Exceptions.Event_Vectors.Delete (Queue.Unhandled_Events, Pos);
Free (Event);
if Len > 0 then
Len := Len - 1;
end if;
else
Pos := Pos + 1;
end if;
end loop;
end Iterate;
end ASF.Contexts.Exceptions.Iterator;
|
-----------------------------------------------------------------------
-- asf-contexts-exceptions-iterator -- Exception handlers in faces context
-- Copyright (C) 2011, 2021, 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.Unchecked_Deallocation;
-- ------------------------------
-- Iterate over the exception events which are in the queue and execute the given procedure.
-- The procedure should return True in <b>Remove</b> to indicate that the exception has been
-- processed.
--
-- Notes: this procedure should not be called directly (use ASF.Contexts.Faces.Iterate).
-- This procedure is separate to avoid circular dependency.
-- ------------------------------
package body ASF.Contexts.Exceptions.Iterator is
procedure Iterate
(Queue : in out Exception_Queue;
Context : in out ASF.Contexts.Faces.Faces_Context'Class;
Process : not null
access procedure (Event : in ASF.Events.Exceptions.Exception_Event'Class;
Remove : out Boolean;
Context : in out Contexts.Faces.Faces_Context'Class)) is
procedure Free is
new Ada.Unchecked_Deallocation (Object => ASF.Events.Exceptions.Exception_Event'Class,
Name => ASF.Events.Exceptions.Exception_Event_Access);
Event : ASF.Events.Exceptions.Exception_Event_Access;
Remove : Boolean := False;
Pos : Natural := 1;
Len : Natural := Natural (Queue.Unhandled_Events.Length);
begin
while Pos <= Len loop
Event := Queue.Unhandled_Events.Element (Pos);
Process (Event.all, Remove, Context);
if Remove then
ASF.Events.Exceptions.Event_Vectors.Delete (Queue.Unhandled_Events, Pos);
Free (Event);
if Len > 0 then
Len := Len - 1;
end if;
else
Pos := Pos + 1;
end if;
end loop;
end Iterate;
end ASF.Contexts.Exceptions.Iterator;
|
Fix compilation warning: remove spurious spaces
|
Fix compilation warning: remove spurious spaces
|
Ada
|
apache-2.0
|
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
|
beb20dc1d95e8b13f6a7f5d454db334fedfdec1b
|
testutil/aunit/util-tests-reporter.adb
|
testutil/aunit/util-tests-reporter.adb
|
------------------------------------------------------------------------------
-- --
-- GNAT COMPILER COMPONENTS --
-- --
-- A U N I T . R E P O R T E R . X M L --
-- --
-- B o d y --
-- --
-- --
-- Copyright (C) 2000-2009, AdaCore --
-- --
-- GNAT is free software; you can redistribute it and/or modify it under --
-- terms of the GNU General Public License as published by the Free Soft- --
-- ware Foundation; either version 2, or (at your option) any later ver- --
-- sion. GNAT is distributed in the hope that it will be useful, but WITH- --
-- OUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY --
-- or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License --
-- for more details. You should have received a copy of the GNU General --
-- Public License distributed with GNAT; see file COPYING. If not, write --
-- to the Free Software Foundation, 51 Franklin Street, Fifth Floor, --
-- Boston, MA 02110-1301, USA. --
-- --
-- GNAT is maintained by AdaCore (http://www.adacore.com) --
-- --
------------------------------------------------------------------------------
with Util.Strings;
with Util.Strings.Transforms;
with AUnit.Time_Measure;
-- Very simple reporter to console
package body Util.Tests.Reporter is
use AUnit.Test_Results;
use type AUnit.Message_String;
use type AUnit.Time_Measure.Time;
use Ada.Text_IO;
procedure Print_Summary (R : in out Result'Class);
procedure Dump_Result_List (File : in Ada.Text_IO.File_Type;
L : in Result_Lists.List);
-- List failed assertions
-- procedure Put_Measure is new Gen_Put_Measure;
-- Output elapsed time
procedure Report_Test (File : in Ada.Text_IO.File_Type;
Test : in Test_Result);
-- Report a single assertion failure or unexpected exception
procedure Put (File : in Ada.Text_IO.File_Type;
I : in Integer);
procedure Put (File : in Ada.Text_IO.File_Type;
T : in AUnit.Time_Measure.Time);
procedure Put (File : in Ada.Text_IO.File_Type;
I : in Integer) is
begin
Ada.Text_IO.Put (File, Util.Strings.Image (I));
end Put;
procedure Put (File : in Ada.Text_IO.File_Type;
T : in AUnit.Time_Measure.Time) is
use Ada.Calendar;
D : constant Duration := T.Stop - T.Start;
S : constant String := Duration'Image (D);
Pos : Natural := S'Last;
begin
while Pos > S'First and S (Pos) = '0' loop
Pos := Pos - 1;
end loop;
if D >= 0.0 then
Put (File, S (S'First + 1 .. Pos));
else
Put (File, S (S'First .. Pos));
end if;
end Put;
----------------------
-- Dump_Result_List --
----------------------
procedure Dump_Result_List (File : in Ada.Text_IO.File_Type;
L : in Result_Lists.List) is
use Result_Lists;
C : Cursor := First (L);
begin
-- Note: can't use Iterate because it violates restriction
-- No_Implicit_Dynamic_Code
while Has_Element (C) loop
Report_Test (File, Element (C));
Next (C);
end loop;
end Dump_Result_List;
------------
-- Report --
------------
procedure Report (Engine : XML_Reporter;
R : in out Result'Class)
is
Output : Ada.Text_IO.File_Type;
begin
Ada.Text_IO.Create (File => Output,
Mode => Ada.Text_IO.Out_File,
Name => To_String (Engine.File));
Engine.Report (Output, R);
Ada.Text_IO.Close (Output);
end Report;
procedure Print_Summary (R : in out Result'Class) is
S_Count : constant Integer := Integer (Success_Count (R));
F_Count : constant Integer := Integer (Failure_Count (R));
E_Count : constant Integer := Integer (Error_Count (R));
begin
New_Line;
Put ("Total Tests Run: ");
Put (Util.Strings.Image (Integer (Test_Count (R))));
New_Line;
Put ("Successful Tests: ");
Put (Util.Strings.Image (S_Count));
New_Line;
Put ("Failed Assertions: ");
Put (Util.Strings.Image (F_Count));
New_Line;
Put ("Unexpected Errors: ");
Put (Util.Strings.Image (E_Count));
New_Line;
end Print_Summary;
------------
-- Report --
------------
procedure Report (Engine : XML_Reporter;
File : in out Ada.Text_IO.File_Type;
R : in out Result'Class)
is
pragma Unreferenced (Engine);
begin
Put_Line (File, "<?xml version='1.0' encoding='utf-8' ?>");
Put (File, "<TestRun");
if Elapsed (R) /= AUnit.Time_Measure.Null_Time then
Put (File, " elapsed='");
Put (File, Elapsed (R));
Put_Line (File, "'>");
else
Put_Line (File, ">");
end if;
Print_Summary (R);
Put_Line (File, " <Statistics>");
Put (File, " <Tests>");
Put (File, Integer (Test_Count (R)));
Put_Line (File, "</Tests>");
Put (File, " <FailuresTotal>");
Put (File, Integer (Failure_Count (R)) + Integer (Error_Count (R)));
Put_Line (File, "</FailuresTotal>");
Put (File, " <Failures>");
Put (File, Integer (Failure_Count (R)));
Put_Line (File, "</Failures>");
Put (File, " <Errors>");
Put (File, Integer (Error_Count (R)));
Put_Line (File, "</Errors>");
Put_Line (File, " </Statistics>");
declare
S : Result_Lists.List;
begin
Put_Line (File, " <SuccessfulTests>");
Successes (R, S);
Dump_Result_List (File, S);
Put_Line (File, " </SuccessfulTests>");
end;
Put_Line (File, " <FailedTests>");
declare
F : Result_Lists.List;
begin
Failures (R, F);
Dump_Result_List (File, F);
end;
declare
E : Result_Lists.List;
begin
Errors (R, E);
Dump_Result_List (File, E);
end;
Put_Line (File, " </FailedTests>");
Put_Line (File, "</TestRun>");
end Report;
------------------
-- Report_Error --
------------------
procedure Report_Test (File : in Ada.Text_IO.File_Type;
Test : in Test_Result) is
use Util.Strings.Transforms;
use type Ada.Calendar.Time;
Is_Assert : Boolean;
begin
Put (File, " <Test");
if Test.Elapsed /= AUnit.Time_Measure.Null_Time then
Put (File, " elapsed='");
Put (File, Test.Elapsed);
Put_Line (File, "'>");
else
Put_Line (File, ">");
end if;
Put (File, " <Name>");
Put (File, Escape_Xml (Test.Test_Name.all));
if Test.Routine_Name /= null then
Put (File, " : ");
Put (File, Escape_Xml (Test.Routine_Name.all));
end if;
Put_Line (File, "</Name>");
if Test.Failure /= null or else Test.Error /= null then
if Test.Failure /= null then
Is_Assert := True;
else
Is_Assert := False;
end if;
Put (File, " <FailureType>");
if Is_Assert then
Put (File, "Assertion");
else
Put (File, "Error");
end if;
Put_Line (File, "</FailureType>");
Put (File, " <Message>");
if Is_Assert then
Put (File, Escape_Xml (Test.Failure.Message.all));
else
Put (File, Test.Error.Exception_Name.all);
end if;
Put_Line (File, "</Message>");
if Is_Assert then
Put_Line (File, " <Location>");
Put (File, " <File>");
Put (File, Escape_Xml (Test.Failure.Source_Name.all));
Put_Line (File, "</File>");
Put (File, " <Line>");
Put (File, Test.Failure.Line);
Put_Line (File, "</Line>");
Put_Line (File, " </Location>");
else
Put_Line (File, " <Exception>");
Put (File, " <Message>");
Put (File, Test.Error.Exception_Name.all);
Put_Line (File, "</Message>");
if Test.Error.Exception_Message /= null then
Put (File, " <Information>");
Put (File, Escape_Xml (Test.Error.Exception_Message.all));
Put_Line (File, "</Information>");
end if;
if Test.Error.Traceback /= null then
Put (File, " <Traceback>");
Put (File, Escape_Xml (Test.Error.Traceback.all));
Put_Line (File, "</Traceback>");
end if;
Put_Line (File, " </Exception>");
end if;
end if;
Put_Line (File, " </Test>");
end Report_Test;
end Util.Tests.Reporter;
|
------------------------------------------------------------------------------
-- --
-- GNAT COMPILER COMPONENTS --
-- --
-- A U N I T . R E P O R T E R . X M L --
-- --
-- B o d y --
-- --
-- --
-- Copyright (C) 2000-2009, AdaCore --
-- --
-- GNAT is free software; you can redistribute it and/or modify it under --
-- terms of the GNU General Public License as published by the Free Soft- --
-- ware Foundation; either version 2, or (at your option) any later ver- --
-- sion. GNAT is distributed in the hope that it will be useful, but WITH- --
-- OUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY --
-- or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License --
-- for more details. You should have received a copy of the GNU General --
-- Public License distributed with GNAT; see file COPYING. If not, write --
-- to the Free Software Foundation, 51 Franklin Street, Fifth Floor, --
-- Boston, MA 02110-1301, USA. --
-- --
-- GNAT is maintained by AdaCore (http://www.adacore.com) --
-- --
------------------------------------------------------------------------------
with Util.Strings;
with Util.Strings.Transforms;
with AUnit.Time_Measure;
-- Very simple reporter to console
package body Util.Tests.Reporter is
use AUnit.Test_Results;
use type AUnit.Message_String;
use type AUnit.Time_Measure.Time;
use Ada.Text_IO;
procedure Print_Summary (R : in out Result'Class);
procedure Dump_Result_List (File : in Ada.Text_IO.File_Type;
L : in Result_Lists.List);
-- List failed assertions
-- procedure Put_Measure is new Gen_Put_Measure;
-- Output elapsed time
procedure Report_Test (File : in Ada.Text_IO.File_Type;
Test : in Test_Result);
-- Report a single assertion failure or unexpected exception
procedure Put (File : in Ada.Text_IO.File_Type;
I : in Integer);
procedure Put (File : in Ada.Text_IO.File_Type;
T : in AUnit.Time_Measure.Time);
procedure Put (File : in Ada.Text_IO.File_Type;
I : in Integer) is
begin
Ada.Text_IO.Put (File, Util.Strings.Image (I));
end Put;
procedure Put (File : in Ada.Text_IO.File_Type;
T : in AUnit.Time_Measure.Time) is
use Ada.Calendar;
D : constant Duration := T.Stop - T.Start;
S : constant String := Duration'Image (D);
Pos : Natural := S'Last;
begin
while Pos > S'First and S (Pos) = '0' loop
Pos := Pos - 1;
end loop;
if D >= 0.0 then
Put (File, S (S'First + 1 .. Pos));
else
Put (File, S (S'First .. Pos));
end if;
end Put;
----------------------
-- Dump_Result_List --
----------------------
procedure Dump_Result_List (File : in Ada.Text_IO.File_Type;
L : in Result_Lists.List) is
use Result_Lists;
C : Cursor := First (L);
begin
-- Note: can't use Iterate because it violates restriction
-- No_Implicit_Dynamic_Code
while Has_Element (C) loop
Report_Test (File, Element (C));
Next (C);
end loop;
end Dump_Result_List;
------------
-- Report --
------------
procedure Report (Engine : in XML_Reporter;
R : in out Result'Class;
Options : in AUnit.Options.AUnit_Options := AUnit.Options.Default_Options)
is
Output : Ada.Text_IO.File_Type;
begin
Ada.Text_IO.Create (File => Output,
Mode => Ada.Text_IO.Out_File,
Name => To_String (Engine.File));
Engine.Report (Output, R);
Ada.Text_IO.Close (Output);
end Report;
procedure Print_Summary (R : in out Result'Class) is
S_Count : constant Integer := Integer (Success_Count (R));
F_Count : constant Integer := Integer (Failure_Count (R));
E_Count : constant Integer := Integer (Error_Count (R));
begin
New_Line;
Put ("Total Tests Run: ");
Put (Util.Strings.Image (Integer (Test_Count (R))));
New_Line;
Put ("Successful Tests: ");
Put (Util.Strings.Image (S_Count));
New_Line;
Put ("Failed Assertions: ");
Put (Util.Strings.Image (F_Count));
New_Line;
Put ("Unexpected Errors: ");
Put (Util.Strings.Image (E_Count));
New_Line;
end Print_Summary;
------------
-- Report --
------------
procedure Report (Engine : XML_Reporter;
File : in out Ada.Text_IO.File_Type;
R : in out Result'Class)
is
pragma Unreferenced (Engine);
begin
Put_Line (File, "<?xml version='1.0' encoding='utf-8' ?>");
Put (File, "<TestRun");
if Elapsed (R) /= AUnit.Time_Measure.Null_Time then
Put (File, " elapsed='");
Put (File, Elapsed (R));
Put_Line (File, "'>");
else
Put_Line (File, ">");
end if;
Print_Summary (R);
Put_Line (File, " <Statistics>");
Put (File, " <Tests>");
Put (File, Integer (Test_Count (R)));
Put_Line (File, "</Tests>");
Put (File, " <FailuresTotal>");
Put (File, Integer (Failure_Count (R)) + Integer (Error_Count (R)));
Put_Line (File, "</FailuresTotal>");
Put (File, " <Failures>");
Put (File, Integer (Failure_Count (R)));
Put_Line (File, "</Failures>");
Put (File, " <Errors>");
Put (File, Integer (Error_Count (R)));
Put_Line (File, "</Errors>");
Put_Line (File, " </Statistics>");
declare
S : Result_Lists.List;
begin
Put_Line (File, " <SuccessfulTests>");
Successes (R, S);
Dump_Result_List (File, S);
Put_Line (File, " </SuccessfulTests>");
end;
Put_Line (File, " <FailedTests>");
declare
F : Result_Lists.List;
begin
Failures (R, F);
Dump_Result_List (File, F);
end;
declare
E : Result_Lists.List;
begin
Errors (R, E);
Dump_Result_List (File, E);
end;
Put_Line (File, " </FailedTests>");
Put_Line (File, "</TestRun>");
end Report;
------------------
-- Report_Error --
------------------
procedure Report_Test (File : in Ada.Text_IO.File_Type;
Test : in Test_Result) is
use Util.Strings.Transforms;
use type Ada.Calendar.Time;
Is_Assert : Boolean;
begin
Put (File, " <Test");
if Test.Elapsed /= AUnit.Time_Measure.Null_Time then
Put (File, " elapsed='");
Put (File, Test.Elapsed);
Put_Line (File, "'>");
else
Put_Line (File, ">");
end if;
Put (File, " <Name>");
Put (File, Escape_Xml (Test.Test_Name.all));
if Test.Routine_Name /= null then
Put (File, " : ");
Put (File, Escape_Xml (Test.Routine_Name.all));
end if;
Put_Line (File, "</Name>");
if Test.Failure /= null or else Test.Error /= null then
if Test.Failure /= null then
Is_Assert := True;
else
Is_Assert := False;
end if;
Put (File, " <FailureType>");
if Is_Assert then
Put (File, "Assertion");
else
Put (File, "Error");
end if;
Put_Line (File, "</FailureType>");
Put (File, " <Message>");
if Is_Assert then
Put (File, Escape_Xml (Test.Failure.Message.all));
else
Put (File, Test.Error.Exception_Name.all);
end if;
Put_Line (File, "</Message>");
if Is_Assert then
Put_Line (File, " <Location>");
Put (File, " <File>");
Put (File, Escape_Xml (Test.Failure.Source_Name.all));
Put_Line (File, "</File>");
Put (File, " <Line>");
Put (File, Test.Failure.Line);
Put_Line (File, "</Line>");
Put_Line (File, " </Location>");
else
Put_Line (File, " <Exception>");
Put (File, " <Message>");
Put (File, Test.Error.Exception_Name.all);
Put_Line (File, "</Message>");
if Test.Error.Exception_Message /= null then
Put (File, " <Information>");
Put (File, Escape_Xml (Test.Error.Exception_Message.all));
Put_Line (File, "</Information>");
end if;
if Test.Error.Traceback /= null then
Put (File, " <Traceback>");
Put (File, Escape_Xml (Test.Error.Traceback.all));
Put_Line (File, "</Traceback>");
end if;
Put_Line (File, " </Exception>");
end if;
end if;
Put_Line (File, " </Test>");
end Report_Test;
end Util.Tests.Reporter;
|
Fix compilation with AUnit 2014
|
Fix compilation with AUnit 2014
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
e26d83a7d6bf3c99b138e31e43fb0006aae997a8
|
src/security-auth.ads
|
src/security-auth.ads
|
-----------------------------------------------------------------------
-- security-auth -- Authentication Support
-- Copyright (C) 2009, 2010, 2011, 2012, 2013 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Ada.Calendar;
with Ada.Finalization;
-- == Auth ==
-- The <b>Security.Auth</b> package implements an authentication framework that is
-- suitable for OpenID 2.0, OAuth 2.0 and later for OpenID Connect. It allows an application
-- to authenticate users using an external authorization server such as Google, Facebook,
-- Google +, Twitter and others.
--
-- See OpenID Authentication 2.0 - Final
-- http://openid.net/specs/openid-authentication-2_0.html
--
-- See OpenID Connect Standard 1.0
-- http://openid.net/specs/openid-connect-standard-1_0.html
--
-- See Facebook API: The Login Flow for Web (without JavaScript SDK)
-- https://developers.facebook.com/docs/facebook-login/login-flow-for-web-no-jssdk/
--
-- Despite their subtle differences, all these authentication frameworks share almost
-- a common flow. The API provided by <b>Security.Auth</b> defines an abstraction suitable
-- for all these frameworks.
--
-- There are basically two steps that an application must implement:
--
-- * <b>Discovery</b>: to resolve and use the OpenID provider and redirect the user to the
-- provider authentication form.
-- * <b>Verify</b>: to decode the authentication and check its result.
--
-- [http://ada-security.googlecode.com/svn/wiki/OpenID.png]
--
-- The authentication process is the following:
--
-- * The application should redirect the user to the authentication URL.
-- * The OpenID provider authenticate the user and redirects the user to the callback CB.
-- * The association is decoded from the callback parameter.
-- * The <b>Verify</b> procedure is called with the association to check the result and
-- obtain the authentication results.
--
-- === Initialization ===
-- The initialization process must be done before each two steps (discovery and verify).
-- The Authentication manager must be declared and configured.
--
-- Mgr : Security.Auth.Manager;
--
-- For the configuration, the <b>Initialize</b> procedure is called to configure
-- the Auth realm and set the authentication return callback URL. The return callback
-- must be a valid URL that is based on the realm. Example:
--
-- Mgr.Initialize (Name => "http://app.site.com/auth",
-- Return_To => "http://app.site.com/auth/verify",
-- Realm => "openid");
--
-- After this initialization, the authentication manager can be used in the authentication
-- process.
--
-- @include security-auth-openid.ads
-- @include security-auth-oauth.ads
--
-- === Discovery: creating the authentication URL ===
-- The first step is to create an authentication URL to which the user must be redirected.
-- In this step, we have to create an OpenID manager, discover the OpenID provider,
-- do the association and get an <b>End_Point</b>. The OpenID provider is specified as an
-- URL, below is an example for Google OpenID:
--
-- Provider : constant String := "https://www.google.com/accounts/o8/id";
-- OP : Security.Auth.End_Point;
-- Assoc : constant Security.Auth.Association_Access := new Security.Auth.Association;
--
-- The following steps are performed:
--
-- * The <b>Discover</b> procedure is called to retrieve from the OpenID provider the XRDS
-- stream and identify the provider. An <b>End_Point</b> is returned in <tt>OP</tt>.
-- * The <b>Associate</b> procedure is called to make the association with the <b>End_Point</b>.
-- The <b>Association</b> record holds session, and authentication.
--
-- Mgr.Discover (Provider, OP); -- Yadis discovery (get the XRDS file).
-- Mgr.Associate (OP, Assoc.all);-- Associate and get an end-point with a key.
--
-- After this first step, you must manage to save the association in the HTTP session.
-- Then you must redirect to the authentication URL that is obtained by using:
--
-- Auth_URL : constant String := Mgr.Get_Authentication_URL (OP, Assoc.all);
--
-- === Verify: acknowledge the authentication in the callback URL ===
-- The second step is done when the user has finished the authentication successfully or not.
-- For this step, the application must get back the association that was saved in the session.
-- It must also prepare a parameters object that allows the OpenID framework to get the
-- URI parameters from the return callback.
--
-- Assoc : Association_Access := ...; -- Get the association saved in the session.
-- Credential : Security.Auth.Authentication;
-- Params : Auth_Params;
--
-- The auth manager must be initialized and the <b>Verify</b> procedure is called with
-- the association, parameters and the authentication result. The <b>Get_Status</b> function
-- must be used to check that the authentication succeeded.
--
-- Mgr.Verify (Assoc.all, Params, Credential);
-- if Security.Auth.Get_Status (Credential) = Security.Auth.AUTHENTICATED then ... -- Success.
--
-- === Principal creation ===
-- After the user is successfully authenticated, a user principal can be created and saved in
-- the session. The user principal can then be used to assign permissions to that user and
-- enforce the application permissions using the security policy manger.
--
-- P : Security.Auth.Principal_Access := Security.Auth.Create_Principal (Credential);
--
package Security.Auth is
-- Use an authentication server implementing OpenID 2.0.
PROVIDER_OPENID : constant String := "openid";
-- Use the Facebook OAuth 2.0 - draft 12 authentication server.
PROVIDER_FACEBOOK : constant String := "facebook";
Invalid_End_Point : exception;
Service_Error : exception;
type Parameters is limited interface;
function Get_Parameter (Params : in Parameters;
Name : in String) return String is abstract;
-- ------------------------------
-- Auth provider
-- ------------------------------
-- The <b>End_Point</b> represents the authentication provider that will authenticate
-- the user.
type End_Point is private;
function To_String (OP : End_Point) return String;
-- ------------------------------
-- Association
-- ------------------------------
-- The association contains the shared secret between the relying party
-- and the authentication provider. The association can be cached and reused to authenticate
-- different users using the same authentication provider. The association also has an
-- expiration date.
type Association is private;
-- Get the provider.
function Get_Provider (Assoc : in Association) return String;
-- Dump the association as a string (for debugging purposes)
function To_String (Assoc : Association) return String;
type Auth_Result is (AUTHENTICATED, CANCEL, SETUP_NEEDED, UNKNOWN, INVALID_SIGNATURE);
-- ------------------------------
-- Authentication result
-- ------------------------------
--
type Authentication is private;
-- Get the email address
function Get_Email (Auth : in Authentication) return String;
-- Get the user first name.
function Get_First_Name (Auth : in Authentication) return String;
-- Get the user last name.
function Get_Last_Name (Auth : in Authentication) return String;
-- Get the user full name.
function Get_Full_Name (Auth : in Authentication) return String;
-- Get the user identity.
function Get_Identity (Auth : in Authentication) return String;
-- Get the user claimed identity.
function Get_Claimed_Id (Auth : in Authentication) return String;
-- Get the user language.
function Get_Language (Auth : in Authentication) return String;
-- Get the user country.
function Get_Country (Auth : in Authentication) return String;
-- Get the result of the authentication.
function Get_Status (Auth : in Authentication) return Auth_Result;
-- ------------------------------
-- Default principal
-- ------------------------------
type Principal is new Security.Principal with private;
type Principal_Access is access all Principal'Class;
-- Get the principal name.
function Get_Name (From : in Principal) return String;
-- Get the user email address.
function Get_Email (From : in Principal) return String;
-- Get the authentication data.
function Get_Authentication (From : in Principal) return Authentication;
-- Create a principal with the given authentication results.
function Create_Principal (Auth : in Authentication) return Principal_Access;
-- ------------------------------
-- Authentication Manager
-- ------------------------------
-- The <b>Manager</b> provides the core operations for the authentication process.
type Manager is tagged limited private;
-- Initialize the authentication realm.
procedure Initialize (Realm : in out Manager;
Params : in Parameters'Class;
Provider : in String := PROVIDER_OPENID);
-- Discover the authentication provider that must be used to authenticate the user.
-- The <b>Name</b> can be an URL or an alias that identifies the provider.
-- A cached OpenID provider can be returned. The discover step may do nothing for
-- authentication providers based on OAuth.
-- (See OpenID Section 7.3 Discovery)
procedure Discover (Realm : in out Manager;
Name : in String;
Result : out End_Point);
-- Associate the application (relying party) with the authentication provider.
-- The association can be cached.
-- (See OpenID Section 8 Establishing Associations)
procedure Associate (Realm : in out Manager;
OP : in End_Point;
Result : out Association);
-- Get the authentication URL to which the user must be redirected for authentication
-- by the authentication server.
function Get_Authentication_URL (Realm : in Manager;
OP : in End_Point;
Assoc : in Association) return String;
-- Verify the authentication result
procedure Verify (Realm : in out Manager;
Assoc : in Association;
Request : in Parameters'Class;
Result : out Authentication);
private
use Ada.Strings.Unbounded;
type Association is record
Provider : Unbounded_String;
Session_Type : Unbounded_String;
Assoc_Type : Unbounded_String;
Assoc_Handle : Unbounded_String;
Mac_Key : Unbounded_String;
Expired : Ada.Calendar.Time;
end record;
type Authentication is record
Status : Auth_Result;
Identity : Unbounded_String;
Claimed_Id : Unbounded_String;
Email : Unbounded_String;
Full_Name : Unbounded_String;
First_Name : Unbounded_String;
Last_Name : Unbounded_String;
Language : Unbounded_String;
Country : Unbounded_String;
Gender : Unbounded_String;
Timezone : Unbounded_String;
Nickname : Unbounded_String;
end record;
type End_Point is record
URL : Unbounded_String;
Alias : Unbounded_String;
Expired : Ada.Calendar.Time;
end record;
type Manager_Access is access all Manager'Class;
type Manager is new Ada.Finalization.Limited_Controlled with record
Provider : Unbounded_String;
Delegate : Manager_Access;
end record;
type Principal is new Security.Principal with record
Auth : Authentication;
end record;
procedure Set_Result (Result : in out Authentication;
Status : in Auth_Result;
Message : in String);
end Security.Auth;
|
-----------------------------------------------------------------------
-- security-auth -- Authentication Support
-- Copyright (C) 2009, 2010, 2011, 2012, 2013 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Ada.Calendar;
with Ada.Finalization;
-- == Auth ==
-- The <b>Security.Auth</b> package implements an authentication framework that is
-- suitable for OpenID 2.0, OAuth 2.0 and later for OpenID Connect. It allows an application
-- to authenticate users using an external authorization server such as Google, Facebook,
-- Google +, Twitter and others.
--
-- See OpenID Authentication 2.0 - Final
-- http://openid.net/specs/openid-authentication-2_0.html
--
-- See OpenID Connect Standard 1.0
-- http://openid.net/specs/openid-connect-standard-1_0.html
--
-- See Facebook API: The Login Flow for Web (without JavaScript SDK)
-- https://developers.facebook.com/docs/facebook-login/login-flow-for-web-no-jssdk/
--
-- Despite their subtle differences, all these authentication frameworks share almost
-- a common flow. The API provided by <b>Security.Auth</b> defines an abstraction suitable
-- for all these frameworks.
--
-- There are basically two steps that an application must implement:
--
-- * <b>Discovery</b>: to resolve and use the OpenID provider and redirect the user to the
-- provider authentication form.
-- * <b>Verify</b>: to decode the authentication and check its result.
--
-- [http://ada-security.googlecode.com/svn/wiki/OpenID.png]
--
-- The authentication process is the following:
--
-- * The application should redirect the user to the authentication URL.
-- * The OpenID provider authenticate the user and redirects the user to the callback CB.
-- * The association is decoded from the callback parameter.
-- * The <b>Verify</b> procedure is called with the association to check the result and
-- obtain the authentication results.
--
-- === Initialization ===
-- The initialization process must be done before each two steps (discovery and verify).
-- The Authentication manager must be declared and configured.
--
-- Mgr : Security.Auth.Manager;
--
-- For the configuration, the <b>Initialize</b> procedure is called to configure
-- the Auth realm and set the authentication return callback URL. The return callback
-- must be a valid URL that is based on the realm. Example:
--
-- Mgr.Initialize (Name => "http://app.site.com/auth",
-- Return_To => "http://app.site.com/auth/verify",
-- Realm => "openid");
--
-- After this initialization, the authentication manager can be used in the authentication
-- process.
--
-- @include security-auth-openid.ads
-- @include security-auth-oauth.ads
--
-- === Discovery: creating the authentication URL ===
-- The first step is to create an authentication URL to which the user must be redirected.
-- In this step, we have to create an OpenID manager, discover the OpenID provider,
-- do the association and get an <b>End_Point</b>. The OpenID provider is specified as an
-- URL, below is an example for Google OpenID:
--
-- Provider : constant String := "https://www.google.com/accounts/o8/id";
-- OP : Security.Auth.End_Point;
-- Assoc : constant Security.Auth.Association_Access := new Security.Auth.Association;
--
-- The following steps are performed:
--
-- * The <b>Discover</b> procedure is called to retrieve from the OpenID provider the XRDS
-- stream and identify the provider. An <b>End_Point</b> is returned in <tt>OP</tt>.
-- * The <b>Associate</b> procedure is called to make the association with the <b>End_Point</b>.
-- The <b>Association</b> record holds session, and authentication.
--
-- Mgr.Discover (Provider, OP); -- Yadis discovery (get the XRDS file).
-- Mgr.Associate (OP, Assoc.all);-- Associate and get an end-point with a key.
--
-- After this first step, you must manage to save the association in the HTTP session.
-- Then you must redirect to the authentication URL that is obtained by using:
--
-- Auth_URL : constant String := Mgr.Get_Authentication_URL (OP, Assoc.all);
--
-- === Verify: acknowledge the authentication in the callback URL ===
-- The second step is done when the user has finished the authentication successfully or not.
-- For this step, the application must get back the association that was saved in the session.
-- It must also prepare a parameters object that allows the OpenID framework to get the
-- URI parameters from the return callback.
--
-- Assoc : Association_Access := ...; -- Get the association saved in the session.
-- Credential : Security.Auth.Authentication;
-- Params : Auth_Params;
--
-- The auth manager must be initialized and the <b>Verify</b> procedure is called with
-- the association, parameters and the authentication result. The <b>Get_Status</b> function
-- must be used to check that the authentication succeeded.
--
-- Mgr.Verify (Assoc.all, Params, Credential);
-- if Security.Auth.Get_Status (Credential) = Security.Auth.AUTHENTICATED then ... -- Success.
--
-- === Principal creation ===
-- After the user is successfully authenticated, a user principal can be created and saved in
-- the session. The user principal can then be used to assign permissions to that user and
-- enforce the application permissions using the security policy manger.
--
-- P : Security.Auth.Principal_Access := Security.Auth.Create_Principal (Credential);
--
package Security.Auth is
-- Use an authentication server implementing OpenID 2.0.
PROVIDER_OPENID : constant String := "openid";
-- Use the Facebook OAuth 2.0 - draft 12 authentication server.
PROVIDER_FACEBOOK : constant String := "facebook";
Invalid_End_Point : exception;
Service_Error : exception;
type Parameters is limited interface;
function Get_Parameter (Params : in Parameters;
Name : in String) return String is abstract;
-- ------------------------------
-- Auth provider
-- ------------------------------
-- The <b>End_Point</b> represents the authentication provider that will authenticate
-- the user.
type End_Point is private;
function To_String (OP : End_Point) return String;
-- ------------------------------
-- Association
-- ------------------------------
-- The association contains the shared secret between the relying party
-- and the authentication provider. The association can be cached and reused to authenticate
-- different users using the same authentication provider. The association also has an
-- expiration date.
type Association is private;
-- Get the provider.
function Get_Provider (Assoc : in Association) return String;
-- Dump the association as a string (for debugging purposes)
function To_String (Assoc : Association) return String;
type Auth_Result is (AUTHENTICATED, CANCEL, SETUP_NEEDED, UNKNOWN, INVALID_SIGNATURE);
-- ------------------------------
-- Authentication result
-- ------------------------------
--
type Authentication is private;
-- Get the email address
function Get_Email (Auth : in Authentication) return String;
-- Get the user first name.
function Get_First_Name (Auth : in Authentication) return String;
-- Get the user last name.
function Get_Last_Name (Auth : in Authentication) return String;
-- Get the user full name.
function Get_Full_Name (Auth : in Authentication) return String;
-- Get the user identity.
function Get_Identity (Auth : in Authentication) return String;
-- Get the user claimed identity.
function Get_Claimed_Id (Auth : in Authentication) return String;
-- Get the user language.
function Get_Language (Auth : in Authentication) return String;
-- Get the user country.
function Get_Country (Auth : in Authentication) return String;
-- Get the result of the authentication.
function Get_Status (Auth : in Authentication) return Auth_Result;
-- ------------------------------
-- Default principal
-- ------------------------------
type Principal is new Security.Principal with private;
type Principal_Access is access all Principal'Class;
-- Get the principal name.
function Get_Name (From : in Principal) return String;
-- Get the user email address.
function Get_Email (From : in Principal) return String;
-- Get the authentication data.
function Get_Authentication (From : in Principal) return Authentication;
-- Create a principal with the given authentication results.
function Create_Principal (Auth : in Authentication) return Principal_Access;
-- ------------------------------
-- Authentication Manager
-- ------------------------------
-- The <b>Manager</b> provides the core operations for the authentication process.
type Manager is tagged limited private;
-- Initialize the authentication realm.
procedure Initialize (Realm : in out Manager;
Params : in Parameters'Class;
Name : in String := PROVIDER_OPENID);
-- Discover the authentication provider that must be used to authenticate the user.
-- The <b>Name</b> can be an URL or an alias that identifies the provider.
-- A cached OpenID provider can be returned. The discover step may do nothing for
-- authentication providers based on OAuth.
-- (See OpenID Section 7.3 Discovery)
procedure Discover (Realm : in out Manager;
Name : in String;
Result : out End_Point);
-- Associate the application (relying party) with the authentication provider.
-- The association can be cached.
-- (See OpenID Section 8 Establishing Associations)
procedure Associate (Realm : in out Manager;
OP : in End_Point;
Result : out Association);
-- Get the authentication URL to which the user must be redirected for authentication
-- by the authentication server.
function Get_Authentication_URL (Realm : in Manager;
OP : in End_Point;
Assoc : in Association) return String;
-- Verify the authentication result
procedure Verify (Realm : in out Manager;
Assoc : in Association;
Request : in Parameters'Class;
Result : out Authentication);
private
use Ada.Strings.Unbounded;
type Association is record
Provider : Unbounded_String;
Session_Type : Unbounded_String;
Assoc_Type : Unbounded_String;
Assoc_Handle : Unbounded_String;
Mac_Key : Unbounded_String;
Expired : Ada.Calendar.Time;
end record;
type Authentication is record
Status : Auth_Result;
Identity : Unbounded_String;
Claimed_Id : Unbounded_String;
Email : Unbounded_String;
Full_Name : Unbounded_String;
First_Name : Unbounded_String;
Last_Name : Unbounded_String;
Language : Unbounded_String;
Country : Unbounded_String;
Gender : Unbounded_String;
Timezone : Unbounded_String;
Nickname : Unbounded_String;
end record;
type End_Point is record
URL : Unbounded_String;
Alias : Unbounded_String;
Expired : Ada.Calendar.Time;
end record;
type Manager_Access is access all Manager'Class;
type Manager is new Ada.Finalization.Limited_Controlled with record
Provider : Unbounded_String;
Delegate : Manager_Access;
end record;
type Principal is new Security.Principal with record
Auth : Authentication;
end record;
procedure Set_Result (Result : in out Authentication;
Status : in Auth_Result;
Message : in String);
end Security.Auth;
|
Rename the Initialize parameters
|
Rename the Initialize parameters
|
Ada
|
apache-2.0
|
stcarrez/ada-security
|
8771e9affef5033749f6f6be52e17ff47e88a5d2
|
asfunit/asf-tests.adb
|
asfunit/asf-tests.adb
|
-----------------------------------------------------------------------
-- ASF tests - ASF Tests Framework
-- Copyright (C) 2011, 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with GNAT.Regpat;
with Ada.Strings.Unbounded;
with Util.Files;
with Util.Log.Loggers;
with ASF.Streams;
with ASF.Servlets.Faces;
with ASF.Servlets.Files;
with ASF.Servlets.Ajax;
with ASF.Servlets.Measures;
with ASF.Responses;
with ASF.Responses.Tools;
with ASF.Filters.Dump;
package body ASF.Tests is
use Ada.Strings.Unbounded;
use Util.Tests;
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("ASF.Tests");
CONTEXT_PATH : constant String := "/asfunit";
Server : access ASF.Server.Container;
App : ASF.Applications.Main.Application_Access := null;
Faces : aliased ASF.Servlets.Faces.Faces_Servlet;
Files : aliased ASF.Servlets.Files.File_Servlet;
Ajax : aliased ASF.Servlets.Ajax.Ajax_Servlet;
Dump : aliased ASF.Filters.Dump.Dump_Filter;
Measures : aliased ASF.Servlets.Measures.Measure_Servlet;
-- Save the response headers and content in a file
procedure Save_Response (Name : in String;
Response : in out ASF.Responses.Mockup.Response);
-- ------------------------------
-- Initialize the awa test framework mockup.
-- ------------------------------
procedure Initialize (Props : in Util.Properties.Manager;
Application : in ASF.Applications.Main.Application_Access := null;
Factory : in out ASF.Applications.Main.Application_Factory'Class) is
use type ASF.Applications.Main.Application_Access;
C : ASF.Applications.Config;
begin
if Application /= null then
App := Application;
else
App := new ASF.Applications.Main.Application;
end if;
Server := new ASF.Server.Container;
Server.Register_Application (CONTEXT_PATH, App.all'Access);
C.Copy (Props);
App.Initialize (C, Factory);
App.Register ("layoutMsg", "layout");
App.Set_Global ("contextPath", CONTEXT_PATH);
-- Register the servlets and filters
App.Add_Servlet (Name => "faces", Server => Faces'Access);
App.Add_Servlet (Name => "files", Server => Files'Access);
App.Add_Servlet (Name => "ajax", Server => Ajax'Access);
App.Add_Servlet (Name => "measures", Server => Measures'Access);
App.Add_Filter (Name => "dump", Filter => Dump'Access);
App.Add_Filter (Name => "measures", Filter => Measures'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 => "*.properties");
App.Add_Mapping (Name => "files", Pattern => "*.xhtml");
App.Add_Mapping (Name => "ajax", Pattern => "/ajax/*");
App.Add_Mapping (Name => "measures", Pattern => "stats.xml");
App.Add_Filter_Mapping (Name => "measures", Pattern => "*");
App.Add_Filter_Mapping (Name => "measures", Pattern => "/ajax/*");
App.Add_Filter_Mapping (Name => "measures", Pattern => "*.html");
App.Add_Filter_Mapping (Name => "measures", Pattern => "*.xhtml");
App.Add_Filter_Mapping (Name => "dump", Pattern => "*.html");
App.Add_Filter_Mapping (Name => "dump", Pattern => "*.css");
App.Add_Filter_Mapping (Name => "dump", Pattern => "/ajax/*");
end Initialize;
-- ------------------------------
-- Get the server
-- ------------------------------
function Get_Server return access ASF.Server.Container is
begin
return Server;
end Get_Server;
-- ------------------------------
-- Get the test application.
-- ------------------------------
function Get_Application return ASF.Applications.Main.Application_Access is
begin
return App;
end Get_Application;
-- ------------------------------
-- Save the response headers and content in a file
-- ------------------------------
procedure Save_Response (Name : in String;
Response : in out ASF.Responses.Mockup.Response) is
use ASF.Responses;
Info : constant String := Tools.To_String (Reply => Response,
Html => False,
Print_Headers => True);
Result_Path : constant String := Util.Tests.Get_Test_Path ("regtests/result");
Content : Unbounded_String;
Stream : ASF.Streams.Print_Stream := Response.Get_Output_Stream;
begin
Response.Read_Content (Content);
Stream.Write (Content);
Insert (Content, 1, Info);
Util.Files.Write_File (Result_Path & "/" & Name, Content);
end Save_Response;
-- ------------------------------
-- Simulate a raw request. The URI and method must have been set on the Request object.
-- ------------------------------
procedure Do_Req (Request : in out ASF.Requests.Mockup.Request;
Response : in out ASF.Responses.Mockup.Response) is
begin
-- For the purpose of writing tests, clear the buffer before invoking the service.
Response.Clear;
Server.Service (Request => Request,
Response => Response);
end Do_Req;
-- ------------------------------
-- Simulate a GET request on the given URI with the request parameters.
-- Get the result in the response object.
-- ------------------------------
procedure Do_Get (Request : in out ASF.Requests.Mockup.Request;
Response : in out ASF.Responses.Mockup.Response;
URI : in String;
Save : in String := "") is
begin
Request.Set_Method (Method => "GET");
Request.Set_Request_URI (URI => CONTEXT_PATH & URI);
Request.Set_Protocol (Protocol => "HTTP/1.1");
Do_Req (Request, Response);
if Save'Length > 0 then
Save_Response (Save, Response);
end if;
end Do_Get;
-- ------------------------------
-- Simulate a POST request on the given URI with the request parameters.
-- Get the result in the response object.
-- ------------------------------
procedure Do_Post (Request : in out ASF.Requests.Mockup.Request;
Response : in out ASF.Responses.Mockup.Response;
URI : in String;
Save : in String := "") is
begin
Request.Set_Method (Method => "POST");
Request.Set_Request_URI (URI => CONTEXT_PATH & URI);
Request.Set_Protocol (Protocol => "HTTP/1.1");
Do_Req (Request, Response);
if Save'Length > 0 then
Save_Response (Save, Response);
end if;
end Do_Post;
-- ------------------------------
-- Check that the response body contains the string
-- ------------------------------
procedure Assert_Contains (T : in Util.Tests.Test'Class;
Value : in String;
Reply : in out ASF.Responses.Mockup.Response;
Message : in String := "Test failed";
Source : String := GNAT.Source_Info.File;
Line : Natural := GNAT.Source_Info.Line) is
Stream : ASF.Streams.Print_Stream := Reply.Get_Output_Stream;
Content : Unbounded_String;
begin
Reply.Read_Content (Content);
Stream.Write (Content);
Assert_Equals (T, ASF.Responses.SC_OK, Reply.Get_Status, "Invalid response", Source, Line);
T.Assert (Condition => Index (Content, Value) > 0,
Message => Message & ": value '" & Value & "' not found",
Source => Source,
Line => Line);
end Assert_Contains;
-- ------------------------------
-- Check that the response body matches the regular expression
-- ------------------------------
procedure Assert_Matches (T : in Util.Tests.Test'Class;
Pattern : in String;
Reply : in out ASF.Responses.Mockup.Response;
Message : in String := "Test failed";
Source : String := GNAT.Source_Info.File;
Line : Natural := GNAT.Source_Info.Line) is
use GNAT.Regpat;
Stream : ASF.Streams.Print_Stream := Reply.Get_Output_Stream;
Content : Unbounded_String;
Regexp : constant Pattern_Matcher := Compile (Expression => Pattern,
Flags => Multiple_Lines);
begin
Reply.Read_Content (Content);
Stream.Write (Content);
Assert_Equals (T, ASF.Responses.SC_OK, Reply.Get_Status, "Invalid response", Source, Line);
T.Assert (Condition => Match (Regexp, To_String (Content)),
Message => Message & ": does not match '" & Pattern & "'",
Source => Source,
Line => Line);
end Assert_Matches;
-- ------------------------------
-- Check that the response body is a redirect to the given URI.
-- ------------------------------
procedure Assert_Redirect (T : in Util.Tests.Test'Class;
Value : in String;
Reply : in out ASF.Responses.Mockup.Response;
Message : in String := "Test failed";
Source : String := GNAT.Source_Info.File;
Line : Natural := GNAT.Source_Info.Line) is
begin
Assert_Equals (T, ASF.Responses.SC_MOVED_TEMPORARILY, Reply.Get_Status,
"Invalid response", Source, Line);
Util.Tests.Assert_Equals (T, Value, Reply.Get_Header ("Location"),
Message & ": missing Location",
Source, Line);
end Assert_Redirect;
end ASF.Tests;
|
-----------------------------------------------------------------------
-- ASF tests - ASF Tests Framework
-- 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 GNAT.Regpat;
with Ada.Strings.Unbounded;
with Util.Files;
with ASF.Streams;
with ASF.Servlets.Faces;
with ASF.Servlets.Files;
with ASF.Servlets.Ajax;
with ASF.Servlets.Measures;
with ASF.Responses;
with ASF.Responses.Tools;
with ASF.Filters.Dump;
package body ASF.Tests is
use Ada.Strings.Unbounded;
use Util.Tests;
CONTEXT_PATH : constant String := "/asfunit";
Server : access ASF.Server.Container;
App : ASF.Applications.Main.Application_Access := null;
Faces : aliased ASF.Servlets.Faces.Faces_Servlet;
Files : aliased ASF.Servlets.Files.File_Servlet;
Ajax : aliased ASF.Servlets.Ajax.Ajax_Servlet;
Dump : aliased ASF.Filters.Dump.Dump_Filter;
Measures : aliased ASF.Servlets.Measures.Measure_Servlet;
-- Save the response headers and content in a file
procedure Save_Response (Name : in String;
Response : in out ASF.Responses.Mockup.Response);
-- ------------------------------
-- Initialize the awa test framework mockup.
-- ------------------------------
procedure Initialize (Props : in Util.Properties.Manager;
Application : in ASF.Applications.Main.Application_Access := null;
Factory : in out ASF.Applications.Main.Application_Factory'Class) is
use type ASF.Applications.Main.Application_Access;
C : ASF.Applications.Config;
begin
if Application /= null then
App := Application;
else
App := new ASF.Applications.Main.Application;
end if;
Server := new ASF.Server.Container;
Server.Register_Application (CONTEXT_PATH, App.all'Access);
C.Copy (Props);
App.Initialize (C, Factory);
App.Register ("layoutMsg", "layout");
App.Set_Global ("contextPath", CONTEXT_PATH);
-- Register the servlets and filters
App.Add_Servlet (Name => "faces", Server => Faces'Access);
App.Add_Servlet (Name => "files", Server => Files'Access);
App.Add_Servlet (Name => "ajax", Server => Ajax'Access);
App.Add_Servlet (Name => "measures", Server => Measures'Access);
App.Add_Filter (Name => "dump", Filter => Dump'Access);
App.Add_Filter (Name => "measures", Filter => Measures'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 => "*.properties");
App.Add_Mapping (Name => "files", Pattern => "*.xhtml");
App.Add_Mapping (Name => "ajax", Pattern => "/ajax/*");
App.Add_Mapping (Name => "measures", Pattern => "stats.xml");
App.Add_Filter_Mapping (Name => "measures", Pattern => "*");
App.Add_Filter_Mapping (Name => "measures", Pattern => "/ajax/*");
App.Add_Filter_Mapping (Name => "measures", Pattern => "*.html");
App.Add_Filter_Mapping (Name => "measures", Pattern => "*.xhtml");
App.Add_Filter_Mapping (Name => "dump", Pattern => "*.html");
App.Add_Filter_Mapping (Name => "dump", Pattern => "*.css");
App.Add_Filter_Mapping (Name => "dump", Pattern => "/ajax/*");
end Initialize;
-- ------------------------------
-- Get the server
-- ------------------------------
function Get_Server return access ASF.Server.Container is
begin
return Server;
end Get_Server;
-- ------------------------------
-- Get the test application.
-- ------------------------------
function Get_Application return ASF.Applications.Main.Application_Access is
begin
return App;
end Get_Application;
-- ------------------------------
-- Save the response headers and content in a file
-- ------------------------------
procedure Save_Response (Name : in String;
Response : in out ASF.Responses.Mockup.Response) is
use ASF.Responses;
Info : constant String := Tools.To_String (Reply => Response,
Html => False,
Print_Headers => True);
Result_Path : constant String := Util.Tests.Get_Test_Path ("regtests/result");
Content : Unbounded_String;
Stream : ASF.Streams.Print_Stream := Response.Get_Output_Stream;
begin
Response.Read_Content (Content);
Stream.Write (Content);
Insert (Content, 1, Info);
Util.Files.Write_File (Result_Path & "/" & Name, Content);
end Save_Response;
-- ------------------------------
-- Simulate a raw request. The URI and method must have been set on the Request object.
-- ------------------------------
procedure Do_Req (Request : in out ASF.Requests.Mockup.Request;
Response : in out ASF.Responses.Mockup.Response) is
begin
-- For the purpose of writing tests, clear the buffer before invoking the service.
Response.Clear;
Server.Service (Request => Request,
Response => Response);
end Do_Req;
-- ------------------------------
-- Simulate a GET request on the given URI with the request parameters.
-- Get the result in the response object.
-- ------------------------------
procedure Do_Get (Request : in out ASF.Requests.Mockup.Request;
Response : in out ASF.Responses.Mockup.Response;
URI : in String;
Save : in String := "") is
begin
Request.Set_Method (Method => "GET");
Request.Set_Request_URI (URI => CONTEXT_PATH & URI);
Request.Set_Protocol (Protocol => "HTTP/1.1");
Do_Req (Request, Response);
if Save'Length > 0 then
Save_Response (Save, Response);
end if;
end Do_Get;
-- ------------------------------
-- Simulate a POST request on the given URI with the request parameters.
-- Get the result in the response object.
-- ------------------------------
procedure Do_Post (Request : in out ASF.Requests.Mockup.Request;
Response : in out ASF.Responses.Mockup.Response;
URI : in String;
Save : in String := "") is
begin
Request.Set_Method (Method => "POST");
Request.Set_Request_URI (URI => CONTEXT_PATH & URI);
Request.Set_Protocol (Protocol => "HTTP/1.1");
Do_Req (Request, Response);
if Save'Length > 0 then
Save_Response (Save, Response);
end if;
end Do_Post;
-- ------------------------------
-- Check that the response body contains the string
-- ------------------------------
procedure Assert_Contains (T : in Util.Tests.Test'Class;
Value : in String;
Reply : in out ASF.Responses.Mockup.Response;
Message : in String := "Test failed";
Source : String := GNAT.Source_Info.File;
Line : Natural := GNAT.Source_Info.Line) is
Stream : ASF.Streams.Print_Stream := Reply.Get_Output_Stream;
Content : Unbounded_String;
begin
Reply.Read_Content (Content);
Stream.Write (Content);
Assert_Equals (T, ASF.Responses.SC_OK, Reply.Get_Status, "Invalid response", Source, Line);
T.Assert (Condition => Index (Content, Value) > 0,
Message => Message & ": value '" & Value & "' not found",
Source => Source,
Line => Line);
end Assert_Contains;
-- ------------------------------
-- Check that the response body matches the regular expression
-- ------------------------------
procedure Assert_Matches (T : in Util.Tests.Test'Class;
Pattern : in String;
Reply : in out ASF.Responses.Mockup.Response;
Message : in String := "Test failed";
Source : String := GNAT.Source_Info.File;
Line : Natural := GNAT.Source_Info.Line) is
use GNAT.Regpat;
Stream : ASF.Streams.Print_Stream := Reply.Get_Output_Stream;
Content : Unbounded_String;
Regexp : constant Pattern_Matcher := Compile (Expression => Pattern,
Flags => Multiple_Lines);
begin
Reply.Read_Content (Content);
Stream.Write (Content);
Assert_Equals (T, ASF.Responses.SC_OK, Reply.Get_Status, "Invalid response", Source, Line);
T.Assert (Condition => Match (Regexp, To_String (Content)),
Message => Message & ": does not match '" & Pattern & "'",
Source => Source,
Line => Line);
end Assert_Matches;
-- ------------------------------
-- Check that the response body is a redirect to the given URI.
-- ------------------------------
procedure Assert_Redirect (T : in Util.Tests.Test'Class;
Value : in String;
Reply : in out ASF.Responses.Mockup.Response;
Message : in String := "Test failed";
Source : String := GNAT.Source_Info.File;
Line : Natural := GNAT.Source_Info.Line) is
begin
Assert_Equals (T, ASF.Responses.SC_MOVED_TEMPORARILY, Reply.Get_Status,
"Invalid response", Source, Line);
Util.Tests.Assert_Equals (T, Value, Reply.Get_Header ("Location"),
Message & ": missing Location",
Source, Line);
end Assert_Redirect;
end ASF.Tests;
|
Fix compilation warning
|
Fix compilation warning
|
Ada
|
apache-2.0
|
Letractively/ada-asf,Letractively/ada-asf,Letractively/ada-asf
|
a8d0e1ba523f916469087ece484a68e7e7c01e26
|
matp/src/events/mat-events-timelines.adb
|
matp/src/events/mat-events-timelines.adb
|
-----------------------------------------------------------------------
-- 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 MAT.Frames;
package body MAT.Events.Timelines is
use MAT.Events.Targets;
ITERATE_COUNT : constant MAT.Events.Event_Id_Type := 10_000;
procedure Extract (Target : in out MAT.Events.Targets.Target_Events'Class;
Into : in out Timeline_Info_Vector) is
use type MAT.Types.Target_Time;
use type MAT.Types.Target_Size;
procedure Collect (Event : in MAT.Events.Target_Event_Type);
First_Event : MAT.Events.Target_Event_Type;
Last_Event : MAT.Events.Target_Event_Type;
Prev_Event : MAT.Events.Target_Event_Type;
Info : Timeline_Info;
First_Id : MAT.Events.Event_Id_Type;
procedure Collect (Event : in MAT.Events.Target_Event_Type) is
Dt : constant MAT.Types.Target_Time := Event.Time - Prev_Event.Time;
begin
if Dt > 500_000 then
Into.Append (Info);
Info.Malloc_Count := 0;
Info.Realloc_Count := 0;
Info.Free_Count := 0;
Info.First_Event := Event;
Info.Free_Size := 0;
Info.Alloc_Size := 0;
Prev_Event := Event;
end if;
Info.Last_Event := Event;
if Event.Event = 2 then
Info.Malloc_Count := Info.Malloc_Count + 1;
Info.Alloc_Size := Info.Alloc_Size + Event.Size;
elsif Event.Event = 3 then
Info.Realloc_Count := Info.Realloc_Count + 1;
Info.Alloc_Size := Info.Alloc_Size + Event.Size;
Info.Free_Size := Info.Free_Size + Event.Old_Size;
elsif Event.Event = 4 then
Info.Free_Count := Info.Free_Count + 1;
Info.Free_Size := Info.Free_Size + Event.Size;
end if;
end Collect;
begin
Target.Get_Limits (First_Event, Last_Event);
Prev_Event := First_Event;
Info.First_Event := First_Event;
First_Id := First_Event.Id;
while First_Id < Last_Event.Id loop
Target.Iterate (Start => First_Id,
Finish => First_Id + ITERATE_COUNT,
Process => Collect'Access);
First_Id := First_Id + ITERATE_COUNT;
end loop;
end Extract;
-- ------------------------------
-- 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.Target_Event_Type;
Max : in Positive;
List : in out MAT.Events.Tools.Target_Event_Vector) is
procedure Collect_Free (Event : in MAT.Events.Target_Event_Type);
procedure Collect_Alloc (Event : in MAT.Events.Target_Event_Type);
First_Id : MAT.Events.Event_Id_Type;
Last_Id : MAT.Events.Event_Id_Type;
First_Event : MAT.Events.Target_Event_Type;
Last_Event : MAT.Events.Target_Event_Type;
Addr : MAT.Types.Target_Addr := Event.Addr;
Done : exception;
procedure Collect_Free (Event : in MAT.Events.Target_Event_Type) is
begin
if Event.Index = MAT.Events.MSG_FREE and then Event.Addr = Addr then
List.Append (Event);
raise Done;
end if;
if Event.Index = MAT.Events.MSG_REALLOC and then Event.Old_Addr = Addr then
List.Append (Event);
if Positive (List.Length) >= Max then
raise Done;
end if;
Addr := Event.Addr;
end if;
end Collect_Free;
procedure Collect_Alloc (Event : in MAT.Events.Target_Event_Type) is
begin
if Event.Index = MAT.Events.MSG_MALLOC and then Event.Addr = Addr then
List.Append (Event);
raise Done;
end if;
if Event.Index = MAT.Events.MSG_REALLOC and then Event.Addr = Addr then
List.Append (Event);
if Positive (List.Length) >= Max then
raise Done;
end if;
Addr := Event.Old_Addr;
end if;
end Collect_Alloc;
begin
Target.Get_Limits (First_Event, Last_Event);
First_Id := Event.Id;
if Event.Index = MAT.Events.MSG_FREE then
-- Search backward for MSG_MALLOC and MSG_REALLOC.
First_Id := First_Id - 1;
while First_Id > First_Event.Id loop
if First_Id > ITERATE_COUNT then
Last_Id := First_Id - ITERATE_COUNT;
else
Last_Id := First_Event.Id;
end if;
Target.Iterate (Start => First_Id,
Finish => Last_Id,
Process => Collect_Alloc'Access);
First_Id := Last_Id;
end loop;
else
-- Search forward for MSG_REALLOC and MSG_FREE
First_Id := First_Id + 1;
while First_Id < Last_Event.Id loop
Target.Iterate (Start => First_Id,
Finish => First_Id + ITERATE_COUNT,
Process => Collect_Free'Access);
First_Id := First_Id + ITERATE_COUNT;
end loop;
end if;
exception
when Done =>
null;
end Find_Related;
-- ------------------------------
-- 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.Tools.Size_Event_Info_Map) is
procedure Collect_Event (Event : in MAT.Events.Target_Event_Type);
procedure Collect_Event (Event : in MAT.Events.Target_Event_Type) is
procedure Update_Size (Size : in MAT.Types.Target_Size;
Info : in out MAT.Events.Tools.Event_Info_Type);
procedure Update_Size (Size : in MAT.Types.Target_Size;
Info : in out MAT.Events.Tools.Event_Info_Type) is
pragma Unreferenced (Size);
begin
Info.Count := Info.Count + 1;
Info.Last_Event := Event;
if Event.Index = MAT.Events.MSG_MALLOC then
Info.Alloc_Size := Info.Alloc_Size + Event.Size;
elsif Event.Index = MAT.Events.MSG_REALLOC then
Info.Alloc_Size := Info.Alloc_Size + Event.Size;
Info.Free_Size := Info.Alloc_Size + Event.Old_Size;
else
Info.Free_Size := Info.Alloc_Size + Event.Size;
end if;
end Update_Size;
begin
-- Look for malloc or realloc events which are selected by the filter.
if (Event.Index /= MAT.Events.MSG_MALLOC
and Event.Index /= MAT.Events.MSG_FREE
and Event.Index /= MAT.Events.MSG_REALLOC)
or else not Filter.Is_Selected (Event)
then
return;
end if;
declare
Pos : constant MAT.Events.Tools.Size_Event_Info_Cursor := Sizes.Find (Event.Size);
begin
if MAT.Events.Tools.Size_Event_Info_Maps.Has_Element (Pos) then
-- Increment the count and update the last event.
Sizes.Update_Element (Pos, Update_Size'Access);
else
declare
Info : MAT.Events.Tools.Event_Info_Type;
begin
-- Insert a new size with the event.
Info.First_Event := Event;
Info.Last_Event := Event;
Info.Count := 1;
if Event.Index = MAT.Events.MSG_MALLOC then
Info.Alloc_Size := Event.Size;
elsif Event.Index = MAT.Events.MSG_REALLOC then
Info.Alloc_Size := Event.Size;
Info.Free_Size := Event.Old_Size;
else
Info.Free_Size := Event.Size;
end if;
Sizes.Insert (Event.Size, Info);
end;
end if;
end;
end Collect_Event;
begin
Target.Iterate (Process => Collect_Event'Access);
end Find_Sizes;
-- ------------------------------
-- 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.Tools.Frame_Event_Info_Map) is
procedure Collect_Event (Event : in MAT.Events.Target_Event_Type);
procedure Collect_Event (Event : in MAT.Events.Target_Event_Type) is
procedure Update_Size (Key : in MAT.Events.Tools.Frame_Key_Type;
Info : in out MAT.Events.Tools.Event_Info_Type);
procedure Update_Size (Key : in MAT.Events.Tools.Frame_Key_Type;
Info : in out MAT.Events.Tools.Event_Info_Type) is
pragma Unreferenced (Key);
begin
Info.Count := Info.Count + 1;
Info.Last_Event := Event;
end Update_Size;
begin
-- Look for events which are selected by the filter.
if not Filter.Is_Selected (Event) then
return;
end if;
declare
Backtrace : constant MAT.Frames.Frame_Table := MAT.Frames.Backtrace (Event.Frame);
Key : MAT.Events.Tools.Frame_Key_Type;
begin
for I in Backtrace'Range loop
exit when I > Depth;
Key.Addr := Backtrace (I);
Key.Level := I;
declare
Pos : constant MAT.Events.Tools.Frame_Event_Info_Cursor
:= Frames.Find (Key);
begin
if MAT.Events.Tools.Frame_Event_Info_Maps.Has_Element (Pos) then
-- Increment the count and update the last event.
Frames.Update_Element (Pos, Update_Size'Access);
else
declare
Info : MAT.Events.Tools.Event_Info_Type;
begin
-- Insert a new size with the event.
Info.First_Event := Event;
Info.Last_Event := Event;
Info.Frame_Addr := Key.Addr;
Info.Count := 1;
Frames.Insert (Key, Info);
end;
end if;
end;
end loop;
end;
end Collect_Event;
begin
Target.Iterate (Process => Collect_Event'Access);
end Find_Frames;
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 MAT.Frames;
package body MAT.Events.Timelines is
use MAT.Events.Targets;
ITERATE_COUNT : constant MAT.Events.Event_Id_Type := 10_000;
procedure Extract (Target : in out MAT.Events.Targets.Target_Events'Class;
Into : in out Timeline_Info_Vector) is
use type MAT.Types.Target_Time;
use type MAT.Types.Target_Size;
procedure Collect (Event : in MAT.Events.Target_Event_Type);
First_Event : MAT.Events.Target_Event_Type;
Last_Event : MAT.Events.Target_Event_Type;
Prev_Event : MAT.Events.Target_Event_Type;
Info : Timeline_Info;
First_Id : MAT.Events.Event_Id_Type;
procedure Collect (Event : in MAT.Events.Target_Event_Type) is
Dt : constant MAT.Types.Target_Time := Event.Time - Prev_Event.Time;
begin
if Dt > 500_000 then
Into.Append (Info);
Info.Malloc_Count := 0;
Info.Realloc_Count := 0;
Info.Free_Count := 0;
Info.First_Event := Event;
Info.Free_Size := 0;
Info.Alloc_Size := 0;
Prev_Event := Event;
end if;
Info.Last_Event := Event;
if Event.Event = 2 then
Info.Malloc_Count := Info.Malloc_Count + 1;
Info.Alloc_Size := Info.Alloc_Size + Event.Size;
elsif Event.Event = 3 then
Info.Realloc_Count := Info.Realloc_Count + 1;
Info.Alloc_Size := Info.Alloc_Size + Event.Size;
Info.Free_Size := Info.Free_Size + Event.Old_Size;
elsif Event.Event = 4 then
Info.Free_Count := Info.Free_Count + 1;
Info.Free_Size := Info.Free_Size + Event.Size;
end if;
end Collect;
begin
Target.Get_Limits (First_Event, Last_Event);
Prev_Event := First_Event;
Info.First_Event := First_Event;
First_Id := First_Event.Id;
while First_Id < Last_Event.Id loop
Target.Iterate (Start => First_Id,
Finish => First_Id + ITERATE_COUNT,
Process => Collect'Access);
First_Id := First_Id + ITERATE_COUNT;
end loop;
end Extract;
-- ------------------------------
-- 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.Target_Event_Type;
Max : in Positive;
List : in out MAT.Events.Tools.Target_Event_Vector) is
procedure Collect_Free (Event : in MAT.Events.Target_Event_Type);
procedure Collect_Alloc (Event : in MAT.Events.Target_Event_Type);
First_Id : MAT.Events.Event_Id_Type;
Last_Id : MAT.Events.Event_Id_Type;
First_Event : MAT.Events.Target_Event_Type;
Last_Event : MAT.Events.Target_Event_Type;
Addr : MAT.Types.Target_Addr := Event.Addr;
Done : exception;
procedure Collect_Free (Event : in MAT.Events.Target_Event_Type) is
begin
if Event.Index = MAT.Events.MSG_FREE and then Event.Addr = Addr then
List.Append (Event);
raise Done;
end if;
if Event.Index = MAT.Events.MSG_REALLOC and then Event.Old_Addr = Addr then
List.Append (Event);
if Positive (List.Length) >= Max then
raise Done;
end if;
Addr := Event.Addr;
end if;
end Collect_Free;
procedure Collect_Alloc (Event : in MAT.Events.Target_Event_Type) is
begin
if Event.Index = MAT.Events.MSG_MALLOC and then Event.Addr = Addr then
List.Append (Event);
raise Done;
end if;
if Event.Index = MAT.Events.MSG_REALLOC and then Event.Addr = Addr then
List.Append (Event);
if Positive (List.Length) >= Max then
raise Done;
end if;
Addr := Event.Old_Addr;
end if;
end Collect_Alloc;
begin
Target.Get_Limits (First_Event, Last_Event);
First_Id := Event.Id;
if Event.Index = MAT.Events.MSG_FREE then
-- Search backward for MSG_MALLOC and MSG_REALLOC.
First_Id := First_Id - 1;
while First_Id > First_Event.Id loop
if First_Id > ITERATE_COUNT then
Last_Id := First_Id - ITERATE_COUNT;
else
Last_Id := First_Event.Id;
end if;
Target.Iterate (Start => First_Id,
Finish => Last_Id,
Process => Collect_Alloc'Access);
First_Id := Last_Id;
end loop;
else
-- Search forward for MSG_REALLOC and MSG_FREE
First_Id := First_Id + 1;
while First_Id < Last_Event.Id loop
Target.Iterate (Start => First_Id,
Finish => First_Id + ITERATE_COUNT,
Process => Collect_Free'Access);
First_Id := First_Id + ITERATE_COUNT;
end loop;
end if;
exception
when Done =>
null;
end Find_Related;
-- ------------------------------
-- 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.Tools.Size_Event_Info_Map) is
procedure Collect_Event (Event : in MAT.Events.Target_Event_Type);
procedure Collect_Event (Event : in MAT.Events.Target_Event_Type) is
procedure Update_Size (Size : in MAT.Types.Target_Size;
Info : in out MAT.Events.Tools.Event_Info_Type);
procedure Update_Size (Size : in MAT.Types.Target_Size;
Info : in out MAT.Events.Tools.Event_Info_Type) is
pragma Unreferenced (Size);
begin
Info.Count := Info.Count + 1;
Info.Last_Event := Event;
if Event.Index = MAT.Events.MSG_MALLOC then
Info.Alloc_Size := Info.Alloc_Size + Event.Size;
elsif Event.Index = MAT.Events.MSG_REALLOC then
Info.Alloc_Size := Info.Alloc_Size + Event.Size;
Info.Free_Size := Info.Alloc_Size + Event.Old_Size;
else
Info.Free_Size := Info.Alloc_Size + Event.Size;
end if;
end Update_Size;
begin
-- Look for malloc or realloc events which are selected by the filter.
if (Event.Index /= MAT.Events.MSG_MALLOC
and Event.Index /= MAT.Events.MSG_FREE
and Event.Index /= MAT.Events.MSG_REALLOC)
or else not Filter.Is_Selected (Event)
then
return;
end if;
declare
Pos : constant MAT.Events.Tools.Size_Event_Info_Cursor := Sizes.Find (Event.Size);
begin
if MAT.Events.Tools.Size_Event_Info_Maps.Has_Element (Pos) then
-- Increment the count and update the last event.
Sizes.Update_Element (Pos, Update_Size'Access);
else
declare
Info : MAT.Events.Tools.Event_Info_Type;
begin
-- Insert a new size with the event.
Info.First_Event := Event;
Info.Last_Event := Event;
Info.Count := 1;
if Event.Index = MAT.Events.MSG_MALLOC then
Info.Alloc_Size := Event.Size;
elsif Event.Index = MAT.Events.MSG_REALLOC then
Info.Alloc_Size := Event.Size;
Info.Free_Size := Event.Old_Size;
else
Info.Free_Size := Event.Size;
end if;
Sizes.Insert (Event.Size, Info);
end;
end if;
end;
end Collect_Event;
begin
Target.Iterate (Process => Collect_Event'Access);
end Find_Sizes;
-- ------------------------------
-- 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.Tools.Frame_Event_Info_Map) is
procedure Collect_Event (Event : in MAT.Events.Target_Event_Type);
procedure Collect_Event (Event : in MAT.Events.Target_Event_Type) is
procedure Update_Size (Key : in MAT.Events.Tools.Frame_Key_Type;
Info : in out MAT.Events.Tools.Event_Info_Type);
procedure Update_Size (Key : in MAT.Events.Tools.Frame_Key_Type;
Info : in out MAT.Events.Tools.Event_Info_Type) is
pragma Unreferenced (Key);
begin
Info.Count := Info.Count + 1;
Info.Last_Event := Event;
if Event.Event = 2 then
Info.Malloc_Count := Info.Malloc_Count + 1;
Info.Alloc_Size := Info.Alloc_Size + Event.Size;
elsif Event.Event = 3 then
Info.Realloc_Count := Info.Realloc_Count + 1;
Info.Alloc_Size := Info.Alloc_Size + Event.Size;
Info.Free_Size := Info.Free_Size + Event.Old_Size;
elsif Event.Event = 4 then
Info.Free_Count := Info.Free_Count + 1;
Info.Free_Size := Info.Free_Size + Event.Size;
end if;
end Update_Size;
begin
-- Look for events which are selected by the filter.
if not Filter.Is_Selected (Event) then
return;
end if;
declare
Backtrace : constant MAT.Frames.Frame_Table := MAT.Frames.Backtrace (Event.Frame);
Key : MAT.Events.Tools.Frame_Key_Type;
begin
for I in Backtrace'Range loop
exit when I > Depth;
Key.Addr := Backtrace (Backtrace'Last - I + 1);
Key.Level := I;
declare
Pos : constant MAT.Events.Tools.Frame_Event_Info_Cursor
:= Frames.Find (Key);
begin
if MAT.Events.Tools.Frame_Event_Info_Maps.Has_Element (Pos) then
-- Increment the count and update the last event.
Frames.Update_Element (Pos, Update_Size'Access);
else
declare
Info : MAT.Events.Tools.Event_Info_Type;
begin
-- Insert a new size with the event.
Info.First_Event := Event;
Info.Last_Event := Event;
Info.Frame_Addr := Key.Addr;
Info.Count := 1;
Frames.Insert (Key, Info);
end;
end if;
end;
end loop;
end;
end Collect_Event;
begin
Target.Iterate (Process => Collect_Event'Access);
end Find_Frames;
end MAT.Events.Timelines;
|
Update Find_Frames to collect the malloc count, realloc count, free count
|
Update Find_Frames to collect the malloc count, realloc count, free count
|
Ada
|
apache-2.0
|
stcarrez/mat,stcarrez/mat,stcarrez/mat
|
9a0a077e41245b3d670d547ae0156ddd6de0a9c9
|
src/gen-artifacts-xmi.ads
|
src/gen-artifacts-xmi.ads
|
-----------------------------------------------------------------------
-- gen-artifacts-xmi -- UML-XMI artifact for Code Generator
-- Copyright (C) 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with DOM.Core;
with Gen.Model.Packages;
with Gen.Model.XMI;
with Util.Strings.Sets;
-- The <b>Gen.Artifacts.XMI</b> package is an artifact for the generation of Ada code
-- from an UML XMI description.
package Gen.Artifacts.XMI is
-- ------------------------------
-- UML XMI artifact
-- ------------------------------
type Artifact is new Gen.Artifacts.Artifact with private;
-- After the configuration file is read, processes the node whose root
-- is passed in <b>Node</b> and initializes the <b>Model</b> with the information.
overriding
procedure Initialize (Handler : in out Artifact;
Path : in String;
Node : in DOM.Core.Node;
Model : in out Gen.Model.Packages.Model_Definition'Class;
Context : in out Generator'Class);
-- Prepare the model after all the configuration files have been read and before
-- actually invoking the generation.
overriding
procedure Prepare (Handler : in out Artifact;
Model : in out Gen.Model.Packages.Model_Definition'Class;
Context : in out Generator'Class);
-- Read the UML/XMI model file.
procedure Read_Model (Handler : in out Artifact;
File : in String;
Context : in out Generator'Class;
Is_Predefined : in Boolean := False);
private
-- Read the UML profiles that are referenced by the current models.
-- The UML profiles are installed in the UML config directory for dynamo's installation.
procedure Read_Profiles (Handler : in out Artifact;
Context : in out Generator'Class);
type Artifact is new Gen.Artifacts.Artifact with record
Nodes : aliased Gen.Model.XMI.UML_Model;
-- A set of profiles that are necessary for the model definitions.
Profiles : aliased Util.Strings.Sets.Set;
Has_Config : Boolean := False;
-- Stereotype which triggers the generation of database table.
Table_Stereotype : Gen.Model.XMI.Stereotype_Element_Access;
PK_Stereotype : Gen.Model.XMI.Stereotype_Element_Access;
FK_Stereotype : Gen.Model.XMI.Stereotype_Element_Access;
Data_Model_Stereotype : Gen.Model.XMI.Stereotype_Element_Access;
Nullable_Stereotype : Gen.Model.XMI.Stereotype_Element_Access;
Not_Null_Stereotype : Gen.Model.XMI.Stereotype_Element_Access;
Use_FK_Stereotype : Gen.Model.XMI.Stereotype_Element_Access;
Version_Stereotype : Gen.Model.XMI.Stereotype_Element_Access;
-- Tag definitions which control the generation.
Has_List_Tag : Gen.Model.XMI.Tag_Definition_Element_Access;
Table_Name_Tag : Gen.Model.XMI.Tag_Definition_Element_Access;
Sql_Type_Tag : Gen.Model.XMI.Tag_Definition_Element_Access;
Generator_Tag : Gen.Model.XMI.Tag_Definition_Element_Access;
Literal_Tag : Gen.Model.XMI.Tag_Definition_Element_Access;
Sql_Length_Tag : Gen.Model.XMI.Tag_Definition_Element_Access;
-- Stereotype which triggers the generation of AWA bean types.
Bean_Stereotype : Gen.Model.XMI.Stereotype_Element_Access;
end record;
end Gen.Artifacts.XMI;
|
-----------------------------------------------------------------------
-- gen-artifacts-xmi -- UML-XMI artifact for Code Generator
-- 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 DOM.Core;
with Gen.Model.Packages;
with Gen.Model.XMI;
with Util.Strings.Sets;
-- The <b>Gen.Artifacts.XMI</b> package is an artifact for the generation of Ada code
-- from an UML XMI description.
package Gen.Artifacts.XMI is
-- ------------------------------
-- UML XMI artifact
-- ------------------------------
type Artifact is new Gen.Artifacts.Artifact with private;
-- After the configuration file is read, processes the node whose root
-- is passed in <b>Node</b> and initializes the <b>Model</b> with the information.
overriding
procedure Initialize (Handler : in out Artifact;
Path : in String;
Node : in DOM.Core.Node;
Model : in out Gen.Model.Packages.Model_Definition'Class;
Context : in out Generator'Class);
-- Prepare the model after all the configuration files have been read and before
-- actually invoking the generation.
overriding
procedure Prepare (Handler : in out Artifact;
Model : in out Gen.Model.Packages.Model_Definition'Class;
Context : in out Generator'Class);
-- Read the UML/XMI model file.
procedure Read_Model (Handler : in out Artifact;
File : in String;
Context : in out Generator'Class;
Is_Predefined : in Boolean := False);
private
-- Read the UML profiles that are referenced by the current models.
-- The UML profiles are installed in the UML config directory for dynamo's installation.
procedure Read_Profiles (Handler : in out Artifact;
Context : in out Generator'Class);
type Artifact is new Gen.Artifacts.Artifact with record
Nodes : aliased Gen.Model.XMI.UML_Model;
-- A set of profiles that are necessary for the model definitions.
Profiles : aliased Util.Strings.Sets.Set;
Has_Config : Boolean := False;
-- Stereotype which triggers the generation of database table.
Table_Stereotype : Gen.Model.XMI.Stereotype_Element_Access;
PK_Stereotype : Gen.Model.XMI.Stereotype_Element_Access;
FK_Stereotype : Gen.Model.XMI.Stereotype_Element_Access;
Data_Model_Stereotype : Gen.Model.XMI.Stereotype_Element_Access;
Nullable_Stereotype : Gen.Model.XMI.Stereotype_Element_Access;
Not_Null_Stereotype : Gen.Model.XMI.Stereotype_Element_Access;
Use_FK_Stereotype : Gen.Model.XMI.Stereotype_Element_Access;
Version_Stereotype : Gen.Model.XMI.Stereotype_Element_Access;
-- Tag definitions which control the generation.
Has_List_Tag : Gen.Model.XMI.Tag_Definition_Element_Access;
Table_Name_Tag : Gen.Model.XMI.Tag_Definition_Element_Access;
Sql_Type_Tag : Gen.Model.XMI.Tag_Definition_Element_Access;
Generator_Tag : Gen.Model.XMI.Tag_Definition_Element_Access;
Literal_Tag : Gen.Model.XMI.Tag_Definition_Element_Access;
Sql_Length_Tag : Gen.Model.XMI.Tag_Definition_Element_Access;
-- Stereotype which triggers the generation of AWA bean types.
Bean_Stereotype : Gen.Model.XMI.Stereotype_Element_Access;
Limited_Bean_Stereotype : Gen.Model.XMI.Stereotype_Element_Access;
end record;
end Gen.Artifacts.XMI;
|
Add a Limited_Bean_Stereotype member in the XMI artifact
|
Add a Limited_Bean_Stereotype member in the XMI artifact
|
Ada
|
apache-2.0
|
Letractively/ada-gen,Letractively/ada-gen,Letractively/ada-gen,Letractively/ada-gen
|
387b0718d6e45154659e5dd233fabfc8de2db4bd
|
orka_plugin_atmosphere/src/orka-features-atmosphere-rendering.adb
|
orka_plugin_atmosphere/src/orka-features-atmosphere-rendering.adb
|
-- SPDX-License-Identifier: Apache-2.0
--
-- Copyright (c) 2020 onox <[email protected]>
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
with Ada.Characters.Latin_1;
with Ada.Numerics.Generic_Elementary_Functions;
with GL.Buffers;
with Orka.Rendering.Drawing;
with Orka.Transforms.Doubles.Matrices;
with Orka.Transforms.Doubles.Vectors;
with Orka.Transforms.Doubles.Vector_Conversions;
with Orka.Transforms.Singles.Vectors;
package body Orka.Features.Atmosphere.Rendering is
package EF is new Ada.Numerics.Generic_Elementary_Functions (GL.Types.Double);
Altitude_Hack_Threshold : constant := 8000.0;
function Create_Atmosphere
(Data : aliased Model_Data;
Location : Resources.Locations.Location_Ptr;
Parameters : Model_Parameters := (others => <>)) return Atmosphere
is
Atmosphere_Model : constant Model := Create_Model (Data'Access, Location);
Sky_GLSL : constant String := Resources.Convert
(Orka.Resources.Byte_Array'(Location.Read_Data ("atmosphere/sky.frag").Get));
use Ada.Characters.Latin_1;
use Rendering.Programs;
use Rendering.Programs.Modules;
Sky_Shader : constant String :=
"#version 420 core" & LF &
(if Data.Luminance /= None then "#define USE_LUMINANCE" & LF else "") &
"const float kLengthUnitInMeters = " & Data.Length_Unit_In_Meters'Image & ";" & LF &
Sky_GLSL & LF;
Shader_Module : constant Rendering.Programs.Modules.Module := Atmosphere_Model.Get_Shader;
begin
return Result : Atmosphere :=
(Program => Create_Program (Modules.Module_Array'
(Modules.Create_Module (Location, VS => "atmosphere/sky.vert"),
Modules.Create_Module_From_Sources (FS => Sky_Shader),
Shader_Module)),
Module => Shader_Module,
Parameters => Parameters,
Bottom_Radius => Data.Bottom_Radius,
Distance_Scale => 1.0 / Data.Length_Unit_In_Meters,
others => <>)
do
Result.Uniform_Ground_Hack := Result.Program.Uniform ("ground_hack");
Result.Uniform_Camera_Offset := Result.Program.Uniform ("camera_offset");
Result.Uniform_Camera_Pos := Result.Program.Uniform ("camera_pos");
Result.Uniform_Planet_Pos := Result.Program.Uniform ("planet_pos");
Result.Uniform_View := Result.Program.Uniform ("view");
Result.Uniform_Proj := Result.Program.Uniform ("proj");
Result.Uniform_Sun_Dir := Result.Program.Uniform ("sun_direction");
Result.Uniform_Star_Dir := Result.Program.Uniform ("star_direction");
Result.Uniform_Star_Size := Result.Program.Uniform ("star_size");
end return;
end Create_Atmosphere;
function Shader_Module (Object : Atmosphere) return Orka.Rendering.Programs.Modules.Module is
(Object.Module);
function Flattened_Vector
(Parameters : Model_Parameters;
Direction : Orka.Transforms.Doubles.Vectors.Vector4)
return Orka.Transforms.Doubles.Vectors.Vector4 is
Altitude : constant := 0.0;
Flattening : GL.Types.Double renames Parameters.Flattening;
E2 : constant GL.Types.Double := 2.0 * Flattening - Flattening**2;
N : constant GL.Types.Double := Parameters.Semi_Major_Axis /
EF.Sqrt (1.0 - E2 * Direction (Orka.Z)**2);
begin
return
(Direction (Orka.X) * (N + Altitude),
Direction (Orka.Y) * (N + Altitude),
Direction (Orka.Z) * (N * (1.0 - E2) + Altitude),
1.0);
end Flattened_Vector;
package Matrices renames Orka.Transforms.Doubles.Matrices;
procedure Render
(Object : in out Atmosphere;
Camera : Cameras.Camera_Ptr;
Planet : Behaviors.Behavior_Ptr;
Star : Behaviors.Behavior_Ptr)
is
function "*" (Left : Matrices.Matrix4; Right : Matrices.Vector4) return Matrices.Vector4
renames Matrices."*";
function "*" (Left, Right : Matrices.Matrix4) return Matrices.Matrix4 renames Matrices."*";
function Far_Plane (Value : GL.Types.Compare_Function) return GL.Types.Compare_Function is
(case Value is
when Less | LEqual => LEqual,
when Greater | GEqual => GEqual,
when others => raise Constraint_Error);
Original_Function : constant GL.Types.Compare_Function := GL.Buffers.Depth_Function;
use Orka.Transforms.Doubles.Vectors;
use Orka.Transforms.Doubles.Vector_Conversions;
use all type Orka.Transforms.Doubles.Vectors.Vector4;
Planet_To_Camera : constant Vector4 := Camera.View_Position - Planet.Position;
Planet_To_Star : constant Vector4 := Star.Position - Planet.Position;
Camera_To_Star : constant Vector4 := Star.Position - Camera.View_Position;
procedure Apply_Hacks is
GL_To_Geo : constant Matrices.Matrix4 := Matrices.R
(Matrices.Vectors.Normalize ((1.0, 1.0, 1.0, 0.0)),
(2.0 / 3.0) * Ada.Numerics.Pi);
Earth_Tilt : constant Matrices.Matrix4 := Matrices.R
(Matrices.Vectors.Normalize ((1.0, 0.0, 0.0, 0.0)),
Object.Parameters.Axial_Tilt);
Inverse_Inertial : constant Matrices.Matrix4 := Earth_Tilt * GL_To_Geo;
Camera_Normal_Inert : constant Vector4 := Normalize (Inverse_Inertial * Planet_To_Camera);
Actual_Surface : constant Vector4 := Flattened_Vector
(Object.Parameters, Camera_Normal_Inert);
Expected_Surface : constant Vector4 := Camera_Normal_Inert * Object.Bottom_Radius;
Offset : constant Vector4 := Expected_Surface - Actual_Surface;
Altitude : constant Double := Length (Planet_To_Camera) - Length (Actual_Surface);
begin
Object.Uniform_Ground_Hack.Set_Boolean (Altitude < Altitude_Hack_Threshold);
Object.Uniform_Camera_Offset.Set_Vector (Convert (Offset * Object.Distance_Scale));
end Apply_Hacks;
begin
if Object.Parameters.Flattening > 0.0 then
Apply_Hacks;
else
Object.Uniform_Ground_Hack.Set_Boolean (False);
Object.Uniform_Camera_Offset.Set_Vector (Orka.Transforms.Singles.Vectors.Zero_Point);
end if;
Object.Uniform_Camera_Pos.Set_Vector (Orka.Transforms.Singles.Vectors.Zero_Point);
Object.Uniform_Planet_Pos.Set_Vector (Convert (-Planet_To_Camera * Object.Distance_Scale));
Object.Uniform_Sun_Dir.Set_Vector (Convert (Normalize (Planet_To_Star)));
Object.Uniform_Star_Dir.Set_Vector (Convert (Normalize (Camera_To_Star)));
-- Use distance to star and its radius instead of the
-- Sun_Angular_Radius of Model_Data
declare
Angular_Radius : constant GL.Types.Double :=
EF.Arctan (Object.Parameters.Star_Radius, Length (Camera_To_Star));
begin
Object.Uniform_Star_Size.Set_Single (GL.Types.Single (EF.Cos (Angular_Radius)));
end;
Object.Uniform_View.Set_Matrix (Camera.View_Matrix);
Object.Uniform_Proj.Set_Matrix (Camera.Projection_Matrix);
Object.Program.Use_Program;
GL.Buffers.Set_Depth_Function (Far_Plane (Original_Function));
Orka.Rendering.Drawing.Draw (GL.Types.Triangles, 0, 3);
GL.Buffers.Set_Depth_Function (Original_Function);
end Render;
end Orka.Features.Atmosphere.Rendering;
|
-- SPDX-License-Identifier: Apache-2.0
--
-- Copyright (c) 2020 onox <[email protected]>
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
with Ada.Characters.Latin_1;
with Ada.Numerics.Generic_Elementary_Functions;
with GL.Buffers;
with Orka.Rendering.Drawing;
with Orka.Transforms.Doubles.Matrices;
with Orka.Transforms.Doubles.Vectors;
with Orka.Transforms.Doubles.Vector_Conversions;
with Orka.Transforms.Singles.Vectors;
package body Orka.Features.Atmosphere.Rendering is
package EF is new Ada.Numerics.Generic_Elementary_Functions (GL.Types.Double);
Altitude_Hack_Threshold : constant := 8000.0;
function Create_Atmosphere
(Data : aliased Model_Data;
Location : Resources.Locations.Location_Ptr;
Parameters : Model_Parameters := (others => <>)) return Atmosphere
is
Atmosphere_Model : constant Model := Create_Model (Data'Access, Location);
Sky_GLSL : constant String := Resources.Convert
(Orka.Resources.Byte_Array'(Location.Read_Data ("atmosphere/sky.frag").Get));
use Ada.Characters.Latin_1;
use Rendering.Programs;
use Rendering.Programs.Modules;
Sky_Shader : constant String :=
"#version 420 core" & LF &
(if Data.Luminance /= None then "#define USE_LUMINANCE" & LF else "") &
"const float kLengthUnitInMeters = " & Data.Length_Unit_In_Meters'Image & ";" & LF &
Sky_GLSL & LF;
Shader_Module : constant Rendering.Programs.Modules.Module := Atmosphere_Model.Get_Shader;
begin
return Result : Atmosphere :=
(Program => Create_Program (Modules.Module_Array'
(Modules.Create_Module (Location, VS => "atmosphere/sky.vert"),
Modules.Create_Module_From_Sources (FS => Sky_Shader),
Shader_Module)),
Module => Shader_Module,
Parameters => Parameters,
Bottom_Radius => Data.Bottom_Radius,
Distance_Scale => 1.0 / Data.Length_Unit_In_Meters,
others => <>)
do
Result.Uniform_Ground_Hack := Result.Program.Uniform ("ground_hack");
Result.Uniform_Camera_Offset := Result.Program.Uniform ("camera_offset");
Result.Uniform_Camera_Pos := Result.Program.Uniform ("camera_pos");
Result.Uniform_Planet_Pos := Result.Program.Uniform ("planet_pos");
Result.Uniform_View := Result.Program.Uniform ("view");
Result.Uniform_Proj := Result.Program.Uniform ("proj");
Result.Uniform_Sun_Dir := Result.Program.Uniform ("sun_direction");
Result.Uniform_Star_Dir := Result.Program.Uniform ("star_direction");
Result.Uniform_Star_Size := Result.Program.Uniform ("star_size");
end return;
end Create_Atmosphere;
function Shader_Module (Object : Atmosphere) return Orka.Rendering.Programs.Modules.Module is
(Object.Module);
function Flattened_Vector
(Parameters : Model_Parameters;
Direction : Orka.Transforms.Doubles.Vectors.Vector4)
return Orka.Transforms.Doubles.Vectors.Vector4 is
Altitude : constant := 0.0;
Flattening : GL.Types.Double renames Parameters.Flattening;
E2 : constant GL.Types.Double := 2.0 * Flattening - Flattening**2;
N : constant GL.Types.Double := Parameters.Semi_Major_Axis /
EF.Sqrt (1.0 - E2 * Direction (Orka.Z)**2);
begin
return
(Direction (Orka.X) * (N + Altitude),
Direction (Orka.Y) * (N + Altitude),
Direction (Orka.Z) * (N * (1.0 - E2) + Altitude),
1.0);
end Flattened_Vector;
package Matrices renames Orka.Transforms.Doubles.Matrices;
procedure Render
(Object : in out Atmosphere;
Camera : Cameras.Camera_Ptr;
Planet : Behaviors.Behavior_Ptr;
Star : Behaviors.Behavior_Ptr)
is
function "*" (Left : Matrices.Matrix4; Right : Matrices.Vector4) return Matrices.Vector4
renames Matrices."*";
function "*" (Left, Right : Matrices.Matrix4) return Matrices.Matrix4 renames Matrices."*";
function Far_Plane (Value : GL.Types.Compare_Function) return GL.Types.Compare_Function is
(case Value is
when Less | LEqual => LEqual,
when Greater | GEqual => GEqual,
when others => raise Constraint_Error);
Original_Function : constant GL.Types.Compare_Function := GL.Buffers.Depth_Function;
use Orka.Transforms.Doubles.Vectors;
use Orka.Transforms.Doubles.Vector_Conversions;
use all type Orka.Transforms.Doubles.Vectors.Vector4;
Planet_To_Camera : constant Vector4 := Camera.View_Position - Planet.Position;
Planet_To_Star : constant Vector4 := Star.Position - Planet.Position;
Camera_To_Star : constant Vector4 := Star.Position - Camera.View_Position;
procedure Apply_Hacks is
GL_To_Geo : constant Matrices.Matrix4 := Matrices.R
(Matrices.Vectors.Normalize ((1.0, 1.0, 1.0, 0.0)),
(2.0 / 3.0) * Ada.Numerics.Pi);
Earth_Tilt : constant Matrices.Matrix4 := Matrices.R
(Matrices.Vectors.Normalize ((1.0, 0.0, 0.0, 0.0)),
Object.Parameters.Axial_Tilt);
Inverse_Inertial : constant Matrices.Matrix4 := Earth_Tilt * GL_To_Geo;
Camera_Normal_Inert : constant Vector4 := Normalize (Inverse_Inertial * Planet_To_Camera);
Actual_Surface : constant Vector4 := Flattened_Vector
(Object.Parameters, Camera_Normal_Inert);
Expected_Surface : constant Vector4 := Camera_Normal_Inert * Object.Bottom_Radius;
Offset : constant Vector4 := Expected_Surface - Actual_Surface;
Altitude : constant Double := Length (Planet_To_Camera) - Length (Actual_Surface);
begin
Object.Uniform_Ground_Hack.Set_Boolean (Altitude < Altitude_Hack_Threshold);
Object.Uniform_Camera_Offset.Set_Vector (Convert (Offset * Object.Distance_Scale));
end Apply_Hacks;
begin
if Object.Parameters.Flattening > 0.0 then
Apply_Hacks;
else
Object.Uniform_Ground_Hack.Set_Boolean (False);
Object.Uniform_Camera_Offset.Set_Vector (Orka.Transforms.Singles.Vectors.Zero);
end if;
Object.Uniform_Camera_Pos.Set_Vector (Orka.Transforms.Singles.Vectors.Zero);
Object.Uniform_Planet_Pos.Set_Vector (Convert (-Planet_To_Camera * Object.Distance_Scale));
Object.Uniform_Sun_Dir.Set_Vector (Convert (Normalize (Planet_To_Star)));
Object.Uniform_Star_Dir.Set_Vector (Convert (Normalize (Camera_To_Star)));
-- Use distance to star and its radius instead of the
-- Sun_Angular_Radius of Model_Data
declare
Angular_Radius : constant GL.Types.Double :=
EF.Arctan (Object.Parameters.Star_Radius, Length (Camera_To_Star));
begin
Object.Uniform_Star_Size.Set_Single (GL.Types.Single (EF.Cos (Angular_Radius)));
end;
Object.Uniform_View.Set_Matrix (Camera.View_Matrix);
Object.Uniform_Proj.Set_Matrix (Camera.Projection_Matrix);
Object.Program.Use_Program;
GL.Buffers.Set_Depth_Function (Far_Plane (Original_Function));
Orka.Rendering.Drawing.Draw (GL.Types.Triangles, 0, 3);
GL.Buffers.Set_Depth_Function (Original_Function);
end Render;
end Orka.Features.Atmosphere.Rendering;
|
Fix compilation after changes to orka_transforms
|
atmosphere: Fix compilation after changes to orka_transforms
Signed-off-by: onox <[email protected]>
|
Ada
|
apache-2.0
|
onox/orka
|
28fef00c9c4b70bcd425efee41622875bf0cc910
|
src/util-serialize-io-csv.adb
|
src/util-serialize-io-csv.adb
|
-----------------------------------------------------------------------
-- util-serialize-io-csv -- CSV Serialization Driver
-- Copyright (C) 2011, 2015, 2016, 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Ada.Characters.Latin_1;
with Ada.IO_Exceptions;
with Util.Strings;
with Util.Dates.ISO8601;
package body Util.Serialize.IO.CSV is
-- ------------------------------
-- Set the field separator. The default field separator is the comma (',').
-- ------------------------------
procedure Set_Field_Separator (Stream : in out Output_Stream;
Separator : in Character) is
begin
Stream.Separator := Separator;
end Set_Field_Separator;
-- ------------------------------
-- Enable or disable the double quotes by default for strings.
-- ------------------------------
procedure Set_Quotes (Stream : in out Output_Stream;
Enable : in Boolean) is
begin
Stream.Quote := Enable;
end Set_Quotes;
-- ------------------------------
-- Write the value as a CSV cell. Special characters are escaped using the CSV
-- escape rules.
-- ------------------------------
procedure Write_Cell (Stream : in out Output_Stream;
Value : in String) is
begin
if Stream.Column > 1 then
Stream.Write (Stream.Separator);
end if;
Stream.Column := Stream.Column + 1;
if Stream.Quote then
Stream.Write ('"');
end if;
for I in Value'Range loop
if Value (I) = '"' then
Stream.Write ("""""");
else
Stream.Write (Value (I));
end if;
end loop;
if Stream.Quote then
Stream.Write ('"');
end if;
end Write_Cell;
procedure Write_Cell (Stream : in out Output_Stream;
Value : in Integer) is
begin
if Stream.Column > 1 then
Stream.Write (Stream.Separator);
end if;
Stream.Column := Stream.Column + 1;
Stream.Write (Util.Strings.Image (Value));
end Write_Cell;
procedure Write_Cell (Stream : in out Output_Stream;
Value : in Boolean) is
begin
if Stream.Column > 1 then
Stream.Write (Stream.Separator);
end if;
Stream.Column := Stream.Column + 1;
if Value then
Stream.Write ("true");
else
Stream.Write ("false");
end if;
end Write_Cell;
procedure Write_Cell (Stream : in out Output_Stream;
Value : in Util.Beans.Objects.Object) is
use Util.Beans.Objects;
begin
case Util.Beans.Objects.Get_Type (Value) is
when TYPE_NULL =>
if Stream.Column > 1 then
Stream.Write (Stream.Separator);
end if;
Stream.Column := Stream.Column + 1;
if Stream.Quote then
Stream.Write ("""null""");
else
Stream.Write ("null");
end if;
when TYPE_BOOLEAN =>
if Stream.Column > 1 then
Stream.Write (Stream.Separator);
end if;
Stream.Column := Stream.Column + 1;
if Util.Beans.Objects.To_Boolean (Value) then
Stream.Write ("true");
else
Stream.Write ("false");
end if;
when TYPE_INTEGER =>
if Stream.Column > 1 then
Stream.Write (Stream.Separator);
end if;
Stream.Column := Stream.Column + 1;
-- Stream.Write ('"');
Stream.Write (Util.Beans.Objects.To_Long_Long_Integer (Value));
-- Stream.Write ('"');
when others =>
Stream.Write_Cell (Util.Beans.Objects.To_String (Value));
end case;
end Write_Cell;
-- ------------------------------
-- Start a new row.
-- ------------------------------
procedure New_Row (Stream : in out Output_Stream) is
begin
while Stream.Column < Stream.Max_Columns loop
Stream.Write (Stream.Separator);
Stream.Column := Stream.Column + 1;
end loop;
Stream.Write (ASCII.CR);
Stream.Write (ASCII.LF);
Stream.Column := 1;
Stream.Row := Stream.Row + 1;
end New_Row;
-- -----------------------
-- Write the attribute name/value pair.
-- -----------------------
overriding
procedure Write_Attribute (Stream : in out Output_Stream;
Name : in String;
Value : in String) is
pragma Unreferenced (Name);
begin
Stream.Write_Cell (Value);
end Write_Attribute;
overriding
procedure Write_Wide_Attribute (Stream : in out Output_Stream;
Name : in String;
Value : in Wide_Wide_String) is
begin
null;
end Write_Wide_Attribute;
overriding
procedure Write_Attribute (Stream : in out Output_Stream;
Name : in String;
Value : in Integer) is
pragma Unreferenced (Name);
begin
Stream.Write_Cell (Value);
end Write_Attribute;
overriding
procedure Write_Attribute (Stream : in out Output_Stream;
Name : in String;
Value : in Boolean) is
pragma Unreferenced (Name);
begin
Stream.Write_Cell (Value);
end Write_Attribute;
overriding
procedure Write_Attribute (Stream : in out Output_Stream;
Name : in String;
Value : in Util.Beans.Objects.Object) is
pragma Unreferenced (Name);
begin
Stream.Write_Cell (Value);
end Write_Attribute;
procedure Write_Entity (Stream : in out Output_Stream;
Name : in String;
Value : in Util.Beans.Objects.Object) is
pragma Unreferenced (Name);
begin
Stream.Write_Cell (Value);
end Write_Entity;
-- -----------------------
-- Write the entity value.
-- -----------------------
overriding
procedure Write_Entity (Stream : in out Output_Stream;
Name : in String;
Value : in String) is
pragma Unreferenced (Name);
begin
Stream.Write_Cell (Value);
end Write_Entity;
overriding
procedure Write_Wide_Entity (Stream : in out Output_Stream;
Name : in String;
Value : in Wide_Wide_String) is
begin
null;
end Write_Wide_Entity;
overriding
procedure Write_Entity (Stream : in out Output_Stream;
Name : in String;
Value : in Boolean) is
pragma Unreferenced (Name);
begin
Stream.Write_Cell (Value);
end Write_Entity;
overriding
procedure Write_Entity (Stream : in out Output_Stream;
Name : in String;
Value : in Integer) is
pragma Unreferenced (Name);
begin
Stream.Write_Cell (Value);
end Write_Entity;
overriding
procedure Write_Entity (Stream : in out Output_Stream;
Name : in String;
Value : in Ada.Calendar.Time) is
begin
Stream.Write_Entity (Name, Util.Dates.ISO8601.Image (Value, Util.Dates.ISO8601.SUBSECOND));
end Write_Entity;
overriding
procedure Write_Long_Entity (Stream : in out Output_Stream;
Name : in String;
Value : in Long_Long_Integer) is
begin
null;
end Write_Long_Entity;
overriding
procedure Write_Enum_Entity (Stream : in out Output_Stream;
Name : in String;
Value : in String) is
begin
Stream.Write_Entity (Name, Value);
end Write_Enum_Entity;
-- ------------------------------
-- Get the header name for the given column.
-- If there was no header line, build a default header for the column.
-- ------------------------------
function Get_Header_Name (Handler : in Parser;
Column : in Column_Type) return String is
use type Ada.Containers.Count_Type;
Default_Header : constant String := "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
Result : String (1 .. 10);
N, R : Natural;
Pos : Positive := Result'Last;
begin
if Handler.Headers.Length >= Ada.Containers.Count_Type (Column) then
return Handler.Headers.Element (Positive (Column));
end if;
N := Natural (Column - 1);
loop
R := N mod 26;
N := N / 26;
Result (Pos) := Default_Header (R + 1);
exit when N = 0;
Pos := Pos - 1;
end loop;
return Result (Pos .. Result'Last);
end Get_Header_Name;
-- ------------------------------
-- Set the cell value at the given row and column.
-- The default implementation finds the column header name and
-- invokes <b>Write_Entity</b> with the header name and the value.
-- ------------------------------
procedure Set_Cell (Handler : in out Parser;
Value : in String;
Row : in Row_Type;
Column : in Column_Type) is
use Ada.Containers;
begin
if Row = 0 then
-- Build the headers table.
declare
Missing : constant Integer := Integer (Column) - Integer (Handler.Headers.Length);
begin
if Missing > 0 then
Handler.Headers.Set_Length (Handler.Headers.Length + Count_Type (Missing));
end if;
Handler.Headers.Replace_Element (Positive (Column), Value);
end;
else
declare
Name : constant String := Handler.Get_Header_Name (Column);
begin
-- Detect a new row. Close the current object and start a new one.
if Handler.Row /= Row then
if Row > 1 then
Parser'Class (Handler).Finish_Object ("");
end if;
Parser'Class (Handler).Start_Object ("");
end if;
Handler.Row := Row;
Parser'Class (Handler).Set_Member (Name, Util.Beans.Objects.To_Object (Value));
end;
end if;
end Set_Cell;
-- ------------------------------
-- Set the field separator. The default field separator is the comma (',').
-- ------------------------------
procedure Set_Field_Separator (Handler : in out Parser;
Separator : in Character) is
begin
Handler.Separator := Separator;
end Set_Field_Separator;
-- ------------------------------
-- Get the field separator.
-- ------------------------------
function Get_Field_Separator (Handler : in Parser) return Character is
begin
return Handler.Separator;
end Get_Field_Separator;
-- ------------------------------
-- Set the comment separator. When a comment separator is defined, a line which starts
-- with the comment separator will be ignored. The row number will not be incremented.
-- ------------------------------
procedure Set_Comment_Separator (Handler : in out Parser;
Separator : in Character) is
begin
Handler.Comment := Separator;
end Set_Comment_Separator;
-- ------------------------------
-- Get the comment separator. Returns ASCII.NUL if comments are not supported.
-- ------------------------------
function Get_Comment_Separator (Handler : in Parser) return Character is
begin
return Handler.Comment;
end Get_Comment_Separator;
-- ------------------------------
-- Setup the CSV parser and mapper to use the default column header names.
-- When activated, the first row is assumed to contain the first item to de-serialize.
-- ------------------------------
procedure Set_Default_Headers (Handler : in out Parser;
Mode : in Boolean := True) is
begin
Handler.Use_Default_Headers := Mode;
end Set_Default_Headers;
-- ------------------------------
-- Parse the stream using the CSV parser.
-- Call <b>Set_Cell</b> for each cell that has been parsed indicating the row and
-- column numbers as well as the cell value.
-- ------------------------------
overriding
procedure Parse (Handler : in out Parser;
Stream : in out Util.Streams.Buffered.Buffered_Stream'Class) is
use Ada.Strings.Unbounded;
C : Character;
Token : Unbounded_String;
Column : Column_Type := 1;
Row : Row_Type := 0;
In_Quote_Token : Boolean := False;
In_Escape : Boolean := False;
Ignore_Row : Boolean := False;
Context : Element_Context_Access;
begin
Context_Stack.Push (Handler.Stack);
Context := Context_Stack.Current (Handler.Stack);
Context.Active_Nodes (1) := Handler.Mapping_Tree'Unchecked_Access;
if Handler.Use_Default_Headers then
Row := 1;
end if;
Handler.Headers.Clear;
loop
Stream.Read (Char => C);
if C = Ada.Characters.Latin_1.CR or C = Ada.Characters.Latin_1.LF then
if C = Ada.Characters.Latin_1.LF then
Handler.Line_Number := Handler.Line_Number + 1;
end if;
if not Ignore_Row then
if In_Quote_Token and not In_Escape then
Append (Token, C);
elsif Column > 1 or else Length (Token) > 0 then
Parser'Class (Handler).Set_Cell (To_String (Token), Row, Column);
Set_Unbounded_String (Token, "");
Row := Row + 1;
Column := 1;
In_Quote_Token := False;
In_Escape := False;
end if;
else
Ignore_Row := False;
end if;
elsif C = Handler.Separator and not Ignore_Row then
if In_Quote_Token and not In_Escape then
Append (Token, C);
else
Parser'Class (Handler).Set_Cell (To_String (Token), Row, Column);
Set_Unbounded_String (Token, "");
Column := Column + 1;
In_Quote_Token := False;
In_Escape := False;
end if;
elsif C = '"' and not Ignore_Row then
if In_Quote_Token then
In_Escape := True;
elsif In_Escape then
Append (Token, C);
In_Escape := False;
elsif Ada.Strings.Unbounded.Length (Token) = 0 then
In_Quote_Token := True;
else
Append (Token, C);
end if;
elsif C = Handler.Comment and Handler.Comment /= ASCII.NUL
and Column = 1 and Length (Token) = 0
then
Ignore_Row := True;
elsif not Ignore_Row then
Append (Token, C);
In_Escape := False;
end if;
end loop;
exception
when Ada.IO_Exceptions.Data_Error =>
Parser'Class (Handler).Set_Cell (To_String (Token), Row, Column);
Context_Stack.Pop (Handler.Stack);
return;
end Parse;
-- ------------------------------
-- Get the current location (file and line) to report an error message.
-- ------------------------------
overriding
function Get_Location (Handler : in Parser) return String is
begin
return Util.Strings.Image (Handler.Line_Number);
end Get_Location;
end Util.Serialize.IO.CSV;
|
-----------------------------------------------------------------------
-- util-serialize-io-csv -- CSV Serialization Driver
-- Copyright (C) 2011, 2015, 2016, 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Ada.Characters.Latin_1;
with Ada.IO_Exceptions;
with Util.Strings;
with Util.Dates.ISO8601;
package body Util.Serialize.IO.CSV is
-- ------------------------------
-- Set the field separator. The default field separator is the comma (',').
-- ------------------------------
procedure Set_Field_Separator (Stream : in out Output_Stream;
Separator : in Character) is
begin
Stream.Separator := Separator;
end Set_Field_Separator;
-- ------------------------------
-- Enable or disable the double quotes by default for strings.
-- ------------------------------
procedure Set_Quotes (Stream : in out Output_Stream;
Enable : in Boolean) is
begin
Stream.Quote := Enable;
end Set_Quotes;
-- ------------------------------
-- Write the value as a CSV cell. Special characters are escaped using the CSV
-- escape rules.
-- ------------------------------
procedure Write_Cell (Stream : in out Output_Stream;
Value : in String) is
begin
if Stream.Column > 1 then
Stream.Write (Stream.Separator);
end if;
Stream.Column := Stream.Column + 1;
if Stream.Quote then
Stream.Write ('"');
end if;
for I in Value'Range loop
if Value (I) = '"' then
Stream.Write ("""""");
else
Stream.Write (Value (I));
end if;
end loop;
if Stream.Quote then
Stream.Write ('"');
end if;
end Write_Cell;
procedure Write_Cell (Stream : in out Output_Stream;
Value : in Integer) is
begin
if Stream.Column > 1 then
Stream.Write (Stream.Separator);
end if;
Stream.Column := Stream.Column + 1;
Stream.Write (Util.Strings.Image (Value));
end Write_Cell;
procedure Write_Cell (Stream : in out Output_Stream;
Value : in Boolean) is
begin
if Stream.Column > 1 then
Stream.Write (Stream.Separator);
end if;
Stream.Column := Stream.Column + 1;
if Value then
Stream.Write ("true");
else
Stream.Write ("false");
end if;
end Write_Cell;
procedure Write_Cell (Stream : in out Output_Stream;
Value : in Util.Beans.Objects.Object) is
use Util.Beans.Objects;
begin
case Util.Beans.Objects.Get_Type (Value) is
when TYPE_NULL =>
if Stream.Column > 1 then
Stream.Write (Stream.Separator);
end if;
Stream.Column := Stream.Column + 1;
if Stream.Quote then
Stream.Write ("""null""");
else
Stream.Write ("null");
end if;
when TYPE_BOOLEAN =>
if Stream.Column > 1 then
Stream.Write (Stream.Separator);
end if;
Stream.Column := Stream.Column + 1;
if Util.Beans.Objects.To_Boolean (Value) then
Stream.Write ("true");
else
Stream.Write ("false");
end if;
when TYPE_INTEGER =>
if Stream.Column > 1 then
Stream.Write (Stream.Separator);
end if;
Stream.Column := Stream.Column + 1;
-- Stream.Write ('"');
Stream.Write (Util.Beans.Objects.To_Long_Long_Integer (Value));
-- Stream.Write ('"');
when others =>
Stream.Write_Cell (Util.Beans.Objects.To_String (Value));
end case;
end Write_Cell;
-- ------------------------------
-- Start a new row.
-- ------------------------------
procedure New_Row (Stream : in out Output_Stream) is
begin
while Stream.Column < Stream.Max_Columns loop
Stream.Write (Stream.Separator);
Stream.Column := Stream.Column + 1;
end loop;
Stream.Write (ASCII.CR);
Stream.Write (ASCII.LF);
Stream.Column := 1;
Stream.Row := Stream.Row + 1;
end New_Row;
-- -----------------------
-- Write the attribute name/value pair.
-- -----------------------
overriding
procedure Write_Attribute (Stream : in out Output_Stream;
Name : in String;
Value : in String) is
pragma Unreferenced (Name);
begin
Stream.Write_Cell (Value);
end Write_Attribute;
overriding
procedure Write_Wide_Attribute (Stream : in out Output_Stream;
Name : in String;
Value : in Wide_Wide_String) is
begin
null;
end Write_Wide_Attribute;
overriding
procedure Write_Attribute (Stream : in out Output_Stream;
Name : in String;
Value : in Integer) is
pragma Unreferenced (Name);
begin
Stream.Write_Cell (Value);
end Write_Attribute;
overriding
procedure Write_Attribute (Stream : in out Output_Stream;
Name : in String;
Value : in Boolean) is
pragma Unreferenced (Name);
begin
Stream.Write_Cell (Value);
end Write_Attribute;
overriding
procedure Write_Attribute (Stream : in out Output_Stream;
Name : in String;
Value : in Util.Beans.Objects.Object) is
pragma Unreferenced (Name);
begin
Stream.Write_Cell (Value);
end Write_Attribute;
procedure Write_Entity (Stream : in out Output_Stream;
Name : in String;
Value : in Util.Beans.Objects.Object) is
pragma Unreferenced (Name);
begin
Stream.Write_Cell (Value);
end Write_Entity;
-- -----------------------
-- Write the entity value.
-- -----------------------
overriding
procedure Write_Entity (Stream : in out Output_Stream;
Name : in String;
Value : in String) is
pragma Unreferenced (Name);
begin
Stream.Write_Cell (Value);
end Write_Entity;
overriding
procedure Write_Wide_Entity (Stream : in out Output_Stream;
Name : in String;
Value : in Wide_Wide_String) is
begin
null;
end Write_Wide_Entity;
overriding
procedure Write_Entity (Stream : in out Output_Stream;
Name : in String;
Value : in Boolean) is
pragma Unreferenced (Name);
begin
Stream.Write_Cell (Value);
end Write_Entity;
overriding
procedure Write_Entity (Stream : in out Output_Stream;
Name : in String;
Value : in Integer) is
pragma Unreferenced (Name);
begin
Stream.Write_Cell (Value);
end Write_Entity;
overriding
procedure Write_Entity (Stream : in out Output_Stream;
Name : in String;
Value : in Ada.Calendar.Time) is
begin
Stream.Write_Entity (Name, Util.Dates.ISO8601.Image (Value, Util.Dates.ISO8601.SUBSECOND));
end Write_Entity;
overriding
procedure Write_Long_Entity (Stream : in out Output_Stream;
Name : in String;
Value : in Long_Long_Integer) is
begin
null;
end Write_Long_Entity;
overriding
procedure Write_Enum_Entity (Stream : in out Output_Stream;
Name : in String;
Value : in String) is
begin
Stream.Write_Entity (Name, Value);
end Write_Enum_Entity;
-- ------------------------------
-- Get the header name for the given column.
-- If there was no header line, build a default header for the column.
-- ------------------------------
function Get_Header_Name (Handler : in Parser;
Column : in Column_Type) return String is
use type Ada.Containers.Count_Type;
Default_Header : constant String := "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
Result : String (1 .. 10);
N, R : Natural;
Pos : Positive := Result'Last;
begin
if Handler.Headers.Length >= Ada.Containers.Count_Type (Column) then
return Handler.Headers.Element (Positive (Column));
end if;
N := Natural (Column - 1);
loop
R := N mod 26;
N := N / 26;
Result (Pos) := Default_Header (R + 1);
exit when N = 0;
Pos := Pos - 1;
end loop;
return Result (Pos .. Result'Last);
end Get_Header_Name;
-- ------------------------------
-- Set the cell value at the given row and column.
-- The default implementation finds the column header name and
-- invokes <b>Write_Entity</b> with the header name and the value.
-- ------------------------------
procedure Set_Cell (Handler : in out Parser;
Value : in String;
Row : in Row_Type;
Column : in Column_Type) is
use Ada.Containers;
begin
if Row = 0 then
-- Build the headers table.
declare
Missing : constant Integer := Integer (Column) - Integer (Handler.Headers.Length);
begin
if Missing > 0 then
Handler.Headers.Set_Length (Handler.Headers.Length + Count_Type (Missing));
end if;
Handler.Headers.Replace_Element (Positive (Column), Value);
end;
else
declare
Name : constant String := Handler.Get_Header_Name (Column);
begin
-- Detect a new row. Close the current object and start a new one.
if Handler.Row /= Row then
if Row > 1 then
Handler.Sink.Finish_Object ("");
end if;
Handler.Sink.Start_Object ("");
end if;
Handler.Row := Row;
Handler.Sink.Set_Member (Name, Util.Beans.Objects.To_Object (Value));
end;
end if;
end Set_Cell;
-- ------------------------------
-- Set the field separator. The default field separator is the comma (',').
-- ------------------------------
procedure Set_Field_Separator (Handler : in out Parser;
Separator : in Character) is
begin
Handler.Separator := Separator;
end Set_Field_Separator;
-- ------------------------------
-- Get the field separator.
-- ------------------------------
function Get_Field_Separator (Handler : in Parser) return Character is
begin
return Handler.Separator;
end Get_Field_Separator;
-- ------------------------------
-- Set the comment separator. When a comment separator is defined, a line which starts
-- with the comment separator will be ignored. The row number will not be incremented.
-- ------------------------------
procedure Set_Comment_Separator (Handler : in out Parser;
Separator : in Character) is
begin
Handler.Comment := Separator;
end Set_Comment_Separator;
-- ------------------------------
-- Get the comment separator. Returns ASCII.NUL if comments are not supported.
-- ------------------------------
function Get_Comment_Separator (Handler : in Parser) return Character is
begin
return Handler.Comment;
end Get_Comment_Separator;
-- ------------------------------
-- Setup the CSV parser and mapper to use the default column header names.
-- When activated, the first row is assumed to contain the first item to de-serialize.
-- ------------------------------
procedure Set_Default_Headers (Handler : in out Parser;
Mode : in Boolean := True) is
begin
Handler.Use_Default_Headers := Mode;
end Set_Default_Headers;
-- ------------------------------
-- Parse the stream using the CSV parser.
-- Call <b>Set_Cell</b> for each cell that has been parsed indicating the row and
-- column numbers as well as the cell value.
-- ------------------------------
overriding
procedure Parse (Handler : in out Parser;
Stream : in out Util.Streams.Buffered.Buffered_Stream'Class;
Sink : in out Reader'Class) is
use Ada.Strings.Unbounded;
C : Character;
Token : Unbounded_String;
Column : Column_Type := 1;
Row : Row_Type := 0;
In_Quote_Token : Boolean := False;
In_Escape : Boolean := False;
Ignore_Row : Boolean := False;
-- Context : Element_Context_Access;
begin
-- Context_Stack.Push (Handler.Stack);
-- Context := Context_Stack.Current (Handler.Stack);
-- Context.Active_Nodes (1) := Handler.Mapping_Tree'Unchecked_Access;
if Handler.Use_Default_Headers then
Row := 1;
end if;
Handler.Headers.Clear;
Handler.Sink := Sink'Unchecked_Access;
loop
Stream.Read (Char => C);
if C = Ada.Characters.Latin_1.CR or C = Ada.Characters.Latin_1.LF then
if C = Ada.Characters.Latin_1.LF then
Handler.Line_Number := Handler.Line_Number + 1;
end if;
if not Ignore_Row then
if In_Quote_Token and not In_Escape then
Append (Token, C);
elsif Column > 1 or else Length (Token) > 0 then
Parser'Class (Handler).Set_Cell (To_String (Token), Row, Column);
Set_Unbounded_String (Token, "");
Row := Row + 1;
Column := 1;
In_Quote_Token := False;
In_Escape := False;
end if;
else
Ignore_Row := False;
end if;
elsif C = Handler.Separator and not Ignore_Row then
if In_Quote_Token and not In_Escape then
Append (Token, C);
else
Parser'Class (Handler).Set_Cell (To_String (Token), Row, Column);
Set_Unbounded_String (Token, "");
Column := Column + 1;
In_Quote_Token := False;
In_Escape := False;
end if;
elsif C = '"' and not Ignore_Row then
if In_Quote_Token then
In_Escape := True;
elsif In_Escape then
Append (Token, C);
In_Escape := False;
elsif Ada.Strings.Unbounded.Length (Token) = 0 then
In_Quote_Token := True;
else
Append (Token, C);
end if;
elsif C = Handler.Comment and Handler.Comment /= ASCII.NUL
and Column = 1 and Length (Token) = 0
then
Ignore_Row := True;
elsif not Ignore_Row then
Append (Token, C);
In_Escape := False;
end if;
end loop;
Handler.Sink := null;
exception
when Ada.IO_Exceptions.Data_Error =>
Parser'Class (Handler).Set_Cell (To_String (Token), Row, Column);
-- Context_Stack.Pop (Handler.Stack);
Handler.Sink := null;
return;
end Parse;
-- ------------------------------
-- Get the current location (file and line) to report an error message.
-- ------------------------------
overriding
function Get_Location (Handler : in Parser) return String is
begin
return Util.Strings.Image (Handler.Line_Number);
end Get_Location;
end Util.Serialize.IO.CSV;
|
Use the Reader interface to give information that was read
|
Use the Reader interface to give information that was read
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
29b814231fe1f4abbf39c57f60e2d33fb22e87e9
|
src/gen-artifacts-docs.ads
|
src/gen-artifacts-docs.ads
|
-----------------------------------------------------------------------
-- gen-artifacts-docs -- Artifact for documentation
-- Copyright (C) 2012, 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Containers.Indefinite_Vectors;
with Ada.Containers.Indefinite_Hashed_Maps;
with Ada.Strings.Hash;
with Ada.Strings.Unbounded;
with Gen.Model.Packages;
-- with Asis;
-- with Asis.Text;
-- with Asis.Elements;
-- with Asis.Exceptions;
-- with Asis.Errors;
-- with Asis.Implementation;
-- with Asis.Elements;
-- with Asis.Declarations;
-- The <b>Gen.Artifacts.Docs</b> package is an artifact for the generation of
-- application documentation. Its purpose is to scan the project source files
-- and extract some interesting information for a developer's guide. The artifact
-- scans the Ada source files, the XML configuration files, the XHTML files.
--
-- The generated documentation is intended to be published on a web site.
-- The Google Wiki style is generated by default.
--
-- 1/ In the first step, the project files are scanned and the useful
-- documentation is extracted.
--
-- 2/ In the second step, the documentation is merged and reconciled. Links to
-- documentation pages and references are setup and the final pages are generated.
--
-- Ada
-- ---
-- The documentation starts at the first '== TITLE ==' marker and finishes before the
-- package specification.
--
-- XHTML
-- -----
-- Same as Ada.
--
-- XML Files
-- ----------
-- The documentation is part of the XML and the <b>documentation</b> or <b>description</b>
-- tags are extracted.
package Gen.Artifacts.Docs is
-- Tag marker (same as Java).
TAG_CHAR : constant Character := '@';
-- Specific tags recognized when analyzing the documentation.
TAG_AUTHOR : constant String := "author";
TAG_TITLE : constant String := "title";
TAG_INCLUDE : constant String := "include";
TAG_SEE : constant String := "see";
type Doc_Format is (DOC_MARKDOWN, DOC_WIKI_GOOGLE);
-- ------------------------------
-- Documentation artifact
-- ------------------------------
type Artifact is new Gen.Artifacts.Artifact with private;
-- 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);
-- Set the output document format to generate.
procedure Set_Format (Handler : in out Artifact;
Format : in Doc_Format);
private
type Line_Kind is (L_TEXT, L_LIST, L_LIST_ITEM, L_SEE, L_INCLUDE);
type Line_Type (Len : Natural) is record
Kind : Line_Kind := L_TEXT;
Content : String (1 .. Len);
end record;
package Line_Vectors is
new Ada.Containers.Indefinite_Vectors (Index_Type => Positive,
Element_Type => Line_Type);
type Doc_State is (IN_PARA, IN_SEPARATOR, IN_CODE, IN_CODE_SEPARATOR, IN_LIST);
type File_Document is record
Name : Ada.Strings.Unbounded.Unbounded_String;
Title : Ada.Strings.Unbounded.Unbounded_String;
State : Doc_State := IN_PARA;
Line_Number : Natural := 0;
Lines : Line_Vectors.Vector;
Was_Included : Boolean := False;
end record;
package Doc_Maps is
new Ada.Containers.Indefinite_Hashed_Maps (Key_Type => String,
Element_Type => File_Document,
Hash => Ada.Strings.Hash,
Equivalent_Keys => "=");
-- Include the document extract represented by <b>Name</b> into the document <b>Into</b>.
-- The included document is marked so that it will not be generated.
procedure Include (Docs : in out Doc_Maps.Map;
Into : in out File_Document;
Name : in String;
Position : in Natural);
-- Generate the project documentation that was collected in <b>Docs</b>.
-- The documentation is merged so that the @include tags are replaced by the matching
-- document extracts.
procedure Generate (Docs : in out Doc_Maps.Map;
Dir : in String);
-- Returns True if the line indicates a bullet or numbered list.
function Is_List (Line : in String) return Boolean;
-- Returns True if the line indicates a code sample.
function Is_Code (Line : in String) return Boolean;
-- Append a raw text line to the document.
procedure Append_Line (Doc : in out File_Document;
Line : in String);
-- Look and analyze the tag defined on the line.
procedure Append_Tag (Doc : in out File_Document;
Tag : in String);
-- Analyse the documentation line and collect the documentation text.
procedure Append (Doc : in out File_Document;
Line : in String);
-- After having collected the documentation, terminate the document by making sure
-- the opened elements are closed.
procedure Finish (Doc : in out File_Document);
-- Set the name associated with the document extract.
procedure Set_Name (Doc : in out File_Document;
Name : in String);
-- Set the title associated with the document extract.
procedure Set_Title (Doc : in out File_Document;
Title : in String);
-- Scan the files in the directory refered to by <b>Path</b> and collect the documentation
-- in the <b>Docs</b> hashed map.
procedure Scan_Files (Handler : in out Artifact;
Path : in String;
Docs : in out Doc_Maps.Map);
-- Read the Ada specification file and collect the useful documentation.
-- To keep the implementation simple, we don't use the ASIS packages to scan and extract
-- the documentation. We don't need to look at the Ada specification itself. Instead,
-- we assume that the Ada source follows some Ada style guidelines.
procedure Read_Ada_File (Handler : in out Artifact;
File : in String;
Result : in out File_Document);
procedure Read_Xml_File (Handler : in out Artifact;
File : in String;
Result : in out File_Document);
type Artifact is new Gen.Artifacts.Artifact with record
Xslt_Command : Ada.Strings.Unbounded.Unbounded_String;
Format : Doc_Format := DOC_WIKI_GOOGLE;
end record;
end Gen.Artifacts.Docs;
|
-----------------------------------------------------------------------
-- gen-artifacts-docs -- Artifact for documentation
-- Copyright (C) 2012, 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Containers.Indefinite_Vectors;
with Ada.Containers.Indefinite_Hashed_Maps;
with Ada.Strings.Hash;
with Ada.Strings.Unbounded;
with Gen.Model.Packages;
-- with Asis;
-- with Asis.Text;
-- with Asis.Elements;
-- with Asis.Exceptions;
-- with Asis.Errors;
-- with Asis.Implementation;
-- with Asis.Elements;
-- with Asis.Declarations;
-- The <b>Gen.Artifacts.Docs</b> package is an artifact for the generation of
-- application documentation. Its purpose is to scan the project source files
-- and extract some interesting information for a developer's guide. The artifact
-- scans the Ada source files, the XML configuration files, the XHTML files.
--
-- The generated documentation is intended to be published on a web site.
-- The Google Wiki style is generated by default.
--
-- 1/ In the first step, the project files are scanned and the useful
-- documentation is extracted.
--
-- 2/ In the second step, the documentation is merged and reconciled. Links to
-- documentation pages and references are setup and the final pages are generated.
--
-- Ada
-- ---
-- The documentation starts at the first '== TITLE ==' marker and finishes before the
-- package specification.
--
-- XHTML
-- -----
-- Same as Ada.
--
-- XML Files
-- ----------
-- The documentation is part of the XML and the <b>documentation</b> or <b>description</b>
-- tags are extracted.
package Gen.Artifacts.Docs is
-- Tag marker (same as Java).
TAG_CHAR : constant Character := '@';
-- Specific tags recognized when analyzing the documentation.
TAG_AUTHOR : constant String := "author";
TAG_TITLE : constant String := "title";
TAG_INCLUDE : constant String := "include";
TAG_SEE : constant String := "see";
type Doc_Format is (DOC_MARKDOWN, DOC_WIKI_GOOGLE);
-- ------------------------------
-- Documentation artifact
-- ------------------------------
type Artifact is new Gen.Artifacts.Artifact with private;
-- 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);
-- Set the output document format to generate.
procedure Set_Format (Handler : in out Artifact;
Format : in Doc_Format);
private
type Line_Kind is (L_TEXT, L_LIST, L_LIST_ITEM, L_SEE, L_INCLUDE);
type Line_Type (Len : Natural) is record
Kind : Line_Kind := L_TEXT;
Content : String (1 .. Len);
end record;
package Line_Vectors is
new Ada.Containers.Indefinite_Vectors (Index_Type => Positive,
Element_Type => Line_Type);
type Doc_State is (IN_PARA, IN_SEPARATOR, IN_CODE, IN_CODE_SEPARATOR, IN_LIST);
type Document_Formatter is abstract tagged null record;
type Document_Formatter_Access is access all Document_Formatter'Class;
type File_Document is record
Name : Ada.Strings.Unbounded.Unbounded_String;
Title : Ada.Strings.Unbounded.Unbounded_String;
State : Doc_State := IN_PARA;
Line_Number : Natural := 0;
Lines : Line_Vectors.Vector;
Was_Included : Boolean := False;
Formatter : Document_Formatter_Access;
end record;
-- Get the document name from the file document (ex: <name>.wiki or <name>.md).
function Get_Document_Name (Formatter : in Document_Formatter;
Document : in File_Document) return String is abstract;
package Doc_Maps is
new Ada.Containers.Indefinite_Hashed_Maps (Key_Type => String,
Element_Type => File_Document,
Hash => Ada.Strings.Hash,
Equivalent_Keys => "=");
-- Include the document extract represented by <b>Name</b> into the document <b>Into</b>.
-- The included document is marked so that it will not be generated.
procedure Include (Docs : in out Doc_Maps.Map;
Into : in out File_Document;
Name : in String;
Position : in Natural);
-- Generate the project documentation that was collected in <b>Docs</b>.
-- The documentation is merged so that the @include tags are replaced by the matching
-- document extracts.
procedure Generate (Docs : in out Doc_Maps.Map;
Dir : in String);
-- Returns True if the line indicates a bullet or numbered list.
function Is_List (Line : in String) return Boolean;
-- Returns True if the line indicates a code sample.
function Is_Code (Line : in String) return Boolean;
-- Append a raw text line to the document.
procedure Append_Line (Doc : in out File_Document;
Line : in String);
-- Look and analyze the tag defined on the line.
procedure Append_Tag (Doc : in out File_Document;
Tag : in String);
-- Analyse the documentation line and collect the documentation text.
procedure Append (Doc : in out File_Document;
Line : in String);
-- After having collected the documentation, terminate the document by making sure
-- the opened elements are closed.
procedure Finish (Doc : in out File_Document);
-- Set the name associated with the document extract.
procedure Set_Name (Doc : in out File_Document;
Name : in String);
-- Set the title associated with the document extract.
procedure Set_Title (Doc : in out File_Document;
Title : in String);
-- Scan the files in the directory refered to by <b>Path</b> and collect the documentation
-- in the <b>Docs</b> hashed map.
procedure Scan_Files (Handler : in out Artifact;
Path : in String;
Docs : in out Doc_Maps.Map);
-- Read the Ada specification file and collect the useful documentation.
-- To keep the implementation simple, we don't use the ASIS packages to scan and extract
-- the documentation. We don't need to look at the Ada specification itself. Instead,
-- we assume that the Ada source follows some Ada style guidelines.
procedure Read_Ada_File (Handler : in out Artifact;
File : in String;
Result : in out File_Document);
procedure Read_Xml_File (Handler : in out Artifact;
File : in String;
Result : in out File_Document);
type Artifact is new Gen.Artifacts.Artifact with record
Xslt_Command : Ada.Strings.Unbounded.Unbounded_String;
Format : Doc_Format := DOC_WIKI_GOOGLE;
end record;
end Gen.Artifacts.Docs;
|
Declare the Get_Document_Name function and the Document_Formatter abstract type
|
Declare the Get_Document_Name function and the Document_Formatter abstract type
|
Ada
|
apache-2.0
|
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
|
3ca2d7225a7a5adcbffaee7ed9da4ec2e19376a0
|
src/sys/os-windows/util-processes-os.adb
|
src/sys/os-windows/util-processes-os.adb
|
-----------------------------------------------------------------------
-- util-processes-os -- System specific and low level operations
-- Copyright (C) 2011, 2012, 2018, 2019 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with System;
with Ada.Unchecked_Deallocation;
with Ada.Characters.Conversions;
with Ada.Directories;
with Util.Log.Loggers;
package body Util.Processes.Os is
use type Interfaces.C.size_t;
-- The logger
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Util.Processes.Os");
procedure Free is
new Ada.Unchecked_Deallocation (Object => Interfaces.C.wchar_array,
Name => Wchar_Ptr);
function To_WSTR (Value : in String) return Wchar_Ptr;
-- ------------------------------
-- Wait for the process to exit.
-- ------------------------------
overriding
procedure Wait (Sys : in out System_Process;
Proc : in out Process'Class;
Timeout : in Duration) is
use type Util.Streams.Output_Stream_Access;
Result : DWORD;
T : DWORD;
Code : aliased DWORD;
Status : BOOL;
begin
-- Close the input stream pipe if there is one.
if Proc.Input /= null then
Util.Streams.Raw.Raw_Stream'Class (Proc.Input.all).Close;
end if;
if Timeout < 0.0 then
T := DWORD'Last;
else
T := DWORD (Timeout * 1000.0);
end if;
Log.Debug ("Waiting {0}", DWORD'Image (T));
Result := Wait_For_Single_Object (H => Sys.Process_Info.hProcess,
Time => T);
Log.Debug ("Status {0}", DWORD'Image (Result));
Status := Get_Exit_Code_Process (Proc => Sys.Process_Info.hProcess,
Code => Code'Unchecked_Access);
if Status = 0 then
Log.Error ("Process is still running. Error {0}", Integer'Image (Get_Last_Error));
end if;
Proc.Exit_Value := Integer (Code);
Log.Debug ("Process exit is: {0}", Integer'Image (Proc.Exit_Value));
end Wait;
-- ------------------------------
-- Terminate the process by sending a signal on Unix and exiting the process on Windows.
-- This operation is not portable and has a different behavior between Unix and Windows.
-- Its intent is to stop the process.
-- ------------------------------
overriding
procedure Stop (Sys : in out System_Process;
Proc : in out Process'Class;
Signal : in Positive := 15) is
pragma Unreferenced (Proc);
Result : Integer;
pragma Unreferenced (Result);
begin
Result := Terminate_Process (Sys.Process_Info.hProcess, DWORD (Signal));
end Stop;
procedure Prepare_Working_Directory (Sys : in out System_Process;
Proc : in out Process'Class) is
Dir : constant String := Ada.Strings.Unbounded.To_String (Proc.Dir);
begin
Free (Sys.Dir);
if Dir'Length > 0 then
if not Ada.Directories.Exists (Dir)
or else Ada.Directories.Kind (Dir) /= Ada.Directories.Directory
then
raise Ada.Directories.Name_Error with "Invalid directory: " & Dir;
end if;
Sys.Dir := To_WSTR (Dir);
end if;
end Prepare_Working_Directory;
-- Spawn a new process.
overriding
procedure Spawn (Sys : in out System_Process;
Proc : in out Process'Class;
Mode : in Pipe_Mode := NONE) is
use Util.Streams.Raw;
use Ada.Characters.Conversions;
use Interfaces.C;
use type System.Address;
Result : Integer;
Startup : aliased Startup_Info;
R : BOOL;
begin
Sys.Prepare_Working_Directory (Proc);
-- Since checks are disabled, verify by hand that the argv table is correct.
if Sys.Command = null or else Sys.Command'Length < 1 then
raise Program_Error with "Invalid process argument list";
end if;
Startup.cb := Startup'Size / 8;
Startup.hStdInput := Get_Std_Handle (STD_INPUT_HANDLE);
Startup.hStdOutput := Get_Std_Handle (STD_OUTPUT_HANDLE);
Startup.hStdError := Get_Std_Handle (STD_ERROR_HANDLE);
if Mode = READ or Mode = READ_WRITE or Mode = READ_ALL then
Build_Output_Pipe (Proc, Startup);
end if;
if Mode = WRITE or Mode = READ_WRITE or Mode = READ_WRITE_ALL then
Build_Input_Pipe (Proc, Startup);
end if;
-- Start the child process.
Result := Create_Process (System.Null_Address,
Sys.Command.all'Address,
null,
null,
True,
16#0#,
System.Null_Address,
Sys.Dir.all'Address,
Startup'Unchecked_Access,
Sys.Process_Info'Unchecked_Access);
-- Close the handles which are not necessary.
if Startup.hStdInput /= Get_Std_Handle (STD_INPUT_HANDLE) then
R := Close_Handle (Startup.hStdInput);
end if;
if Startup.hStdOutput /= Get_Std_Handle (STD_OUTPUT_HANDLE) then
R := Close_Handle (Startup.hStdOutput);
end if;
if Startup.hStdError /= Get_Std_Handle (STD_ERROR_HANDLE) then
R := Close_Handle (Startup.hStdError);
end if;
if Result /= 1 then
Result := Get_Last_Error;
Log.Error ("Process creation failed: {0}", Integer'Image (Result));
raise Process_Error with "Cannot create process";
end if;
Proc.Pid := Process_Identifier (Sys.Process_Info.dwProcessId);
end Spawn;
-- ------------------------------
-- Create the output stream to read/write on the process input/output.
-- Setup the file to be closed on exec.
-- ------------------------------
function Create_Stream (File : in Util.Streams.Raw.File_Type)
return Util.Streams.Raw.Raw_Stream_Access is
Stream : constant Util.Streams.Raw.Raw_Stream_Access := new Util.Streams.Raw.Raw_Stream;
begin
Stream.Initialize (File);
return Stream;
end Create_Stream;
-- ------------------------------
-- Build the output pipe redirection to read the process output.
-- ------------------------------
procedure Build_Output_Pipe (Proc : in out Process'Class;
Into : in out Startup_Info) is
Sec : aliased Security_Attributes;
Read_Handle : aliased HANDLE;
Write_Handle : aliased HANDLE;
Read_Pipe_Handle : aliased HANDLE;
Error_Handle : aliased HANDLE;
Result : BOOL;
Current_Proc : constant HANDLE := Get_Current_Process;
begin
Sec.Length := Sec'Size / 8;
Sec.Inherit := True;
Sec.Security_Descriptor := System.Null_Address;
Result := Create_Pipe (Read_Handle => Read_Handle'Unchecked_Access,
Write_Handle => Write_Handle'Unchecked_Access,
Attributes => Sec'Unchecked_Access,
Buf_Size => 0);
if Result = 0 then
Log.Error ("Cannot create pipe: {0}", Integer'Image (Get_Last_Error));
raise Program_Error with "Cannot create pipe";
end if;
Result := Duplicate_Handle (SourceProcessHandle => Current_Proc,
SourceHandle => Read_Handle,
TargetProcessHandle => Current_Proc,
TargetHandle => Read_Pipe_Handle'Unchecked_Access,
DesiredAccess => 0,
InheritHandle => 0,
Options => 2);
if Result = 0 then
raise Program_Error with "Cannot create pipe";
end if;
Result := Close_Handle (Read_Handle);
Result := Duplicate_Handle (SourceProcessHandle => Current_Proc,
SourceHandle => Write_Handle,
TargetProcessHandle => Current_Proc,
TargetHandle => Error_Handle'Unchecked_Access,
DesiredAccess => 0,
InheritHandle => 1,
Options => 2);
if Result = 0 then
raise Program_Error with "Cannot create pipe";
end if;
Into.dwFlags := 16#100#;
Into.hStdOutput := Write_Handle;
Into.hStdError := Error_Handle;
Proc.Output := Create_Stream (Read_Pipe_Handle).all'Access;
end Build_Output_Pipe;
-- ------------------------------
-- Build the input pipe redirection to write the process standard input.
-- ------------------------------
procedure Build_Input_Pipe (Proc : in out Process'Class;
Into : in out Startup_Info) is
Sec : aliased Security_Attributes;
Read_Handle : aliased HANDLE;
Write_Handle : aliased HANDLE;
Write_Pipe_Handle : aliased HANDLE;
Result : BOOL;
Current_Proc : constant HANDLE := Get_Current_Process;
begin
Sec.Length := Sec'Size / 8;
Sec.Inherit := True;
Sec.Security_Descriptor := System.Null_Address;
Result := Create_Pipe (Read_Handle => Read_Handle'Unchecked_Access,
Write_Handle => Write_Handle'Unchecked_Access,
Attributes => Sec'Unchecked_Access,
Buf_Size => 0);
if Result = 0 then
Log.Error ("Cannot create pipe: {0}", Integer'Image (Get_Last_Error));
raise Program_Error with "Cannot create pipe";
end if;
Result := Duplicate_Handle (SourceProcessHandle => Current_Proc,
SourceHandle => Write_Handle,
TargetProcessHandle => Current_Proc,
TargetHandle => Write_Pipe_Handle'Unchecked_Access,
DesiredAccess => 0,
InheritHandle => 0,
Options => 2);
if Result = 0 then
raise Program_Error with "Cannot create pipe";
end if;
Result := Close_Handle (Write_Handle);
Into.dwFlags := 16#100#;
Into.hStdInput := Read_Handle;
Proc.Input := Create_Stream (Write_Pipe_Handle).all'Access;
end Build_Input_Pipe;
-- ------------------------------
-- Append the argument to the process argument list.
-- ------------------------------
overriding
procedure Append_Argument (Sys : in out System_Process;
Arg : in String) is
Len : Interfaces.C.size_t := Arg'Length;
begin
if Sys.Command /= null then
Len := Len + Sys.Command'Length + 2;
declare
S : constant Wchar_Ptr := new Interfaces.C.wchar_array (0 .. Len);
begin
S (Sys.Command'Range) := Sys.Command.all;
Free (Sys.Command);
Sys.Command := S;
end;
Sys.Command (Sys.Pos) := Interfaces.C.To_C (' ');
Sys.Pos := Sys.Pos + 1;
else
Sys.Command := new Interfaces.C.wchar_array (0 .. Len + 1);
Sys.Pos := 0;
end if;
for I in Arg'Range loop
Sys.Command (Sys.Pos)
:= Interfaces.C.To_C (Ada.Characters.Conversions.To_Wide_Character (Arg (I)));
Sys.Pos := Sys.Pos + 1;
end loop;
Sys.Command (Sys.Pos) := Interfaces.C.wide_nul;
end Append_Argument;
function To_WSTR (Value : in String) return Wchar_Ptr is
Result : constant Wchar_Ptr := new Interfaces.C.wchar_array (0 .. Value'Length + 1);
Pos : Interfaces.C.size_t := 0;
begin
for C of Value loop
Result (Pos)
:= Interfaces.C.To_C (Ada.Characters.Conversions.To_Wide_Character (C));
Pos := Pos + 1;
end loop;
Result (Pos) := Interfaces.C.wide_nul;
return Result;
end To_WSTR;
-- ------------------------------
-- Set the process input, output and error streams to redirect and use specified files.
-- ------------------------------
overriding
procedure Set_Streams (Sys : in out System_Process;
Input : in String;
Output : in String;
Error : in String;
Append_Output : in Boolean;
Append_Error : in Boolean;
To_Close : in File_Type_Array_Access) is
begin
if Input'Length > 0 then
Sys.In_File := To_WSTR (Input);
end if;
if Output'Length > 0 then
Sys.Out_File := To_WSTR (Output);
Sys.Out_Append := Append_Output;
end if;
if Error'Length > 0 then
Sys.Err_File := To_WSTR (Error);
Sys.Err_Append := Append_Error;
end if;
Sys.To_Close := To_Close;
end Set_Streams;
-- ------------------------------
-- Deletes the storage held by the system process.
-- ------------------------------
overriding
procedure Finalize (Sys : in out System_Process) is
use type System.Address;
Result : BOOL;
pragma Unreferenced (Result);
begin
if Sys.Process_Info.hProcess /= NO_FILE then
Result := Close_Handle (Sys.Process_Info.hProcess);
Sys.Process_Info.hProcess := NO_FILE;
end if;
if Sys.Process_Info.hThread /= NO_FILE then
Result := Close_Handle (Sys.Process_Info.hThread);
Sys.Process_Info.hThread := NO_FILE;
end if;
Free (Sys.In_File);
Free (Sys.Out_File);
Free (Sys.Err_File);
Free (Sys.Dir);
Free (Sys.Command);
end Finalize;
end Util.Processes.Os;
|
-----------------------------------------------------------------------
-- util-processes-os -- System specific and low level operations
-- Copyright (C) 2011, 2012, 2018, 2019 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with System;
with Ada.Unchecked_Deallocation;
with Ada.Characters.Conversions;
with Ada.Directories;
with Util.Log.Loggers;
package body Util.Processes.Os is
use type Interfaces.C.size_t;
use type Util.Systems.Os.HANDLE;
use type Ada.Directories.File_Kind;
-- The logger
Log : constant Log.Loggers.Logger := Log.Loggers.Create ("Util.Processes.Os");
procedure Free is
new Ada.Unchecked_Deallocation (Object => Interfaces.C.wchar_array,
Name => Wchar_Ptr);
function To_WSTR (Value : in String) return Wchar_Ptr;
procedure Prepare_Working_Directory (Sys : in out System_Process;
Proc : in out Process'Class);
procedure Redirect_Output (Path : in Wchar_Ptr;
Append : in Boolean;
Output : out HANDLE);
procedure Redirect_Input (Path : in Wchar_Ptr;
Input : out HANDLE);
-- ------------------------------
-- Wait for the process to exit.
-- ------------------------------
overriding
procedure Wait (Sys : in out System_Process;
Proc : in out Process'Class;
Timeout : in Duration) is
use type Util.Streams.Output_Stream_Access;
Result : DWORD;
T : DWORD;
Code : aliased DWORD;
Status : BOOL;
begin
-- Close the input stream pipe if there is one.
if Proc.Input /= null then
Util.Streams.Raw.Raw_Stream'Class (Proc.Input.all).Close;
end if;
if Timeout < 0.0 then
T := DWORD'Last;
else
T := DWORD (Timeout * 1000.0);
end if;
Log.Debug ("Waiting {0}", DWORD'Image (T));
Result := Wait_For_Single_Object (H => Sys.Process_Info.hProcess,
Time => T);
Log.Debug ("Status {0}", DWORD'Image (Result));
Status := Get_Exit_Code_Process (Proc => Sys.Process_Info.hProcess,
Code => Code'Unchecked_Access);
if Status = 0 then
Log.Error ("Process is still running. Error {0}", Integer'Image (Get_Last_Error));
end if;
Proc.Exit_Value := Integer (Code);
Log.Debug ("Process exit is: {0}", Integer'Image (Proc.Exit_Value));
end Wait;
-- ------------------------------
-- Terminate the process by sending a signal on Unix and exiting the process on Windows.
-- This operation is not portable and has a different behavior between Unix and Windows.
-- Its intent is to stop the process.
-- ------------------------------
overriding
procedure Stop (Sys : in out System_Process;
Proc : in out Process'Class;
Signal : in Positive := 15) is
pragma Unreferenced (Proc);
Result : Integer;
pragma Unreferenced (Result);
begin
Result := Terminate_Process (Sys.Process_Info.hProcess, DWORD (Signal));
end Stop;
procedure Prepare_Working_Directory (Sys : in out System_Process;
Proc : in out Process'Class) is
Dir : constant String := Ada.Strings.Unbounded.To_String (Proc.Dir);
begin
Free (Sys.Dir);
if Dir'Length > 0 then
if not Ada.Directories.Exists (Dir)
or else Ada.Directories.Kind (Dir) /= Ada.Directories.Directory
then
raise Ada.Directories.Name_Error with "Invalid directory: " & Dir;
end if;
Sys.Dir := To_WSTR (Dir);
end if;
end Prepare_Working_Directory;
procedure Redirect_Output (Path : in Wchar_Ptr;
Append : in Boolean;
Output : out HANDLE) is
Sec : aliased Security_Attributes;
begin
Sec.Length := Security_Attributes'Size / 8;
Sec.Security_Descriptor := System.Null_Address;
Sec.Inherit := True;
Output := Create_File (Path.all'Address,
(if Append then FILE_APPEND_DATA else GENERIC_WRITE),
FILE_SHARE_WRITE + FILE_SHARE_READ,
Sec'Unchecked_Access,
(if Append then OPEN_ALWAYS else CREATE_ALWAYS),
FILE_ATTRIBUTE_NORMAL,
NO_FILE);
if Output = INVALID_HANDLE_VALUE then
Log.Error ("Cannot create process output file: {0}", Integer'Image (Get_Last_Error));
raise Process_Error with "Cannot create process output file";
end if;
end Redirect_Output;
procedure Redirect_Input (Path : in Wchar_Ptr;
Input : out HANDLE) is
Sec : aliased Security_Attributes;
begin
Sec.Length := Security_Attributes'Size / 8;
Sec.Security_Descriptor := System.Null_Address;
Sec.Inherit := True;
Input := Create_File (Path.all'Address,
GENERIC_READ,
FILE_SHARE_READ,
Sec'Unchecked_Access,
OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL,
NO_FILE);
if Input = INVALID_HANDLE_VALUE then
Log.Error ("Cannot open process input file: {0}", Integer'Image (Get_Last_Error));
raise Process_Error with "Cannot open process input file";
end if;
end Redirect_Input;
-- Spawn a new process.
overriding
procedure Spawn (Sys : in out System_Process;
Proc : in out Process'Class;
Mode : in Pipe_Mode := NONE) is
use Util.Streams.Raw;
use Ada.Characters.Conversions;
use Interfaces.C;
use type System.Address;
Result : Integer;
Startup : aliased Startup_Info;
R : BOOL with Unreferenced;
begin
Sys.Prepare_Working_Directory (Proc);
-- Since checks are disabled, verify by hand that the argv table is correct.
if Sys.Command = null or else Sys.Command'Length < 1 then
raise Program_Error with "Invalid process argument list";
end if;
Startup.cb := Startup'Size / 8;
Startup.hStdInput := Get_Std_Handle (STD_INPUT_HANDLE);
Startup.hStdOutput := Get_Std_Handle (STD_OUTPUT_HANDLE);
Startup.hStdError := Get_Std_Handle (STD_ERROR_HANDLE);
if Mode = READ or Mode = READ_WRITE or Mode = READ_ALL then
Build_Output_Pipe (Proc, Startup);
elsif Sys.Out_File /= null then
Redirect_Output (Sys.Out_File, Sys.Out_Append, Startup.hStdOutput);
Startup.dwFlags := 16#100#;
end if;
if Sys.Err_File /= null then
Redirect_Output (Sys.Err_File, Sys.Err_Append, Startup.hStdError);
Startup.dwFlags := 16#100#;
end if;
if Mode = WRITE or Mode = READ_WRITE or Mode = READ_WRITE_ALL then
Build_Input_Pipe (Proc, Startup);
elsif Sys.In_File /= null then
Redirect_Input (Sys.In_File, Startup.hStdInput);
Startup.dwFlags := 16#100#;
end if;
-- Start the child process.
if Sys.Dir /= null then
Result := Create_Process (System.Null_Address,
Sys.Command.all'Address,
null,
null,
True,
16#0#,
System.Null_Address,
Sys.Dir.all'Address,
Startup'Unchecked_Access,
Sys.Process_Info'Unchecked_Access);
else
Result := Create_Process (System.Null_Address,
Sys.Command.all'Address,
null,
null,
True,
16#0#,
System.Null_Address,
System.Null_Address,
Startup'Unchecked_Access,
Sys.Process_Info'Unchecked_Access);
end if;
-- Close the handles which are not necessary.
if Startup.hStdInput /= Get_Std_Handle (STD_INPUT_HANDLE) then
R := Close_Handle (Startup.hStdInput);
end if;
if Startup.hStdOutput /= Get_Std_Handle (STD_OUTPUT_HANDLE) then
R := Close_Handle (Startup.hStdOutput);
end if;
if Startup.hStdError /= Get_Std_Handle (STD_ERROR_HANDLE) then
R := Close_Handle (Startup.hStdError);
end if;
if Result /= 1 then
Result := Get_Last_Error;
Log.Error ("Process creation failed: {0}", Integer'Image (Result));
raise Process_Error with "Cannot create process";
end if;
Proc.Pid := Process_Identifier (Sys.Process_Info.dwProcessId);
end Spawn;
-- ------------------------------
-- Create the output stream to read/write on the process input/output.
-- Setup the file to be closed on exec.
-- ------------------------------
function Create_Stream (File : in Util.Streams.Raw.File_Type)
return Util.Streams.Raw.Raw_Stream_Access is
Stream : constant Util.Streams.Raw.Raw_Stream_Access := new Util.Streams.Raw.Raw_Stream;
begin
Stream.Initialize (File);
return Stream;
end Create_Stream;
-- ------------------------------
-- Build the output pipe redirection to read the process output.
-- ------------------------------
procedure Build_Output_Pipe (Proc : in out Process'Class;
Into : in out Startup_Info) is
Sec : aliased Security_Attributes;
Read_Handle : aliased HANDLE;
Write_Handle : aliased HANDLE;
Read_Pipe_Handle : aliased HANDLE;
Error_Handle : aliased HANDLE;
Result : BOOL;
R : BOOL with Unreferenced;
Current_Proc : constant HANDLE := Get_Current_Process;
begin
Sec.Length := Sec'Size / 8;
Sec.Inherit := True;
Sec.Security_Descriptor := System.Null_Address;
Result := Create_Pipe (Read_Handle => Read_Handle'Unchecked_Access,
Write_Handle => Write_Handle'Unchecked_Access,
Attributes => Sec'Unchecked_Access,
Buf_Size => 0);
if Result = 0 then
Log.Error ("Cannot create pipe: {0}", Integer'Image (Get_Last_Error));
raise Program_Error with "Cannot create pipe";
end if;
Result := Duplicate_Handle (SourceProcessHandle => Current_Proc,
SourceHandle => Read_Handle,
TargetProcessHandle => Current_Proc,
TargetHandle => Read_Pipe_Handle'Unchecked_Access,
DesiredAccess => 0,
InheritHandle => 0,
Options => 2);
if Result = 0 then
Log.Error ("Cannot create pipe: {0}", Integer'Image (Get_Last_Error));
raise Program_Error with "Cannot create pipe";
end if;
R := Close_Handle (Read_Handle);
Result := Duplicate_Handle (SourceProcessHandle => Current_Proc,
SourceHandle => Write_Handle,
TargetProcessHandle => Current_Proc,
TargetHandle => Error_Handle'Unchecked_Access,
DesiredAccess => 0,
InheritHandle => 1,
Options => 2);
if Result = 0 then
Log.Error ("Cannot create pipe: {0}", Integer'Image (Get_Last_Error));
raise Program_Error with "Cannot create pipe";
end if;
Into.dwFlags := 16#100#;
Into.hStdOutput := Write_Handle;
Into.hStdError := Error_Handle;
Proc.Output := Create_Stream (Read_Pipe_Handle).all'Access;
end Build_Output_Pipe;
-- ------------------------------
-- Build the input pipe redirection to write the process standard input.
-- ------------------------------
procedure Build_Input_Pipe (Proc : in out Process'Class;
Into : in out Startup_Info) is
Sec : aliased Security_Attributes;
Read_Handle : aliased HANDLE;
Write_Handle : aliased HANDLE;
Write_Pipe_Handle : aliased HANDLE;
Result : BOOL;
R : BOOL with Unreferenced;
Current_Proc : constant HANDLE := Get_Current_Process;
begin
Sec.Length := Sec'Size / 8;
Sec.Inherit := True;
Sec.Security_Descriptor := System.Null_Address;
Result := Create_Pipe (Read_Handle => Read_Handle'Unchecked_Access,
Write_Handle => Write_Handle'Unchecked_Access,
Attributes => Sec'Unchecked_Access,
Buf_Size => 0);
if Result = 0 then
Log.Error ("Cannot create pipe: {0}", Integer'Image (Get_Last_Error));
raise Program_Error with "Cannot create pipe";
end if;
Result := Duplicate_Handle (SourceProcessHandle => Current_Proc,
SourceHandle => Write_Handle,
TargetProcessHandle => Current_Proc,
TargetHandle => Write_Pipe_Handle'Unchecked_Access,
DesiredAccess => 0,
InheritHandle => 0,
Options => 2);
if Result = 0 then
Log.Error ("Cannot create pipe: {0}", Integer'Image (Get_Last_Error));
raise Program_Error with "Cannot create pipe";
end if;
R := Close_Handle (Write_Handle);
Into.dwFlags := 16#100#;
Into.hStdInput := Read_Handle;
Proc.Input := Create_Stream (Write_Pipe_Handle).all'Access;
end Build_Input_Pipe;
-- ------------------------------
-- Append the argument to the process argument list.
-- ------------------------------
overriding
procedure Append_Argument (Sys : in out System_Process;
Arg : in String) is
Len : Interfaces.C.size_t := Arg'Length;
begin
if Sys.Command /= null then
Len := Len + Sys.Command'Length + 2;
declare
S : constant Wchar_Ptr := new Interfaces.C.wchar_array (0 .. Len);
begin
S (Sys.Command'Range) := Sys.Command.all;
Free (Sys.Command);
Sys.Command := S;
end;
Sys.Command (Sys.Pos) := Interfaces.C.To_C (' ');
Sys.Pos := Sys.Pos + 1;
else
Sys.Command := new Interfaces.C.wchar_array (0 .. Len + 1);
Sys.Pos := 0;
end if;
for I in Arg'Range loop
Sys.Command (Sys.Pos)
:= Interfaces.C.To_C (Ada.Characters.Conversions.To_Wide_Character (Arg (I)));
Sys.Pos := Sys.Pos + 1;
end loop;
Sys.Command (Sys.Pos) := Interfaces.C.wide_nul;
end Append_Argument;
function To_WSTR (Value : in String) return Wchar_Ptr is
Result : constant Wchar_Ptr := new Interfaces.C.wchar_array (0 .. Value'Length + 1);
Pos : Interfaces.C.size_t := 0;
begin
for C of Value loop
Result (Pos)
:= Interfaces.C.To_C (Ada.Characters.Conversions.To_Wide_Character (C));
Pos := Pos + 1;
end loop;
Result (Pos) := Interfaces.C.wide_nul;
return Result;
end To_WSTR;
-- ------------------------------
-- Set the process input, output and error streams to redirect and use specified files.
-- ------------------------------
overriding
procedure Set_Streams (Sys : in out System_Process;
Input : in String;
Output : in String;
Error : in String;
Append_Output : in Boolean;
Append_Error : in Boolean;
To_Close : in File_Type_Array_Access) is
begin
if Input'Length > 0 then
Sys.In_File := To_WSTR (Input);
end if;
if Output'Length > 0 then
Sys.Out_File := To_WSTR (Output);
Sys.Out_Append := Append_Output;
end if;
if Error'Length > 0 then
Sys.Err_File := To_WSTR (Error);
Sys.Err_Append := Append_Error;
end if;
Sys.To_Close := To_Close;
end Set_Streams;
-- ------------------------------
-- Deletes the storage held by the system process.
-- ------------------------------
overriding
procedure Finalize (Sys : in out System_Process) is
use type System.Address;
Result : BOOL;
pragma Unreferenced (Result);
begin
if Sys.Process_Info.hProcess /= NO_FILE then
Result := Close_Handle (Sys.Process_Info.hProcess);
Sys.Process_Info.hProcess := NO_FILE;
end if;
if Sys.Process_Info.hThread /= NO_FILE then
Result := Close_Handle (Sys.Process_Info.hThread);
Sys.Process_Info.hThread := NO_FILE;
end if;
Free (Sys.In_File);
Free (Sys.Out_File);
Free (Sys.Err_File);
Free (Sys.Dir);
Free (Sys.Command);
end Finalize;
end Util.Processes.Os;
|
Implement redirection of stdin/stdout/stderr to/from a file when launching a process
|
Implement redirection of stdin/stdout/stderr to/from a file when launching a process
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
0467b6f6e9f758eb58733f91c9161d5e9bc1cd86
|
src/os-linux/util-streams-raw.ads
|
src/os-linux/util-streams-raw.ads
|
-----------------------------------------------------------------------
-- util-streams-raw -- Raw streams for Unix based systems
-- Copyright (C) 2011, 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.Finalization;
with Util.Systems.Os;
with Util.Systems.Types;
-- The <b>Util.Streams.Raw</b> package provides a stream directly on top of
-- file system operations <b>read</b> and <b>write</b>.
package Util.Streams.Raw is
-- -----------------------
-- File stream
-- -----------------------
-- The <b>Raw_Stream</b> is an output/input stream that reads or writes
-- into a file-based stream.
type Raw_Stream is new Ada.Finalization.Limited_Controlled and Output_Stream
and Input_Stream with private;
type Raw_Stream_Access is access all Raw_Stream'Class;
-- Initialize the raw stream to read and write on the given file descriptor.
procedure Initialize (Stream : in out Raw_Stream;
File : in Util.Systems.Os.File_Type);
-- Close the stream.
overriding
procedure Close (Stream : in out Raw_Stream);
-- Write the buffer array to the output stream.
procedure Write (Stream : in out Raw_Stream;
Buffer : in Ada.Streams.Stream_Element_Array);
-- Read into the buffer as many bytes as possible and return in
-- <b>last</b> the position of the last byte read.
procedure Read (Stream : in out Raw_Stream;
Into : out Ada.Streams.Stream_Element_Array;
Last : out Ada.Streams.Stream_Element_Offset);
-- Reposition the read/write file offset.
procedure Seek (Stream : in out Raw_Stream;
Pos : in Util.Systems.Types.off_t;
Mode : in Util.Systems.Types.Seek_Mode);
private
use Ada.Streams;
-- Flush the stream and release the buffer.
procedure Finalize (Object : in out Raw_Stream);
type Raw_Stream is new Ada.Finalization.Limited_Controlled
and Output_Stream and Input_Stream with record
File : Util.Systems.Os.File_Type := Util.Systems.Os.NO_FILE;
end record;
end Util.Streams.Raw;
|
-----------------------------------------------------------------------
-- util-streams-raw -- Raw streams for Unix based systems
-- Copyright (C) 2011, 2016, 2018 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Finalization;
with Util.Systems.Os;
with Util.Systems.Types;
-- === Raw files ===
-- The <b>Util.Streams.Raw</b> package provides a stream directly on top of
-- file system operations <b>read</b> and <b>write</b>.
package Util.Streams.Raw is
-- -----------------------
-- File stream
-- -----------------------
-- The <b>Raw_Stream</b> is an output/input stream that reads or writes
-- into a file-based stream.
type Raw_Stream is new Ada.Finalization.Limited_Controlled and Output_Stream
and Input_Stream with private;
type Raw_Stream_Access is access all Raw_Stream'Class;
-- Initialize the raw stream to read and write on the given file descriptor.
procedure Initialize (Stream : in out Raw_Stream;
File : in Util.Systems.Os.File_Type);
-- Close the stream.
overriding
procedure Close (Stream : in out Raw_Stream);
-- Write the buffer array to the output stream.
procedure Write (Stream : in out Raw_Stream;
Buffer : in Ada.Streams.Stream_Element_Array);
-- Read into the buffer as many bytes as possible and return in
-- <b>last</b> the position of the last byte read.
procedure Read (Stream : in out Raw_Stream;
Into : out Ada.Streams.Stream_Element_Array;
Last : out Ada.Streams.Stream_Element_Offset);
-- Reposition the read/write file offset.
procedure Seek (Stream : in out Raw_Stream;
Pos : in Util.Systems.Types.off_t;
Mode : in Util.Systems.Types.Seek_Mode);
private
use Ada.Streams;
-- Flush the stream and release the buffer.
procedure Finalize (Object : in out Raw_Stream);
type Raw_Stream is new Ada.Finalization.Limited_Controlled
and Output_Stream and Input_Stream with record
File : Util.Systems.Os.File_Type := Util.Systems.Os.NO_FILE;
end record;
end Util.Streams.Raw;
|
Document the streams framework
|
Document the streams framework
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
10fb31f4d005c73c152358a93eb1339bce97d2a6
|
awa/regtests/awa-testsuite.adb
|
awa/regtests/awa-testsuite.adb
|
-----------------------------------------------------------------------
-- Util testsuite - Util Testsuite
-- Copyright (C) 2009, 2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with AWA.Users.Services.Tests;
with AWA.Users.Tests;
with AWA.Blogs.Modules.Tests;
with AWA.Blogs.Tests;
with AWA.Helpers.Selectors.Tests;
with AWA.Storages.Services.Tests;
with AWA.Events.Services.Tests;
with AWA.Mail.Clients.Tests;
with AWA.Mail.Modules.Tests;
with AWA.Images.Modules.Tests;
with AWA.Votes.Modules.Tests;
with AWA.Tags.Modules.Tests;
with AWA.Questions.Modules.Tests;
with AWA.Questions.Tests;
with AWA.Counters.Modules.Tests;
with AWA.Workspaces.Tests;
with AWA.Modules.Tests;
with ASF.Converters.Dates;
with AWA.Users.Modules;
with AWA.Mail.Modules;
with AWA.Blogs.Modules;
with AWA.Workspaces.Modules;
with AWA.Storages.Modules;
with AWA.Images.Modules;
with AWA.Questions.Modules;
with AWA.Votes.Modules;
with AWA.Tags.Modules;
with AWA.Changelogs.Modules;
with AWA.Counters.Modules;
with AWA.Converters.Dates;
with AWA.Tests;
with AWA.Services.Contexts;
with AWA.Jobs.Services.Tests;
with AWA.Jobs.Modules.Tests;
with AWA.Settings.Modules.Tests;
with AWA.Comments.Modules.Tests;
with AWA.Changelogs.Modules.Tests;
with AWA.Wikis.Modules.Tests;
with AWA.Wikis.Tests;
with AWA.Commands.Tests;
with ADO.Drivers;
with Servlet.Server;
package body AWA.Testsuite is
Users : aliased AWA.Users.Modules.User_Module;
Workspaces : aliased AWA.Workspaces.Modules.Workspace_Module;
Mail : aliased AWA.Mail.Modules.Mail_Module;
Jobs : aliased AWA.Jobs.Modules.Job_Module;
Comments : aliased AWA.Comments.Modules.Comment_Module;
Blogs : aliased AWA.Blogs.Modules.Blog_Module;
Storages : aliased AWA.Storages.Modules.Storage_Module;
Images : aliased AWA.Images.Modules.Image_Module;
Questions : aliased AWA.Questions.Modules.Question_Module;
Votes : aliased AWA.Votes.Modules.Vote_Module;
Tags : aliased AWA.Tags.Modules.Tag_Module;
Settings : aliased AWA.Settings.Modules.Setting_Module;
Changelogs : aliased AWA.Changelogs.Modules.Changelog_Module;
Wikis : aliased AWA.Wikis.Modules.Wiki_Module;
Counters : aliased AWA.Counters.Modules.Counter_Module;
Date_Converter : aliased ASF.Converters.Dates.Date_Converter;
Rel_Date_Converter : aliased AWA.Converters.Dates.Relative_Date_Converter;
Tests : aliased Util.Tests.Test_Suite;
function Suite return Util.Tests.Access_Test_Suite is
Ret : constant Util.Tests.Access_Test_Suite := Tests'Access;
begin
AWA.Modules.Tests.Add_Tests (Ret);
AWA.Events.Services.Tests.Add_Tests (Ret);
AWA.Mail.Clients.Tests.Add_Tests (Ret);
AWA.Mail.Modules.Tests.Add_Tests (Ret);
AWA.Users.Services.Tests.Add_Tests (Ret);
AWA.Users.Tests.Add_Tests (Ret);
AWA.Workspaces.Tests.Add_Tests (Ret);
AWA.Counters.Modules.Tests.Add_Tests (Ret);
AWA.Helpers.Selectors.Tests.Add_Tests (Ret);
AWA.Jobs.Modules.Tests.Add_Tests (Ret);
AWA.Jobs.Services.Tests.Add_Tests (Ret);
AWA.Settings.Modules.Tests.Add_Tests (Ret);
AWA.Comments.Modules.Tests.Add_Tests (Ret);
AWA.Blogs.Modules.Tests.Add_Tests (Ret);
AWA.Blogs.Tests.Add_Tests (Ret);
AWA.Storages.Services.Tests.Add_Tests (Ret);
AWA.Images.Modules.Tests.Add_Tests (Ret);
AWA.Changelogs.Modules.Tests.Add_Tests (Ret);
AWA.Votes.Modules.Tests.Add_Tests (Ret);
AWA.Tags.Modules.Tests.Add_Tests (Ret);
AWA.Questions.Modules.Tests.Add_Tests (Ret);
AWA.Questions.Tests.Add_Tests (Ret);
AWA.Wikis.Modules.Tests.Add_Tests (Ret);
AWA.Wikis.Tests.Add_Tests (Ret);
AWA.Commands.Tests.Add_Tests (Ret);
return Ret;
end Suite;
procedure Initialize (Props : in Util.Properties.Manager) is
begin
Initialize (null, Props, True);
end Initialize;
-- ------------------------------
-- Initialize the AWA test framework mockup.
-- ------------------------------
procedure Initialize (App : in AWA.Applications.Application_Access;
Props : in Util.Properties.Manager;
Add_Modules : in Boolean) is
use AWA.Applications;
begin
ADO.Drivers.Initialize;
AWA.Tests.Initialize (App, Props, Add_Modules);
if Add_Modules then
declare
Application : constant Applications.Application_Access := AWA.Tests.Get_Application;
Ctx : AWA.Services.Contexts.Service_Context;
Users : constant AWA.Users.Modules.User_Module_Access := AWA.Testsuite.Users'Access;
begin
Ctx.Set_Context (Application, null);
Register (App => Application.all'Access,
Name => AWA.Users.Modules.NAME,
URI => "user",
Module => Users.all'Access);
Register (App => Application.all'Access,
Name => "mail",
URI => "mail",
Module => Mail'Access);
Register (App => Application.all'Access,
Name => "workspaces",
URI => "workspaces",
Module => Workspaces'Access);
Register (App => Application.all'Access,
Name => AWA.Counters.Modules.NAME,
URI => "counters",
Module => Counters'Access);
Register (App => Application.all'Access,
Name => AWA.Comments.Modules.NAME,
URI => "comments",
Module => Comments'Access);
Register (App => Application.all'Access,
Name => AWA.Storages.Modules.NAME,
URI => "storages",
Module => Storages'Access);
Register (App => Application.all'Access,
Name => AWA.Jobs.Modules.NAME,
URI => "jobs",
Module => Jobs'Access);
Register (App => Application.all'Access,
Name => AWA.Images.Modules.NAME,
URI => "images",
Module => Images'Access);
Register (App => Application.all'Access,
Name => AWA.Settings.Modules.NAME,
URI => "settings",
Module => Settings'Access);
Register (App => Application.all'Access,
Name => AWA.Votes.Modules.NAME,
URI => "votes",
Module => Votes'Access);
Register (App => Application.all'Access,
Name => AWA.Changelogs.Modules.NAME,
URI => "changelogs",
Module => Changelogs'Access);
Register (App => Application.all'Access,
Name => AWA.Tags.Modules.NAME,
URI => "tags",
Module => Tags'Access);
Register (App => Application.all'Access,
Name => AWA.Blogs.Modules.NAME,
URI => "blogs",
Module => Blogs'Access);
Register (App => Application.all'Access,
Name => AWA.Questions.Modules.NAME,
URI => "questions",
Module => Questions'Access);
Register (App => Application.all'Access,
Name => AWA.Wikis.Modules.NAME,
URI => "wikis",
Module => Wikis'Access);
Application.Add_Converter (Name => "dateConverter",
Converter => Date_Converter'Access);
Application.Add_Converter (Name => "smartDateConverter",
Converter => Rel_Date_Converter'Access);
Application.Start;
-- if Props.Exists ("test.server") then
-- declare
-- WS : ASF.Server.Web.AWS_Container;
-- begin
-- Application.Add_Converter (Name => "dateConverter",
-- Converter => Date_Converter'Access);
-- Application.Add_Converter (Name => "smartDateConverter",
-- Converter => Rel_Date_Converter'Access);
--
-- WS.Register_Application ("/asfunit", Application.all'Access);
--
-- WS.Start;
-- delay 6000.0;
-- end;
-- end if;
Servlet.Server.Set_Context (Application.all'Access);
end;
end if;
end Initialize;
end AWA.Testsuite;
|
-----------------------------------------------------------------------
-- Util testsuite - Util Testsuite
-- Copyright (C) 2009 - 2020 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with AWA.Users.Services.Tests;
with AWA.Users.Tests;
with AWA.Blogs.Modules.Tests;
with AWA.Blogs.Tests;
with AWA.Helpers.Selectors.Tests;
with AWA.Storages.Services.Tests;
with AWA.Events.Services.Tests;
with AWA.Mail.Clients.Tests;
with AWA.Mail.Modules.Tests;
with AWA.Images.Modules.Tests;
with AWA.Votes.Modules.Tests;
with AWA.Tags.Modules.Tests;
with AWA.Questions.Modules.Tests;
with AWA.Questions.Tests;
with AWA.Counters.Modules.Tests;
with AWA.Workspaces.Tests;
with AWA.Modules.Tests;
with ASF.Converters.Dates;
with AWA.Users.Modules;
with AWA.Mail.Modules;
with AWA.Blogs.Modules;
with AWA.Workspaces.Modules;
with AWA.Storages.Modules;
with AWA.Images.Modules;
with AWA.Questions.Modules;
with AWA.Votes.Modules;
with AWA.Tags.Modules;
with AWA.Changelogs.Modules;
with AWA.Counters.Modules;
with AWA.Converters.Dates;
with AWA.Tests;
with AWA.Services.Contexts;
with AWA.Jobs.Services.Tests;
with AWA.Jobs.Modules.Tests;
with AWA.Settings.Modules.Tests;
with AWA.Comments.Modules.Tests;
with AWA.Changelogs.Modules.Tests;
with AWA.Wikis.Modules.Tests;
with AWA.Wikis.Tests;
with AWA.Commands.Tests;
with ADO.Drivers;
with Servlet.Server;
package body AWA.Testsuite is
Users : aliased AWA.Users.Modules.User_Module;
Workspaces : aliased AWA.Workspaces.Modules.Workspace_Module;
Mail : aliased AWA.Mail.Modules.Mail_Module;
Jobs : aliased AWA.Jobs.Modules.Job_Module;
Comments : aliased AWA.Comments.Modules.Comment_Module;
Blogs : aliased AWA.Blogs.Modules.Blog_Module;
Storages : aliased AWA.Storages.Modules.Storage_Module;
Images : aliased AWA.Images.Modules.Image_Module;
Questions : aliased AWA.Questions.Modules.Question_Module;
Votes : aliased AWA.Votes.Modules.Vote_Module;
Tags : aliased AWA.Tags.Modules.Tag_Module;
Settings : aliased AWA.Settings.Modules.Setting_Module;
Changelogs : aliased AWA.Changelogs.Modules.Changelog_Module;
Wikis : aliased AWA.Wikis.Modules.Wiki_Module;
Counters : aliased AWA.Counters.Modules.Counter_Module;
Date_Converter : aliased ASF.Converters.Dates.Date_Converter;
Rel_Date_Converter : aliased AWA.Converters.Dates.Relative_Date_Converter;
Tests : aliased Util.Tests.Test_Suite;
function Suite return Util.Tests.Access_Test_Suite is
Ret : constant Util.Tests.Access_Test_Suite := Tests'Access;
begin
AWA.Commands.Tests.Add_Tests (Ret);
AWA.Jobs.Modules.Tests.Add_Tests (Ret);
AWA.Jobs.Services.Tests.Add_Tests (Ret);
AWA.Settings.Modules.Tests.Add_Tests (Ret);
AWA.Comments.Modules.Tests.Add_Tests (Ret);
AWA.Blogs.Modules.Tests.Add_Tests (Ret);
AWA.Blogs.Tests.Add_Tests (Ret);
AWA.Storages.Services.Tests.Add_Tests (Ret);
AWA.Images.Modules.Tests.Add_Tests (Ret);
AWA.Changelogs.Modules.Tests.Add_Tests (Ret);
AWA.Votes.Modules.Tests.Add_Tests (Ret);
AWA.Tags.Modules.Tests.Add_Tests (Ret);
AWA.Questions.Modules.Tests.Add_Tests (Ret);
AWA.Questions.Tests.Add_Tests (Ret);
AWA.Wikis.Modules.Tests.Add_Tests (Ret);
AWA.Wikis.Tests.Add_Tests (Ret);
AWA.Events.Services.Tests.Add_Tests (Ret);
AWA.Mail.Clients.Tests.Add_Tests (Ret);
AWA.Mail.Modules.Tests.Add_Tests (Ret);
AWA.Workspaces.Tests.Add_Tests (Ret);
AWA.Users.Services.Tests.Add_Tests (Ret);
AWA.Users.Tests.Add_Tests (Ret);
AWA.Counters.Modules.Tests.Add_Tests (Ret);
AWA.Helpers.Selectors.Tests.Add_Tests (Ret);
AWA.Modules.Tests.Add_Tests (Ret);
return Ret;
end Suite;
procedure Initialize (Props : in Util.Properties.Manager) is
begin
Initialize (null, Props, True);
end Initialize;
-- ------------------------------
-- Initialize the AWA test framework mockup.
-- ------------------------------
procedure Initialize (App : in AWA.Applications.Application_Access;
Props : in Util.Properties.Manager;
Add_Modules : in Boolean) is
use AWA.Applications;
begin
ADO.Drivers.Initialize;
AWA.Tests.Initialize (App, Props, Add_Modules);
if Add_Modules then
declare
Application : constant Applications.Application_Access := AWA.Tests.Get_Application;
Ctx : AWA.Services.Contexts.Service_Context;
Users : constant AWA.Users.Modules.User_Module_Access := AWA.Testsuite.Users'Access;
begin
Ctx.Set_Context (Application, null);
Register (App => Application.all'Access,
Name => AWA.Users.Modules.NAME,
URI => "user",
Module => Users.all'Access);
Register (App => Application.all'Access,
Name => "mail",
URI => "mail",
Module => Mail'Access);
Register (App => Application.all'Access,
Name => "workspaces",
URI => "workspaces",
Module => Workspaces'Access);
Register (App => Application.all'Access,
Name => AWA.Counters.Modules.NAME,
URI => "counters",
Module => Counters'Access);
Register (App => Application.all'Access,
Name => AWA.Comments.Modules.NAME,
URI => "comments",
Module => Comments'Access);
Register (App => Application.all'Access,
Name => AWA.Storages.Modules.NAME,
URI => "storages",
Module => Storages'Access);
Register (App => Application.all'Access,
Name => AWA.Jobs.Modules.NAME,
URI => "jobs",
Module => Jobs'Access);
Register (App => Application.all'Access,
Name => AWA.Images.Modules.NAME,
URI => "images",
Module => Images'Access);
Register (App => Application.all'Access,
Name => AWA.Settings.Modules.NAME,
URI => "settings",
Module => Settings'Access);
Register (App => Application.all'Access,
Name => AWA.Votes.Modules.NAME,
URI => "votes",
Module => Votes'Access);
Register (App => Application.all'Access,
Name => AWA.Changelogs.Modules.NAME,
URI => "changelogs",
Module => Changelogs'Access);
Register (App => Application.all'Access,
Name => AWA.Tags.Modules.NAME,
URI => "tags",
Module => Tags'Access);
Register (App => Application.all'Access,
Name => AWA.Blogs.Modules.NAME,
URI => "blogs",
Module => Blogs'Access);
Register (App => Application.all'Access,
Name => AWA.Questions.Modules.NAME,
URI => "questions",
Module => Questions'Access);
Register (App => Application.all'Access,
Name => AWA.Wikis.Modules.NAME,
URI => "wikis",
Module => Wikis'Access);
Application.Add_Converter (Name => "dateConverter",
Converter => Date_Converter'Access);
Application.Add_Converter (Name => "smartDateConverter",
Converter => Rel_Date_Converter'Access);
Application.Start;
-- if Props.Exists ("test.server") then
-- declare
-- WS : ASF.Server.Web.AWS_Container;
-- begin
-- Application.Add_Converter (Name => "dateConverter",
-- Converter => Date_Converter'Access);
-- Application.Add_Converter (Name => "smartDateConverter",
-- Converter => Rel_Date_Converter'Access);
--
-- WS.Register_Application ("/asfunit", Application.all'Access);
--
-- WS.Start;
-- delay 6000.0;
-- end;
-- end if;
Servlet.Server.Set_Context (Application.all'Access);
end;
end if;
end Initialize;
end AWA.Testsuite;
|
Fix order of execution of unit tests so that the AWA.Commands test are executed last
|
Fix order of execution of unit tests so that the AWA.Commands test are executed last
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.