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
|
---|---|---|---|---|---|---|---|---|---|
a784572d7cb4755c8144b1861caed33d45118812
|
src/wiki-render-text.ads
|
src/wiki-render-text.ads
|
-----------------------------------------------------------------------
-- wiki-render-text -- Wiki Text renderer
-- Copyright (C) 2011, 2012, 2013, 2015, 2016 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Wiki.Attributes;
with Wiki.Streams;
with Wiki.Strings;
-- == Text Renderer ==
-- The <tt>Text_Renderer</tt> allows to render a wiki document into a text content.
-- The formatting rules are ignored except for the paragraphs and sections.
package Wiki.Render.Text is
-- ------------------------------
-- Wiki to Text renderer
-- ------------------------------
type Text_Renderer is new Wiki.Render.Renderer with private;
-- Set the output stream.
procedure Set_Output_Stream (Engine : in out Text_Renderer;
Stream : in Streams.Output_Stream_Access);
-- Render the node instance from the document.
overriding
procedure Render (Engine : in out Text_Renderer;
Doc : in Wiki.Nodes.Document;
Node : in Wiki.Nodes.Node_Type);
-- Add a line break (<br>).
procedure Add_Line_Break (Document : in out Text_Renderer);
-- Add a blockquote (<blockquote>). The level indicates the blockquote nested level.
-- The blockquote must be closed at the next header.
procedure Add_Blockquote (Document : in out Text_Renderer;
Level : in Natural);
-- Add a list item (<li>). Close the previous paragraph and list item if any.
-- The list item will be closed at the next list item, next paragraph or next header.
procedure Add_List_Item (Document : in out Text_Renderer;
Level : in Positive;
Ordered : in Boolean);
-- Add a link.
procedure Add_Link (Document : in out Text_Renderer;
Title : in Wiki.Strings.WString;
Attr : in Wiki.Attributes.Attribute_List_Type);
-- Add an image.
procedure Add_Image (Document : in out Text_Renderer;
Link : in Unbounded_Wide_Wide_String;
Alt : in Unbounded_Wide_Wide_String;
Position : in Unbounded_Wide_Wide_String;
Description : in Unbounded_Wide_Wide_String);
-- Add a text block that is pre-formatted.
procedure Add_Preformatted (Document : in out Text_Renderer;
Text : in Unbounded_Wide_Wide_String;
Format : in Unbounded_Wide_Wide_String);
-- Finish the document after complete wiki text has been parsed.
overriding
procedure Finish (Document : in out Text_Renderer);
private
-- Emit a new line.
procedure New_Line (Document : in out Text_Renderer);
procedure Close_Paragraph (Document : in out Text_Renderer);
procedure Open_Paragraph (Document : in out Text_Renderer);
type Text_Renderer is new Wiki.Render.Renderer with record
Output : Streams.Output_Stream_Access := null;
Format : Wiki.Format_Map := (others => False);
Has_Paragraph : Boolean := False;
Need_Paragraph : Boolean := False;
Empty_Line : Boolean := True;
Indent_Level : Natural := 0;
end record;
end Wiki.Render.Text;
|
-----------------------------------------------------------------------
-- wiki-render-text -- Wiki Text renderer
-- Copyright (C) 2011, 2012, 2013, 2015, 2016 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Wiki.Attributes;
with Wiki.Streams;
with Wiki.Strings;
-- == Text Renderer ==
-- The <tt>Text_Renderer</tt> allows to render a wiki document into a text content.
-- The formatting rules are ignored except for the paragraphs and sections.
package Wiki.Render.Text is
-- ------------------------------
-- Wiki to Text renderer
-- ------------------------------
type Text_Renderer is new Wiki.Render.Renderer with private;
-- Set the output stream.
procedure Set_Output_Stream (Engine : in out Text_Renderer;
Stream : in Streams.Output_Stream_Access);
-- Render the node instance from the document.
overriding
procedure Render (Engine : in out Text_Renderer;
Doc : in Wiki.Nodes.Document;
Node : in Wiki.Nodes.Node_Type);
-- Add a line break (<br>).
procedure Add_Line_Break (Document : in out Text_Renderer);
-- Add a blockquote (<blockquote>). The level indicates the blockquote nested level.
-- The blockquote must be closed at the next header.
procedure Add_Blockquote (Document : in out Text_Renderer;
Level : in Natural);
-- 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 Text_Renderer;
Level : in Positive;
Ordered : in Boolean);
-- Add a link.
procedure Add_Link (Document : in out Text_Renderer;
Title : in Wiki.Strings.WString;
Attr : in Wiki.Attributes.Attribute_List_Type);
-- Add an image.
procedure Add_Image (Document : in out Text_Renderer;
Link : in Unbounded_Wide_Wide_String;
Alt : in Unbounded_Wide_Wide_String;
Position : in Unbounded_Wide_Wide_String;
Description : in Unbounded_Wide_Wide_String);
-- Add a text block that is pre-formatted.
procedure Add_Preformatted (Document : in out Text_Renderer;
Text : in Unbounded_Wide_Wide_String;
Format : in Unbounded_Wide_Wide_String);
-- Finish the document after complete wiki text has been parsed.
overriding
procedure Finish (Document : in out Text_Renderer);
private
-- Emit a new line.
procedure New_Line (Document : in out Text_Renderer);
procedure Close_Paragraph (Document : in out Text_Renderer);
procedure Open_Paragraph (Document : in out Text_Renderer);
type Text_Renderer is new Wiki.Render.Renderer with record
Output : Streams.Output_Stream_Access := null;
Format : Wiki.Format_Map := (others => False);
Has_Paragraph : Boolean := False;
Need_Paragraph : Boolean := False;
Empty_Line : Boolean := True;
Indent_Level : Natural := 0;
end record;
end Wiki.Render.Text;
|
Rename Add_List_Item into Render_List_Item
|
Rename Add_List_Item into Render_List_Item
|
Ada
|
apache-2.0
|
stcarrez/ada-wiki,stcarrez/ada-wiki
|
d1cbef7f2e3f00e824e0bcbc1e3c6b999e238b39
|
awa/regtests/awa-events-services-tests.adb
|
awa/regtests/awa-events-services-tests.adb
|
-----------------------------------------------------------------------
-- events-tests -- Unit tests for AWA events
-- Copyright (C) 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Test_Caller;
with Util.Beans.Methods;
with Util.Log.Loggers;
with Util.Measures;
with Util.Concurrent.Counters;
with EL.Beans;
with EL.Expressions;
with EL.Contexts.Default;
with ASF.Applications;
with ASF.Servlets.Faces;
with AWA.Applications;
with AWA.Applications.Configs;
with AWA.Applications.Factory;
with AWA.Events.Action_Method;
with AWA.Services.Contexts;
with AWA.Events.Queues;
with AWA.Events.Services;
package body AWA.Events.Services.Tests is
use AWA.Events.Services;
use Util.Log;
Log : constant Loggers.Logger := Loggers.Create ("AWA.Events.Tests");
package Event_Test_4 is new AWA.Events.Definition (Name => "event-test-4");
package Event_Test_1 is new AWA.Events.Definition (Name => "event-test-1");
package Event_Test_3 is new AWA.Events.Definition (Name => "event-test-3");
package Event_Test_2 is new AWA.Events.Definition (Name => "event-test-2");
package Event_Test_5 is new AWA.Events.Definition (Name => "event-test-5");
package Caller is new Util.Test_Caller (Test, "Events.Tests");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test AWA.Events.Get_Event_Name",
Test_Get_Event_Name'Access);
Caller.Add_Test (Suite, "Test AWA.Events.Find_Event_Index",
Test_Find_Event'Access);
Caller.Add_Test (Suite, "Test AWA.Events.Initialize",
Test_Initialize'Access);
Caller.Add_Test (Suite, "Test AWA.Events.Add_Action",
Test_Add_Action'Access);
Caller.Add_Test (Suite, "Test AWA.Events.Dispatch_Synchronous",
Test_Dispatch_Synchronous'Access);
Caller.Add_Test (Suite, "Test AWA.Events.Dispatch_Fifo",
Test_Dispatch_Fifo'Access);
Caller.Add_Test (Suite, "Test AWA.Events.Dispatch_Persist",
Test_Dispatch_Persist'Access);
Caller.Add_Test (Suite, "Test AWA.Events.Dispatch_Synchronous_Dyn",
Test_Dispatch_Synchronous_Dyn'Access);
Caller.Add_Test (Suite, "Test AWA.Events.Dispatch_Synchronous_Raise",
Test_Dispatch_Synchronous_Raise'Access);
end Add_Tests;
type Action_Bean is new Util.Beans.Basic.Bean
and Util.Beans.Methods.Method_Bean with record
Count : Natural := 0;
Priority : Integer := 0;
Raise_Exception : Boolean := False;
end record;
type Action_Bean_Access is access all Action_Bean'Class;
-- Get the value identified by the name.
-- If the name cannot be found, the method should return the Null object.
overriding
function Get_Value (From : in Action_Bean;
Name : in String) return Util.Beans.Objects.Object;
-- Set the value identified by the name.
-- If the name cannot be found, the method should raise the No_Value
-- exception.
overriding
procedure Set_Value (From : in out Action_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object);
overriding
function Get_Method_Bindings (From : in Action_Bean)
return Util.Beans.Methods.Method_Binding_Array_Access;
procedure Event_Action (From : in out Action_Bean;
Event : in AWA.Events.Module_Event'Class);
function Create_Action_Bean return Util.Beans.Basic.Readonly_Bean_Access;
package Event_Action_Binding is
new AWA.Events.Action_Method.Bind (Bean => Action_Bean,
Method => Event_Action,
Name => "send");
Binding_Array : aliased constant Util.Beans.Methods.Method_Binding_Array
:= (1 => Event_Action_Binding.Proxy'Access);
-- ------------------------------
-- 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 Action_Bean;
Name : in String) return Util.Beans.Objects.Object is
pragma Unreferenced (From, Name);
begin
return Util.Beans.Objects.Null_Object;
end Get_Value;
-- ------------------------------
-- Set the value identified by the name.
-- If the name cannot be found, the method should raise the No_Value
-- exception.
-- ------------------------------
overriding
procedure Set_Value (From : in out Action_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object) is
begin
if Name = "priority" then
From.Priority := Util.Beans.Objects.To_Integer (Value);
elsif Name = "raise_exception" then
From.Raise_Exception := Util.Beans.Objects.To_Boolean (Value);
end if;
end Set_Value;
overriding
function Get_Method_Bindings (From : in Action_Bean)
return Util.Beans.Methods.Method_Binding_Array_Access is
pragma Unreferenced (From);
begin
return Binding_Array'Access;
end Get_Method_Bindings;
Action_Exception : exception;
Global_Counter : Util.Concurrent.Counters.Counter;
procedure Event_Action (From : in out Action_Bean;
Event : in AWA.Events.Module_Event'Class) is
pragma Unreferenced (Event);
begin
if From.Raise_Exception then
raise Action_Exception with "Raising an exception from the event action bean";
end if;
From.Count := From.Count + 1;
Util.Concurrent.Counters.Increment (Global_Counter);
end Event_Action;
function Create_Action_Bean return Util.Beans.Basic.Readonly_Bean_Access is
Result : constant Action_Bean_Access := new Action_Bean;
begin
return Result.all'Access;
end Create_Action_Bean;
-- ------------------------------
-- Test searching an event name in the definition list.
-- ------------------------------
procedure Test_Find_Event (T : in out Test) is
begin
Util.Tests.Assert_Equals (T, Integer (Event_Test_4.Kind),
Integer (Find_Event_Index ("event-test-4")), "Find_Event");
Util.Tests.Assert_Equals (T, Integer (Event_Test_5.Kind),
Integer (Find_Event_Index ("event-test-5")), "Find_Event");
Util.Tests.Assert_Equals (T, Integer (Event_Test_1.Kind),
Integer (Find_Event_Index ("event-test-1")), "Find_Event");
end Test_Find_Event;
-- ------------------------------
-- Test the Get_Event_Type_Name internal operation.
-- ------------------------------
procedure Test_Get_Event_Name (T : in out Test) is
begin
Util.Tests.Assert_Equals (T, "event-test-1", Get_Event_Type_Name (Event_Test_1.Kind).all,
"Get_Event_Type_Name");
Util.Tests.Assert_Equals (T, "event-test-2", Get_Event_Type_Name (Event_Test_2.Kind).all,
"Get_Event_Type_Name");
Util.Tests.Assert_Equals (T, "event-test-3", Get_Event_Type_Name (Event_Test_3.Kind).all,
"Get_Event_Type_Name");
Util.Tests.Assert_Equals (T, "event-test-4", Get_Event_Type_Name (Event_Test_4.Kind).all,
"Get_Event_Type_Name");
Util.Tests.Assert_Equals (T, "event-test-5", Get_Event_Type_Name (Event_Test_5.Kind).all,
"Get_Event_Type_Name");
end Test_Get_Event_Name;
-- ------------------------------
-- Test creation and initialization of event manager.
-- ------------------------------
procedure Test_Initialize (T : in out Test) is
App : constant AWA.Applications.Application_Access := AWA.Tests.Get_Application;
Manager : Event_Manager;
begin
Manager.Initialize (App.all'Access);
T.Assert (Manager.Actions /= null, "Initialization failed");
end Test_Initialize;
-- ------------------------------
-- Test adding an action.
-- ------------------------------
procedure Test_Add_Action (T : in out Test) is
App : constant AWA.Applications.Application_Access := AWA.Tests.Get_Application;
Manager : Event_Manager;
Ctx : EL.Contexts.Default.Default_Context;
Action : constant EL.Expressions.Method_Expression
:= EL.Expressions.Create_Expression ("#{a.send}", Ctx);
Props : EL.Beans.Param_Vectors.Vector;
Queue : Queue_Ref;
Index : constant Event_Index := Find_Event_Index ("event-test-4");
begin
Manager.Initialize (App.all'Access);
Queue := AWA.Events.Queues.Create_Queue ("test", "fifo", Props, Ctx);
Manager.Add_Queue (Queue);
for I in 1 .. 10 loop
Manager.Add_Action (Event => "event-test-4",
Queue => Queue,
Action => Action,
Params => Props);
Util.Tests.Assert_Equals (T, 1, Integer (Manager.Actions (Index).Queues.Length),
"Add_Action failed");
end loop;
end Test_Add_Action;
-- ------------------------------
-- Test dispatching events
-- ------------------------------
procedure Dispatch_Event (T : in out Test;
Kind : in Event_Index;
Expect_Count : in Natural;
Expect_Prio : in Natural) is
Factory : AWA.Applications.Factory.Application_Factory;
Conf : ASF.Applications.Config;
Ctx : aliased EL.Contexts.Default.Default_Context;
Path : constant String := Util.Tests.Get_Test_Path ("regtests/config/event-test.xml");
Action : aliased Action_Bean;
begin
Conf.Set ("database", Util.Tests.Get_Parameter ("database"));
declare
App : aliased AWA.Tests.Test_Application;
S : Util.Measures.Stamp;
Faces : aliased ASF.Servlets.Faces.Faces_Servlet;
SC : AWA.Services.Contexts.Service_Context;
begin
App.Initialize (Conf => Conf,
Factory => Factory);
App.Set_Global ("event_test",
Util.Beans.Objects.To_Object (Action'Unchecked_Access,
Util.Beans.Objects.STATIC));
SC.Set_Context (App'Unchecked_Access, null);
App.Add_Servlet (Name => "faces", Server => Faces'Unchecked_Access);
App.Register_Class ("AWA.Events.Tests.Event_Action",
Create_Action_Bean'Access);
AWA.Applications.Configs.Read_Configuration (App => App,
File => Path,
Context => Ctx'Unchecked_Access);
Util.Measures.Report (S, "Initialize AWA application and read config");
App.Start;
Util.Measures.Report (S, "Start event tasks");
for I in 1 .. 100 loop
declare
Event : Module_Event;
begin
Event.Set_Event_Kind (Kind);
Event.Set_Parameter ("prio", "3");
Event.Set_Parameter ("template", "def");
App.Send_Event (Event);
end;
end loop;
Util.Measures.Report (S, "Send 100 events");
-- Wait for the dispatcher to process the events but do not wait more than 10 secs.
for I in 1 .. 10_000 loop
exit when Action.Count = Expect_Count;
delay 0.1;
end loop;
end;
Log.Info ("Action count: {0}", Natural'Image (Action.Count));
Log.Info ("Priority: {0}", Integer'Image (Action.Priority));
Util.Tests.Assert_Equals (T, Expect_Count, Action.Count,
"invalid number of calls for the action (global bean)");
Util.Tests.Assert_Equals (T, Expect_Prio, Action.Priority,
"prio parameter not transmitted (global bean)");
end Dispatch_Event;
-- ------------------------------
-- Test dispatching synchronous event to a global bean.
-- ------------------------------
procedure Test_Dispatch_Synchronous (T : in out Test) is
begin
T.Dispatch_Event (Event_Test_1.Kind, 500, 3);
end Test_Dispatch_Synchronous;
-- ------------------------------
-- Test dispatching event through a fifo queue.
-- ------------------------------
procedure Test_Dispatch_Fifo (T : in out Test) is
begin
T.Dispatch_Event (Event_Test_2.Kind, 200, 3);
end Test_Dispatch_Fifo;
-- ------------------------------
-- Test dispatching event through a database queue.
-- ------------------------------
procedure Test_Dispatch_Persist (T : in out Test) is
begin
T.Dispatch_Event (Event_Test_5.Kind, 100, 3);
end Test_Dispatch_Persist;
-- ------------------------------
-- Test dispatching synchronous event to a dynamic bean (created on demand).
-- ------------------------------
procedure Test_Dispatch_Synchronous_Dyn (T : in out Test) is
begin
T.Dispatch_Event (Event_Test_3.Kind, 0, 0);
end Test_Dispatch_Synchronous_Dyn;
-- ------------------------------
-- Test dispatching synchronous event to a dynamic bean and raise an exception in the action.
-- ------------------------------
procedure Test_Dispatch_Synchronous_Raise (T : in out Test) is
begin
T.Dispatch_Event (Event_Test_4.Kind, 0, 0);
end Test_Dispatch_Synchronous_Raise;
end AWA.Events.Services.Tests;
|
-----------------------------------------------------------------------
-- events-tests -- Unit tests for AWA events
-- 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 Util.Test_Caller;
with Util.Beans.Methods;
with Util.Log.Loggers;
with Util.Measures;
with Util.Concurrent.Counters;
with EL.Beans;
with EL.Expressions;
with EL.Contexts.Default;
with ASF.Applications;
with ASF.Servlets.Faces;
with AWA.Applications;
with AWA.Applications.Configs;
with AWA.Applications.Factory;
with AWA.Events.Action_Method;
with AWA.Services.Contexts;
with AWA.Events.Queues;
with AWA.Events.Services;
package body AWA.Events.Services.Tests is
use AWA.Events.Services;
use Util.Log;
Log : constant Loggers.Logger := Loggers.Create ("AWA.Events.Tests");
package Event_Test_4 is new AWA.Events.Definition (Name => "event-test-4");
package Event_Test_1 is new AWA.Events.Definition (Name => "event-test-1");
package Event_Test_3 is new AWA.Events.Definition (Name => "event-test-3");
package Event_Test_2 is new AWA.Events.Definition (Name => "event-test-2");
package Event_Test_5 is new AWA.Events.Definition (Name => "event-test-5");
package Caller is new Util.Test_Caller (Test, "Events.Tests");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test AWA.Events.Get_Event_Name",
Test_Get_Event_Name'Access);
Caller.Add_Test (Suite, "Test AWA.Events.Find_Event_Index",
Test_Find_Event'Access);
Caller.Add_Test (Suite, "Test AWA.Events.Initialize",
Test_Initialize'Access);
Caller.Add_Test (Suite, "Test AWA.Events.Add_Action",
Test_Add_Action'Access);
Caller.Add_Test (Suite, "Test AWA.Events.Dispatch_Synchronous",
Test_Dispatch_Synchronous'Access);
Caller.Add_Test (Suite, "Test AWA.Events.Dispatch_Fifo",
Test_Dispatch_Fifo'Access);
Caller.Add_Test (Suite, "Test AWA.Events.Dispatch_Persist",
Test_Dispatch_Persist'Access);
Caller.Add_Test (Suite, "Test AWA.Events.Dispatch_Synchronous_Dyn",
Test_Dispatch_Synchronous_Dyn'Access);
Caller.Add_Test (Suite, "Test AWA.Events.Dispatch_Synchronous_Raise",
Test_Dispatch_Synchronous_Raise'Access);
end Add_Tests;
type Action_Bean is new Util.Beans.Basic.Bean
and Util.Beans.Methods.Method_Bean with record
Count : Natural := 0;
Priority : Integer := 0;
Raise_Exception : Boolean := False;
end record;
type Action_Bean_Access is access all Action_Bean'Class;
-- Get the value identified by the name.
-- If the name cannot be found, the method should return the Null object.
overriding
function Get_Value (From : in Action_Bean;
Name : in String) return Util.Beans.Objects.Object;
-- Set the value identified by the name.
-- If the name cannot be found, the method should raise the No_Value
-- exception.
overriding
procedure Set_Value (From : in out Action_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object);
overriding
function Get_Method_Bindings (From : in Action_Bean)
return Util.Beans.Methods.Method_Binding_Array_Access;
procedure Event_Action (From : in out Action_Bean;
Event : in AWA.Events.Module_Event'Class);
function Create_Action_Bean return Util.Beans.Basic.Readonly_Bean_Access;
package Event_Action_Binding is
new AWA.Events.Action_Method.Bind (Bean => Action_Bean,
Method => Event_Action,
Name => "send");
Binding_Array : aliased constant Util.Beans.Methods.Method_Binding_Array
:= (1 => Event_Action_Binding.Proxy'Access);
-- ------------------------------
-- 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 Action_Bean;
Name : in String) return Util.Beans.Objects.Object is
pragma Unreferenced (From, Name);
begin
return Util.Beans.Objects.Null_Object;
end Get_Value;
-- ------------------------------
-- Set the value identified by the name.
-- If the name cannot be found, the method should raise the No_Value
-- exception.
-- ------------------------------
overriding
procedure Set_Value (From : in out Action_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object) is
begin
if Name = "priority" then
From.Priority := Util.Beans.Objects.To_Integer (Value);
elsif Name = "raise_exception" then
From.Raise_Exception := Util.Beans.Objects.To_Boolean (Value);
end if;
end Set_Value;
overriding
function Get_Method_Bindings (From : in Action_Bean)
return Util.Beans.Methods.Method_Binding_Array_Access is
pragma Unreferenced (From);
begin
return Binding_Array'Access;
end Get_Method_Bindings;
Action_Exception : exception;
Global_Counter : Util.Concurrent.Counters.Counter;
procedure Event_Action (From : in out Action_Bean;
Event : in AWA.Events.Module_Event'Class) is
pragma Unreferenced (Event);
begin
if From.Raise_Exception then
raise Action_Exception with "Raising an exception from the event action bean";
end if;
From.Count := From.Count + 1;
Util.Concurrent.Counters.Increment (Global_Counter);
end Event_Action;
function Create_Action_Bean return Util.Beans.Basic.Readonly_Bean_Access is
Result : constant Action_Bean_Access := new Action_Bean;
begin
return Result.all'Access;
end Create_Action_Bean;
-- ------------------------------
-- Test searching an event name in the definition list.
-- ------------------------------
procedure Test_Find_Event (T : in out Test) is
begin
Util.Tests.Assert_Equals (T, Integer (Event_Test_4.Kind),
Integer (Find_Event_Index ("event-test-4")), "Find_Event");
Util.Tests.Assert_Equals (T, Integer (Event_Test_5.Kind),
Integer (Find_Event_Index ("event-test-5")), "Find_Event");
Util.Tests.Assert_Equals (T, Integer (Event_Test_1.Kind),
Integer (Find_Event_Index ("event-test-1")), "Find_Event");
end Test_Find_Event;
-- ------------------------------
-- Test the Get_Event_Type_Name internal operation.
-- ------------------------------
procedure Test_Get_Event_Name (T : in out Test) is
begin
Util.Tests.Assert_Equals (T, "event-test-1", Get_Event_Type_Name (Event_Test_1.Kind).all,
"Get_Event_Type_Name");
Util.Tests.Assert_Equals (T, "event-test-2", Get_Event_Type_Name (Event_Test_2.Kind).all,
"Get_Event_Type_Name");
Util.Tests.Assert_Equals (T, "event-test-3", Get_Event_Type_Name (Event_Test_3.Kind).all,
"Get_Event_Type_Name");
Util.Tests.Assert_Equals (T, "event-test-4", Get_Event_Type_Name (Event_Test_4.Kind).all,
"Get_Event_Type_Name");
Util.Tests.Assert_Equals (T, "event-test-5", Get_Event_Type_Name (Event_Test_5.Kind).all,
"Get_Event_Type_Name");
end Test_Get_Event_Name;
-- ------------------------------
-- Test creation and initialization of event manager.
-- ------------------------------
procedure Test_Initialize (T : in out Test) is
App : constant AWA.Applications.Application_Access := AWA.Tests.Get_Application;
Manager : Event_Manager;
begin
Manager.Initialize (App.all'Access);
T.Assert (Manager.Actions /= null, "Initialization failed");
end Test_Initialize;
-- ------------------------------
-- Test adding an action.
-- ------------------------------
procedure Test_Add_Action (T : in out Test) is
App : constant AWA.Applications.Application_Access := AWA.Tests.Get_Application;
Manager : Event_Manager;
Ctx : EL.Contexts.Default.Default_Context;
Action : constant EL.Expressions.Method_Expression
:= EL.Expressions.Create_Expression ("#{a.send}", Ctx);
Props : EL.Beans.Param_Vectors.Vector;
Queue : Queue_Ref;
Index : constant Event_Index := Find_Event_Index ("event-test-4");
begin
Manager.Initialize (App.all'Access);
Queue := AWA.Events.Queues.Create_Queue ("test", "fifo", Props, Ctx);
Manager.Add_Queue (Queue);
for I in 1 .. 10 loop
Manager.Add_Action (Event => "event-test-4",
Queue => Queue,
Action => Action,
Params => Props);
Util.Tests.Assert_Equals (T, 1, Integer (Manager.Actions (Index).Queues.Length),
"Add_Action failed");
end loop;
end Test_Add_Action;
-- ------------------------------
-- Test dispatching events
-- ------------------------------
procedure Dispatch_Event (T : in out Test;
Kind : in Event_Index;
Expect_Count : in Natural;
Expect_Prio : in Natural) is
Factory : AWA.Applications.Factory.Application_Factory;
Conf : ASF.Applications.Config;
Ctx : aliased EL.Contexts.Default.Default_Context;
Path : constant String := Util.Tests.Get_Test_Path ("regtests/config/event-test.xml");
Action : aliased Action_Bean;
begin
Conf.Set ("database", Util.Tests.Get_Parameter ("database"));
declare
App : aliased AWA.Tests.Test_Application;
S : Util.Measures.Stamp;
Faces : aliased ASF.Servlets.Faces.Faces_Servlet;
SC : AWA.Services.Contexts.Service_Context;
begin
App.Initialize (Conf => Conf,
Factory => Factory);
App.Set_Global ("event_test",
Util.Beans.Objects.To_Object (Action'Unchecked_Access,
Util.Beans.Objects.STATIC));
SC.Set_Context (App'Unchecked_Access, null);
App.Add_Servlet (Name => "faces", Server => Faces'Unchecked_Access);
App.Register_Class ("AWA.Events.Tests.Event_Action",
Create_Action_Bean'Access);
AWA.Applications.Configs.Read_Configuration (App => App,
File => Path,
Context => Ctx'Unchecked_Access,
Override_Context => True);
Util.Measures.Report (S, "Initialize AWA application and read config");
App.Start;
Util.Measures.Report (S, "Start event tasks");
for I in 1 .. 100 loop
declare
Event : Module_Event;
begin
Event.Set_Event_Kind (Kind);
Event.Set_Parameter ("prio", "3");
Event.Set_Parameter ("template", "def");
App.Send_Event (Event);
end;
end loop;
Util.Measures.Report (S, "Send 100 events");
-- Wait for the dispatcher to process the events but do not wait more than 10 secs.
for I in 1 .. 10_000 loop
exit when Action.Count = Expect_Count;
delay 0.1;
end loop;
end;
Log.Info ("Action count: {0}", Natural'Image (Action.Count));
Log.Info ("Priority: {0}", Integer'Image (Action.Priority));
Util.Tests.Assert_Equals (T, Expect_Count, Action.Count,
"invalid number of calls for the action (global bean)");
Util.Tests.Assert_Equals (T, Expect_Prio, Action.Priority,
"prio parameter not transmitted (global bean)");
end Dispatch_Event;
-- ------------------------------
-- Test dispatching synchronous event to a global bean.
-- ------------------------------
procedure Test_Dispatch_Synchronous (T : in out Test) is
begin
T.Dispatch_Event (Event_Test_1.Kind, 500, 3);
end Test_Dispatch_Synchronous;
-- ------------------------------
-- Test dispatching event through a fifo queue.
-- ------------------------------
procedure Test_Dispatch_Fifo (T : in out Test) is
begin
T.Dispatch_Event (Event_Test_2.Kind, 200, 3);
end Test_Dispatch_Fifo;
-- ------------------------------
-- Test dispatching event through a database queue.
-- ------------------------------
procedure Test_Dispatch_Persist (T : in out Test) is
begin
T.Dispatch_Event (Event_Test_5.Kind, 100, 3);
end Test_Dispatch_Persist;
-- ------------------------------
-- Test dispatching synchronous event to a dynamic bean (created on demand).
-- ------------------------------
procedure Test_Dispatch_Synchronous_Dyn (T : in out Test) is
begin
T.Dispatch_Event (Event_Test_3.Kind, 0, 0);
end Test_Dispatch_Synchronous_Dyn;
-- ------------------------------
-- Test dispatching synchronous event to a dynamic bean and raise an exception in the action.
-- ------------------------------
procedure Test_Dispatch_Synchronous_Raise (T : in out Test) is
begin
T.Dispatch_Event (Event_Test_4.Kind, 0, 0);
end Test_Dispatch_Synchronous_Raise;
end AWA.Events.Services.Tests;
|
Update the test after changes in the Load_Configuration procedure
|
Update the test after changes in the Load_Configuration procedure
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
b43017d441cb8f6ac5dab4ae0386abc318f283be
|
src/wiki-render-text.ads
|
src/wiki-render-text.ads
|
-----------------------------------------------------------------------
-- wiki-render-text -- Wiki Text renderer
-- Copyright (C) 2011, 2012, 2013, 2015, 2016 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Wiki.Attributes;
with Wiki.Documents;
with Wiki.Streams;
-- == Text Renderer ==
-- The <tt>Text_Renderer</tt> allows to render a wiki document into a text content.
-- The formatting rules are ignored except for the paragraphs and sections.
package Wiki.Render.Text is
-- ------------------------------
-- Wiki to Text renderer
-- ------------------------------
type Text_Renderer is new Wiki.Render.Renderer with private;
-- Set the output stream.
procedure Set_Output_Stream (Engine : in out Text_Renderer;
Stream : in Streams.Output_Stream_Access);
-- Render the node instance from the document.
overriding
procedure Render (Engine : in out Text_Renderer;
Doc : in Wiki.Nodes.Document;
Node : in Wiki.Nodes.Node_Type);
-- Add a line break (<br>).
procedure Add_Line_Break (Document : in out Text_Renderer);
-- Add a blockquote (<blockquote>). The level indicates the blockquote nested level.
-- The blockquote must be closed at the next header.
procedure Add_Blockquote (Document : in out Text_Renderer;
Level : in Natural);
-- Add a list item (<li>). Close the previous paragraph and list item if any.
-- The list item will be closed at the next list item, next paragraph or next header.
procedure Add_List_Item (Document : in out Text_Renderer;
Level : in Positive;
Ordered : in Boolean);
-- Add a link.
procedure Add_Link (Document : in out Text_Renderer;
Name : in Unbounded_Wide_Wide_String;
Link : in Unbounded_Wide_Wide_String;
Language : in Unbounded_Wide_Wide_String;
Title : in Unbounded_Wide_Wide_String);
-- Add an image.
procedure Add_Image (Document : in out Text_Renderer;
Link : in Unbounded_Wide_Wide_String;
Alt : in Unbounded_Wide_Wide_String;
Position : in Unbounded_Wide_Wide_String;
Description : in Unbounded_Wide_Wide_String);
-- Add a quote.
procedure Add_Quote (Document : in out Text_Renderer;
Quote : in Unbounded_Wide_Wide_String;
Link : in Unbounded_Wide_Wide_String;
Language : in Unbounded_Wide_Wide_String);
-- Add a text block that is pre-formatted.
procedure Add_Preformatted (Document : in out Text_Renderer;
Text : in Unbounded_Wide_Wide_String;
Format : in Unbounded_Wide_Wide_String);
procedure Start_Element (Document : in out Text_Renderer;
Name : in Unbounded_Wide_Wide_String;
Attributes : in Wiki.Attributes.Attribute_List_Type);
procedure End_Element (Document : in out Text_Renderer;
Name : in Unbounded_Wide_Wide_String);
-- Finish the document after complete wiki text has been parsed.
overriding
procedure Finish (Document : in out Text_Renderer);
private
-- Emit a new line.
procedure New_Line (Document : in out Text_Renderer);
procedure Close_Paragraph (Document : in out Text_Renderer);
procedure Open_Paragraph (Document : in out Text_Renderer);
type Text_Renderer is new Wiki.Render.Renderer with record
Output : Streams.Output_Stream_Access := null;
Format : Wiki.Documents.Format_Map := (others => False);
Has_Paragraph : Boolean := False;
Need_Paragraph : Boolean := False;
Empty_Line : Boolean := True;
Indent_Level : Natural := 0;
end record;
end Wiki.Render.Text;
|
-----------------------------------------------------------------------
-- wiki-render-text -- Wiki Text renderer
-- Copyright (C) 2011, 2012, 2013, 2015, 2016 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Wiki.Attributes;
with Wiki.Documents;
with Wiki.Streams;
-- == Text Renderer ==
-- The <tt>Text_Renderer</tt> allows to render a wiki document into a text content.
-- The formatting rules are ignored except for the paragraphs and sections.
package Wiki.Render.Text is
-- ------------------------------
-- Wiki to Text renderer
-- ------------------------------
type Text_Renderer is new Wiki.Render.Renderer with private;
-- Set the output stream.
procedure Set_Output_Stream (Engine : in out Text_Renderer;
Stream : in Streams.Output_Stream_Access);
-- Render the node instance from the document.
overriding
procedure Render (Engine : in out Text_Renderer;
Doc : in Wiki.Nodes.Document;
Node : in Wiki.Nodes.Node_Type);
-- Add a line break (<br>).
procedure Add_Line_Break (Document : in out Text_Renderer);
-- Add a blockquote (<blockquote>). The level indicates the blockquote nested level.
-- The blockquote must be closed at the next header.
procedure Add_Blockquote (Document : in out Text_Renderer;
Level : in Natural);
-- Add a list item (<li>). Close the previous paragraph and list item if any.
-- The list item will be closed at the next list item, next paragraph or next header.
procedure Add_List_Item (Document : in out Text_Renderer;
Level : in Positive;
Ordered : in Boolean);
-- Add a link.
procedure Add_Link (Document : in out Text_Renderer;
Name : in Unbounded_Wide_Wide_String;
Link : in Unbounded_Wide_Wide_String;
Language : in Unbounded_Wide_Wide_String;
Title : in Unbounded_Wide_Wide_String);
-- Add an image.
procedure Add_Image (Document : in out Text_Renderer;
Link : in Unbounded_Wide_Wide_String;
Alt : in Unbounded_Wide_Wide_String;
Position : in Unbounded_Wide_Wide_String;
Description : in Unbounded_Wide_Wide_String);
-- Add a quote.
procedure Add_Quote (Document : in out Text_Renderer;
Quote : in Unbounded_Wide_Wide_String;
Link : in Unbounded_Wide_Wide_String;
Language : in Unbounded_Wide_Wide_String);
-- Add a text block that is pre-formatted.
procedure Add_Preformatted (Document : in out Text_Renderer;
Text : in Unbounded_Wide_Wide_String;
Format : in Unbounded_Wide_Wide_String);
-- Finish the document after complete wiki text has been parsed.
overriding
procedure Finish (Document : in out Text_Renderer);
private
-- Emit a new line.
procedure New_Line (Document : in out Text_Renderer);
procedure Close_Paragraph (Document : in out Text_Renderer);
procedure Open_Paragraph (Document : in out Text_Renderer);
type Text_Renderer is new Wiki.Render.Renderer with record
Output : Streams.Output_Stream_Access := null;
Format : Wiki.Documents.Format_Map := (others => False);
Has_Paragraph : Boolean := False;
Need_Paragraph : Boolean := False;
Empty_Line : Boolean := True;
Indent_Level : Natural := 0;
end record;
end Wiki.Render.Text;
|
Remove the Start_Element and End_Element operations
|
Remove the Start_Element and End_Element operations
|
Ada
|
apache-2.0
|
stcarrez/ada-wiki,stcarrez/ada-wiki
|
bc6eab9ca99a390a037541248e8f2a0034ac29c5
|
src/wiki-render-wiki.ads
|
src/wiki-render-wiki.ads
|
-----------------------------------------------------------------------
-- wiki-render-wiki -- Wiki to 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 Ada.Strings.Wide_Wide_Maps;
with Wiki.Documents;
with Wiki.Attributes;
with Wiki.Streams;
with Wiki.Parsers;
-- == Wiki Renderer ==
-- The <tt>Wiki_Renderer</tt> allows to render a wiki document into another wiki content.
-- The formatting rules are ignored except for the paragraphs and sections.
package Wiki.Render.Wiki is
use Standard.Wiki.Attributes;
-- ------------------------------
-- Wiki to HTML writer
-- ------------------------------
type Wiki_Renderer is new Renderer with private;
-- Set the output stream.
procedure Set_Output_Stream (Engine : in out Wiki_Renderer;
Stream : in Streams.Output_Stream_Access;
Format : in Parsers.Wiki_Syntax_Type);
-- Render the node instance from the document.
overriding
procedure Render (Engine : in out Wiki_Renderer;
Doc : in Nodes.Document;
Node : in Nodes.Node_Type);
-- Add a section header in the document.
procedure Render_Header (Engine : in out Wiki_Renderer;
Header : in Wide_Wide_String;
Level : in Positive);
-- Add a paragraph (<p>). Close the previous paragraph if any.
-- The paragraph must be closed at the next paragraph or next header.
procedure Add_Paragraph (Engine : in out Wiki_Renderer);
-- 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 Wiki_Renderer;
Level : in Natural);
-- Add a list item (<li>). Close the previous paragraph and list item if any.
-- The list item will be closed at the next list item, next paragraph or next header.
procedure Add_List_Item (Engine : in out Wiki_Renderer;
Level : in Positive;
Ordered : in Boolean);
-- Render a link.
procedure Render_Link (Engine : in out Wiki_Renderer;
Name : in WString;
Attrs : in Attributes.Attribute_List_Type);
-- Render an image.
procedure Render_Image (Engine : in out Wiki_Renderer;
Link : in WString;
Attrs : in Attributes.Attribute_List_Type);
-- Render a quote.
procedure Render_Quote (Engine : in out Wiki_Renderer;
Title : in WString;
Attrs : in Attributes.Attribute_List_Type);
-- Add a text block with the given format.
procedure Render_Text (Engine : in out Wiki_Renderer;
Text : in Wide_Wide_String;
Format : in Format_Map);
-- Add a text block that is pre-formatted.
procedure Add_Preformatted (Engine : in out Wiki_Renderer;
Text : in Unbounded_Wide_Wide_String;
Format : in Unbounded_Wide_Wide_String);
procedure Render_Tag (Engine : in out Wiki_Renderer;
Doc : in Nodes.Document;
Node : in Nodes.Node_Type);
-- Finish the document after complete wiki text has been parsed.
procedure Finish (Engine : in out Wiki_Renderer);
-- Set the text style format.
procedure Set_Format (Engine : in out Wiki_Renderer;
Format : in Format_Map);
private
type Wide_String_Access is access constant Wide_Wide_String;
type Wiki_Tag_Type is (Header_Start, Header_End,
Img_Start, Img_End,
Link_Start, Link_End, Link_Separator,
Preformat_Start, Preformat_End,
List_Start, List_Item, List_Ordered_Item,
Line_Break, Escape_Rule,
Horizontal_Rule,
Blockquote_Start, Blockquote_End);
type Wiki_Tag_Array is array (Wiki_Tag_Type) of Wide_String_Access;
type Wiki_Format_Array is array (Format_Type) of Wide_String_Access;
-- Emit a new line.
procedure New_Line (Engine : in out Wiki_Renderer);
procedure Close_Paragraph (Engine : in out Wiki_Renderer);
procedure Open_Paragraph (Engine : in out Wiki_Renderer);
procedure Start_Keep_Content (Engine : in out Wiki_Renderer);
type List_Style_Array is array (1 .. 32) of Boolean;
EMPTY_TAG : aliased constant Wide_Wide_String := "";
type Wiki_Renderer is new Renderer with record
Output : Streams.Output_Stream_Access := null;
Syntax : Parsers.Wiki_Syntax_Type := Parsers.SYNTAX_CREOLE;
Format : Format_Map := (others => False);
Tags : Wiki_Tag_Array := (others => EMPTY_TAG'Access);
Style_Start_Tags : Wiki_Format_Array := (others => EMPTY_TAG'Access);
Style_End_Tags : Wiki_Format_Array := (others => EMPTY_TAG'Access);
Escape_Set : Ada.Strings.Wide_Wide_Maps.Wide_Wide_Character_Set;
Has_Paragraph : Boolean := False;
Has_Item : Boolean := False;
Need_Paragraph : Boolean := False;
Empty_Line : Boolean := True;
Keep_Content : Boolean := False;
In_List : Boolean := False;
Invert_Header_Level : Boolean := False;
Allow_Link_Language : Boolean := False;
Current_Level : Natural := 0;
Quote_Level : Natural := 0;
UL_List_Level : Natural := 0;
OL_List_Level : Natural := 0;
Current_Style : Format_Map := (others => False);
Content : Unbounded_Wide_Wide_String;
Link_Href : Unbounded_Wide_Wide_String;
Link_Title : Unbounded_Wide_Wide_String;
Link_Lang : Unbounded_Wide_Wide_String;
end record;
end Wiki.Render.Wiki;
|
-----------------------------------------------------------------------
-- wiki-render-wiki -- Wiki to 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 Ada.Strings.Wide_Wide_Maps;
with Wiki.Documents;
with Wiki.Attributes;
with Wiki.Streams;
with Wiki.Parsers;
with Wiki.Strings;
-- == Wiki Renderer ==
-- The <tt>Wiki_Renderer</tt> allows to render a wiki document into another wiki content.
-- The formatting rules are ignored except for the paragraphs and sections.
package Wiki.Render.Wiki is
use Standard.Wiki.Attributes;
-- ------------------------------
-- Wiki to HTML writer
-- ------------------------------
type Wiki_Renderer is new Renderer with private;
-- Set the output stream.
procedure Set_Output_Stream (Engine : in out Wiki_Renderer;
Stream : in Streams.Output_Stream_Access;
Format : in Parsers.Wiki_Syntax_Type);
-- Render the node instance from the document.
overriding
procedure Render (Engine : in out Wiki_Renderer;
Doc : in Nodes.Document;
Node : in Nodes.Node_Type);
-- Add a section header in the document.
procedure Render_Header (Engine : in out Wiki_Renderer;
Header : in Wide_Wide_String;
Level : in Positive);
-- Add a paragraph (<p>). Close the previous paragraph if any.
-- The paragraph must be closed at the next paragraph or next header.
procedure Add_Paragraph (Engine : in out Wiki_Renderer);
-- 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 Wiki_Renderer;
Level : in Natural);
-- Add a list item (<li>). Close the previous paragraph and list item if any.
-- The list item will be closed at the next list item, next paragraph or next header.
procedure Add_List_Item (Engine : in out Wiki_Renderer;
Level : in Positive;
Ordered : in Boolean);
-- Render a link.
procedure Render_Link (Engine : in out Wiki_Renderer;
Name : in Strings.WString;
Attrs : in Attributes.Attribute_List_Type);
-- Render an image.
procedure Render_Image (Engine : in out Wiki_Renderer;
Link : in Strings.WString;
Attrs : in Attributes.Attribute_List_Type);
-- Render a quote.
procedure Render_Quote (Engine : in out Wiki_Renderer;
Title : in Strings.WString;
Attrs : in Attributes.Attribute_List_Type);
-- Add a text block with the given format.
procedure Render_Text (Engine : in out Wiki_Renderer;
Text : in Wide_Wide_String;
Format : in Format_Map);
-- Add a text block that is pre-formatted.
procedure Add_Preformatted (Engine : in out Wiki_Renderer;
Text : in Unbounded_Wide_Wide_String;
Format : in Unbounded_Wide_Wide_String);
procedure Render_Tag (Engine : in out Wiki_Renderer;
Doc : in Nodes.Document;
Node : in Nodes.Node_Type);
-- Finish the document after complete wiki text has been parsed.
procedure Finish (Engine : in out Wiki_Renderer);
-- Set the text style format.
procedure Set_Format (Engine : in out Wiki_Renderer;
Format : in Format_Map);
private
type Wide_String_Access is access constant Wide_Wide_String;
type Wiki_Tag_Type is (Header_Start, Header_End,
Img_Start, Img_End,
Link_Start, Link_End, Link_Separator,
Preformat_Start, Preformat_End,
List_Start, List_Item, List_Ordered_Item,
Line_Break, Escape_Rule,
Horizontal_Rule,
Blockquote_Start, Blockquote_End);
type Wiki_Tag_Array is array (Wiki_Tag_Type) of Wide_String_Access;
type Wiki_Format_Array is array (Format_Type) of Wide_String_Access;
-- Emit a new line.
procedure New_Line (Engine : in out Wiki_Renderer);
procedure Close_Paragraph (Engine : in out Wiki_Renderer);
procedure Open_Paragraph (Engine : in out Wiki_Renderer);
procedure Start_Keep_Content (Engine : in out Wiki_Renderer);
type List_Style_Array is array (1 .. 32) of Boolean;
EMPTY_TAG : aliased constant Wide_Wide_String := "";
type Wiki_Renderer is new Renderer with record
Output : Streams.Output_Stream_Access := null;
Syntax : Parsers.Wiki_Syntax_Type := Parsers.SYNTAX_CREOLE;
Format : Format_Map := (others => False);
Tags : Wiki_Tag_Array := (others => EMPTY_TAG'Access);
Style_Start_Tags : Wiki_Format_Array := (others => EMPTY_TAG'Access);
Style_End_Tags : Wiki_Format_Array := (others => EMPTY_TAG'Access);
Escape_Set : Ada.Strings.Wide_Wide_Maps.Wide_Wide_Character_Set;
Has_Paragraph : Boolean := False;
Has_Item : Boolean := False;
Need_Paragraph : Boolean := False;
Empty_Line : Boolean := True;
Keep_Content : Boolean := False;
In_List : Boolean := False;
Invert_Header_Level : Boolean := False;
Allow_Link_Language : Boolean := False;
Current_Level : Natural := 0;
Quote_Level : Natural := 0;
UL_List_Level : Natural := 0;
OL_List_Level : Natural := 0;
Current_Style : Format_Map := (others => False);
Content : Unbounded_Wide_Wide_String;
Link_Href : Unbounded_Wide_Wide_String;
Link_Title : Unbounded_Wide_Wide_String;
Link_Lang : Unbounded_Wide_Wide_String;
end record;
end Wiki.Render.Wiki;
|
Use Wiki.Strings package
|
Use Wiki.Strings package
|
Ada
|
apache-2.0
|
stcarrez/ada-wiki,stcarrez/ada-wiki
|
09232c86fdfbccd44fe9f5952034f6f8cfb52ca6
|
src/wiki-render-html.ads
|
src/wiki-render-html.ads
|
-----------------------------------------------------------------------
-- wiki-render-html -- Wiki HTML renderer
-- Copyright (C) 2011, 2012, 2013, 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Wiki.Attributes;
with Wiki.Documents;
with Wiki.Writers;
-- == HTML Renderer ==
-- The <tt>Text_Renderer</tt> allows to render a wiki document into a text content.
-- The formatting rules are ignored except for the paragraphs and sections.
package Wiki.Render.Html is
-- ------------------------------
-- Wiki to HTML writer
-- ------------------------------
type Html_Renderer is new Wiki.Documents.Document_Reader with private;
-- Set the output writer.
procedure Set_Writer (Document : in out Html_Renderer;
Writer : in Wiki.Writers.Html_Writer_Type_Access);
-- Set the link renderer.
procedure Set_Link_Renderer (Document : in out Html_Renderer;
Links : in Link_Renderer_Access);
-- Add a section header in the document.
overriding
procedure Add_Header (Document : in out Html_Renderer;
Header : in Unbounded_Wide_Wide_String;
Level : in Positive);
-- Add a line break (<br>).
overriding
procedure Add_Line_Break (Document : in out Html_Renderer);
-- Add a paragraph (<p>). Close the previous paragraph if any.
-- The paragraph must be closed at the next paragraph or next header.
overriding
procedure Add_Paragraph (Document : in out Html_Renderer);
-- Add a blockquote (<blockquote>). The level indicates the blockquote nested level.
-- The blockquote must be closed at the next header.
overriding
procedure Add_Blockquote (Document : in out Html_Renderer;
Level : in Natural);
-- Add a list item (<li>). Close the previous paragraph and list item if any.
-- The list item will be closed at the next list item, next paragraph or next header.
overriding
procedure Add_List_Item (Document : in out Html_Renderer;
Level : in Positive;
Ordered : in Boolean);
-- Add an horizontal rule (<hr>).
overriding
procedure Add_Horizontal_Rule (Document : in out Html_Renderer);
-- Add a link.
overriding
procedure Add_Link (Document : in out Html_Renderer;
Name : in Unbounded_Wide_Wide_String;
Link : in Unbounded_Wide_Wide_String;
Language : in Unbounded_Wide_Wide_String;
Title : in Unbounded_Wide_Wide_String);
-- Add an image.
overriding
procedure Add_Image (Document : in out Html_Renderer;
Link : in Unbounded_Wide_Wide_String;
Alt : in Unbounded_Wide_Wide_String;
Position : in Unbounded_Wide_Wide_String;
Description : in Unbounded_Wide_Wide_String);
-- Add a quote.
overriding
procedure Add_Quote (Document : in out Html_Renderer;
Quote : in Unbounded_Wide_Wide_String;
Link : in Unbounded_Wide_Wide_String;
Language : in Unbounded_Wide_Wide_String);
-- Add a text block with the given format.
overriding
procedure Add_Text (Document : in out Html_Renderer;
Text : in Unbounded_Wide_Wide_String;
Format : in Wiki.Documents.Format_Map);
-- 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);
overriding
procedure Start_Element (Document : in out Html_Renderer;
Name : in Unbounded_Wide_Wide_String;
Attributes : in Wiki.Attributes.Attribute_List_Type);
overriding
procedure End_Element (Document : in out Html_Renderer;
Name : in Unbounded_Wide_Wide_String);
-- Finish the document after complete wiki text has been parsed.
overriding
procedure Finish (Document : in out Html_Renderer);
private
procedure Close_Paragraph (Document : in out Html_Renderer);
procedure Open_Paragraph (Document : in out Html_Renderer);
type List_Style_Array is array (1 .. 32) of Boolean;
Default_Links : aliased Default_Link_Renderer;
type Html_Renderer is new Wiki.Documents.Document_Reader with record
Writer : Wiki.Writers.Html_Writer_Type_Access := null;
Format : Wiki.Documents.Format_Map := (others => False);
Links : Link_Renderer_Access := Default_Links'Access;
Has_Paragraph : Boolean := False;
Need_Paragraph : Boolean := False;
Current_Level : Natural := 0;
List_Styles : List_Style_Array := (others => False);
Has_Item : Boolean := False;
Quote_Level : Natural := 0;
Html_Level : Natural := 0;
end record;
end Wiki.Render.Html;
|
-----------------------------------------------------------------------
-- wiki-render-html -- Wiki HTML renderer
-- Copyright (C) 2011, 2012, 2013, 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Wiki.Attributes;
with Wiki.Documents;
with Wiki.Writers;
-- == HTML Renderer ==
-- The <tt>Text_Renderer</tt> allows to render a wiki document into a text content.
-- The formatting rules are ignored except for the paragraphs and sections.
package Wiki.Render.Html is
-- ------------------------------
-- Wiki to HTML writer
-- ------------------------------
type Html_Renderer is new Wiki.Documents.Document_Reader with private;
-- Set the output writer.
procedure Set_Writer (Document : in out Html_Renderer;
Writer : in Wiki.Writers.Html_Writer_Type_Access);
-- Set the link renderer.
procedure Set_Link_Renderer (Document : in out Html_Renderer;
Links : in Link_Renderer_Access);
-- Add a section header in the document.
overriding
procedure Add_Header (Document : in out Html_Renderer;
Header : in Unbounded_Wide_Wide_String;
Level : in Positive);
-- Add a line break (<br>).
overriding
procedure Add_Line_Break (Document : in out Html_Renderer);
-- Add a paragraph (<p>). Close the previous paragraph if any.
-- The paragraph must be closed at the next paragraph or next header.
overriding
procedure Add_Paragraph (Document : in out Html_Renderer);
-- Add a blockquote (<blockquote>). The level indicates the blockquote nested level.
-- The blockquote must be closed at the next header.
overriding
procedure Add_Blockquote (Document : in out Html_Renderer;
Level : in Natural);
-- Add a list item (<li>). Close the previous paragraph and list item if any.
-- The list item will be closed at the next list item, next paragraph or next header.
overriding
procedure Add_List_Item (Document : in out Html_Renderer;
Level : in Positive;
Ordered : in Boolean);
-- Add an horizontal rule (<hr>).
overriding
procedure Add_Horizontal_Rule (Document : in out Html_Renderer);
-- Add a link.
overriding
procedure Add_Link (Document : in out Html_Renderer;
Name : in Unbounded_Wide_Wide_String;
Link : in Unbounded_Wide_Wide_String;
Language : in Unbounded_Wide_Wide_String;
Title : in Unbounded_Wide_Wide_String);
-- Add an image.
overriding
procedure Add_Image (Document : in out Html_Renderer;
Link : in Unbounded_Wide_Wide_String;
Alt : in Unbounded_Wide_Wide_String;
Position : in Unbounded_Wide_Wide_String;
Description : in Unbounded_Wide_Wide_String);
-- Add a quote.
overriding
procedure Add_Quote (Document : in out Html_Renderer;
Quote : in Unbounded_Wide_Wide_String;
Link : in Unbounded_Wide_Wide_String;
Language : in Unbounded_Wide_Wide_String);
-- Add a text block with the given format.
overriding
procedure Add_Text (Document : in out Html_Renderer;
Text : in Unbounded_Wide_Wide_String;
Format : in Wiki.Documents.Format_Map);
-- 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);
overriding
procedure Start_Element (Document : in out Html_Renderer;
Name : in Unbounded_Wide_Wide_String;
Attributes : in Wiki.Attributes.Attribute_List_Type);
overriding
procedure End_Element (Document : in out Html_Renderer;
Name : in Unbounded_Wide_Wide_String);
-- Finish the document after complete wiki text has been parsed.
overriding
procedure Finish (Document : in out Html_Renderer);
private
procedure Close_Paragraph (Document : in out Html_Renderer);
procedure Open_Paragraph (Document : in out Html_Renderer);
type List_Style_Array is array (1 .. 32) of Boolean;
Default_Links : aliased Default_Link_Renderer;
type Html_Renderer is new Wiki.Documents.Document_Reader with record
Writer : Wiki.Writers.Html_Writer_Type_Access := null;
Format : Wiki.Documents.Format_Map := (others => False);
Links : Link_Renderer_Access := Default_Links'Access;
Has_Paragraph : Boolean := False;
Need_Paragraph : Boolean := False;
Has_Item : Boolean := False;
Current_Level : Natural := 0;
List_Styles : List_Style_Array := (others => False);
Quote_Level : Natural := 0;
Html_Level : Natural := 0;
end record;
end Wiki.Render.Html;
|
Reorganize record definition layout
|
Reorganize record definition layout
|
Ada
|
apache-2.0
|
stcarrez/ada-wiki,stcarrez/ada-wiki
|
125ce0bc2cfa29e380cea5b2cbf23948a6a5bc18
|
mat/src/frames/mat-frames-targets.adb
|
mat/src/frames/mat-frames-targets.adb
|
-----------------------------------------------------------------------
-- mat-frames-targets - Representation of stack frames
-- Copyright (C) 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
package body MAT.Frames.Targets is
-- ------------------------------
-- Insert in the frame tree the new stack frame represented by <tt>Pc</tt>.
-- If the frame is already known, the frame reference counter is incremented.
-- The frame represented by <tt>Pc</tt> is returned in <tt>Result</tt>.
-- ------------------------------
procedure Insert (Frame : in out Target_Frames;
Pc : in Frame_Table;
Result : out Frame_Type) is
begin
Frame.Frames.Insert (Pc, Result);
end Insert;
-- ------------------------------
-- Get the number of different stack frames which have been registered.
-- ------------------------------
function Get_Frame_Count (Frame : in Target_Frames) return Natural is
begin
return Frame.Frames.Get_Frame_Count;
end Get_Frame_Count;
protected body Frames_Type is
-- ------------------------------
-- Get the number of different stack frames which have been registered.
-- ------------------------------
function Get_Frame_Count return Natural is
begin
return Root.Used;
end Get_Frame_Count;
-- ------------------------------
-- Insert in the frame tree the new stack frame represented by <tt>Pc</tt>.
-- If the frame is already known, the frame reference counter is incremented.
-- The frame represented by <tt>Pc</tt> is returned in <tt>Result</tt>.
-- ------------------------------
procedure Insert (Pc : in Frame_Table;
Result : out Frame_Type) is
begin
MAT.Frames.Insert (Root, Pc, Result);
end Insert;
-- ------------------------------
-- Clear and destroy all the frame instances.
-- ------------------------------
procedure Clear is
begin
Destroy (Root);
end Clear;
end Frames_Type;
-- ------------------------------
-- Release all the stack frames.
-- ------------------------------
overriding
procedure Finalize (Frames : in out Target_Frames) is
begin
Frames.Frames.Clear;
end Finalize;
end MAT.Frames.Targets;
|
-----------------------------------------------------------------------
-- mat-frames-targets - Representation of stack frames
-- Copyright (C) 2015, 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.
-----------------------------------------------------------------------
package body MAT.Frames.Targets is
-- ------------------------------
-- Insert in the frame tree the new stack frame represented by <tt>Pc</tt>.
-- If the frame is already known, the frame reference counter is incremented.
-- The frame represented by <tt>Pc</tt> is returned in <tt>Result</tt>.
-- ------------------------------
procedure Insert (Frame : in out Target_Frames;
Pc : in Frame_Table;
Result : out Frame_Type) is
begin
Frame.Frames.Insert (Pc, Result);
end Insert;
-- ------------------------------
-- Get the number of different stack frames which have been registered.
-- ------------------------------
function Get_Frame_Count (Frame : in Target_Frames) return Natural is
begin
return Frame.Frames.Get_Frame_Count;
end Get_Frame_Count;
protected body Frames_Type is
-- ------------------------------
-- Get the number of different stack frames which have been registered.
-- ------------------------------
function Get_Frame_Count return Natural is
begin
return Count_Children (Root, True);
end Get_Frame_Count;
-- ------------------------------
-- Insert in the frame tree the new stack frame represented by <tt>Pc</tt>.
-- If the frame is already known, the frame reference counter is incremented.
-- The frame represented by <tt>Pc</tt> is returned in <tt>Result</tt>.
-- ------------------------------
procedure Insert (Pc : in Frame_Table;
Result : out Frame_Type) is
begin
MAT.Frames.Insert (Root, Pc, Result);
end Insert;
-- ------------------------------
-- Clear and destroy all the frame instances.
-- ------------------------------
procedure Clear is
begin
Destroy (Root);
end Clear;
end Frames_Type;
-- ------------------------------
-- Release all the stack frames.
-- ------------------------------
overriding
procedure Finalize (Frames : in out Target_Frames) is
begin
Frames.Frames.Clear;
end Finalize;
end MAT.Frames.Targets;
|
Fix Get_Frame_Count to return the number of different stack frames
|
Fix Get_Frame_Count to return the number of different stack frames
|
Ada
|
apache-2.0
|
stcarrez/mat,stcarrez/mat,stcarrez/mat
|
a68020add454fd29e5f6da94517dd61accad00c5
|
awa/src/awa-events-queues-persistents.adb
|
awa/src/awa-events-queues-persistents.adb
|
-----------------------------------------------------------------------
-- awa-events-queues-persistents -- AWA Event Queues
-- 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.Calendar;
with Ada.Strings.Unbounded;
with Util.Log.Loggers;
with Util.Serialize.IO.XML;
with Util.Properties;
with Util.Streams.Texts;
with Util.Streams.Buffered;
with Util.Serialize.Tools;
with AWA.Services.Contexts;
with AWA.Users.Models;
with ADO;
with ADO.Queries;
with ADO.Sessions;
with ADO.SQL;
package body AWA.Events.Queues.Persistents is
use Util.Log;
Log : constant Loggers.Logger := Loggers.Create ("AWA.Events.Queues.Persistents");
-- ------------------------------
-- Get the queue name.
-- ------------------------------
overriding
function Get_Name (From : in Persistent_Queue) return String is
begin
return From.Name;
end Get_Name;
-- ------------------------------
-- Get the model queue reference object.
-- Returns a null object if the queue is not persistent.
-- ------------------------------
overriding
function Get_Queue (From : in Persistent_Queue) return AWA.Events.Models.Queue_Ref is
begin
return From.Queue;
end Get_Queue;
-- ------------------------------
-- Queue the event. The event is saved in the database with a relation to
-- the user, the user session, the event queue and the event type.
-- ------------------------------
overriding
procedure Enqueue (Into : in out Persistent_Queue;
Event : in AWA.Events.Module_Event'Class) is
use Ada.Strings.Unbounded;
use Util.Streams;
procedure Add_Property (Name, Value : in Util.Properties.Value);
Ctx : constant Services.Contexts.Service_Context_Access := AWA.Services.Contexts.Current;
DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx);
Msg : AWA.Events.Models.Message_Ref;
Has_Param : Boolean := False;
Output : Util.Serialize.IO.XML.Output_Stream;
procedure Add_Property (Name, Value : in Util.Properties.Value) is
begin
if not Has_Param then
Output.Initialize (Size => 10000);
Has_Param := True;
Output.Start_Entity (Name => "params");
end if;
Output.Start_Entity (Name => "param");
Output.Write_Attribute (Name => "name",
Value => Util.Beans.Objects.To_Object (Name));
Output.Write_String (Value => To_String (Value));
Output.End_Entity (Name => "param");
end Add_Property;
begin
Ctx.Start;
Msg.Set_Queue (Into.Queue);
Msg.Set_User (Ctx.Get_User);
Msg.Set_Session (Ctx.Get_User_Session);
Msg.Set_Create_Date (Event.Get_Time);
Msg.Set_Status (AWA.Events.Models.QUEUED);
-- Collect the event parameters in a string and format the result in XML.
-- If there is no parameter, avoid the overhead of allocating and formatting this.
Event.Props.Iterate (Process => Add_Property'Access);
if Has_Param then
Output.End_Entity (Name => "params");
Msg.Set_Parameters (Util.Streams.Texts.To_String (Buffered.Buffered_Stream (Output)));
end if;
-- Msg.Set_Message_Type
Msg.Save (DB);
Ctx.Commit;
Log.Info ("Event {0} created", ADO.Identifier'Image (Msg.Get_Id));
end Enqueue;
overriding
procedure Dequeue (From : in out Persistent_Queue;
Process : access procedure (Event : in Module_Event'Class)) is
package AC renames AWA.Services.Contexts;
-- Prepare the message by indicating in the database it is going to be processed
-- by the given server and task.
procedure Prepare_Message (Msg : in out Models.Message_Ref);
-- Dispatch the event.
procedure Dispatch_Message (Msg : in out Models.Message_Ref);
-- Finish processing the message by marking it as being processed.
procedure Finish_Message (Msg : in out Models.Message_Ref);
Ctx : constant AC.Service_Context_Access := AC.Current;
DB : ADO.Sessions.Master_Session := AC.Get_Master_Session (Ctx);
Messages : Models.Message_Vector;
Query : ADO.Queries.Context;
Task_Id : Integer := 0;
-- ------------------------------
-- Prepare the message by indicating in the database it is going to be processed
-- by the given server and task.
-- ------------------------------
procedure Prepare_Message (Msg : in out Models.Message_Ref) is
begin
Msg.Set_Status (Models.PROCESSING);
Msg.Set_Server_Id (From.Server_Id);
Msg.Set_Task_Id (Task_Id);
Msg.Set_Processing_Date (ADO.Nullable_Time '(Is_Null => False,
Value => Ada.Calendar.Clock));
Msg.Save (DB);
end Prepare_Message;
-- Dispatch the event.
procedure Dispatch_Message (Msg : in out Models.Message_Ref) is
User : constant AWA.Users.Models.User_Ref'Class := Msg.Get_User;
Session : constant AWA.Users.Models.Session_Ref'Class := Msg.Get_Session;
Event : Module_Event;
begin
Process (Event);
end Dispatch_Message;
-- ------------------------------
-- Finish processing the message by marking it as being processed.
-- ------------------------------
procedure Finish_Message (Msg : in out Models.Message_Ref) is
begin
Msg.Set_Status (Models.PROCESSED);
Msg.Set_Finish_Date (ADO.Nullable_Time '(Is_Null => False,
Value => Ada.Calendar.Clock));
Msg.Save (DB);
end Finish_Message;
Count : Natural;
begin
Ctx.Start;
Query.Set_Query (Models.Query_Queue_Pending_Message);
Query.Bind_Param ("queue", From.Queue.Get_Id);
Query.Bind_Param ("max", From.Max_Batch);
Models.List (Messages, DB, Query);
Count := Natural (Messages.Length);
-- Prepare the event messages by marking them in the database.
-- This makes sure that no other server or task (if any), will process them.
if Count > 0 then
for I in 0 .. Count - 1 loop
Messages.Update_Element (Index => I,
Process => Prepare_Message'Access);
end loop;
end if;
Ctx.Commit;
if Count = 0 then
return;
end if;
-- Dispatch each event.
for I in 0 .. Count - 1 loop
Messages.Update_Element (Index => I,
Process => Dispatch_Message'Access);
end loop;
-- After having dispatched the events, mark them as dispatched in the queue.
Ctx.Start;
for I in 0 .. Count - 1 loop
Messages.Update_Element (Index => I,
Process => Finish_Message'Access);
end loop;
Ctx.Commit;
end Dequeue;
-- ------------------------------
-- Create the queue associated with the given name and configure it by using
-- the configuration properties.
-- ------------------------------
function Create_Queue (Name : in String;
Props : in EL.Beans.Param_Vectors.Vector;
Context : in EL.Contexts.ELContext'Class) return Queue_Access is
package AC renames AWA.Services.Contexts;
Ctx : constant AC.Service_Context_Access := AC.Current;
Session : ADO.Sessions.Master_Session := AC.Get_Master_Session (Ctx);
Queue : AWA.Events.Models.Queue_Ref;
Query : ADO.SQL.Query;
Found : Boolean;
begin
Session.Begin_Transaction;
-- Find the queue instance which matches the name.
Query.Set_Filter ("o.name = ?");
Query.Add_Param (Name);
Queue.Find (Session => Session,
Query => Query,
Found => Found);
-- But create the queue instance if it does not exist.
if not Found then
Log.Info ("Creating database queue {0}", Name);
Queue.Set_Name (Name);
Queue.Save (Session);
else
Log.Info ("Using database queue {0}", Name);
end if;
Session.Commit;
declare
Result : constant Persistent_Queue_Access
:= new Persistent_Queue '(Name_Length => Name'Length,
Name => Name,
Queue => Queue,
others => <>);
begin
return Result.all'Access;
end;
end Create_Queue;
end AWA.Events.Queues.Persistents;
|
-----------------------------------------------------------------------
-- awa-events-queues-persistents -- AWA Event Queues
-- 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.Calendar;
with Ada.Strings.Unbounded;
with Util.Log.Loggers;
with Util.Serialize.Tools;
with AWA.Services.Contexts;
with AWA.Users.Models;
with AWA.Applications;
with AWA.Events.Services;
with ADO;
with ADO.Queries;
with ADO.Sessions;
with ADO.SQL;
package body AWA.Events.Queues.Persistents is
package AC renames AWA.Services.Contexts;
use Util.Log;
Log : constant Loggers.Logger := Loggers.Create ("AWA.Events.Queues.Persistents");
-- ------------------------------
-- Get the queue name.
-- ------------------------------
overriding
function Get_Name (From : in Persistent_Queue) return String is
begin
return From.Name;
end Get_Name;
-- ------------------------------
-- Get the model queue reference object.
-- Returns a null object if the queue is not persistent.
-- ------------------------------
overriding
function Get_Queue (From : in Persistent_Queue) return AWA.Events.Models.Queue_Ref is
begin
return From.Queue;
end Get_Queue;
-- ------------------------------
-- Queue the event. The event is saved in the database with a relation to
-- the user, the user session, the event queue and the event type.
-- ------------------------------
overriding
procedure Enqueue (Into : in out Persistent_Queue;
Event : in AWA.Events.Module_Event'Class) is
procedure Set_Event (Manager : in out AWA.Events.Services.Event_Manager);
Ctx : constant AC.Service_Context_Access := AC.Current;
App : constant AWA.Applications.Application_Access := Ctx.Get_Application;
DB : ADO.Sessions.Master_Session := AC.Get_Master_Session (Ctx);
Msg : AWA.Events.Models.Message_Ref;
procedure Set_Event (Manager : in out AWA.Events.Services.Event_Manager) is
begin
Manager.Set_Message_Type (Msg, Event.Get_Event_Kind);
end Set_Event;
begin
App.Do_Event_Manager (Set_Event'Access);
Ctx.Start;
Msg.Set_Queue (Into.Queue);
Msg.Set_User (Ctx.Get_User);
Msg.Set_Session (Ctx.Get_User_Session);
Msg.Set_Create_Date (Event.Get_Time);
Msg.Set_Status (AWA.Events.Models.QUEUED);
-- Collect the event parameters in a string and format the result in JSON.
Msg.Set_Parameters (Util.Serialize.Tools.To_JSON (Event.Props));
Msg.Save (DB);
Ctx.Commit;
Log.Info ("Event {0} created", ADO.Identifier'Image (Msg.Get_Id));
end Enqueue;
overriding
procedure Dequeue (From : in out Persistent_Queue;
Process : access procedure (Event : in Module_Event'Class)) is
-- Prepare the message by indicating in the database it is going to be processed
-- by the given server and task.
procedure Prepare_Message (Msg : in out Models.Message_Ref);
-- Dispatch the event.
procedure Dispatch_Message (Msg : in out Models.Message_Ref);
-- Finish processing the message by marking it as being processed.
procedure Finish_Message (Msg : in out Models.Message_Ref);
Ctx : constant AC.Service_Context_Access := AC.Current;
DB : ADO.Sessions.Master_Session := AC.Get_Master_Session (Ctx);
Messages : Models.Message_Vector;
Query : ADO.Queries.Context;
Task_Id : Integer := 0;
-- ------------------------------
-- Prepare the message by indicating in the database it is going to be processed
-- by the given server and task.
-- ------------------------------
procedure Prepare_Message (Msg : in out Models.Message_Ref) is
begin
Msg.Set_Status (Models.PROCESSING);
Msg.Set_Server_Id (From.Server_Id);
Msg.Set_Task_Id (Task_Id);
Msg.Set_Processing_Date (ADO.Nullable_Time '(Is_Null => False,
Value => Ada.Calendar.Clock));
Msg.Save (DB);
end Prepare_Message;
-- Dispatch the event.
procedure Dispatch_Message (Msg : in out Models.Message_Ref) is
User : constant AWA.Users.Models.User_Ref'Class := Msg.Get_User;
Session : constant AWA.Users.Models.Session_Ref'Class := Msg.Get_Session;
Event : Module_Event;
begin
Event.Set_Event_Kind (AWA.Events.Find_Event_Index (Msg.Get_Message_Type.Get_Name));
Util.Serialize.Tools.From_JSON (Msg.Get_Parameters, Event.Props);
Process (Event);
exception
when E : others =>
Log.Error ("Exception when processing event", E, True);
end Dispatch_Message;
-- ------------------------------
-- Finish processing the message by marking it as being processed.
-- ------------------------------
procedure Finish_Message (Msg : in out Models.Message_Ref) is
begin
Msg.Set_Status (Models.PROCESSED);
Msg.Set_Finish_Date (ADO.Nullable_Time '(Is_Null => False,
Value => Ada.Calendar.Clock));
Msg.Save (DB);
end Finish_Message;
Count : Natural;
begin
Ctx.Start;
Query.Set_Query (Models.Query_Queue_Pending_Message);
Query.Bind_Param ("queue", From.Queue.Get_Id);
Query.Bind_Param ("max", From.Max_Batch);
Models.List (Messages, DB, Query);
Count := Natural (Messages.Length);
-- Prepare the event messages by marking them in the database.
-- This makes sure that no other server or task (if any), will process them.
if Count > 0 then
for I in 0 .. Count - 1 loop
Messages.Update_Element (Index => I,
Process => Prepare_Message'Access);
end loop;
end if;
Ctx.Commit;
if Count = 0 then
return;
end if;
-- Dispatch each event.
for I in 0 .. Count - 1 loop
Messages.Update_Element (Index => I,
Process => Dispatch_Message'Access);
end loop;
-- After having dispatched the events, mark them as dispatched in the queue.
Ctx.Start;
for I in 0 .. Count - 1 loop
Messages.Update_Element (Index => I,
Process => Finish_Message'Access);
end loop;
Ctx.Commit;
end Dequeue;
-- ------------------------------
-- Create the queue associated with the given name and configure it by using
-- the configuration properties.
-- ------------------------------
function Create_Queue (Name : in String;
Props : in EL.Beans.Param_Vectors.Vector;
Context : in EL.Contexts.ELContext'Class) return Queue_Access is
package AC renames AWA.Services.Contexts;
Ctx : constant AC.Service_Context_Access := AC.Current;
Session : ADO.Sessions.Master_Session := AC.Get_Master_Session (Ctx);
Queue : AWA.Events.Models.Queue_Ref;
Query : ADO.SQL.Query;
Found : Boolean;
begin
Session.Begin_Transaction;
-- Find the queue instance which matches the name.
Query.Set_Filter ("o.name = ?");
Query.Add_Param (Name);
Queue.Find (Session => Session,
Query => Query,
Found => Found);
-- But create the queue instance if it does not exist.
if not Found then
Log.Info ("Creating database queue {0}", Name);
Queue.Set_Name (Name);
Queue.Save (Session);
else
Log.Info ("Using database queue {0}", Name);
end if;
Session.Commit;
declare
Result : constant Persistent_Queue_Access
:= new Persistent_Queue '(Name_Length => Name'Length,
Name => Name,
Queue => Queue,
others => <>);
begin
return Result.all'Access;
end;
end Create_Queue;
end AWA.Events.Queues.Persistents;
|
Save the event properties using a JSON formatter Restore the event properties after loading the event message from database
|
Save the event properties using a JSON formatter
Restore the event properties after loading the event message from database
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
a6e7194e243f5755cfd4dc25230003d567226ffe
|
regtests/babel-streams-tests.ads
|
regtests/babel-streams-tests.ads
|
-----------------------------------------------------------------------
-- babel-streams-tests - Unit tests for babel streams
-- Copyright (C) 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Tests;
package Babel.Streams.Tests is
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite);
type Test is new Util.Tests.Test with null record;
-- Test the Find function resolving some existing user.
procedure Test_Stream_Composition (T : in out Test);
end Babel.Streams.Tests;
|
-----------------------------------------------------------------------
-- babel-streams-tests - Unit tests for babel streams
-- Copyright (C) 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Tests;
package Babel.Streams.Tests is
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite);
type Test is new Util.Tests.Test with null record;
-- Test the Find function resolving some existing user.
procedure Test_Stream_Composition (T : in out Test);
-- Stream copy, compression and decompression test.
-- Create a compressed version of the source file and then decompress the result.
-- The source file is then compared to the decompressed result and must match.
procedure Do_Copy (T : in out Test;
Pool : in out Babel.Files.Buffers.Buffer_Pool;
Src : in String);
end Babel.Streams.Tests;
|
Declare the Do_Copy procedure
|
Declare the Do_Copy procedure
|
Ada
|
apache-2.0
|
stcarrez/babel
|
c1f83f1e4591854dfdac6b951d190cb6f719a8e6
|
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 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;
|
-----------------------------------------------------------------------
-- asf-beans-mappers -- Read XML managed bean declaratiosn
-- Copyright (C) 2010, 2011, 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Beans.Objects;
with Util.Serialize.Mappers.Record_Mapper;
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
Mapper : in out Util.Serialize.Mappers.Processing;
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;
|
Update the Reader_Config to use the new parser/mapper interface
|
Update the Reader_Config to use the new parser/mapper interface
|
Ada
|
apache-2.0
|
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
|
26fccc569b0fa43203af537af59318e73934e76b
|
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.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;
|
-----------------------------------------------------------------------
-- 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 Ada.Directories;
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);
Driver : constant String := Cfg.Get_Driver;
Database : constant String := Cfg.Get_Database;
Path : constant String :=
"db/regtests/" & Cfg.Get_Driver & "/create-ado-" & Driver & ".sql";
pragma Unreferenced (Msg);
begin
if Driver = "sqlite" then
if Ada.Directories.Exists (Database & ".test") then
Ada.Directories.Delete_File (Database & ".test");
end if;
Cfg.Set_Database (Database & ".test");
ADO.Schemas.Databases.Create_Database (Admin => Cfg,
Config => Cfg,
Schema_Path => Path,
Messages => Msg);
T.Assert (Ada.Directories.Exists (Database & ".test"),
"The sqlite database was not created");
else
ADO.Schemas.Databases.Create_Database (Admin => Cfg,
Config => Cfg,
Schema_Path => Path,
Messages => Msg);
end if;
end Test_Create_Schema;
end ADO.Schemas.Tests;
|
Fix Test_Create_Schema to test on SQLite
|
Fix Test_Create_Schema to test on SQLite
|
Ada
|
apache-2.0
|
stcarrez/ada-ado
|
e709a5c6bd88ee1a5d7d24e9d4266c27bd59ccee
|
tools/druss-commands.ads
|
tools/druss-commands.ads
|
-----------------------------------------------------------------------
-- druss-commands -- Commands available for Druss
-- Copyright (C) 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Commands.Drivers;
with Util.Commands.Consoles;
with Util.Commands.Consoles.Text;
with Druss.Gateways;
package Druss.Commands is
-- The list of fields that are printed on the console.
type Field_Type is (F_IP_ADDR,
F_BBOX_IP_ADDR,
F_WAN_IP,
F_ETHERNET,
F_INTERNET,
F_VOIP,
F_HOSTNAME,
F_CONNECTION,
F_DEVTYPE,
F_ACTIVE,
F_LINK,
F_WIFI,
F_WIFI5,
F_ACCESS_CONTROL,
F_DYNDNS,
F_DEVICES,
F_UPTIME,
F_COUNT,
F_BOOL,
F_CHANNEL,
F_PROTOCOL,
F_ENCRYPTION,
F_SSID);
-- The type of notice that are reported.
type Notice_Type is (N_HELP,
N_USAGE,
N_INFO);
-- Make the generic abstract console interface.
package Consoles is
new Util.Commands.Consoles (Field_Type => Field_Type,
Notice_Type => Notice_Type);
-- And the text console to write on stdout (a Gtk console could be done someday).
package Text_Consoles is
new Consoles.Text;
type Context_Type is limited record
Gateways : Druss.Gateways.Gateway_Vector;
Console : Consoles.Console_Access;
end record;
package Drivers is
new Util.Commands.Drivers (Context_Type => Context_Type,
Driver_Name => "druss-drivers");
subtype Argument_List is Util.Commands.Argument_List;
Driver : Drivers.Driver_Type;
procedure Gateway_Command (Command : in Drivers.Command_Type'Class;
Args : in Util.Commands.Argument_List'Class;
Arg_Pos : in Positive;
Process : access procedure (Gateway : in out Gateways.Gateway_Type;
Param : in String);
Context : in out Context_Type);
procedure Initialize;
-- Print the bbox API status.
procedure Print_Status (Console : in Consoles.Console_Access;
Field : in Field_Type;
Value : in String);
-- Print a ON/OFF status.
procedure Print_On_Off (Console : in Consoles.Console_Access;
Field : in Field_Type;
Value : in String);
-- Print a uptime.
procedure Print_Uptime (Console : in Consoles.Console_Access;
Field : in Field_Type;
Value : in String);
-- Print a performance measure in us or ms.
procedure Print_Perf (Console : in Consoles.Console_Access;
Field : in Field_Type;
Value : in String);
end Druss.Commands;
|
-----------------------------------------------------------------------
-- druss-commands -- Commands available for Druss
-- Copyright (C) 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Commands.Drivers;
with Util.Commands.Consoles;
with Util.Commands.Consoles.Text;
with Druss.Gateways;
package Druss.Commands is
-- Device selector to select all, active or inactive devices.
type Device_Selector_Type is (DEVICE_ALL, DEVICE_ACTIVE, DEVICE_INACTIVE);
-- The list of fields that are printed on the console.
type Field_Type is (F_IP_ADDR,
F_BBOX_IP_ADDR,
F_WAN_IP,
F_ETHERNET,
F_INTERNET,
F_VOIP,
F_HOSTNAME,
F_CONNECTION,
F_DEVTYPE,
F_ACTIVE,
F_LINK,
F_WIFI,
F_WIFI5,
F_ACCESS_CONTROL,
F_DYNDNS,
F_DEVICES,
F_UPTIME,
F_COUNT,
F_BOOL,
F_CHANNEL,
F_PROTOCOL,
F_ENCRYPTION,
F_SSID);
-- The type of notice that are reported.
type Notice_Type is (N_HELP,
N_USAGE,
N_INFO);
-- Make the generic abstract console interface.
package Consoles is
new Util.Commands.Consoles (Field_Type => Field_Type,
Notice_Type => Notice_Type);
-- And the text console to write on stdout (a Gtk console could be done someday).
package Text_Consoles is
new Consoles.Text;
type Context_Type is limited record
Gateways : Druss.Gateways.Gateway_Vector;
Console : Consoles.Console_Access;
end record;
package Drivers is
new Util.Commands.Drivers (Context_Type => Context_Type,
Driver_Name => "druss-drivers");
subtype Argument_List is Util.Commands.Argument_List;
Driver : Drivers.Driver_Type;
procedure Gateway_Command (Command : in Drivers.Command_Type'Class;
Args : in Util.Commands.Argument_List'Class;
Arg_Pos : in Positive;
Process : access procedure (Gateway : in out Gateways.Gateway_Type;
Param : in String);
Context : in out Context_Type);
procedure Initialize;
-- Print the bbox API status.
procedure Print_Status (Console : in Consoles.Console_Access;
Field : in Field_Type;
Value : in String);
-- Print a ON/OFF status.
procedure Print_On_Off (Console : in Consoles.Console_Access;
Field : in Field_Type;
Value : in String);
-- Print a uptime.
procedure Print_Uptime (Console : in Consoles.Console_Access;
Field : in Field_Type;
Value : in String);
-- Print a performance measure in us or ms.
procedure Print_Perf (Console : in Consoles.Console_Access;
Field : in Field_Type;
Value : in String);
end Druss.Commands;
|
Declare the Device_Selector_Type type
|
Declare the Device_Selector_Type type
|
Ada
|
apache-2.0
|
stcarrez/bbox-ada-api
|
c574607181e1b5f79a17833b19f8d06d17999507
|
tools/druss-commands.ads
|
tools/druss-commands.ads
|
-----------------------------------------------------------------------
-- druss-commands -- Commands available for Druss
-- Copyright (C) 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Commands.Drivers;
with Util.Commands.Consoles;
with Util.Commands.Consoles.Text;
with Druss.Gateways;
package Druss.Commands is
-- Device selector to select all, active or inactive devices.
type Device_Selector_Type is (DEVICE_ALL, DEVICE_ACTIVE, DEVICE_INACTIVE);
-- The list of fields that are printed on the console.
type Field_Type is (F_IP_ADDR,
F_BBOX_IP_ADDR,
F_WAN_IP,
F_ETHERNET,
F_INTERNET,
F_VOIP,
F_HOSTNAME,
F_CONNECTION,
F_DEVTYPE,
F_ACTIVE,
F_LINK,
F_WIFI,
F_WIFI5,
F_ACCESS_CONTROL,
F_DYNDNS,
F_DEVICES,
F_UPTIME,
F_COUNT,
F_BOOL,
F_CHANNEL,
F_PROTOCOL,
F_ENCRYPTION,
F_SSID);
-- The type of notice that are reported.
type Notice_Type is (N_HELP,
N_USAGE,
N_INFO);
-- Make the generic abstract console interface.
package Consoles is
new Util.Commands.Consoles (Field_Type => Field_Type,
Notice_Type => Notice_Type);
-- And the text console to write on stdout (a Gtk console could be done someday).
package Text_Consoles is
new Consoles.Text;
type Context_Type is limited record
Gateways : Druss.Gateways.Gateway_Vector;
Console : Consoles.Console_Access;
end record;
package Drivers is
new Util.Commands.Drivers (Context_Type => Context_Type,
Driver_Name => "druss-drivers");
subtype Argument_List is Util.Commands.Argument_List;
Driver : Drivers.Driver_Type;
procedure Gateway_Command (Command : in Drivers.Command_Type'Class;
Args : in Util.Commands.Argument_List'Class;
Arg_Pos : in Positive;
Process : access procedure (Gateway : in out Gateways.Gateway_Type;
Param : in String);
Context : in out Context_Type);
procedure Initialize;
-- Print the bbox API status.
procedure Print_Status (Console : in Consoles.Console_Access;
Field : in Field_Type;
Value : in String);
-- Print a ON/OFF status.
procedure Print_On_Off (Console : in Consoles.Console_Access;
Field : in Field_Type;
Value : in String);
-- Print a uptime.
procedure Print_Uptime (Console : in Consoles.Console_Access;
Field : in Field_Type;
Value : in String);
-- Print a performance measure in us or ms.
procedure Print_Perf (Console : in Consoles.Console_Access;
Field : in Field_Type;
Value : in String);
end Druss.Commands;
|
-----------------------------------------------------------------------
-- druss-commands -- Commands available for Druss
-- Copyright (C) 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Commands.Drivers;
with Util.Commands.Consoles;
with Util.Commands.Consoles.Text;
with Druss.Gateways;
package Druss.Commands is
-- Device selector to select all, active or inactive devices.
type Device_Selector_Type is (DEVICE_ALL, DEVICE_ACTIVE, DEVICE_INACTIVE);
-- The list of fields that are printed on the console.
type Field_Type is (F_IP_ADDR,
F_BBOX_IP_ADDR,
F_WAN_IP,
F_ETHERNET,
F_INTERNET,
F_VOIP,
F_HOSTNAME,
F_CONNECTION,
F_DEVTYPE,
F_ACTIVE,
F_LINK,
F_WIFI,
F_WIFI5,
F_ACCESS_CONTROL,
F_DYNDNS,
F_DEVICES,
F_UPTIME,
F_COUNT,
F_BOOL,
F_CHANNEL,
F_PROTOCOL,
F_ENCRYPTION,
F_SSID);
-- The type of notice that are reported.
type Notice_Type is (N_HELP,
N_USAGE,
N_INFO);
-- Make the generic abstract console interface.
package Consoles is
new Util.Commands.Consoles (Field_Type => Field_Type,
Notice_Type => Notice_Type);
-- And the text console to write on stdout (a Gtk console could be done someday).
package Text_Consoles is
new Consoles.Text;
type Context_Type is limited record
Gateways : Druss.Gateways.Gateway_Vector;
Console : Consoles.Console_Access;
end record;
package Drivers is
new Util.Commands.Drivers (Context_Type => Context_Type,
Driver_Name => "druss-drivers");
subtype Argument_List is Util.Commands.Argument_List;
Driver : Drivers.Driver_Type;
procedure Gateway_Command (Command : in Drivers.Command_Type'Class;
Args : in Util.Commands.Argument_List'Class;
Arg_Pos : in Positive;
Process : access procedure (Gateway : in out Gateways.Gateway_Type;
Param : in String);
Context : in out Context_Type);
procedure Initialize;
-- Enter in the interactive main loop waiting for user commands and executing them.
procedure Interactive (Context : in out Context_Type);
-- Print the bbox API status.
procedure Print_Status (Console : in Consoles.Console_Access;
Field : in Field_Type;
Value : in String);
-- Print a ON/OFF status.
procedure Print_On_Off (Console : in Consoles.Console_Access;
Field : in Field_Type;
Value : in String);
-- Print a uptime.
procedure Print_Uptime (Console : in Consoles.Console_Access;
Field : in Field_Type;
Value : in String);
-- Print a performance measure in us or ms.
procedure Print_Perf (Console : in Consoles.Console_Access;
Field : in Field_Type;
Value : in String);
end Druss.Commands;
|
Declare the Interactive procedure
|
Declare the Interactive procedure
|
Ada
|
apache-2.0
|
stcarrez/bbox-ada-api
|
d836bcfc17301595b3cc8675a085d47aa659d128
|
ada/core.adb
|
ada/core.adb
|
with Ada.Characters.Latin_1;
with Ada.Strings.Unbounded;
with Ada.Text_IO;
with Envs;
with Evaluation;
with OpenToken;
with Reader;
with Smart_Pointers;
with Types;
package body Core is
use Types;
-- primitive functions on Smart_Pointer,
function "+" is new Arith_Op ("+", "+");
function "-" is new Arith_Op ("-", "-");
function "*" is new Arith_Op ("*", "*");
function "/" is new Arith_Op ("/", "/");
function "<" is new Rel_Op ("<", "<");
function "<=" is new Rel_Op ("<=", "<=");
function ">" is new Rel_Op (">", ">");
function ">=" is new Rel_Op (">=", ">=");
procedure Add_Defs (Defs : List_Mal_Type; Env : Envs.Env_Handle) is
D, L : List_Mal_Type;
begin
if Evaluation.Debug then
Ada.Text_IO.Put_Line ("Add_Defs " & To_String (Defs));
end if;
D := Defs;
while not Is_Null (D) loop
L := Deref_List (Cdr (D)).all;
Envs.Set
(Env,
Deref_Atom (Car (D)).Get_Atom,
Evaluation.Eval (Car (L), Env));
D := Deref_List (Cdr(L)).all;
end loop;
end Add_Defs;
function Eval_As_Boolean (MH : Types.Mal_Handle) return Boolean is
use Types;
Res : Boolean;
begin
case Deref (MH).Sym_Type is
when Bool =>
Res := Deref_Bool (MH).Get_Bool;
when Atom =>
return not (Deref_Atom (MH).Get_Atom = "nil");
-- when List =>
-- declare
-- L : List_Mal_Type;
-- begin
-- L := Deref_List (MH).all;
-- Res := not Is_Null (L);
-- end;
when others => -- Everything else
Res := True;
end case;
return Res;
end Eval_As_Boolean;
function Is_List (Rest_Handle : Mal_Handle; Env : Envs.Env_Handle)
return Types.Mal_Handle is
First_Param, Evaled_List : Mal_Handle;
Rest_List : Types.List_Mal_Type;
begin
Rest_List := Deref_List (Rest_Handle).all;
First_Param := Car (Rest_List);
return New_Bool_Mal_Type
(Deref (First_Param).Sym_Type = List and then
Deref_List (First_Param).Get_List_Type = List_List);
end Is_List;
function Is_Empty (Rest_Handle : Mal_Handle; Env : Envs.Env_Handle)
return Types.Mal_Handle is
First_Param, Evaled_List : Mal_Handle;
List : List_Mal_Type;
Rest_List : Types.List_Mal_Type;
begin
Rest_List := Deref_List (Rest_Handle).all;
First_Param := Car (Rest_List);
List := Deref_List (First_Param).all;
return New_Bool_Mal_Type (Is_Null (List));
end Is_Empty;
function Eval_As_List (MH : Types.Mal_Handle) return List_Mal_Type is
begin
case Deref (MH).Sym_Type is
when List => return Deref_List (MH).all;
when Atom =>
if Deref_Atom (MH).Get_Atom = "nil" then
return Null_List (List_List);
end if;
when others => null;
end case;
raise Evaluation.Evaluation_Error with "Expecting a List";
return Null_List (List_List);
end Eval_As_List;
function Count (Rest_Handle : Mal_Handle; Env : Envs.Env_Handle)
return Types.Mal_Handle is
First_Param, Evaled_List : Mal_Handle;
List : List_Mal_Type;
Rest_List : Types.List_Mal_Type;
begin
Rest_List := Deref_List (Rest_Handle).all;
First_Param := Car (Rest_List);
List := Eval_As_List (First_Param);
return New_Int_Mal_Type (Length (List));
end Count;
function Cons (Rest_Handle : Mal_Handle; Env : Envs.Env_Handle)
return Types.Mal_Handle is
Rest_List : Types.List_Mal_Type;
First_Param, List_Handle : Mal_Handle;
List : List_Mal_Type;
begin
Rest_List := Deref_List (Rest_Handle).all;
First_Param := Car (Rest_List);
List_Handle := Cdr (Rest_List);
List := Deref_List (List_Handle).all;
List_Handle := Car (List);
List := Deref_List (List_Handle).all;
return Prepend (First_Param, List);
end Cons;
function Concat (Rest_Handle : Mal_Handle; Env : Envs.Env_Handle)
return Types.Mal_Handle is
Rest_List : Types.List_Mal_Type;
begin
Rest_List := Deref_List (Rest_Handle).all;
return Types.Concat (Rest_List, Env);
end Concat;
function New_List (Rest_Handle : Mal_Handle; Env : Envs.Env_Handle)
return Types.Mal_Handle is
Rest_List : Types.List_Mal_Type;
begin
Rest_List := Deref_List (Rest_Handle).all;
return New_List_Mal_Type (The_List => Rest_List);
end New_List;
-- Take a list with two parameters and produce a single result
-- using the Op access-to-function parameter.
function Reduce2
(Op : Binary_Func_Access; LH : Mal_Handle; Env : Envs.Env_Handle)
return Mal_Handle is
Left, Right : Mal_Handle;
L, Rest_List : List_Mal_Type;
begin
L := Deref_List (LH).all;
Left := Car (L);
Rest_List := Deref_List (Cdr (L)).all;
Right := Car (Rest_List);
return Op (Left, Right);
end Reduce2;
function Plus (Rest_Handle : Mal_Handle; Env : Envs.Env_Handle)
return Types.Mal_Handle is
begin
return Reduce2 ("+"'Access, Rest_Handle, Env);
end Plus;
function Minus (Rest_Handle : Mal_Handle; Env : Envs.Env_Handle)
return Types.Mal_Handle is
begin
return Reduce2 ("-"'Access, Rest_Handle, Env);
end Minus;
function Mult (Rest_Handle : Mal_Handle; Env : Envs.Env_Handle)
return Types.Mal_Handle is
begin
return Reduce2 ("*"'Access, Rest_Handle, Env);
end Mult;
function Divide (Rest_Handle : Mal_Handle; Env : Envs.Env_Handle)
return Types.Mal_Handle is
begin
return Reduce2 ("/"'Access, Rest_Handle, Env);
end Divide;
function LT (Rest_Handle : Mal_Handle; Env : Envs.Env_Handle)
return Types.Mal_Handle is
begin
return Reduce2 ("<"'Access, Rest_Handle, Env);
end LT;
function LTE (Rest_Handle : Mal_Handle; Env : Envs.Env_Handle)
return Types.Mal_Handle is
begin
return Reduce2 ("<="'Access, Rest_Handle, Env);
end LTE;
function GT (Rest_Handle : Mal_Handle; Env : Envs.Env_Handle)
return Types.Mal_Handle is
begin
return Reduce2 (">"'Access, Rest_Handle, Env);
end GT;
function GTE (Rest_Handle : Mal_Handle; Env : Envs.Env_Handle)
return Types.Mal_Handle is
begin
return Reduce2 (">="'Access, Rest_Handle, Env);
end GTE;
function EQ (Rest_Handle : Mal_Handle; Env : Envs.Env_Handle)
return Types.Mal_Handle is
begin
return Reduce2 (Types."="'Access, Rest_Handle, Env);
end EQ;
function Pr_Str (Rest_Handle : Mal_Handle; Env : Envs.Env_Handle)
return Types.Mal_Handle is
use Ada.Strings.Unbounded;
Res : Unbounded_String;
begin
return New_String_Mal_Type ('"' & Deref_List (Rest_Handle).Pr_Str & '"');
end Pr_Str;
function Prn (Rest_Handle : Mal_Handle; Env : Envs.Env_Handle)
return Types.Mal_Handle is
use Ada.Strings.Unbounded;
begin
Ada.Text_IO.Put_Line (Deref_List (Rest_Handle).Pr_Str);
return New_Atom_Mal_Type ("nil");
end Prn;
function Println (Rest_Handle : Mal_Handle; Env : Envs.Env_Handle)
return Types.Mal_Handle is
use Ada.Strings.Unbounded;
Res : String := Deref_List (Rest_Handle).Pr_Str (False);
begin
Ada.Text_IO.Put_Line (Res);
return New_Atom_Mal_Type ("nil");
end Println;
function Str (Rest_Handle : Mal_Handle; Env : Envs.Env_Handle)
return Types.Mal_Handle is
use Ada.Strings.Unbounded;
Res : String := Deref_List (Rest_Handle).Cat_Str (False);
begin
return New_String_Mal_Type ('"' & Res & '"');
end Str;
function Read_String (Rest_Handle : Mal_Handle; Env : Envs.Env_Handle)
return Types.Mal_Handle is
Rest_List : Types.List_Mal_Type;
First_Param : Mal_Handle;
begin
Rest_List := Deref_List (Rest_Handle).all;
First_Param := Car (Rest_List);
declare
Str_Param : String := Deref_String (First_Param).Get_String;
Unquoted_Str : String(1 .. Str_Param'Length-2) :=
Str_Param (Str_Param'First+1 .. Str_Param'Last-1);
-- i.e. strip out the double-qoutes surrounding the string.
begin
return Reader.Read_Str (Unquoted_Str);
end;
end Read_String;
function Slurp (Rest_Handle : Mal_Handle; Env : Envs.Env_Handle)
return Types.Mal_Handle is
Rest_List : Types.List_Mal_Type;
First_Param : Mal_Handle;
begin
Rest_List := Deref_List (Rest_Handle).all;
First_Param := Car (Rest_List);
declare
Str_Param : String := Deref_String (First_Param).Get_String;
Unquoted_Str : String(1 .. Str_Param'Length-2) :=
Str_Param (Str_Param'First+1 .. Str_Param'Last-1);
-- i.e. strip out the double-qoutes surrounding the string.
use Ada.Text_IO;
Fn : Ada.Text_IO.File_Type;
Line_Str : String (1..Reader.Max_Line_Len);
File_Str : String (1..Reader.Max_Line_Len);
Last : Natural;
I : Natural := 0;
begin
Ada.Text_IO.Open (Fn, In_File, Unquoted_Str);
while not End_Of_File (Fn) loop
Get_Line (Fn, Line_Str, Last);
if Last > 0 then
File_Str (I+1 .. I+Last) := Line_Str (1 .. Last);
I := I + Last;
File_Str (I+1) := OpenToken.EOL_Character;
I := I + 1;
end if;
end loop;
Ada.Text_IO.Close (Fn);
return New_String_Mal_Type ('"' & File_Str (1..I) & '"');
end;
end Slurp;
procedure Init is
use Envs;
begin
Envs.New_Env;
Set (Get_Current, "true", Types.New_Bool_Mal_Type (True));
Set (Get_Current, "false", Types.New_Bool_Mal_Type (False));
Set (Get_Current, "nil", Types.New_Atom_Mal_Type ("nil"));
Set (Get_Current,
"list?",
New_Func_Mal_Type ("list?", Is_List'access));
Set (Get_Current,
"empty?",
New_Func_Mal_Type ("empty?", Is_Empty'access));
Set (Get_Current,
"count",
New_Func_Mal_Type ("count", Count'access));
Set (Get_Current,
"cons",
New_Func_Mal_Type ("cons", Cons'access));
Set (Get_Current,
"concat",
New_Func_Mal_Type ("concat", Concat'access));
Set (Get_Current,
"list",
New_Func_Mal_Type ("list", New_List'access));
Set (Get_Current,
"pr-str",
New_Func_Mal_Type ("pr-str", Pr_Str'access));
Set (Get_Current,
"str",
New_Func_Mal_Type ("str", Str'access));
Set (Get_Current,
"prn",
New_Func_Mal_Type ("prn", Prn'access));
Set (Get_Current,
"println",
New_Func_Mal_Type ("println", Println'access));
Set (Get_Current,
"eval",
New_Func_Mal_Type ("eval", Evaluation.Eval'access));
Set (Get_Current,
"read-string",
New_Func_Mal_Type ("read-string", Read_String'access));
Set (Get_Current,
"slurp",
New_Func_Mal_Type ("slurp", Slurp'access));
Set (Get_Current,
"+",
New_Func_Mal_Type ("+", Plus'access));
Set (Get_Current,
"-",
New_Func_Mal_Type ("-", Minus'access));
Set (Get_Current,
"*",
New_Func_Mal_Type ("*", Mult'access));
Set (Get_Current,
"/",
New_Func_Mal_Type ("/", Divide'access));
Set (Get_Current,
"<",
New_Func_Mal_Type ("<", LT'access));
Set (Get_Current,
"<=",
New_Func_Mal_Type ("<=", LTE'access));
Set (Get_Current,
">",
New_Func_Mal_Type (">", GT'access));
Set (Get_Current,
">=",
New_Func_Mal_Type (">=", GTE'access));
Set (Get_Current,
"=",
New_Func_Mal_Type ("=", EQ'access));
end Init;
end Core;
|
with Ada.Characters.Latin_1;
with Ada.Strings.Unbounded;
with Ada.Text_IO;
with Envs;
with Evaluation;
with OpenToken;
with Reader;
with Smart_Pointers;
with Types;
package body Core is
use Types;
-- primitive functions on Smart_Pointer,
function "+" is new Arith_Op ("+", "+");
function "-" is new Arith_Op ("-", "-");
function "*" is new Arith_Op ("*", "*");
function "/" is new Arith_Op ("/", "/");
function "<" is new Rel_Op ("<", "<");
function "<=" is new Rel_Op ("<=", "<=");
function ">" is new Rel_Op (">", ">");
function ">=" is new Rel_Op (">=", ">=");
procedure Add_Defs (Defs : List_Mal_Type; Env : Envs.Env_Handle) is
D, L : List_Mal_Type;
begin
if Evaluation.Debug then
Ada.Text_IO.Put_Line ("Add_Defs " & To_String (Defs));
end if;
D := Defs;
while not Is_Null (D) loop
L := Deref_List (Cdr (D)).all;
Envs.Set
(Env,
Deref_Atom (Car (D)).Get_Atom,
Evaluation.Eval (Car (L), Env));
D := Deref_List (Cdr(L)).all;
end loop;
end Add_Defs;
function Eval_As_Boolean (MH : Types.Mal_Handle) return Boolean is
use Types;
Res : Boolean;
begin
case Deref (MH).Sym_Type is
when Bool =>
Res := Deref_Bool (MH).Get_Bool;
when Atom =>
return not (Deref_Atom (MH).Get_Atom = "nil");
-- when List =>
-- declare
-- L : List_Mal_Type;
-- begin
-- L := Deref_List (MH).all;
-- Res := not Is_Null (L);
-- end;
when others => -- Everything else
Res := True;
end case;
return Res;
end Eval_As_Boolean;
function Is_List (Rest_Handle : Mal_Handle; Env : Envs.Env_Handle)
return Types.Mal_Handle is
First_Param, Evaled_List : Mal_Handle;
Rest_List : Types.List_Mal_Type;
begin
Rest_List := Deref_List (Rest_Handle).all;
First_Param := Car (Rest_List);
return New_Bool_Mal_Type
(Deref (First_Param).Sym_Type = List and then
Deref_List (First_Param).Get_List_Type = List_List);
end Is_List;
function Is_Empty (Rest_Handle : Mal_Handle; Env : Envs.Env_Handle)
return Types.Mal_Handle is
First_Param, Evaled_List : Mal_Handle;
List : List_Mal_Type;
Rest_List : Types.List_Mal_Type;
begin
Rest_List := Deref_List (Rest_Handle).all;
First_Param := Car (Rest_List);
List := Deref_List (First_Param).all;
return New_Bool_Mal_Type (Is_Null (List));
end Is_Empty;
function Eval_As_List (MH : Types.Mal_Handle) return List_Mal_Type is
begin
case Deref (MH).Sym_Type is
when List => return Deref_List (MH).all;
when Atom =>
if Deref_Atom (MH).Get_Atom = "nil" then
return Null_List (List_List);
end if;
when others => null;
end case;
raise Evaluation.Evaluation_Error with "Expecting a List";
return Null_List (List_List);
end Eval_As_List;
function Count (Rest_Handle : Mal_Handle; Env : Envs.Env_Handle)
return Types.Mal_Handle is
First_Param, Evaled_List : Mal_Handle;
List : List_Mal_Type;
Rest_List : Types.List_Mal_Type;
begin
Rest_List := Deref_List (Rest_Handle).all;
First_Param := Car (Rest_List);
List := Eval_As_List (First_Param);
return New_Int_Mal_Type (Length (List));
end Count;
function Cons (Rest_Handle : Mal_Handle; Env : Envs.Env_Handle)
return Types.Mal_Handle is
Rest_List : Types.List_Mal_Type;
First_Param, List_Handle : Mal_Handle;
List : List_Mal_Type;
begin
Rest_List := Deref_List (Rest_Handle).all;
First_Param := Car (Rest_List);
List_Handle := Cdr (Rest_List);
List := Deref_List (List_Handle).all;
List_Handle := Car (List);
List := Deref_List (List_Handle).all;
return Prepend (First_Param, List);
end Cons;
function Concat (Rest_Handle : Mal_Handle; Env : Envs.Env_Handle)
return Types.Mal_Handle is
Rest_List : Types.List_Mal_Type;
begin
Rest_List := Deref_List (Rest_Handle).all;
return Types.Concat (Rest_List, Env);
end Concat;
function First (Rest_Handle : Mal_Handle; Env : Envs.Env_Handle)
return Types.Mal_Handle is
Rest_List, First_List : Types.List_Mal_Type;
First_Param : Mal_Handle;
begin
Rest_List := Deref_List (Rest_Handle).all;
First_Param := Car (Rest_List);
First_List := Deref_List (First_Param).all;
return Types.Car (First_List);
end First;
function Rest (Rest_Handle : Mal_Handle; Env : Envs.Env_Handle)
return Types.Mal_Handle is
Rest_List, First_List : Types.List_Mal_Type;
First_Param : Mal_Handle;
begin
Rest_List := Deref_List (Rest_Handle).all;
First_Param := Car (Rest_List);
First_List := Deref_List (First_Param).all;
return Types.Cdr (First_List);
end Rest;
function New_List (Rest_Handle : Mal_Handle; Env : Envs.Env_Handle)
return Types.Mal_Handle is
Rest_List : Types.List_Mal_Type;
begin
Rest_List := Deref_List (Rest_Handle).all;
return New_List_Mal_Type (The_List => Rest_List);
end New_List;
-- Take a list with two parameters and produce a single result
-- using the Op access-to-function parameter.
function Reduce2
(Op : Binary_Func_Access; LH : Mal_Handle; Env : Envs.Env_Handle)
return Mal_Handle is
Left, Right : Mal_Handle;
L, Rest_List : List_Mal_Type;
begin
L := Deref_List (LH).all;
Left := Car (L);
Rest_List := Deref_List (Cdr (L)).all;
Right := Car (Rest_List);
return Op (Left, Right);
end Reduce2;
function Plus (Rest_Handle : Mal_Handle; Env : Envs.Env_Handle)
return Types.Mal_Handle is
begin
return Reduce2 ("+"'Access, Rest_Handle, Env);
end Plus;
function Minus (Rest_Handle : Mal_Handle; Env : Envs.Env_Handle)
return Types.Mal_Handle is
begin
return Reduce2 ("-"'Access, Rest_Handle, Env);
end Minus;
function Mult (Rest_Handle : Mal_Handle; Env : Envs.Env_Handle)
return Types.Mal_Handle is
begin
return Reduce2 ("*"'Access, Rest_Handle, Env);
end Mult;
function Divide (Rest_Handle : Mal_Handle; Env : Envs.Env_Handle)
return Types.Mal_Handle is
begin
return Reduce2 ("/"'Access, Rest_Handle, Env);
end Divide;
function LT (Rest_Handle : Mal_Handle; Env : Envs.Env_Handle)
return Types.Mal_Handle is
begin
return Reduce2 ("<"'Access, Rest_Handle, Env);
end LT;
function LTE (Rest_Handle : Mal_Handle; Env : Envs.Env_Handle)
return Types.Mal_Handle is
begin
return Reduce2 ("<="'Access, Rest_Handle, Env);
end LTE;
function GT (Rest_Handle : Mal_Handle; Env : Envs.Env_Handle)
return Types.Mal_Handle is
begin
return Reduce2 (">"'Access, Rest_Handle, Env);
end GT;
function GTE (Rest_Handle : Mal_Handle; Env : Envs.Env_Handle)
return Types.Mal_Handle is
begin
return Reduce2 (">="'Access, Rest_Handle, Env);
end GTE;
function EQ (Rest_Handle : Mal_Handle; Env : Envs.Env_Handle)
return Types.Mal_Handle is
begin
return Reduce2 (Types."="'Access, Rest_Handle, Env);
end EQ;
function Pr_Str (Rest_Handle : Mal_Handle; Env : Envs.Env_Handle)
return Types.Mal_Handle is
use Ada.Strings.Unbounded;
Res : Unbounded_String;
begin
return New_String_Mal_Type ('"' & Deref_List (Rest_Handle).Pr_Str & '"');
end Pr_Str;
function Prn (Rest_Handle : Mal_Handle; Env : Envs.Env_Handle)
return Types.Mal_Handle is
use Ada.Strings.Unbounded;
begin
Ada.Text_IO.Put_Line (Deref_List (Rest_Handle).Pr_Str);
return New_Atom_Mal_Type ("nil");
end Prn;
function Println (Rest_Handle : Mal_Handle; Env : Envs.Env_Handle)
return Types.Mal_Handle is
use Ada.Strings.Unbounded;
Res : String := Deref_List (Rest_Handle).Pr_Str (False);
begin
Ada.Text_IO.Put_Line (Res);
return New_Atom_Mal_Type ("nil");
end Println;
function Str (Rest_Handle : Mal_Handle; Env : Envs.Env_Handle)
return Types.Mal_Handle is
use Ada.Strings.Unbounded;
Res : String := Deref_List (Rest_Handle).Cat_Str (False);
begin
return New_String_Mal_Type ('"' & Res & '"');
end Str;
function Read_String (Rest_Handle : Mal_Handle; Env : Envs.Env_Handle)
return Types.Mal_Handle is
Rest_List : Types.List_Mal_Type;
First_Param : Mal_Handle;
begin
Rest_List := Deref_List (Rest_Handle).all;
First_Param := Car (Rest_List);
declare
Str_Param : String := Deref_String (First_Param).Get_String;
Unquoted_Str : String(1 .. Str_Param'Length-2) :=
Str_Param (Str_Param'First+1 .. Str_Param'Last-1);
-- i.e. strip out the double-qoutes surrounding the string.
begin
return Reader.Read_Str (Unquoted_Str);
end;
end Read_String;
function Slurp (Rest_Handle : Mal_Handle; Env : Envs.Env_Handle)
return Types.Mal_Handle is
Rest_List : Types.List_Mal_Type;
First_Param : Mal_Handle;
begin
Rest_List := Deref_List (Rest_Handle).all;
First_Param := Car (Rest_List);
declare
Str_Param : String := Deref_String (First_Param).Get_String;
Unquoted_Str : String(1 .. Str_Param'Length-2) :=
Str_Param (Str_Param'First+1 .. Str_Param'Last-1);
-- i.e. strip out the double-qoutes surrounding the string.
use Ada.Text_IO;
Fn : Ada.Text_IO.File_Type;
Line_Str : String (1..Reader.Max_Line_Len);
File_Str : String (1..Reader.Max_Line_Len);
Last : Natural;
I : Natural := 0;
begin
Ada.Text_IO.Open (Fn, In_File, Unquoted_Str);
while not End_Of_File (Fn) loop
Get_Line (Fn, Line_Str, Last);
if Last > 0 then
File_Str (I+1 .. I+Last) := Line_Str (1 .. Last);
I := I + Last;
File_Str (I+1) := OpenToken.EOL_Character;
I := I + 1;
end if;
end loop;
Ada.Text_IO.Close (Fn);
return New_String_Mal_Type ('"' & File_Str (1..I) & '"');
end;
end Slurp;
procedure Init is
use Envs;
begin
Envs.New_Env;
Set (Get_Current, "true", Types.New_Bool_Mal_Type (True));
Set (Get_Current, "false", Types.New_Bool_Mal_Type (False));
Set (Get_Current, "nil", Types.New_Atom_Mal_Type ("nil"));
Set (Get_Current,
"list?",
New_Func_Mal_Type ("list?", Is_List'access));
Set (Get_Current,
"empty?",
New_Func_Mal_Type ("empty?", Is_Empty'access));
Set (Get_Current,
"count",
New_Func_Mal_Type ("count", Count'access));
Set (Get_Current,
"cons",
New_Func_Mal_Type ("cons", Cons'access));
Set (Get_Current,
"concat",
New_Func_Mal_Type ("concat", Concat'access));
Set (Get_Current,
"first",
New_Func_Mal_Type ("first", First'access));
Set (Get_Current,
"rest",
New_Func_Mal_Type ("rest", Rest'access));
Set (Get_Current,
"list",
New_Func_Mal_Type ("list", New_List'access));
Set (Get_Current,
"pr-str",
New_Func_Mal_Type ("pr-str", Pr_Str'access));
Set (Get_Current,
"str",
New_Func_Mal_Type ("str", Str'access));
Set (Get_Current,
"prn",
New_Func_Mal_Type ("prn", Prn'access));
Set (Get_Current,
"println",
New_Func_Mal_Type ("println", Println'access));
Set (Get_Current,
"eval",
New_Func_Mal_Type ("eval", Evaluation.Eval'access));
Set (Get_Current,
"read-string",
New_Func_Mal_Type ("read-string", Read_String'access));
Set (Get_Current,
"slurp",
New_Func_Mal_Type ("slurp", Slurp'access));
Set (Get_Current,
"+",
New_Func_Mal_Type ("+", Plus'access));
Set (Get_Current,
"-",
New_Func_Mal_Type ("-", Minus'access));
Set (Get_Current,
"*",
New_Func_Mal_Type ("*", Mult'access));
Set (Get_Current,
"/",
New_Func_Mal_Type ("/", Divide'access));
Set (Get_Current,
"<",
New_Func_Mal_Type ("<", LT'access));
Set (Get_Current,
"<=",
New_Func_Mal_Type ("<=", LTE'access));
Set (Get_Current,
">",
New_Func_Mal_Type (">", GT'access));
Set (Get_Current,
">=",
New_Func_Mal_Type (">=", GTE'access));
Set (Get_Current,
"=",
New_Func_Mal_Type ("=", EQ'access));
end Init;
end Core;
|
add First and Rest funcs
|
Ada: add First and Rest funcs
|
Ada
|
mpl-2.0
|
joncol/mal,jwalsh/mal,jwalsh/mal,mpwillson/mal,DomBlack/mal,alantsev/mal,joncol/mal,hterkelsen/mal,mpwillson/mal,jwalsh/mal,DomBlack/mal,0gajun/mal,mpwillson/mal,SawyerHood/mal,0gajun/mal,hterkelsen/mal,hterkelsen/mal,jwalsh/mal,hterkelsen/mal,0gajun/mal,alantsev/mal,0gajun/mal,hterkelsen/mal,DomBlack/mal,0gajun/mal,hterkelsen/mal,hterkelsen/mal,hterkelsen/mal,mpwillson/mal,foresterre/mal,0gajun/mal,hterkelsen/mal,hterkelsen/mal,jwalsh/mal,0gajun/mal,jwalsh/mal,0gajun/mal,foresterre/mal,jwalsh/mal,alantsev/mal,0gajun/mal,alantsev/mal,mpwillson/mal,foresterre/mal,DomBlack/mal,jwalsh/mal,0gajun/mal,hterkelsen/mal,jwalsh/mal,alantsev/mal,SawyerHood/mal,alantsev/mal,alantsev/mal,alantsev/mal,mpwillson/mal,SawyerHood/mal,SawyerHood/mal,hterkelsen/mal,alantsev/mal,SawyerHood/mal,jwalsh/mal,foresterre/mal,0gajun/mal,alantsev/mal,foresterre/mal,foresterre/mal,DomBlack/mal,DomBlack/mal,mpwillson/mal,alantsev/mal,0gajun/mal,mpwillson/mal,alantsev/mal,hterkelsen/mal,hterkelsen/mal,jwalsh/mal,foresterre/mal,DomBlack/mal,DomBlack/mal,foresterre/mal,0gajun/mal,hterkelsen/mal,jwalsh/mal,mpwillson/mal,alantsev/mal,jwalsh/mal,alantsev/mal,SawyerHood/mal,DomBlack/mal,SawyerHood/mal,foresterre/mal,DomBlack/mal,DomBlack/mal,DomBlack/mal,DomBlack/mal,hterkelsen/mal,SawyerHood/mal,0gajun/mal,0gajun/mal,DomBlack/mal,DomBlack/mal,DomBlack/mal,SawyerHood/mal,foresterre/mal,foresterre/mal,mpwillson/mal,hterkelsen/mal,foresterre/mal,jwalsh/mal,0gajun/mal,0gajun/mal,SawyerHood/mal,foresterre/mal,mpwillson/mal,DomBlack/mal,hterkelsen/mal,jwalsh/mal,DomBlack/mal,SawyerHood/mal,mpwillson/mal,SawyerHood/mal,mpwillson/mal,SawyerHood/mal,alantsev/mal,alantsev/mal,SawyerHood/mal,DomBlack/mal,alantsev/mal,mpwillson/mal,DomBlack/mal,0gajun/mal,foresterre/mal,foresterre/mal,0gajun/mal,hterkelsen/mal,SawyerHood/mal,foresterre/mal,jwalsh/mal,foresterre/mal,SawyerHood/mal,jwalsh/mal,joncol/mal,SawyerHood/mal,0gajun/mal,DomBlack/mal,SawyerHood/mal
|
56facee6f561d5d6ad0bcb1fe14cb3db9a4cbc4e
|
src/asf-applications-messages-factory.ads
|
src/asf-applications-messages-factory.ads
|
-----------------------------------------------------------------------
-- applications.messages-factory -- Application Message Factory
-- Copyright (C) 2011, 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with ASF.Contexts.Faces;
with ASF.Utils;
package ASF.Applications.Messages.Factory is
-- Get a localized message. The message identifier is composed of a resource bundle name
-- prefix and a bundle key. The prefix and key are separated by the first '.'.
-- If the message identifier does not contain any prefix, the default bundle is "messages".
function Get_Message (Context : in ASF.Contexts.Faces.Faces_Context'Class;
Message_Id : in String) return String;
-- Build a localized message.
function Get_Message (Context : in ASF.Contexts.Faces.Faces_Context'Class;
Message_Id : in String;
Severity : in Messages.Severity := ERROR) return Message;
-- Build a localized message and format the message with one argument.
function Get_Message (Context : in ASF.Contexts.Faces.Faces_Context'Class;
Message_Id : in String;
Param1 : in String;
Severity : in Messages.Severity := ERROR) return Message;
-- Build a localized message and format the message with two argument.
function Get_Message (Context : in ASF.Contexts.Faces.Faces_Context'Class;
Message_Id : in String;
Param1 : in String;
Param2 : in String;
Severity : in Messages.Severity := ERROR) return Message;
-- Build a localized message and format the message with some arguments.
function Get_Message (Context : in ASF.Contexts.Faces.Faces_Context'Class;
Message_Id : in String;
Args : in ASF.Utils.Object_Array;
Severity : in Messages.Severity := ERROR) return Message;
-- Add a localized global message in the current faces context.
procedure Add_Message (Message_Id : in String;
Severity : in Messages.Severity := ERROR);
-- Add a localized global message in the faces context.
procedure Add_Message (Context : in out ASF.Contexts.Faces.Faces_Context'Class;
Message_Id : in String;
Param1 : in String;
Severity : in Messages.Severity := ERROR);
-- Add a localized global message in the faces context.
procedure Add_Message (Context : in out ASF.Contexts.Faces.Faces_Context'Class;
Message_Id : in String;
Severity : in Messages.Severity := ERROR);
end ASF.Applications.Messages.Factory;
|
-----------------------------------------------------------------------
-- applications.messages-factory -- Application Message Factory
-- Copyright (C) 2011, 2012, 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with ASF.Contexts.Faces;
with ASF.Utils;
package ASF.Applications.Messages.Factory is
-- Get a localized message. The message identifier is composed of a resource bundle name
-- prefix and a bundle key. The prefix and key are separated by the first '.'.
-- If the message identifier does not contain any prefix, the default bundle is "messages".
function Get_Message (Context : in ASF.Contexts.Faces.Faces_Context'Class;
Message_Id : in String) return String;
-- Build a localized message.
function Get_Message (Context : in ASF.Contexts.Faces.Faces_Context'Class;
Message_Id : in String;
Severity : in Messages.Severity := ERROR) return Message;
-- Build a localized message and format the message with one argument.
function Get_Message (Context : in ASF.Contexts.Faces.Faces_Context'Class;
Message_Id : in String;
Param1 : in String;
Severity : in Messages.Severity := ERROR) return Message;
-- Build a localized message and format the message with two argument.
function Get_Message (Context : in ASF.Contexts.Faces.Faces_Context'Class;
Message_Id : in String;
Param1 : in String;
Param2 : in String;
Severity : in Messages.Severity := ERROR) return Message;
-- Build a localized message and format the message with some arguments.
function Get_Message (Context : in ASF.Contexts.Faces.Faces_Context'Class;
Message_Id : in String;
Args : in ASF.Utils.Object_Array;
Severity : in Messages.Severity := ERROR) return Message;
-- Add a localized global message in the current faces context.
procedure Add_Message (Message_Id : in String;
Severity : in Messages.Severity := ERROR);
-- Add a localized field message in the current faces context. The message is associated
-- with the component identified by <tt>Client_Id</tt>.
procedure Add_Field_Message (Client_Id : in String;
Message_Id : in String;
Severity : in Messages.Severity := ERROR);
-- Add a localized global message in the faces context.
procedure Add_Message (Context : in out ASF.Contexts.Faces.Faces_Context'Class;
Message_Id : in String;
Param1 : in String;
Severity : in Messages.Severity := ERROR);
-- Add a localized global message in the faces context.
procedure Add_Message (Context : in out ASF.Contexts.Faces.Faces_Context'Class;
Message_Id : in String;
Severity : in Messages.Severity := ERROR);
end ASF.Applications.Messages.Factory;
|
Declare Add_Field_Message procedure
|
Declare Add_Field_Message procedure
|
Ada
|
apache-2.0
|
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
|
77092eb3e3ecf2ca239bdb5c21352e53dd510bac
|
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 Ada.Strings.Wide_Wide_Unbounded;
with Wiki.Helpers;
with Wiki.Parsers.Html.Entities;
package body Wiki.Parsers.Html is
use Ada.Strings.Wide_Wide_Unbounded;
-- Parse an HTML attribute
procedure Parse_Attribute_Name (P : in out Parser;
Name : in out Unbounded_Wide_Wide_String);
-- 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 Unbounded_Wide_Wide_String);
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 Unbounded_Wide_Wide_String) is
C : Wiki.Strings.WChar;
begin
Name := To_Unbounded_Wide_Wide_String ("");
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;
Ada.Strings.Wide_Wide_Unbounded.Append (Name, C);
end loop;
end Parse_Attribute_Name;
procedure Collect_Attribute_Value (P : in out Parser;
Value : in out Unbounded_Wide_Wide_String) is
C : Wiki.Strings.WChar;
Token : Wiki.Strings.WChar;
begin
Value := To_Unbounded_Wide_Wide_String ("");
Peek (P, Token);
if Wiki.Helpers.Is_Space (Token) then
return;
elsif Token = '>' then
Put_Back (P, Token);
return;
elsif Token /= ''' and Token /= '"' then
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;
Append (Value, C);
end loop;
else
while not P.Is_Eof loop
Peek (P, C);
if C = Token then
return;
end if;
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
C : Wiki.Strings.WChar;
Name : Unbounded_Wide_Wide_String;
Value : Unbounded_Wide_Wide_String;
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);
Attributes.Append (P.Attributes, Name, Value);
elsif Wiki.Helpers.Is_Space (C) and Length (Name) > 0 then
Attributes.Append (P.Attributes, Name, Null_Unbounded_Wide_Wide_String);
end if;
end loop;
-- Peek (P, C);
-- Add any pending attribute.
if Length (Name) > 0 then
Attributes.Append (P.Attributes, Name, Null_Unbounded_Wide_Wide_String);
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
Name : Unbounded_Wide_Wide_String;
C : Wiki.Strings.WChar;
Tag : Wiki.Html_Tag;
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);
Tag := Wiki.Find_Tag (To_Wide_Wide_String (Name));
if C = '/' then
Skip_Spaces (P);
Peek (P, C);
if C /= '>' then
Put_Back (P, C);
end if;
Flush_Text (P);
End_Element (P, Tag);
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;
Start_Element (P, Tag, P.Attributes);
end if;
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 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES 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.UString);
-- 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.UString);
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.UString) is
C : Wiki.Strings.WChar;
begin
Name := Wiki.Strings.To_UString ("");
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.Append (Name, C);
end loop;
end Parse_Attribute_Name;
procedure Collect_Attribute_Value (P : in out Parser;
Value : in out Wiki.Strings.UString) 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.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.Append (Value, C);
end loop;
else
while not P.Is_Eof loop
Peek (P, C);
if C = Token then
return;
end if;
Wiki.Strings.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
C : Wiki.Strings.WChar;
Name : Wiki.Strings.UString;
Value : Wiki.Strings.UString;
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);
Attributes.Append (P.Attributes, Name, Value);
elsif Wiki.Helpers.Is_Space (C) and Wiki.Strings.Length (Name) > 0 then
Attributes.Append (P.Attributes, Name, Wiki.Strings.Null_UString);
end if;
end loop;
-- Peek (P, C);
-- Add any pending attribute.
if Wiki.Strings.Length (Name) > 0 then
Attributes.Append (P.Attributes, Name, Wiki.Strings.Null_UString);
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
Name : Wiki.Strings.UString;
C : Wiki.Strings.WChar;
Tag : Wiki.Html_Tag;
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);
Tag := Wiki.Find_Tag (Wiki.Strings.To_WString (Name));
if C = '/' then
Skip_Spaces (P);
Peek (P, C);
if C /= '>' then
Put_Back (P, C);
end if;
Flush_Text (P);
End_Element (P, Tag);
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;
Start_Element (P, Tag, P.Attributes);
end if;
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;
|
Use the Wiki.Strings.UString type and operations
|
Use the Wiki.Strings.UString type and operations
|
Ada
|
apache-2.0
|
stcarrez/ada-wiki,stcarrez/ada-wiki
|
bc7176ed1d2f2d42daab7ce432d4912e4a42ee5e
|
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, 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;
-- Set the indentation level for HTML output stream.
procedure Set_Indent_Level (Writer : in out Html_Output_Stream;
Indent : in Natural) 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 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;
|
-----------------------------------------------------------------------
-- 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;
-- Set the indentation level for HTML output stream.
procedure Set_Indent_Level (Writer : in out Html_Output_Stream;
Indent : in Natural) is null;
-- 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 null;
-- 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;
|
Change Set_Indent_Level and Newline to non abstract because they are not mandatory
|
Change Set_Indent_Level and Newline to non abstract because they are not mandatory
|
Ada
|
apache-2.0
|
stcarrez/ada-wiki,stcarrez/ada-wiki
|
42a9171d3ab79a335ef82b6c3c72a0291ff523be
|
src/asf-components-widgets-likes.adb
|
src/asf-components-widgets-likes.adb
|
-----------------------------------------------------------------------
-- components-widgets-likes -- Social Likes Components
-- Copyright (C) 2013 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Locales;
with Util.Beans.Objects;
with Util.Strings.Tokenizers;
with ASF.Requests;
with ASF.Contexts.Writer;
package body ASF.Components.Widgets.Likes is
FB_LAYOUT_ATTR : aliased constant String := "data-layout";
FB_SHOW_FACES_ATTR : aliased constant String := "data-show-faces";
FB_WIDTH_ATTR : aliased constant String := "data-width";
FB_ACTION_ATTR : aliased constant String := "data-action";
FB_FONT_ATTR : aliased constant String := "data-font";
FB_COlORSCHEME_ATTR : aliased constant String := "data-colorscheme";
FB_REF_ATTR : aliased constant String := "data-ref";
FB_KIDS_ATTR : aliased constant String := "data-kid_directed_site";
TW_VIA_ATTR : aliased constant String := "data-via";
TW_COUNT_ATTR : aliased constant String := "data-count";
TW_SIZE_ATTR : aliased constant String := "data-size";
FACEBOOK_ATTRIBUTE_NAMES : Util.Strings.String_Set.Set;
FACEBOOK_SCRIPT_ATTRIBUTE : constant String := "asf.widgets.facebook.script";
GOOGLE_ATTRIBUTE_NAMES : Util.Strings.String_Set.Set;
GOOGLE_SCRIPT_ATTRIBUTE : constant String := "asf.widgets.google.script";
TWEETER_ATTRIBUTE_NAMES : Util.Strings.String_Set.Set;
TWEETER_SCRIPT_ATTRIBUTE : constant String := "asf.widgets.tweeter.script";
type Like_Generator_Binding is record
Name : Util.Strings.Name_Access;
Generator : Like_Generator_Access;
end record;
type Like_Generator_Array is array (1 .. MAX_LIKE_GENERATOR) of Like_Generator_Binding;
FB_NAME : aliased constant String := "facebook";
FB_GENERATOR : aliased Facebook_Like_Generator;
G_NAME : aliased constant String := "google+";
G_GENERATOR : aliased Google_Like_Generator;
TWEETER_NAME : aliased constant String := "tweeter";
TWEETER_GENERATOR : aliased Tweeter_Like_Generator;
Generators : Like_Generator_Array := (1 => (FB_NAME'Access, FB_GENERATOR'Access),
2 => (G_NAME'Access, G_GENERATOR'Access),
3 => (TWEETER_NAME'Access, TWEETER_GENERATOR'Access),
others => (null, null));
-- ------------------------------
-- Render the facebook like button according to the component attributes.
-- ------------------------------
overriding
procedure Render_Like (Generator : in Facebook_Like_Generator;
UI : in UILike'Class;
Href : in String;
Context : in out ASF.Contexts.Faces.Faces_Context'Class) is
Writer : constant Contexts.Writer.Response_Writer_Access := Context.Get_Response_Writer;
Request : constant ASF.Requests.Request_Access := Context.Get_Request;
begin
if not Context.Is_Ajax_Request and then
Util.Beans.Objects.Is_Null (Request.Get_Attribute (FACEBOOK_SCRIPT_ATTRIBUTE)) then
Request.Set_Attribute (FACEBOOK_SCRIPT_ATTRIBUTE, Util.Beans.Objects.To_Object (True));
Writer.Queue_Script ("(function(d, s, id) { var js, fjs = d.getElementsByTagName(s)[0];"
& "if (d.getElementById(id)) return;"
& "js = d.createElement(s); js.id = id;"
& "js.src = ""//connect.facebook.net/");
Writer.Queue_Script (Util.Locales.To_String (Context.Get_Locale));
Writer.Queue_Script ("/all.js#xfbml=1&;appId=116337738505130");
Writer.Queue_Script (Generator.App_Id);
Writer.Queue_Script (""";fjs.parentNode.insertBefore(js, fjs);"
& "}(document, 'script', 'facebook-jssdk'));");
Writer.Start_Element ("div");
Writer.Write_Attribute ("id", "fb-root");
Writer.End_Element ("div");
end if;
Writer.Start_Element ("div");
Writer.Write_Attribute ("class", "fb-like");
Writer.Write_Attribute ("data-href", Href);
Writer.Write_Attribute ("data-send", "true");
UI.Render_Attributes (Context, FACEBOOK_ATTRIBUTE_NAMES, Writer);
Writer.End_Element ("div");
end Render_Like;
-- ------------------------------
-- Google like generator
-- ------------------------------
overriding
procedure Render_Like (Generator : in Google_Like_Generator;
UI : in UILike'Class;
Href : in String;
Context : in out ASF.Contexts.Faces.Faces_Context'Class) is
pragma Unreferenced (Generator);
Writer : constant Contexts.Writer.Response_Writer_Access := Context.Get_Response_Writer;
Request : constant ASF.Requests.Request_Access := Context.Get_Request;
begin
if not Context.Is_Ajax_Request and then
Util.Beans.Objects.Is_Null (Request.Get_Attribute (GOOGLE_SCRIPT_ATTRIBUTE)) then
Request.Set_Attribute (GOOGLE_SCRIPT_ATTRIBUTE, Util.Beans.Objects.To_Object (True));
Writer.Queue_Include_Script ("https://apis.google.com/js/plusone.js");
end if;
Writer.Start_Element ("div");
Writer.Write_Attribute ("class", "g-plusone");
Writer.Write_Attribute ("data-href", Href);
Writer.Write_Attribute ("data-send", "true");
UI.Render_Attributes (Context, GOOGLE_ATTRIBUTE_NAMES, Writer);
Writer.End_Element ("div");
end Render_Like;
overriding
procedure Render_Like (Generator : in Tweeter_Like_Generator;
UI : in UILike'Class;
Href : in String;
Context : in out ASF.Contexts.Faces.Faces_Context'Class) is
pragma Unreferenced (Generator);
Writer : constant Contexts.Writer.Response_Writer_Access := Context.Get_Response_Writer;
Request : constant ASF.Requests.Request_Access := Context.Get_Request;
Lang : constant String := Util.Locales.Get_ISO3_Language (Context.Get_Locale);
begin
if not Context.Is_Ajax_Request and then
Util.Beans.Objects.Is_Null (Request.Get_Attribute (TWEETER_SCRIPT_ATTRIBUTE)) then
Request.Set_Attribute (TWEETER_SCRIPT_ATTRIBUTE, Util.Beans.Objects.To_Object (True));
Writer.Queue_Script ("!function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0],"
& "p=/^http:/.test(d.location)?'http':'https';"
& "if(!d.getElementById(id)){js=d.createElement(s);js.id=id;"
& "js.src=p+'://platform.twitter.com/widgets.js';"
& "fjs.parentNode.insertBefore(js,fjs);}}"
& "(document, 'script', 'twitter-wjs');");
end if;
Writer.Start_Element ("a");
Writer.Write_Attribute ("href", "https://twitter.com/share");
Writer.Write_Attribute ("class", "twitter-share-button");
Writer.Write_Attribute ("data-url", Href);
Writer.Write_Attribute ("data-lang", Lang);
UI.Render_Attributes (Context, TWEETER_ATTRIBUTE_NAMES, Writer);
Writer.Write_Text ("Tweet");
Writer.End_Element ("a");
end Render_Like;
-- ------------------------------
-- Get the link to submit in the like action.
-- ------------------------------
function Get_Link (UI : in UILike;
Context : in ASF.Contexts.Faces.Faces_Context'Class) return String is
Href : constant String := UI.Get_Attribute ("href", Context, "");
begin
if Href'Length > 0 then
return Href;
else
return Context.Get_Request.Get_Request_URI;
end if;
end Get_Link;
-- ------------------------------
-- Render an image with the source link created from an email address to the Gravatars service.
-- ------------------------------
overriding
procedure Encode_Begin (UI : in UILike;
Context : in out ASF.Contexts.Faces.Faces_Context'Class) is
begin
if UI.Is_Rendered (Context) then
declare
Kind : constant String := UI.Get_Attribute ("type", Context, "");
Href : constant String := UILike'Class (UI).Get_Link (Context);
procedure Render (Name : in String; Done : out Boolean);
procedure Render (Name : in String;
Done : out Boolean) is
use type Util.Strings.Name_Access;
begin
Done := False;
for I in Generators'Range loop
exit when Generators (I).Name = null;
if Generators (I).Name.all = Name then
Generators (I).Generator.Render_Like (UI, Href, Context);
return;
end if;
end loop;
UI.Log_Error ("Like type {0} is not recognized", Name);
end Render;
begin
if Kind'Length = 0 then
UI.Log_Error ("The like type is empty.");
else
Util.Strings.Tokenizers.Iterate_Tokens (Content => Kind, Pattern => ",",
Process => Render'Access);
end if;
end;
end if;
end Encode_Begin;
-- ------------------------------
-- Register the like generator under the given name.
-- ------------------------------
procedure Register_Like (Name : in Util.Strings.Name_Access;
Generator : in Like_Generator_Access) is
use type Util.Strings.Name_Access;
begin
for I in Generators'Range loop
if Generators (I).Name = null then
Generators (I).Name := Name;
Generators (I).Generator := Generator;
return;
end if;
end loop;
end Register_Like;
begin
FACEBOOK_ATTRIBUTE_NAMES.Insert (FB_LAYOUT_ATTR'Access);
FACEBOOK_ATTRIBUTE_NAMES.Insert (FB_SHOW_FACES_ATTR'Access);
FACEBOOK_ATTRIBUTE_NAMES.Insert (FB_WIDTH_ATTR'Access);
FACEBOOK_ATTRIBUTE_NAMES.Insert (FB_ACTION_ATTR'Access);
FACEBOOK_ATTRIBUTE_NAMES.Insert (FB_FONT_ATTR'Access);
FACEBOOK_ATTRIBUTE_NAMES.Insert (FB_COlORSCHEME_ATTR'Access);
FACEBOOK_ATTRIBUTE_NAMES.Insert (FB_REF_ATTR'Access);
FACEBOOK_ATTRIBUTE_NAMES.Insert (FB_KIDS_ATTR'Access);
TWEETER_ATTRIBUTE_NAMES.Insert (TW_SIZE_ATTR'Access);
TWEETER_ATTRIBUTE_NAMES.Insert (TW_COUNT_ATTR'Access);
TWEETER_ATTRIBUTE_NAMES.Insert (TW_VIA_ATTR'Access);
end ASF.Components.Widgets.Likes;
|
-----------------------------------------------------------------------
-- components-widgets-likes -- Social Likes Components
-- Copyright (C) 2013 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Locales;
with Util.Beans.Objects;
with Util.Strings.Tokenizers;
with ASF.Requests;
with ASF.Contexts.Writer;
package body ASF.Components.Widgets.Likes is
FB_LAYOUT_ATTR : aliased constant String := "data-layout";
FB_SHOW_FACES_ATTR : aliased constant String := "data-show-faces";
FB_WIDTH_ATTR : aliased constant String := "data-width";
FB_ACTION_ATTR : aliased constant String := "data-action";
FB_FONT_ATTR : aliased constant String := "data-font";
FB_COlORSCHEME_ATTR : aliased constant String := "data-colorscheme";
FB_REF_ATTR : aliased constant String := "data-ref";
FB_KIDS_ATTR : aliased constant String := "data-kid_directed_site";
FB_SEND_ATTR : aliased constant String := "data-send";
TW_VIA_ATTR : aliased constant String := "data-via";
TW_COUNT_ATTR : aliased constant String := "data-count";
TW_SIZE_ATTR : aliased constant String := "data-size";
G_ANNOTATION_ATTR : aliased constant String := "data-annotation";
G_WIDTH_ATTR : aliased constant String := "data-width";
FACEBOOK_ATTRIBUTE_NAMES : Util.Strings.String_Set.Set;
FACEBOOK_SCRIPT_ATTRIBUTE : constant String := "asf.widgets.facebook.script";
GOOGLE_ATTRIBUTE_NAMES : Util.Strings.String_Set.Set;
GOOGLE_SCRIPT_ATTRIBUTE : constant String := "asf.widgets.google.script";
TWEETER_ATTRIBUTE_NAMES : Util.Strings.String_Set.Set;
TWEETER_SCRIPT_ATTRIBUTE : constant String := "asf.widgets.tweeter.script";
type Like_Generator_Binding is record
Name : Util.Strings.Name_Access;
Generator : Like_Generator_Access;
end record;
type Like_Generator_Array is array (1 .. MAX_LIKE_GENERATOR) of Like_Generator_Binding;
FB_NAME : aliased constant String := "facebook";
FB_GENERATOR : aliased Facebook_Like_Generator;
G_NAME : aliased constant String := "google+";
G_GENERATOR : aliased Google_Like_Generator;
TWEETER_NAME : aliased constant String := "tweeter";
TWEETER_GENERATOR : aliased Tweeter_Like_Generator;
Generators : Like_Generator_Array := (1 => (FB_NAME'Access, FB_GENERATOR'Access),
2 => (G_NAME'Access, G_GENERATOR'Access),
3 => (TWEETER_NAME'Access, TWEETER_GENERATOR'Access),
others => (null, null));
-- ------------------------------
-- Render the facebook like button according to the component attributes.
-- ------------------------------
overriding
procedure Render_Like (Generator : in Facebook_Like_Generator;
UI : in UILike'Class;
Href : in String;
Context : in out ASF.Contexts.Faces.Faces_Context'Class) is
Writer : constant Contexts.Writer.Response_Writer_Access := Context.Get_Response_Writer;
Request : constant ASF.Requests.Request_Access := Context.Get_Request;
begin
if not Context.Is_Ajax_Request and then
Util.Beans.Objects.Is_Null (Request.Get_Attribute (FACEBOOK_SCRIPT_ATTRIBUTE)) then
Request.Set_Attribute (FACEBOOK_SCRIPT_ATTRIBUTE, Util.Beans.Objects.To_Object (True));
Writer.Queue_Script ("(function(d, s, id) { var js, fjs = d.getElementsByTagName(s)[0];"
& "if (d.getElementById(id)) return;"
& "js = d.createElement(s); js.id = id;"
& "js.src = ""//connect.facebook.net/");
Writer.Queue_Script (Util.Locales.To_String (Context.Get_Locale));
Writer.Queue_Script ("/all.js#xfbml=1&;appId=116337738505130");
Writer.Queue_Script (Generator.App_Id);
Writer.Queue_Script (""";fjs.parentNode.insertBefore(js, fjs);"
& "}(document, 'script', 'facebook-jssdk'));");
Writer.Start_Element ("div");
Writer.Write_Attribute ("id", "fb-root");
Writer.End_Element ("div");
end if;
Writer.Start_Element ("div");
Writer.Write_Attribute ("class", "fb-like");
Writer.Write_Attribute ("data-href", Href);
UI.Render_Attributes (Context, FACEBOOK_ATTRIBUTE_NAMES, Writer);
Writer.End_Element ("div");
end Render_Like;
-- ------------------------------
-- Google like generator
-- ------------------------------
overriding
procedure Render_Like (Generator : in Google_Like_Generator;
UI : in UILike'Class;
Href : in String;
Context : in out ASF.Contexts.Faces.Faces_Context'Class) is
pragma Unreferenced (Generator);
Writer : constant Contexts.Writer.Response_Writer_Access := Context.Get_Response_Writer;
Request : constant ASF.Requests.Request_Access := Context.Get_Request;
begin
if not Context.Is_Ajax_Request and then
Util.Beans.Objects.Is_Null (Request.Get_Attribute (GOOGLE_SCRIPT_ATTRIBUTE)) then
Request.Set_Attribute (GOOGLE_SCRIPT_ATTRIBUTE, Util.Beans.Objects.To_Object (True));
Writer.Queue_Include_Script ("https://apis.google.com/js/plusone.js");
end if;
Writer.Start_Element ("div");
Writer.Write_Attribute ("class", "g-plusone");
Writer.Write_Attribute ("data-href", Href);
UI.Render_Attributes (Context, GOOGLE_ATTRIBUTE_NAMES, Writer);
Writer.End_Element ("div");
end Render_Like;
-- ------------------------------
-- Tweeter like generator
-- ------------------------------
overriding
procedure Render_Like (Generator : in Tweeter_Like_Generator;
UI : in UILike'Class;
Href : in String;
Context : in out ASF.Contexts.Faces.Faces_Context'Class) is
pragma Unreferenced (Generator);
Writer : constant Contexts.Writer.Response_Writer_Access := Context.Get_Response_Writer;
Request : constant ASF.Requests.Request_Access := Context.Get_Request;
Lang : constant String := Util.Locales.Get_ISO3_Language (Context.Get_Locale);
begin
if not Context.Is_Ajax_Request and then
Util.Beans.Objects.Is_Null (Request.Get_Attribute (TWEETER_SCRIPT_ATTRIBUTE)) then
Request.Set_Attribute (TWEETER_SCRIPT_ATTRIBUTE, Util.Beans.Objects.To_Object (True));
Writer.Queue_Script ("!function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0],"
& "p=/^http:/.test(d.location)?'http':'https';"
& "if(!d.getElementById(id)){js=d.createElement(s);js.id=id;"
& "js.src=p+'://platform.twitter.com/widgets.js';"
& "fjs.parentNode.insertBefore(js,fjs);}}"
& "(document, 'script', 'twitter-wjs');");
end if;
Writer.Start_Element ("a");
Writer.Write_Attribute ("href", "https://twitter.com/share");
Writer.Write_Attribute ("class", "twitter-share-button");
Writer.Write_Attribute ("data-url", Href);
Writer.Write_Attribute ("data-lang", Lang);
UI.Render_Attributes (Context, TWEETER_ATTRIBUTE_NAMES, Writer);
Writer.Write_Text ("Tweet");
Writer.End_Element ("a");
end Render_Like;
-- ------------------------------
-- Get the link to submit in the like action.
-- ------------------------------
function Get_Link (UI : in UILike;
Context : in ASF.Contexts.Faces.Faces_Context'Class) return String is
Href : constant String := UI.Get_Attribute ("href", Context, "");
begin
if Href'Length > 0 then
return Href;
else
return Context.Get_Request.Get_Request_URI;
end if;
end Get_Link;
-- ------------------------------
-- Render an image with the source link created from an email address to the Gravatars service.
-- ------------------------------
overriding
procedure Encode_Begin (UI : in UILike;
Context : in out ASF.Contexts.Faces.Faces_Context'Class) is
begin
if UI.Is_Rendered (Context) then
declare
Kind : constant String := UI.Get_Attribute ("type", Context, "");
Href : constant String := UILike'Class (UI).Get_Link (Context);
procedure Render (Name : in String; Done : out Boolean);
procedure Render (Name : in String;
Done : out Boolean) is
use type Util.Strings.Name_Access;
begin
Done := False;
for I in Generators'Range loop
exit when Generators (I).Name = null;
if Generators (I).Name.all = Name then
Generators (I).Generator.Render_Like (UI, Href, Context);
return;
end if;
end loop;
UI.Log_Error ("Like type {0} is not recognized", Name);
end Render;
begin
if Kind'Length = 0 then
UI.Log_Error ("The like type is empty.");
else
Util.Strings.Tokenizers.Iterate_Tokens (Content => Kind, Pattern => ",",
Process => Render'Access);
end if;
end;
end if;
end Encode_Begin;
-- ------------------------------
-- Register the like generator under the given name.
-- ------------------------------
procedure Register_Like (Name : in Util.Strings.Name_Access;
Generator : in Like_Generator_Access) is
use type Util.Strings.Name_Access;
begin
for I in Generators'Range loop
if Generators (I).Name = null then
Generators (I).Name := Name;
Generators (I).Generator := Generator;
return;
end if;
end loop;
end Register_Like;
begin
FACEBOOK_ATTRIBUTE_NAMES.Insert (FB_LAYOUT_ATTR'Access);
FACEBOOK_ATTRIBUTE_NAMES.Insert (FB_SHOW_FACES_ATTR'Access);
FACEBOOK_ATTRIBUTE_NAMES.Insert (FB_WIDTH_ATTR'Access);
FACEBOOK_ATTRIBUTE_NAMES.Insert (FB_ACTION_ATTR'Access);
FACEBOOK_ATTRIBUTE_NAMES.Insert (FB_FONT_ATTR'Access);
FACEBOOK_ATTRIBUTE_NAMES.Insert (FB_COlORSCHEME_ATTR'Access);
FACEBOOK_ATTRIBUTE_NAMES.Insert (FB_REF_ATTR'Access);
FACEBOOK_ATTRIBUTE_NAMES.Insert (FB_KIDS_ATTR'Access);
FACEBOOK_ATTRIBUTE_NAMES.Insert (FB_SEND_ATTR'Access);
TWEETER_ATTRIBUTE_NAMES.Insert (TW_SIZE_ATTR'Access);
TWEETER_ATTRIBUTE_NAMES.Insert (TW_COUNT_ATTR'Access);
TWEETER_ATTRIBUTE_NAMES.Insert (TW_VIA_ATTR'Access);
GOOGLE_ATTRIBUTE_NAMES.Insert (G_ANNOTATION_ATTR'Access);
GOOGLE_ATTRIBUTE_NAMES.Insert (G_WIDTH_ATTR'Access);
end ASF.Components.Widgets.Likes;
|
Add control attributes for Google+ and Facebook buttons
|
Add control attributes for Google+ and Facebook buttons
|
Ada
|
apache-2.0
|
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
|
f620708032d414c11d33de8be7cfdaf42ccc4314
|
src/asf-components-widgets-likes.adb
|
src/asf-components-widgets-likes.adb
|
-----------------------------------------------------------------------
-- components-widgets-likes -- Social Likes Components
-- Copyright (C) 2013 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Locales;
with Util.Beans.Objects;
with Util.Strings.Tokenizers;
with ASF.Requests;
with ASF.Contexts.Writer;
package body ASF.Components.Widgets.Likes is
FB_LAYOUT_ATTR : aliased constant String := "data-layout";
FB_SHOW_FACES_ATTR : aliased constant String := "data-show-faces";
FB_WIDTH_ATTR : aliased constant String := "data-width";
FB_ACTION_ATTR : aliased constant String := "data-action";
FB_FONT_ATTR : aliased constant String := "data-font";
FB_COlORSCHEME_ATTR : aliased constant String := "data-colorscheme";
FB_REF_ATTR : aliased constant String := "data-ref";
FB_KIDS_ATTR : aliased constant String := "data-kid_directed_site";
FACEBOOK_ATTRIBUTE_NAMES : Util.Strings.String_Set.Set;
FACEBOOK_SCRIPT_ATTRIBUTE : constant String := "asf.widgets.facebook.script";
GOOGLE_ATTRIBUTE_NAMES : Util.Strings.String_Set.Set;
GOOGLE_SCRIPT_ATTRIBUTE : constant String := "asf.widgets.google.script";
type Like_Generator_Binding is record
Name : Util.Strings.Name_Access;
Generator : Like_Generator_Access;
end record;
type Like_Generator_Array is array (1 .. MAX_LIKE_GENERATOR) of Like_Generator_Binding;
FB_NAME : aliased constant String := "facebook";
FB_GENERATOR : aliased Facebook_Like_Generator;
G_NAME : aliased constant String := "google+";
G_GENERATOR : aliased Google_Like_Generator;
Generators : Like_Generator_Array := (1 => (FB_NAME'Access, FB_GENERATOR'Access),
2 => (G_NAME'Access, G_GENERATOR'Access),
others => (null, null));
-- ------------------------------
-- Render the facebook like button according to the component attributes.
-- ------------------------------
overriding
procedure Render_Like (Generator : in Facebook_Like_Generator;
UI : in UILike'Class;
Href : in String;
Context : in out ASF.Contexts.Faces.Faces_Context'Class) is
Writer : constant Contexts.Writer.Response_Writer_Access := Context.Get_Response_Writer;
Request : constant ASF.Requests.Request_Access := Context.Get_Request;
begin
if not Context.Is_Ajax_Request and then
Util.Beans.Objects.Is_Null (Request.Get_Attribute (FACEBOOK_SCRIPT_ATTRIBUTE)) then
Request.Set_Attribute (FACEBOOK_SCRIPT_ATTRIBUTE, Util.Beans.Objects.To_Object (True));
Writer.Queue_Script ("(function(d, s, id) { var js, fjs = d.getElementsByTagName(s)[0];"
& "if (d.getElementById(id)) return;"
& "js = d.createElement(s); js.id = id;"
& "js.src = ""//connect.facebook.net/");
Writer.Queue_Script (Util.Locales.To_String (Context.Get_Locale));
Writer.Queue_Script ("/all.js#xfbml=1&;appId=116337738505130");
Writer.Queue_Script (Generator.App_Id);
Writer.Queue_Script (""";fjs.parentNode.insertBefore(js, fjs);"
& "}(document, 'script', 'facebook-jssdk'));");
Writer.Start_Element ("div");
Writer.Write_Attribute ("id", "fb-root");
Writer.End_Element ("div");
end if;
Writer.Start_Element ("div");
Writer.Write_Attribute ("class", "fb-like");
Writer.Write_Attribute ("data-href", Href);
Writer.Write_Attribute ("data-send", "true");
UI.Render_Attributes (Context, FACEBOOK_ATTRIBUTE_NAMES, Writer);
Writer.End_Element ("div");
end Render_Like;
-- ------------------------------
-- Google like generator
-- ------------------------------
overriding
procedure Render_Like (Generator : in Google_Like_Generator;
UI : in UILike'Class;
Href : in String;
Context : in out ASF.Contexts.Faces.Faces_Context'Class) is
pragma Unreferenced (Generator);
Writer : constant Contexts.Writer.Response_Writer_Access := Context.Get_Response_Writer;
Request : constant ASF.Requests.Request_Access := Context.Get_Request;
begin
if not Context.Is_Ajax_Request and then
Util.Beans.Objects.Is_Null (Request.Get_Attribute (GOOGLE_SCRIPT_ATTRIBUTE)) then
Request.Set_Attribute (GOOGLE_SCRIPT_ATTRIBUTE, Util.Beans.Objects.To_Object (True));
Writer.Queue_Include_Script ("https://apis.google.com/js/plusone.js");
end if;
Writer.Start_Element ("div");
Writer.Write_Attribute ("class", "g-plusone");
Writer.Write_Attribute ("data-href", Href);
Writer.Write_Attribute ("data-send", "true");
UI.Render_Attributes (Context, GOOGLE_ATTRIBUTE_NAMES, Writer);
Writer.End_Element ("div");
end Render_Like;
-- ------------------------------
-- Get the link to submit in the like action.
-- ------------------------------
function Get_Link (UI : in UILike;
Context : in ASF.Contexts.Faces.Faces_Context'Class) return String is
Href : constant String := UI.Get_Attribute ("href", Context, "");
begin
if Href'Length > 0 then
return Href;
else
return Context.Get_Request.Get_Request_URI;
end if;
end Get_Link;
-- ------------------------------
-- Render an image with the source link created from an email address to the Gravatars service.
-- ------------------------------
overriding
procedure Encode_Begin (UI : in UILike;
Context : in out ASF.Contexts.Faces.Faces_Context'Class) is
begin
if UI.Is_Rendered (Context) then
declare
Kind : constant String := UI.Get_Attribute ("type", Context, "");
Href : constant String := UILike'Class (UI).Get_Link (Context);
procedure Render (Name : in String; Done : out Boolean);
procedure Render (Name : in String;
Done : out Boolean) is
use type Util.Strings.Name_Access;
begin
Done := False;
for I in Generators'Range loop
exit when Generators (I).Name = null;
if Generators (I).Name.all = Name then
Generators (I).Generator.Render_Like (UI, Href, Context);
return;
end if;
end loop;
UI.Log_Error ("Like type {0} is not recognized", Name);
end Render;
begin
if Kind'Length = 0 then
UI.Log_Error ("The like type is empty.");
else
Util.Strings.Tokenizers.Iterate_Tokens (Content => Kind, Pattern => ",",
Process => Render'Access);
end if;
end;
end if;
end Encode_Begin;
-- ------------------------------
-- Register the like generator under the given name.
-- ------------------------------
procedure Register_Like (Name : in Util.Strings.Name_Access;
Generator : in Like_Generator_Access) is
use type Util.Strings.Name_Access;
begin
for I in Generators'Range loop
if Generators (I).Name = null then
Generators (I).Name := Name;
Generators (I).Generator := Generator;
return;
end if;
end loop;
end Register_Like;
begin
FACEBOOK_ATTRIBUTE_NAMES.Insert (FB_LAYOUT_ATTR'Access);
FACEBOOK_ATTRIBUTE_NAMES.Insert (FB_SHOW_FACES_ATTR'Access);
FACEBOOK_ATTRIBUTE_NAMES.Insert (FB_WIDTH_ATTR'Access);
FACEBOOK_ATTRIBUTE_NAMES.Insert (FB_ACTION_ATTR'Access);
FACEBOOK_ATTRIBUTE_NAMES.Insert (FB_FONT_ATTR'Access);
FACEBOOK_ATTRIBUTE_NAMES.Insert (FB_COlORSCHEME_ATTR'Access);
FACEBOOK_ATTRIBUTE_NAMES.Insert (FB_REF_ATTR'Access);
FACEBOOK_ATTRIBUTE_NAMES.Insert (FB_KIDS_ATTR'Access);
end ASF.Components.Widgets.Likes;
|
-----------------------------------------------------------------------
-- components-widgets-likes -- Social Likes Components
-- Copyright (C) 2013 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Locales;
with Util.Beans.Objects;
with Util.Strings.Tokenizers;
with ASF.Requests;
with ASF.Contexts.Writer;
package body ASF.Components.Widgets.Likes is
FB_LAYOUT_ATTR : aliased constant String := "data-layout";
FB_SHOW_FACES_ATTR : aliased constant String := "data-show-faces";
FB_WIDTH_ATTR : aliased constant String := "data-width";
FB_ACTION_ATTR : aliased constant String := "data-action";
FB_FONT_ATTR : aliased constant String := "data-font";
FB_COlORSCHEME_ATTR : aliased constant String := "data-colorscheme";
FB_REF_ATTR : aliased constant String := "data-ref";
FB_KIDS_ATTR : aliased constant String := "data-kid_directed_site";
TW_VIA_ATTR : aliased constant String := "data-via";
TW_COUNT_ATTR : aliased constant String := "data-count";
TW_SIZE_ATTR : aliased constant String := "data-size";
FACEBOOK_ATTRIBUTE_NAMES : Util.Strings.String_Set.Set;
FACEBOOK_SCRIPT_ATTRIBUTE : constant String := "asf.widgets.facebook.script";
GOOGLE_ATTRIBUTE_NAMES : Util.Strings.String_Set.Set;
GOOGLE_SCRIPT_ATTRIBUTE : constant String := "asf.widgets.google.script";
TWEETER_ATTRIBUTE_NAMES : Util.Strings.String_Set.Set;
TWEETER_SCRIPT_ATTRIBUTE : constant String := "asf.widgets.tweeter.script";
type Like_Generator_Binding is record
Name : Util.Strings.Name_Access;
Generator : Like_Generator_Access;
end record;
type Like_Generator_Array is array (1 .. MAX_LIKE_GENERATOR) of Like_Generator_Binding;
FB_NAME : aliased constant String := "facebook";
FB_GENERATOR : aliased Facebook_Like_Generator;
G_NAME : aliased constant String := "google+";
G_GENERATOR : aliased Google_Like_Generator;
TWEETER_NAME : aliased constant String := "tweeter";
TWEETER_GENERATOR : aliased Tweeter_Like_Generator;
Generators : Like_Generator_Array := (1 => (FB_NAME'Access, FB_GENERATOR'Access),
2 => (G_NAME'Access, G_GENERATOR'Access),
3 => (TWEETER_NAME'Access, TWEETER_GENERATOR'Access),
others => (null, null));
-- ------------------------------
-- Render the facebook like button according to the component attributes.
-- ------------------------------
overriding
procedure Render_Like (Generator : in Facebook_Like_Generator;
UI : in UILike'Class;
Href : in String;
Context : in out ASF.Contexts.Faces.Faces_Context'Class) is
Writer : constant Contexts.Writer.Response_Writer_Access := Context.Get_Response_Writer;
Request : constant ASF.Requests.Request_Access := Context.Get_Request;
begin
if not Context.Is_Ajax_Request and then
Util.Beans.Objects.Is_Null (Request.Get_Attribute (FACEBOOK_SCRIPT_ATTRIBUTE)) then
Request.Set_Attribute (FACEBOOK_SCRIPT_ATTRIBUTE, Util.Beans.Objects.To_Object (True));
Writer.Queue_Script ("(function(d, s, id) { var js, fjs = d.getElementsByTagName(s)[0];"
& "if (d.getElementById(id)) return;"
& "js = d.createElement(s); js.id = id;"
& "js.src = ""//connect.facebook.net/");
Writer.Queue_Script (Util.Locales.To_String (Context.Get_Locale));
Writer.Queue_Script ("/all.js#xfbml=1&;appId=116337738505130");
Writer.Queue_Script (Generator.App_Id);
Writer.Queue_Script (""";fjs.parentNode.insertBefore(js, fjs);"
& "}(document, 'script', 'facebook-jssdk'));");
Writer.Start_Element ("div");
Writer.Write_Attribute ("id", "fb-root");
Writer.End_Element ("div");
end if;
Writer.Start_Element ("div");
Writer.Write_Attribute ("class", "fb-like");
Writer.Write_Attribute ("data-href", Href);
Writer.Write_Attribute ("data-send", "true");
UI.Render_Attributes (Context, FACEBOOK_ATTRIBUTE_NAMES, Writer);
Writer.End_Element ("div");
end Render_Like;
-- ------------------------------
-- Google like generator
-- ------------------------------
overriding
procedure Render_Like (Generator : in Google_Like_Generator;
UI : in UILike'Class;
Href : in String;
Context : in out ASF.Contexts.Faces.Faces_Context'Class) is
pragma Unreferenced (Generator);
Writer : constant Contexts.Writer.Response_Writer_Access := Context.Get_Response_Writer;
Request : constant ASF.Requests.Request_Access := Context.Get_Request;
begin
if not Context.Is_Ajax_Request and then
Util.Beans.Objects.Is_Null (Request.Get_Attribute (GOOGLE_SCRIPT_ATTRIBUTE)) then
Request.Set_Attribute (GOOGLE_SCRIPT_ATTRIBUTE, Util.Beans.Objects.To_Object (True));
Writer.Queue_Include_Script ("https://apis.google.com/js/plusone.js");
end if;
Writer.Start_Element ("div");
Writer.Write_Attribute ("class", "g-plusone");
Writer.Write_Attribute ("data-href", Href);
Writer.Write_Attribute ("data-send", "true");
UI.Render_Attributes (Context, GOOGLE_ATTRIBUTE_NAMES, Writer);
Writer.End_Element ("div");
end Render_Like;
overriding
procedure Render_Like (Generator : in Tweeter_Like_Generator;
UI : in UILike'Class;
Href : in String;
Context : in out ASF.Contexts.Faces.Faces_Context'Class) is
pragma Unreferenced (Generator);
Writer : constant Contexts.Writer.Response_Writer_Access := Context.Get_Response_Writer;
Request : constant ASF.Requests.Request_Access := Context.Get_Request;
Lang : constant String := Util.Locales.Get_ISO3_Language (Context.Get_Locale);
begin
if not Context.Is_Ajax_Request and then
Util.Beans.Objects.Is_Null (Request.Get_Attribute (TWEETER_SCRIPT_ATTRIBUTE)) then
Request.Set_Attribute (TWEETER_SCRIPT_ATTRIBUTE, Util.Beans.Objects.To_Object (True));
Writer.Queue_Script ("!function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0],"
& "p=/^http:/.test(d.location)?'http':'https';"
& "if(!d.getElementById(id)){js=d.createElement(s);js.id=id;"
& "js.src=p+'://platform.twitter.com/widgets.js';"
& "fjs.parentNode.insertBefore(js,fjs);}}"
& "(document, 'script', 'twitter-wjs');");
end if;
Writer.Start_Element ("a");
Writer.Write_Attribute ("href", "https://twitter.com/share");
Writer.Write_Attribute ("class", "twitter-share-button");
Writer.Write_Attribute ("data-url", Href);
Writer.Write_Attribute ("data-lang", Lang);
UI.Render_Attributes (Context, TWEETER_ATTRIBUTE_NAMES, Writer);
Writer.Write_Text ("Tweet");
Writer.End_Element ("a");
end Render_Like;
-- ------------------------------
-- Get the link to submit in the like action.
-- ------------------------------
function Get_Link (UI : in UILike;
Context : in ASF.Contexts.Faces.Faces_Context'Class) return String is
Href : constant String := UI.Get_Attribute ("href", Context, "");
begin
if Href'Length > 0 then
return Href;
else
return Context.Get_Request.Get_Request_URI;
end if;
end Get_Link;
-- ------------------------------
-- Render an image with the source link created from an email address to the Gravatars service.
-- ------------------------------
overriding
procedure Encode_Begin (UI : in UILike;
Context : in out ASF.Contexts.Faces.Faces_Context'Class) is
begin
if UI.Is_Rendered (Context) then
declare
Kind : constant String := UI.Get_Attribute ("type", Context, "");
Href : constant String := UILike'Class (UI).Get_Link (Context);
procedure Render (Name : in String; Done : out Boolean);
procedure Render (Name : in String;
Done : out Boolean) is
use type Util.Strings.Name_Access;
begin
Done := False;
for I in Generators'Range loop
exit when Generators (I).Name = null;
if Generators (I).Name.all = Name then
Generators (I).Generator.Render_Like (UI, Href, Context);
return;
end if;
end loop;
UI.Log_Error ("Like type {0} is not recognized", Name);
end Render;
begin
if Kind'Length = 0 then
UI.Log_Error ("The like type is empty.");
else
Util.Strings.Tokenizers.Iterate_Tokens (Content => Kind, Pattern => ",",
Process => Render'Access);
end if;
end;
end if;
end Encode_Begin;
-- ------------------------------
-- Register the like generator under the given name.
-- ------------------------------
procedure Register_Like (Name : in Util.Strings.Name_Access;
Generator : in Like_Generator_Access) is
use type Util.Strings.Name_Access;
begin
for I in Generators'Range loop
if Generators (I).Name = null then
Generators (I).Name := Name;
Generators (I).Generator := Generator;
return;
end if;
end loop;
end Register_Like;
begin
FACEBOOK_ATTRIBUTE_NAMES.Insert (FB_LAYOUT_ATTR'Access);
FACEBOOK_ATTRIBUTE_NAMES.Insert (FB_SHOW_FACES_ATTR'Access);
FACEBOOK_ATTRIBUTE_NAMES.Insert (FB_WIDTH_ATTR'Access);
FACEBOOK_ATTRIBUTE_NAMES.Insert (FB_ACTION_ATTR'Access);
FACEBOOK_ATTRIBUTE_NAMES.Insert (FB_FONT_ATTR'Access);
FACEBOOK_ATTRIBUTE_NAMES.Insert (FB_COlORSCHEME_ATTR'Access);
FACEBOOK_ATTRIBUTE_NAMES.Insert (FB_REF_ATTR'Access);
FACEBOOK_ATTRIBUTE_NAMES.Insert (FB_KIDS_ATTR'Access);
TWEETER_ATTRIBUTE_NAMES.Insert (TW_SIZE_ATTR'Access);
TWEETER_ATTRIBUTE_NAMES.Insert (TW_COUNT_ATTR'Access);
TWEETER_ATTRIBUTE_NAMES.Insert (TW_VIA_ATTR'Access);
end ASF.Components.Widgets.Likes;
|
Implement the Tweeter like generator
|
Implement the Tweeter like generator
|
Ada
|
apache-2.0
|
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
|
4991ccfac1fe1138e375df49d9fe16fb25d103ac
|
src/security-policies-urls.adb
|
src/security-policies-urls.adb
|
-----------------------------------------------------------------------
-- security-policies-urls -- URL security policy
-- Copyright (C) 2010, 2011, 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Unchecked_Deallocation;
with Ada.Strings.Unbounded;
with Util.Refs;
with Util.Beans.Objects;
with Util.Beans.Objects.Vectors;
with Util.Serialize.Mappers;
with Util.Serialize.Mappers.Record_Mapper;
with GNAT.Regexp;
with Security.Controllers;
package body Security.Policies.Urls is
-- ------------------------------
-- URL policy
-- ------------------------------
-- ------------------------------
-- Get the policy name.
-- ------------------------------
overriding
function Get_Name (From : in URL_Policy) return String is
pragma Unreferenced (From);
begin
return NAME;
end Get_Name;
-- Returns True if the user has the permission to access the given URI permission.
function Has_Permission (Manager : in URL_Policy;
Context : in Security_Context_Access;
Permission : in URI_Permission'Class) return Boolean is
Name : constant String_Ref := To_String_Ref (Permission.URI);
Ref : constant Rules_Ref.Ref := Manager.Cache.Get;
Rules : constant Rules_Access := Ref.Value;
Pos : constant Rules_Maps.Cursor := Rules.Map.Find (Name);
Rule : Access_Rule_Ref;
begin
-- If the rule is not in the cache, search for the access rule that
-- matches our URI. Update the cache. This cache update is thread-safe
-- as the cache map is never modified: a new cache map is installed.
if not Rules_Maps.Has_Element (Pos) then
declare
New_Ref : constant Rules_Ref.Ref := Rules_Ref.Create;
begin
Rule := Manager.Find_Access_Rule (Permission.URI);
New_Ref.Value.all.Map := Rules.Map;
New_Ref.Value.all.Map.Insert (Name, Rule);
Manager.Cache.Set (New_Ref);
end;
else
Rule := Rules_Maps.Element (Pos);
end if;
-- Check if the user has one of the required permission.
declare
P : constant Access_Rule_Access := Rule.Value;
Granted : Boolean;
begin
if P /= null then
for I in P.Permissions'Range loop
-- Context.Has_Permission (P.Permissions (I), Granted);
if Granted then
return True;
end if;
end loop;
end if;
end;
return False;
end Has_Permission;
-- Grant the permission to access to the given <b>URI</b> to users having the <b>To</b>
-- permissions.
procedure Grant_URI_Permission (Manager : in out URL_Policy;
URI : in String;
To : in String) is
begin
null;
end Grant_URI_Permission;
-- ------------------------------
-- Policy Configuration
-- ------------------------------
type Policy_Config is record
Id : Natural := 0;
Permissions : Util.Beans.Objects.Vectors.Vector;
Patterns : Util.Beans.Objects.Vectors.Vector;
Manager : URL_Policy_Access;
end record;
type Policy_Config_Access is access all Policy_Config;
-- Setup the XML parser to read the <b>policy</b> description. For example:
-- Find the access rule of the policy that matches the given URI.
-- Returns the No_Rule value (disable access) if no rule is found.
function Find_Access_Rule (Manager : in URL_Policy;
URI : in String) return Access_Rule_Ref is
Matched : Boolean := False;
Result : Access_Rule_Ref;
procedure Match (P : in Policy);
procedure Match (P : in Policy) is
begin
if GNAT.Regexp.Match (URI, P.Pattern) then
Matched := True;
Result := P.Rule;
end if;
end Match;
Last : constant Natural := Manager.Policies.Last_Index;
begin
for I in 1 .. Last loop
Manager.Policies.Query_Element (I, Match'Access);
if Matched then
return Result;
end if;
end loop;
return Result;
end Find_Access_Rule;
-- ------------------------------
-- Initialize the permission manager.
-- ------------------------------
overriding
procedure Initialize (Manager : in out URL_Policy) is
begin
Manager.Cache := new Rules_Ref.Atomic_Ref;
Manager.Cache.Set (Rules_Ref.Create);
end Initialize;
-- ------------------------------
-- Finalize the permission manager.
-- ------------------------------
overriding
procedure Finalize (Manager : in out URL_Policy) is
use Ada.Strings.Unbounded;
use Security.Controllers;
procedure Free is
new Ada.Unchecked_Deallocation (Rules_Ref.Atomic_Ref,
Rules_Ref_Access);
procedure Free is
new Ada.Unchecked_Deallocation (Security.Controllers.Controller'Class,
Security.Controllers.Controller_Access);
procedure Free is
new Ada.Unchecked_Deallocation (Controller_Access_Array,
Controller_Access_Array_Access);
begin
Free (Manager.Cache);
-- for I in Manager.Names'Range loop
-- exit when Manager.Names (I) = null;
-- Ada.Strings.Unbounded.Free (Manager.Names (I));
-- end loop;
end Finalize;
type Policy_Fields is (FIELD_ID, FIELD_PERMISSION, FIELD_URL_PATTERN, FIELD_POLICY);
procedure Set_Member (P : in out Policy_Config;
Field : in Policy_Fields;
Value : in Util.Beans.Objects.Object);
procedure Process (Policy : in Policy_Config);
procedure Set_Member (P : in out Policy_Config;
Field : in Policy_Fields;
Value : in Util.Beans.Objects.Object) is
begin
case Field is
when FIELD_ID =>
P.Id := Util.Beans.Objects.To_Integer (Value);
when FIELD_PERMISSION =>
P.Permissions.Append (Value);
when FIELD_URL_PATTERN =>
P.Patterns.Append (Value);
when FIELD_POLICY =>
Process (P);
P.Id := 0;
P.Permissions.Clear;
P.Patterns.Clear;
end case;
end Set_Member;
procedure Process (Policy : in Policy_Config) is
Pol : Security.Policies.URLs.Policy;
Count : constant Natural := Natural (Policy.Permissions.Length);
Rule : constant Access_Rule_Ref := Access_Rule_Refs.Create (new Access_Rule (Count));
Iter : Util.Beans.Objects.Vectors.Cursor := Policy.Permissions.First;
Pos : Positive := 1;
begin
Pol.Rule := Rule;
-- Step 1: Initialize the list of permission index in Access_Rule from the permission names.
while Util.Beans.Objects.Vectors.Has_Element (Iter) loop
declare
Perm : constant Util.Beans.Objects.Object := Util.Beans.Objects.Vectors.Element (Iter);
Name : constant String := Util.Beans.Objects.To_String (Perm);
begin
Rule.Value.all.Permissions (Pos) := Permissions.Get_Permission_Index (Name);
Pos := Pos + 1;
exception
when Invalid_Name =>
raise Util.Serialize.Mappers.Field_Error with "Invalid permission: " & Name;
end;
Util.Beans.Objects.Vectors.Next (Iter);
end loop;
-- Step 2: Create one policy for each URL pattern
Iter := Policy.Patterns.First;
while Util.Beans.Objects.Vectors.Has_Element (Iter) loop
declare
Pattern : constant Util.Beans.Objects.Object
:= Util.Beans.Objects.Vectors.Element (Iter);
begin
Pol.Id := Policy.Id;
Pol.Pattern := GNAT.Regexp.Compile (Util.Beans.Objects.To_String (Pattern));
Policy.Manager.Policies.Append (Pol);
end;
Util.Beans.Objects.Vectors.Next (Iter);
end loop;
end Process;
package Policy_Mapper is
new Util.Serialize.Mappers.Record_Mapper (Element_Type => Policy_Config,
Element_Type_Access => Policy_Config_Access,
Fields => Policy_Fields,
Set_Member => Set_Member);
Policy_Mapping : aliased Policy_Mapper.Mapper;
-- ------------------------------
-- Setup the XML parser to read the <b>policy</b> description.
-- ------------------------------
overriding
procedure Prepare_Config (Policy : in out URL_Policy;
Reader : in out Util.Serialize.IO.XML.Parser) is
Config : Policy_Config_Access := new Policy_Config;
begin
Reader.Add_Mapping ("policy-rules", Policy_Mapping'Access);
Reader.Add_Mapping ("module", Policy_Mapping'Access);
Config.Manager := Policy'Unchecked_Access;
Policy_Mapper.Set_Context (Reader, Config);
end Prepare_Config;
-- ------------------------------
-- Finish reading the XML policy configuration. The security policy implementation can use
-- this procedure to perform any configuration setup after the configuration is parsed.
-- ------------------------------
overriding
procedure Finish_Config (Into : in out URL_Policy;
Reader : in out Util.Serialize.IO.XML.Parser) is
begin
null;
end Finish_Config;
begin
Policy_Mapping.Add_Mapping ("policy", FIELD_POLICY);
Policy_Mapping.Add_Mapping ("policy/@id", FIELD_ID);
Policy_Mapping.Add_Mapping ("policy/permission", FIELD_PERMISSION);
Policy_Mapping.Add_Mapping ("policy/url-pattern", FIELD_URL_PATTERN);
end Security.Policies.Urls;
|
-----------------------------------------------------------------------
-- security-policies-urls -- URL security policy
-- Copyright (C) 2010, 2011, 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Unchecked_Deallocation;
with Ada.Strings.Unbounded;
with Util.Refs;
with Util.Beans.Objects;
with Util.Beans.Objects.Vectors;
with Util.Serialize.Mappers;
with Util.Serialize.Mappers.Record_Mapper;
with GNAT.Regexp;
with Security.Controllers;
package body Security.Policies.Urls is
-- ------------------------------
-- URL policy
-- ------------------------------
-- ------------------------------
-- Get the policy name.
-- ------------------------------
overriding
function Get_Name (From : in URL_Policy) return String is
pragma Unreferenced (From);
begin
return NAME;
end Get_Name;
-- Returns True if the user has the permission to access the given URI permission.
function Has_Permission (Manager : in URL_Policy;
Context : in Security_Context_Access;
Permission : in URI_Permission'Class) return Boolean is
Name : constant String_Ref := To_String_Ref (Permission.URI);
Ref : constant Rules_Ref.Ref := Manager.Cache.Get;
Rules : constant Rules_Access := Ref.Value;
Pos : constant Rules_Maps.Cursor := Rules.Map.Find (Name);
Rule : Access_Rule_Ref;
begin
-- If the rule is not in the cache, search for the access rule that
-- matches our URI. Update the cache. This cache update is thread-safe
-- as the cache map is never modified: a new cache map is installed.
if not Rules_Maps.Has_Element (Pos) then
declare
New_Ref : constant Rules_Ref.Ref := Rules_Ref.Create;
begin
Rule := Manager.Find_Access_Rule (Permission.URI);
New_Ref.Value.all.Map := Rules.Map;
New_Ref.Value.all.Map.Insert (Name, Rule);
Manager.Cache.Set (New_Ref);
end;
else
Rule := Rules_Maps.Element (Pos);
end if;
-- Check if the user has one of the required permission.
declare
P : constant Access_Rule_Access := Rule.Value;
Granted : Boolean;
begin
if P /= null then
for I in P.Permissions'Range loop
-- Context.Has_Permission (P.Permissions (I), Granted);
if Granted then
return True;
end if;
end loop;
end if;
end;
return False;
end Has_Permission;
-- Grant the permission to access to the given <b>URI</b> to users having the <b>To</b>
-- permissions.
procedure Grant_URI_Permission (Manager : in out URL_Policy;
URI : in String;
To : in String) is
begin
null;
end Grant_URI_Permission;
-- ------------------------------
-- Policy Configuration
-- ------------------------------
type Policy_Config is record
Id : Natural := 0;
Permissions : Util.Beans.Objects.Vectors.Vector;
Patterns : Util.Beans.Objects.Vectors.Vector;
Manager : URL_Policy_Access;
end record;
type Policy_Config_Access is access all Policy_Config;
-- Setup the XML parser to read the <b>policy</b> description. For example:
-- Find the access rule of the policy that matches the given URI.
-- Returns the No_Rule value (disable access) if no rule is found.
function Find_Access_Rule (Manager : in URL_Policy;
URI : in String) return Access_Rule_Ref is
Matched : Boolean := False;
Result : Access_Rule_Ref;
procedure Match (P : in Policy);
procedure Match (P : in Policy) is
begin
if GNAT.Regexp.Match (URI, P.Pattern) then
Matched := True;
Result := P.Rule;
end if;
end Match;
Last : constant Natural := Manager.Policies.Last_Index;
begin
for I in 1 .. Last loop
Manager.Policies.Query_Element (I, Match'Access);
if Matched then
return Result;
end if;
end loop;
return Result;
end Find_Access_Rule;
-- ------------------------------
-- Initialize the permission manager.
-- ------------------------------
overriding
procedure Initialize (Manager : in out URL_Policy) is
begin
Manager.Cache := new Rules_Ref.Atomic_Ref;
Manager.Cache.Set (Rules_Ref.Create);
end Initialize;
-- ------------------------------
-- Finalize the permission manager.
-- ------------------------------
overriding
procedure Finalize (Manager : in out URL_Policy) is
use Ada.Strings.Unbounded;
use Security.Controllers;
procedure Free is
new Ada.Unchecked_Deallocation (Rules_Ref.Atomic_Ref,
Rules_Ref_Access);
begin
Free (Manager.Cache);
-- for I in Manager.Names'Range loop
-- exit when Manager.Names (I) = null;
-- Ada.Strings.Unbounded.Free (Manager.Names (I));
-- end loop;
end Finalize;
type Policy_Fields is (FIELD_ID, FIELD_PERMISSION, FIELD_URL_PATTERN, FIELD_POLICY);
procedure Set_Member (P : in out Policy_Config;
Field : in Policy_Fields;
Value : in Util.Beans.Objects.Object);
procedure Process (Policy : in Policy_Config);
procedure Set_Member (P : in out Policy_Config;
Field : in Policy_Fields;
Value : in Util.Beans.Objects.Object) is
begin
case Field is
when FIELD_ID =>
P.Id := Util.Beans.Objects.To_Integer (Value);
when FIELD_PERMISSION =>
P.Permissions.Append (Value);
when FIELD_URL_PATTERN =>
P.Patterns.Append (Value);
when FIELD_POLICY =>
Process (P);
P.Id := 0;
P.Permissions.Clear;
P.Patterns.Clear;
end case;
end Set_Member;
procedure Process (Policy : in Policy_Config) is
Pol : Security.Policies.URLs.Policy;
Count : constant Natural := Natural (Policy.Permissions.Length);
Rule : constant Access_Rule_Ref := Access_Rule_Refs.Create (new Access_Rule (Count));
Iter : Util.Beans.Objects.Vectors.Cursor := Policy.Permissions.First;
Pos : Positive := 1;
begin
Pol.Rule := Rule;
-- Step 1: Initialize the list of permission index in Access_Rule from the permission names.
while Util.Beans.Objects.Vectors.Has_Element (Iter) loop
declare
Perm : constant Util.Beans.Objects.Object := Util.Beans.Objects.Vectors.Element (Iter);
Name : constant String := Util.Beans.Objects.To_String (Perm);
begin
Rule.Value.all.Permissions (Pos) := Permissions.Get_Permission_Index (Name);
Pos := Pos + 1;
exception
when Invalid_Name =>
raise Util.Serialize.Mappers.Field_Error with "Invalid permission: " & Name;
end;
Util.Beans.Objects.Vectors.Next (Iter);
end loop;
-- Step 2: Create one policy for each URL pattern
Iter := Policy.Patterns.First;
while Util.Beans.Objects.Vectors.Has_Element (Iter) loop
declare
Pattern : constant Util.Beans.Objects.Object
:= Util.Beans.Objects.Vectors.Element (Iter);
begin
Pol.Id := Policy.Id;
Pol.Pattern := GNAT.Regexp.Compile (Util.Beans.Objects.To_String (Pattern));
Policy.Manager.Policies.Append (Pol);
end;
Util.Beans.Objects.Vectors.Next (Iter);
end loop;
end Process;
package Policy_Mapper is
new Util.Serialize.Mappers.Record_Mapper (Element_Type => Policy_Config,
Element_Type_Access => Policy_Config_Access,
Fields => Policy_Fields,
Set_Member => Set_Member);
Policy_Mapping : aliased Policy_Mapper.Mapper;
-- ------------------------------
-- Setup the XML parser to read the <b>policy</b> description.
-- ------------------------------
overriding
procedure Prepare_Config (Policy : in out URL_Policy;
Reader : in out Util.Serialize.IO.XML.Parser) is
Config : Policy_Config_Access := new Policy_Config;
begin
Reader.Add_Mapping ("policy-rules", Policy_Mapping'Access);
Reader.Add_Mapping ("module", Policy_Mapping'Access);
Config.Manager := Policy'Unchecked_Access;
Policy_Mapper.Set_Context (Reader, Config);
end Prepare_Config;
-- ------------------------------
-- Finish reading the XML policy configuration. The security policy implementation can use
-- this procedure to perform any configuration setup after the configuration is parsed.
-- ------------------------------
overriding
procedure Finish_Config (Into : in out URL_Policy;
Reader : in out Util.Serialize.IO.XML.Parser) is
begin
null;
end Finish_Config;
begin
Policy_Mapping.Add_Mapping ("policy", FIELD_POLICY);
Policy_Mapping.Add_Mapping ("policy/@id", FIELD_ID);
Policy_Mapping.Add_Mapping ("policy/permission", FIELD_PERMISSION);
Policy_Mapping.Add_Mapping ("policy/url-pattern", FIELD_URL_PATTERN);
end Security.Policies.Urls;
|
Remove unused Free instantiations
|
Remove unused Free instantiations
|
Ada
|
apache-2.0
|
stcarrez/ada-security
|
f217a7efd1847bf580158c2d96477433a7789758
|
src/security-policies-urls.ads
|
src/security-policies-urls.ads
|
-----------------------------------------------------------------------
-- security-policies-urls -- URL security policy
-- Copyright (C) 2010, 2011, 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Containers.Hashed_Maps;
with Ada.Containers.Vectors;
with Util.Refs;
with Util.Strings;
with Util.Serialize.IO.XML;
with GNAT.Regexp;
-- == URL Security Policy ==
-- The <tt>Security.Policies.Urls</tt> implements a security policy intended to be used
-- in web servers.
--
-- === Policy creation ===
-- An instance of the <tt>URL_Policy</tt> must be created and registered in the policy manager.
-- Get or declare the following variables:
--
-- Manager : Security.Policies.Policy_Manager;
-- Policy : Security.Policies.Urls.URL_Policy_Access;
--
-- Create the URL policy and register it in the policy manager as follows:
--
-- Policy := new URL_Policy;
-- Manager.Add_Policy (Policy.all'Access);
--
-- === Policy Configuration ===
-- Once the URL policy is registered, the policy manager can read and process the following
-- XML configuration:
--
-- <url-policy id='1'>
-- <permission>create-workspace</permission>
-- <permission>admin</permission>
-- <url-pattern>/workspace/create</url-pattern>
-- <url-pattern>/workspace/setup/*</url-pattern>
-- </url-policy>
--
-- This policy gives access to the URL that match one of the URL pattern if the
-- security context has the permission <b>create-workspace</b> or <b>admin</b>.
-- These two permissions are checked according to another security policy.
-- The XML configuration can define several <tt>url-policy</tt>. They are checked in
-- the order defined in the XML. In other words, the first <tt>url-policy</tt> that matches
-- the URL is used to verify the permission.
--
-- The <tt>url-policy</tt> definition can contain several <tt>permission</tt>.
--
-- === Checking for permission ===
-- To check a URL permission, you must declare a <tt>URI_Permission</tt> object with the URL.
--
-- URI : constant String := ...;
-- Perm : constant Policies.URLs.URI_Permission (1, URI'Length)
-- := URI_Permission '(1, Len => URI'Length, URI => URI);
-- Result : Boolean;
--
-- Having the security context, we can check the permission:
--
-- Context.Has_Permission (Perm, Result);
--
package Security.Policies.Urls is
NAME : constant String := "URL-Policy";
-- ------------------------------
-- URI Permission
-- ------------------------------
-- Represents a permission to access a given URI.
type URI_Permission (Id : Permissions.Permission_Index;
Len : Natural) is new Permissions.Permission (Id) with record
URI : String (1 .. Len);
end record;
-- ------------------------------
-- URL policy
-- ------------------------------
type URL_Policy is new Policy with private;
type URL_Policy_Access is access all URL_Policy'Class;
Invalid_Name : exception;
-- Get the policy name.
overriding
function Get_Name (From : in URL_Policy) return String;
-- Returns True if the user has the permission to access the given URI permission.
function Has_Permission (Manager : in URL_Policy;
Context : in Security_Context_Access;
Permission : in URI_Permission'Class) return Boolean;
-- Grant the permission to access to the given <b>URI</b> to users having the <b>To</b>
-- permissions.
procedure Grant_URI_Permission (Manager : in out URL_Policy;
URI : in String;
To : in String);
-- Initialize the permission manager.
overriding
procedure Initialize (Manager : in out URL_Policy);
-- Finalize the permission manager.
overriding
procedure Finalize (Manager : in out URL_Policy);
-- Setup the XML parser to read the <b>policy</b> description.
overriding
procedure Prepare_Config (Policy : in out URL_Policy;
Reader : in out Util.Serialize.IO.XML.Parser);
-- Finish reading the XML policy configuration. The security policy implementation can use
-- this procedure to perform any configuration setup after the configuration is parsed.
overriding
procedure Finish_Config (Into : in out URL_Policy;
Reader : in out Util.Serialize.IO.XML.Parser);
private
use Util.Strings;
-- The <b>Access_Rule</b> represents a list of permissions to verify to grant
-- access to the resource. To make it simple, the user must have one of the
-- permission from the list. Each permission will refer to a specific permission
-- controller.
type Access_Rule (Count : Natural) is new Util.Refs.Ref_Entity with record
Permissions : Permission_Index_Array (1 .. Count);
end record;
type Access_Rule_Access is access all Access_Rule;
package Access_Rule_Refs is
new Util.Refs.Indefinite_References (Element_Type => Access_Rule,
Element_Access => Access_Rule_Access);
subtype Access_Rule_Ref is Access_Rule_Refs.Ref;
-- Find the access rule of the policy that matches the given URI.
-- Returns the No_Rule value (disable access) if no rule is found.
function Find_Access_Rule (Manager : in URL_Policy;
URI : in String) return Access_Rule_Ref;
-- The <b>Policy</b> defines the access rules that are applied on a given
-- URL, set of URLs or files.
type Policy is record
Id : Natural;
Pattern : GNAT.Regexp.Regexp;
Rule : Access_Rule_Ref;
end record;
-- The <b>Policy_Vector</b> represents the whole permission policy. The order of
-- policy in the list is important as policies can override each other.
package Policy_Vector is new Ada.Containers.Vectors (Index_Type => Positive,
Element_Type => Policy);
package Rules_Maps is new Ada.Containers.Hashed_Maps (Key_Type => String_Ref,
Element_Type => Access_Rule_Ref,
Hash => Hash,
Equivalent_Keys => Equivalent_Keys,
"=" => Access_Rule_Refs."=");
type Rules is new Util.Refs.Ref_Entity with record
Map : Rules_Maps.Map;
end record;
type Rules_Access is access all Rules;
package Rules_Ref is new Util.Refs.References (Rules, Rules_Access);
type Rules_Ref_Access is access Rules_Ref.Atomic_Ref;
type Controller_Access_Array_Access is access all Controller_Access_Array;
type URL_Policy is new Security.Policies.Policy with record
Cache : Rules_Ref_Access;
Policies : Policy_Vector.Vector;
end record;
end Security.Policies.Urls;
|
-----------------------------------------------------------------------
-- security-policies-urls -- URL security policy
-- Copyright (C) 2010, 2011, 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Containers.Hashed_Maps;
with Ada.Containers.Vectors;
with Util.Refs;
with Util.Strings;
with Util.Serialize.IO.XML;
with GNAT.Regexp;
-- == URL Security Policy ==
-- The <tt>Security.Policies.Urls</tt> implements a security policy intended to be used
-- in web servers.
--
-- === Policy creation ===
-- An instance of the <tt>URL_Policy</tt> must be created and registered in the policy manager.
-- Get or declare the following variables:
--
-- Manager : Security.Policies.Policy_Manager;
-- Policy : Security.Policies.Urls.URL_Policy_Access;
--
-- Create the URL policy and register it in the policy manager as follows:
--
-- Policy := new URL_Policy;
-- Manager.Add_Policy (Policy.all'Access);
--
-- === Policy Configuration ===
-- Once the URL policy is registered, the policy manager can read and process the following
-- XML configuration:
--
-- <url-policy id='1'>
-- <permission>create-workspace</permission>
-- <permission>admin</permission>
-- <url-pattern>/workspace/create</url-pattern>
-- <url-pattern>/workspace/setup/*</url-pattern>
-- </url-policy>
--
-- This policy gives access to the URL that match one of the URL pattern if the
-- security context has the permission <b>create-workspace</b> or <b>admin</b>.
-- These two permissions are checked according to another security policy.
-- The XML configuration can define several <tt>url-policy</tt>. They are checked in
-- the order defined in the XML. In other words, the first <tt>url-policy</tt> that matches
-- the URL is used to verify the permission.
--
-- The <tt>url-policy</tt> definition can contain several <tt>permission</tt>.
--
-- === Checking for permission ===
-- To check a URL permission, you must declare a <tt>URI_Permission</tt> object with the URL.
--
-- URI : constant String := ...;
-- Perm : constant Policies.URLs.URI_Permission (1, URI'Length)
-- := URI_Permission '(1, Len => URI'Length, URI => URI);
-- Result : Boolean;
--
-- Having the security context, we can check the permission:
--
-- Context.Has_Permission (Perm, Result);
--
package Security.Policies.Urls is
NAME : constant String := "URL-Policy";
package P_URL is new Security.Permissions.Definition ("url");
-- ------------------------------
-- URI Permission
-- ------------------------------
-- Represents a permission to access a given URI.
type URI_Permission (Len : Natural) is new Permissions.Permission (P_URL.Permission) with record
URI : String (1 .. Len);
end record;
-- ------------------------------
-- URL policy
-- ------------------------------
type URL_Policy is new Policy with private;
type URL_Policy_Access is access all URL_Policy'Class;
Invalid_Name : exception;
-- Get the policy name.
overriding
function Get_Name (From : in URL_Policy) return String;
-- Returns True if the user has the permission to access the given URI permission.
function Has_Permission (Manager : in URL_Policy;
Context : in Security_Context_Access;
Permission : in URI_Permission'Class) return Boolean;
-- Grant the permission to access to the given <b>URI</b> to users having the <b>To</b>
-- permissions.
procedure Grant_URI_Permission (Manager : in out URL_Policy;
URI : in String;
To : in String);
-- Initialize the permission manager.
overriding
procedure Initialize (Manager : in out URL_Policy);
-- Finalize the permission manager.
overriding
procedure Finalize (Manager : in out URL_Policy);
-- Setup the XML parser to read the <b>policy</b> description.
overriding
procedure Prepare_Config (Policy : in out URL_Policy;
Reader : in out Util.Serialize.IO.XML.Parser);
-- Finish reading the XML policy configuration. The security policy implementation can use
-- this procedure to perform any configuration setup after the configuration is parsed.
overriding
procedure Finish_Config (Into : in out URL_Policy;
Reader : in out Util.Serialize.IO.XML.Parser);
private
use Util.Strings;
-- The <b>Access_Rule</b> represents a list of permissions to verify to grant
-- access to the resource. To make it simple, the user must have one of the
-- permission from the list. Each permission will refer to a specific permission
-- controller.
type Access_Rule (Count : Natural) is new Util.Refs.Ref_Entity with record
Permissions : Permission_Index_Array (1 .. Count);
end record;
type Access_Rule_Access is access all Access_Rule;
package Access_Rule_Refs is
new Util.Refs.Indefinite_References (Element_Type => Access_Rule,
Element_Access => Access_Rule_Access);
subtype Access_Rule_Ref is Access_Rule_Refs.Ref;
-- Find the access rule of the policy that matches the given URI.
-- Returns the No_Rule value (disable access) if no rule is found.
function Find_Access_Rule (Manager : in URL_Policy;
URI : in String) return Access_Rule_Ref;
-- The <b>Policy</b> defines the access rules that are applied on a given
-- URL, set of URLs or files.
type Policy is record
Id : Natural;
Pattern : GNAT.Regexp.Regexp;
Rule : Access_Rule_Ref;
end record;
-- The <b>Policy_Vector</b> represents the whole permission policy. The order of
-- policy in the list is important as policies can override each other.
package Policy_Vector is new Ada.Containers.Vectors (Index_Type => Positive,
Element_Type => Policy);
package Rules_Maps is new Ada.Containers.Hashed_Maps (Key_Type => String_Ref,
Element_Type => Access_Rule_Ref,
Hash => Hash,
Equivalent_Keys => Equivalent_Keys,
"=" => Access_Rule_Refs."=");
type Rules is new Util.Refs.Ref_Entity with record
Map : Rules_Maps.Map;
end record;
type Rules_Access is access all Rules;
package Rules_Ref is new Util.Refs.References (Rules, Rules_Access);
type Rules_Ref_Access is access Rules_Ref.Atomic_Ref;
type Controller_Access_Array_Access is access all Controller_Access_Array;
type URL_Policy is new Security.Policies.Policy with record
Cache : Rules_Ref_Access;
Policies : Policy_Vector.Vector;
end record;
end Security.Policies.Urls;
|
Define and use the URL permission for the URL_Permission type
|
Define and use the URL permission for the URL_Permission type
|
Ada
|
apache-2.0
|
Letractively/ada-security
|
8c4cb27490e64591e80cef666db142df4efa8f67
|
src/util-serialize-io.adb
|
src/util-serialize-io.adb
|
-----------------------------------------------------------------------
-- util-serialize-io -- IO Drivers for serialization
-- Copyright (C) 2010, 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 Util.Streams.Files;
with Ada.Streams;
with Ada.Streams.Stream_IO;
with Ada.Exceptions;
with Ada.IO_Exceptions;
package body Util.Serialize.IO is
-- use Util.Log;
use type Util.Log.Loggers.Logger_Access;
-- The logger'
Log : aliased constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Util.Serialize.IO",
Util.Log.WARN_LEVEL);
procedure Write_Attribute (Stream : in out Output_Stream'Class;
Name : in String;
Value : in Ada.Strings.Unbounded.Unbounded_String) is
begin
Stream.Write_Attribute (Name, Ada.Strings.Unbounded.To_String (Value));
end Write_Attribute;
procedure Write_Entity (Stream : in out Output_Stream'Class;
Name : in String;
Value : in Ada.Strings.Unbounded.Unbounded_String) is
begin
Stream.Write_Entity (Name, Ada.Strings.Unbounded.To_String (Value));
end Write_Entity;
-- ------------------------------
-- Read the file and parse it using the JSON parser.
-- ------------------------------
procedure Parse (Handler : in out Parser;
File : in String) is
Stream : aliased Util.Streams.Files.File_Stream;
Buffer : Util.Streams.Buffered.Buffered_Stream;
begin
if Handler.Error_Logger = null then
Handler.Error_Logger := Log'Access;
end if;
Handler.Error_Logger.Info ("Reading file {0}", File);
Handler.File := Ada.Strings.Unbounded.To_Unbounded_String (File);
Buffer.Initialize (Output => null,
Input => Stream'Unchecked_Access,
Size => 1024);
Stream.Open (Mode => Ada.Streams.Stream_IO.In_File, Name => File);
Context_Stack.Clear (Handler.Stack);
Parser'Class (Handler).Parse (Buffer);
exception
when Util.Serialize.Mappers.Field_Fatal_Error =>
null;
when Ada.IO_Exceptions.Name_Error =>
Parser'Class (Handler).Error ("File '" & File & "' does not exist.");
when E : others =>
Parser'Class (Handler).Error ("Exception " & Ada.Exceptions.Exception_Name (E));
end Parse;
-- ------------------------------
-- Parse the content string.
-- ------------------------------
procedure Parse_String (Handler : in out Parser;
Content : in String) is
Stream : aliased Util.Streams.Buffered.Buffered_Stream;
begin
if Handler.Error_Logger = null then
Handler.Error_Logger := Log'Access;
end if;
Handler.File := Ada.Strings.Unbounded.To_Unbounded_String ("<inline>");
Stream.Initialize (Content => Content);
Context_Stack.Clear (Handler.Stack);
Parser'Class (Handler).Parse (Stream);
exception
when Util.Serialize.Mappers.Field_Fatal_Error =>
null;
when E : others =>
Parser'Class (Handler).Error ("Exception " & Ada.Exceptions.Exception_Name (E));
end Parse_String;
-- ------------------------------
-- Returns true if the <b>Parse</b> operation detected at least one error.
-- ------------------------------
function Has_Error (Handler : in Parser) return Boolean is
begin
return Handler.Error_Flag;
end Has_Error;
-- ------------------------------
-- Set the error logger to report messages while parsing and reading the input file.
-- ------------------------------
procedure Set_Logger (Handler : in out Parser;
Logger : in Util.Log.Loggers.Logger_Access) is
begin
Handler.Error_Logger := Logger;
end Set_Logger;
-- ------------------------------
-- Push the current context when entering in an element.
-- ------------------------------
procedure Push (Handler : in out Parser) is
use type Util.Serialize.Mappers.Mapper_Access;
begin
Context_Stack.Push (Handler.Stack);
end Push;
-- ------------------------------
-- Pop the context and restore the previous context when leaving an element
-- ------------------------------
procedure Pop (Handler : in out Parser) is
begin
Context_Stack.Pop (Handler.Stack);
end Pop;
function Find_Mapper (Handler : in Parser;
Name : in String) return Util.Serialize.Mappers.Mapper_Access is
pragma Unreferenced (Handler, Name);
begin
return null;
end Find_Mapper;
-- ------------------------------
-- Start a new object associated with the given name. This is called when
-- the '{' is reached. The reader must be updated so that the next
-- <b>Set_Member</b> procedure will associate the name/value pair on the
-- new object.
-- ------------------------------
procedure Start_Object (Handler : in out Parser;
Name : in String) is
use type Util.Serialize.Mappers.Mapper_Access;
Current : constant Element_Context_Access := Context_Stack.Current (Handler.Stack);
Next : Element_Context_Access;
Pos : Positive;
begin
Log.Debug ("Start object {0}", Name);
Context_Stack.Push (Handler.Stack);
Next := Context_Stack.Current (Handler.Stack);
if Current /= null then
Pos := 1;
-- Notify we are entering in the given node for each active mapping.
for I in Current.Active_Nodes'Range loop
declare
Node : constant Mappers.Mapper_Access := Current.Active_Nodes (I);
Child : Mappers.Mapper_Access;
begin
exit when Node = null;
Child := Node.Find_Mapper (Name => Name);
if Child = null and then Node.Is_Wildcard then
Child := Node;
end if;
if Child /= null then
Log.Debug ("{0} is matching {1}", Name, Child.Get_Name);
Child.Start_Object (Handler, Name);
Next.Active_Nodes (Pos) := Child;
Pos := Pos + 1;
end if;
end;
end loop;
while Pos <= Next.Active_Nodes'Last loop
Next.Active_Nodes (Pos) := null;
Pos := Pos + 1;
end loop;
else
Next.Active_Nodes (1) := Handler.Mapping_Tree.Find_Mapper (Name);
end if;
end Start_Object;
-- ------------------------------
-- Finish an object associated with the given name. The reader must be
-- updated to be associated with the previous object.
-- ------------------------------
procedure Finish_Object (Handler : in out Parser;
Name : in String) is
use type Util.Serialize.Mappers.Mapper_Access;
begin
Log.Debug ("Finish object {0}", Name);
declare
Current : constant Element_Context_Access := Context_Stack.Current (Handler.Stack);
begin
if Current /= null then
-- Notify we are leaving the given node for each active mapping.
for I in Current.Active_Nodes'Range loop
declare
Node : constant Mappers.Mapper_Access := Current.Active_Nodes (I);
begin
exit when Node = null;
Node.Finish_Object (Handler, Name);
end;
end loop;
end if;
end;
Handler.Pop;
end Finish_Object;
procedure Start_Array (Handler : in out Parser;
Name : in String) is
pragma Unreferenced (Name);
begin
Handler.Push;
end Start_Array;
procedure Finish_Array (Handler : in out Parser;
Name : in String) is
pragma Unreferenced (Name);
begin
Handler.Pop;
end Finish_Array;
-- -----------------------
-- Set the name/value pair on the current object. For each active mapping,
-- find whether a rule matches our name and execute it.
-- -----------------------
procedure Set_Member (Handler : in out Parser;
Name : in String;
Value : in Util.Beans.Objects.Object;
Attribute : in Boolean := False) is
use Util.Serialize.Mappers;
Current : constant Element_Context_Access := Context_Stack.Current (Handler.Stack);
begin
Log.Debug ("Set member {0}", Name);
if Current /= null then
-- Look each active mapping node.
for I in Current.Active_Nodes'Range loop
declare
Node : constant Mapper_Access := Current.Active_Nodes (I);
begin
exit when Node = null;
Node.Set_Member (Name => Name,
Value => Value,
Attribute => Attribute,
Context => Handler);
exception
when E : Util.Serialize.Mappers.Field_Error =>
Parser'Class (Handler).Error (Message => Ada.Exceptions.Exception_Message (E));
when E : Util.Serialize.Mappers.Field_Fatal_Error =>
Parser'Class (Handler).Error (Message => Ada.Exceptions.Exception_Message (E));
raise;
-- For other exception, report an error with the field name and value.
when E : others =>
Parser'Class (Handler).Error (Message => "Cannot set field '" & Name & "' to '"
& Util.Beans.Objects.To_String (Value) & "': "
& Ada.Exceptions.Exception_Message (E));
raise;
end;
end loop;
end if;
end Set_Member;
-- ------------------------------
-- Get the current location (file and line) to report an error message.
-- ------------------------------
function Get_Location (Handler : in Parser) return String is
begin
return Ada.Strings.Unbounded.To_String (Handler.File);
end Get_Location;
-- ------------------------------
-- Report an error while parsing the input stream. The error message will be reported
-- on the logger associated with the parser. The parser will be set as in error so that
-- the <b>Has_Error</b> function will return True after parsing the whole file.
-- ------------------------------
procedure Error (Handler : in out Parser;
Message : in String) is
begin
Handler.Error_Logger.Error ("{0}: {1}",
Parser'Class (Handler).Get_Location,
Message);
Handler.Error_Flag := True;
end Error;
procedure Add_Mapping (Handler : in out Parser;
Path : in String;
Mapper : in Util.Serialize.Mappers.Mapper_Access) is
begin
Handler.Mapping_Tree.Add_Mapping (Path, Mapper);
end Add_Mapping;
-- ------------------------------
-- Dump the mapping tree on the logger using the INFO log level.
-- ------------------------------
procedure Dump (Handler : in Parser'Class;
Logger : in Util.Log.Loggers.Logger'Class) is
begin
Util.Serialize.Mappers.Dump (Handler.Mapping_Tree, Logger, "Mapping ");
end Dump;
end Util.Serialize.IO;
|
-----------------------------------------------------------------------
-- util-serialize-io -- IO Drivers for serialization
-- Copyright (C) 2010, 2011, 2016, 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Streams.Files;
with Ada.Streams;
with Ada.Streams.Stream_IO;
with Ada.Exceptions;
with Ada.IO_Exceptions;
package body Util.Serialize.IO is
-- use Util.Log;
use type Util.Log.Loggers.Logger_Access;
-- The logger'
Log : aliased constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Util.Serialize.IO",
Util.Log.WARN_LEVEL);
procedure Write_Attribute (Stream : in out Output_Stream'Class;
Name : in String;
Value : in Ada.Strings.Unbounded.Unbounded_String) is
begin
Stream.Write_Attribute (Name, Ada.Strings.Unbounded.To_String (Value));
end Write_Attribute;
procedure Write_Entity (Stream : in out Output_Stream'Class;
Name : in String;
Value : in Ada.Strings.Unbounded.Unbounded_String) is
begin
Stream.Write_Entity (Name, Ada.Strings.Unbounded.To_String (Value));
end Write_Entity;
-- ------------------------------
-- Read the file and parse it using the JSON parser.
-- ------------------------------
procedure Parse (Handler : in out Parser;
File : in String) is
Stream : aliased Util.Streams.Files.File_Stream;
Buffer : Util.Streams.Buffered.Buffered_Stream;
begin
if Handler.Error_Logger = null then
Handler.Error_Logger := Log'Access;
end if;
Handler.Error_Logger.Info ("Reading file {0}", File);
Handler.File := Ada.Strings.Unbounded.To_Unbounded_String (File);
Buffer.Initialize (Output => null,
Input => Stream'Unchecked_Access,
Size => 1024);
Stream.Open (Mode => Ada.Streams.Stream_IO.In_File, Name => File);
Context_Stack.Clear (Handler.Stack);
Parser'Class (Handler).Parse (Buffer);
exception
when Util.Serialize.Mappers.Field_Fatal_Error =>
null;
when Ada.IO_Exceptions.Name_Error =>
Parser'Class (Handler).Error ("File '" & File & "' does not exist.");
when E : others =>
Parser'Class (Handler).Error ("Exception " & Ada.Exceptions.Exception_Name (E));
end Parse;
-- ------------------------------
-- Parse the content string.
-- ------------------------------
procedure Parse_String (Handler : in out Parser;
Content : in String) is
Stream : aliased Util.Streams.Buffered.Buffered_Stream;
begin
if Handler.Error_Logger = null then
Handler.Error_Logger := Log'Access;
end if;
Handler.File := Ada.Strings.Unbounded.To_Unbounded_String ("<inline>");
Stream.Initialize (Content => Content);
Context_Stack.Clear (Handler.Stack);
Parser'Class (Handler).Parse (Stream);
exception
when Util.Serialize.Mappers.Field_Fatal_Error =>
null;
when E : others =>
Parser'Class (Handler).Error ("Exception " & Ada.Exceptions.Exception_Name (E));
end Parse_String;
-- ------------------------------
-- Returns true if the <b>Parse</b> operation detected at least one error.
-- ------------------------------
function Has_Error (Handler : in Parser) return Boolean is
begin
return Handler.Error_Flag;
end Has_Error;
-- ------------------------------
-- Set the error logger to report messages while parsing and reading the input file.
-- ------------------------------
procedure Set_Logger (Handler : in out Parser;
Logger : in Util.Log.Loggers.Logger_Access) is
begin
Handler.Error_Logger := Logger;
end Set_Logger;
-- ------------------------------
-- Push the current context when entering in an element.
-- ------------------------------
procedure Push (Handler : in out Parser) is
use type Util.Serialize.Mappers.Mapper_Access;
begin
Context_Stack.Push (Handler.Stack);
end Push;
-- ------------------------------
-- Pop the context and restore the previous context when leaving an element
-- ------------------------------
procedure Pop (Handler : in out Parser) is
begin
Context_Stack.Pop (Handler.Stack);
end Pop;
function Find_Mapper (Handler : in Parser;
Name : in String) return Util.Serialize.Mappers.Mapper_Access is
pragma Unreferenced (Handler, Name);
begin
return null;
end Find_Mapper;
-- ------------------------------
-- Start a new object associated with the given name. This is called when
-- the '{' is reached. The reader must be updated so that the next
-- <b>Set_Member</b> procedure will associate the name/value pair on the
-- new object.
-- ------------------------------
procedure Start_Object (Handler : in out Parser;
Name : in String) is
use type Util.Serialize.Mappers.Mapper_Access;
Current : constant Element_Context_Access := Context_Stack.Current (Handler.Stack);
Next : Element_Context_Access;
Pos : Positive;
begin
Log.Debug ("Start object {0}", Name);
Context_Stack.Push (Handler.Stack);
Next := Context_Stack.Current (Handler.Stack);
if Current /= null then
Pos := 1;
-- Notify we are entering in the given node for each active mapping.
for I in Current.Active_Nodes'Range loop
declare
Node : constant Mappers.Mapper_Access := Current.Active_Nodes (I);
Child : Mappers.Mapper_Access;
begin
exit when Node = null;
Child := Node.Find_Mapper (Name => Name);
if Child = null and then Node.Is_Wildcard then
Child := Node;
end if;
if Child /= null then
Log.Debug ("{0} is matching {1}", Name, Child.Get_Name);
Child.Start_Object (Handler, Name);
Next.Active_Nodes (Pos) := Child;
Pos := Pos + 1;
end if;
end;
end loop;
while Pos <= Next.Active_Nodes'Last loop
Next.Active_Nodes (Pos) := null;
Pos := Pos + 1;
end loop;
else
Next.Active_Nodes (1) := Handler.Mapping_Tree.Find_Mapper (Name);
end if;
end Start_Object;
-- ------------------------------
-- Finish an object associated with the given name. The reader must be
-- updated to be associated with the previous object.
-- ------------------------------
procedure Finish_Object (Handler : in out Parser;
Name : in String) is
use type Util.Serialize.Mappers.Mapper_Access;
begin
Log.Debug ("Finish object {0}", Name);
declare
Current : constant Element_Context_Access := Context_Stack.Current (Handler.Stack);
begin
if Current /= null then
-- Notify we are leaving the given node for each active mapping.
for I in Current.Active_Nodes'Range loop
declare
Node : constant Mappers.Mapper_Access := Current.Active_Nodes (I);
begin
exit when Node = null;
Node.Finish_Object (Handler, Name);
end;
end loop;
end if;
end;
Handler.Pop;
end Finish_Object;
procedure Start_Array (Handler : in out Parser;
Name : in String) is
pragma Unreferenced (Name);
begin
Handler.Push;
end Start_Array;
procedure Finish_Array (Handler : in out Parser;
Name : in String;
Count : in Natural) is
pragma Unreferenced (Name, Count);
begin
Handler.Pop;
end Finish_Array;
-- -----------------------
-- Set the name/value pair on the current object. For each active mapping,
-- find whether a rule matches our name and execute it.
-- -----------------------
procedure Set_Member (Handler : in out Parser;
Name : in String;
Value : in Util.Beans.Objects.Object;
Attribute : in Boolean := False) is
use Util.Serialize.Mappers;
Current : constant Element_Context_Access := Context_Stack.Current (Handler.Stack);
begin
Log.Debug ("Set member {0}", Name);
if Current /= null then
-- Look each active mapping node.
for I in Current.Active_Nodes'Range loop
declare
Node : constant Mapper_Access := Current.Active_Nodes (I);
begin
exit when Node = null;
Node.Set_Member (Name => Name,
Value => Value,
Attribute => Attribute,
Context => Handler);
exception
when E : Util.Serialize.Mappers.Field_Error =>
Parser'Class (Handler).Error (Message => Ada.Exceptions.Exception_Message (E));
when E : Util.Serialize.Mappers.Field_Fatal_Error =>
Parser'Class (Handler).Error (Message => Ada.Exceptions.Exception_Message (E));
raise;
-- For other exception, report an error with the field name and value.
when E : others =>
Parser'Class (Handler).Error (Message => "Cannot set field '" & Name & "' to '"
& Util.Beans.Objects.To_String (Value) & "': "
& Ada.Exceptions.Exception_Message (E));
raise;
end;
end loop;
end if;
end Set_Member;
-- ------------------------------
-- Get the current location (file and line) to report an error message.
-- ------------------------------
function Get_Location (Handler : in Parser) return String is
begin
return Ada.Strings.Unbounded.To_String (Handler.File);
end Get_Location;
-- ------------------------------
-- Report an error while parsing the input stream. The error message will be reported
-- on the logger associated with the parser. The parser will be set as in error so that
-- the <b>Has_Error</b> function will return True after parsing the whole file.
-- ------------------------------
procedure Error (Handler : in out Parser;
Message : in String) is
begin
Handler.Error_Logger.Error ("{0}: {1}",
Parser'Class (Handler).Get_Location,
Message);
Handler.Error_Flag := True;
end Error;
procedure Add_Mapping (Handler : in out Parser;
Path : in String;
Mapper : in Util.Serialize.Mappers.Mapper_Access) is
begin
Handler.Mapping_Tree.Add_Mapping (Path, Mapper);
end Add_Mapping;
-- ------------------------------
-- Dump the mapping tree on the logger using the INFO log level.
-- ------------------------------
procedure Dump (Handler : in Parser'Class;
Logger : in Util.Log.Loggers.Logger'Class) is
begin
Util.Serialize.Mappers.Dump (Handler.Mapping_Tree, Logger, "Mapping ");
end Dump;
end Util.Serialize.IO;
|
Add Count parameter to the Finish_Array procedure
|
Add Count parameter to the Finish_Array procedure
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
9c0213dfdbd826166f9b41fa9cfb732876dc4a80
|
src/drivers/ado-drivers.ads
|
src/drivers/ado-drivers.ads
|
-----------------------------------------------------------------------
-- ADO Drivers -- Database Drivers
-- Copyright (C) 2010, 2011, 2012, 2013, 2018 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Properties;
-- == Database Drivers ==
-- Database drivers provide operations to access the database. These operations are
-- specific to the database type and the `ADO.Drivers` package among others provide
-- an abstraction that allows to make the different databases look like they have almost
-- the same interface.
--
-- A database driver exists for SQLite, MySQL and PostgreSQL. The driver
-- is either statically linked to the application or it 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 `libada_ado_`. For example, for a `mysql` driver, the shared
-- library name is `libada_ado_mysql.so`.
--
-- | Driver name | Database |
-- | ----------- | --------- |
-- | mysql | MySQL, MariaDB |
-- | sqlite | SQLite |
-- | postgresql | PostgreSQL |
--
-- The database drivers are initialized automatically but in some cases, you may want
-- to control some database driver configuration parameter. In that case,
-- the initialization must be done only once before creating a session
-- factory and getting a database connection. The initialization can be made using
-- a property file which contains the configuration for the database drivers and
-- the database connection properties. For such initialization, you will have to
-- call one of the `Initialize` operation from the `ADO.Drivers` package.
--
-- ADO.Drivers.Initialize ("db.properties");
--
-- The set of configuration properties can be set programatically and passed to the
-- `Initialize` operation.
--
-- Config : Util.Properties.Manager;
-- ...
-- Config.Set ("ado.database", "sqlite:///mydatabase.db");
-- Config.Set ("ado.queries.path", ".;db");
-- ADO.Drivers.Initialize (Config);
--
-- Once initialized, a configuration property can be retrieved by using the `Get_Config`
-- operation.
--
-- URI : constant String := ADO.Drivers.Get_Config ("ado.database");
--
-- Dynamic loading of database drivers is disabled by default for security reasons and
-- it can be enabled by setting the following property in the configuration file:
--
-- ado.drivers.load=true
--
-- Dynamic loading is triggered when a database connection string refers to a database
-- driver which is not known.
--
-- @include ado-mysql.ads
-- @include ado-sqlite.ads
-- @include ado-postgresql.ads
package ADO.Drivers is
use Ada.Strings.Unbounded;
-- Raised for all errors reported by the database.
Database_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;
-- Returns true if the global configuration property is set to true/on.
function Is_On (Name : in String) return Boolean;
private
-- Initialize the drivers which are available.
procedure Initialize;
end ADO.Drivers;
|
-----------------------------------------------------------------------
-- ADO Drivers -- Database Drivers
-- Copyright (C) 2010, 2011, 2012, 2013, 2018 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Properties;
-- == Database Drivers ==
-- Database drivers provide operations to access the database. These operations are
-- specific to the database type and the `ADO.Drivers` package among others provide
-- an abstraction that allows to make the different databases look like they have almost
-- the same interface.
--
-- A database driver exists for SQLite, MySQL and PostgreSQL. The driver
-- is either statically linked to the application or it 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 `libada_ado_`. For example, for a `mysql` driver, the shared
-- library name is `libada_ado_mysql.so`.
--
-- | Driver name | Database |
-- | ----------- | --------- |
-- | mysql | MySQL, MariaDB |
-- | sqlite | SQLite |
-- | postgresql | PostgreSQL |
--
-- The database drivers are initialized automatically but in some cases, you may want
-- to control some database driver configuration parameter. In that case,
-- the initialization must be done only once before creating a session
-- factory and getting a database connection. The initialization can be made using
-- a property file which contains the configuration for the database drivers and
-- the database connection properties. For such initialization, you will have to
-- call one of the `Initialize` operation from the `ADO.Drivers` package.
--
-- ADO.Drivers.Initialize ("db.properties");
--
-- The set of configuration properties can be set programatically and passed to the
-- `Initialize` operation.
--
-- Config : Util.Properties.Manager;
-- ...
-- Config.Set ("ado.database", "sqlite:///mydatabase.db");
-- Config.Set ("ado.queries.path", ".;db");
-- ADO.Drivers.Initialize (Config);
--
-- Once initialized, a configuration property can be retrieved by using the `Get_Config`
-- operation.
--
-- URI : constant String := ADO.Drivers.Get_Config ("ado.database");
--
-- Dynamic loading of database drivers is disabled by default for security reasons and
-- it can be enabled by setting the following property in the configuration file:
--
-- ado.drivers.load=true
--
-- Dynamic loading is triggered when a database connection string refers to a database
-- driver which is not known.
--
-- @include ado-mysql.ads
-- @include ado-sqlite.ads
-- @include ado-postgresql.ads
package ADO.Drivers is
-- Raised for all errors reported by the database.
Database_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;
-- Returns true if the global configuration property is set to true/on.
function Is_On (Name : in String) return Boolean;
private
-- Initialize the drivers which are available.
procedure Initialize;
end ADO.Drivers;
|
Fix compilation warning
|
Fix compilation warning
|
Ada
|
apache-2.0
|
stcarrez/ada-ado
|
c9a5b27e0dfb5f458af71a48e3c01b23c0966582
|
src/gen-artifacts-query.adb
|
src/gen-artifacts-query.adb
|
-----------------------------------------------------------------------
-- gen-artifacts-query -- Query artifact for Code Generator
-- Copyright (C) 2011 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Ada.Directories;
with Gen.Utils;
with Gen.Model.Tables;
with Gen.Model.Queries;
with Util.Log.Loggers;
with Util.Encoders.HMAC.SHA1;
-- The <b>Gen.Artifacts.Query</b> package is an artifact for the generation of
-- data structures returned by queries.
package body Gen.Artifacts.Query is
use Ada.Strings.Unbounded;
use Gen.Model;
use Gen.Model.Tables;
use Gen.Model.Queries;
use type DOM.Core.Node;
use Util.Log;
Log : constant Loggers.Logger := Loggers.Create ("Gen.Artifacts.Query");
-- ------------------------------
-- After the configuration file is read, processes the node whose root
-- is passed in <b>Node</b> and initializes the <b>Model</b> with the information.
-- ------------------------------
procedure Initialize (Handler : in Artifact;
Path : in String;
Node : in DOM.Core.Node;
Model : in out Gen.Model.Packages.Model_Definition'Class;
Context : in out Generator'Class) is
pragma Unreferenced (Handler);
procedure Register_Column (Table : in out Query_Definition;
Column : in DOM.Core.Node);
procedure Register_Columns (Table : in out Query_Definition);
procedure Register_Mapping (Query : in out Gen.Model.Queries.Query_Definition;
Node : in DOM.Core.Node);
procedure Register_Mapping (Model : in out Gen.Model.Packages.Model_Definition;
Node : in DOM.Core.Node);
procedure Register_Query (Query : in out Gen.Model.Queries.Query_Definition;
Node : in DOM.Core.Node);
Hash : Unbounded_String;
-- ------------------------------
-- Register the column definition in the table
-- ------------------------------
procedure Register_Column (Table : in out Query_Definition;
Column : in DOM.Core.Node) is
Name : constant Unbounded_String := Gen.Model.Get_Attribute (Column, "name");
C : constant Column_Definition_Access := new Column_Definition;
begin
C.Node := Column;
C.Number := Table.Members.Get_Count;
Table.Members.Append (C);
C.Type_Name := To_Unbounded_String (Get_Normalized_Type (Column, "type"));
C.Is_Inserted := False;
C.Is_Updated := False;
C.Not_Null := False;
C.Unique := False;
-- Construct the hash for this column mapping.
Append (Hash, ",type=");
Append (Hash, C.Type_Name);
Append (Hash, ",name=");
Append (Hash, Name);
end Register_Column;
-- ------------------------------
-- Register all the columns defined in the table
-- ------------------------------
procedure Register_Columns (Table : in out Query_Definition) is
procedure Iterate is new Gen.Utils.Iterate_Nodes (T => Query_Definition,
Process => Register_Column);
begin
Log.Debug ("Register columns from query {0}", Table.Name);
Iterate (Table, Table.Node, "property");
end Register_Columns;
-- ------------------------------
-- Register a new class definition in the model.
-- ------------------------------
procedure Register_Mapping (Query : in out Gen.Model.Queries.Query_Definition;
Node : in DOM.Core.Node) is
Name : constant Unbounded_String := Gen.Model.Get_Attribute (Node, "name");
begin
Query.Node := Node;
Query.Set_Table_Name (Query.Get_Attribute ("name"));
if Name /= "" then
Query.Name := Name;
else
Query.Name := To_Unbounded_String (Gen.Utils.Get_Query_Name (Path));
end if;
-- Construct the hash for this column mapping.
Append (Hash, "class=");
Append (Hash, Query.Name);
Log.Debug ("Register query {0} with type {0}", Query.Name, Query.Type_Name);
Register_Columns (Query);
end Register_Mapping;
-- ------------------------------
-- Register a new query.
-- ------------------------------
procedure Register_Query (Query : in out Gen.Model.Queries.Query_Definition;
Node : in DOM.Core.Node) is
C : constant Column_Definition_Access := new Column_Definition;
begin
C.Node := Node;
C.Number := Query.Queries.Get_Count;
Query.Queries.Append (C);
end Register_Query;
-- ------------------------------
-- Register a model mapping
-- ------------------------------
procedure Register_Mapping (Model : in out Gen.Model.Packages.Model_Definition;
Node : in DOM.Core.Node) is
procedure Iterate_Mapping is
new Gen.Utils.Iterate_Nodes (T => Gen.Model.Queries.Query_Definition,
Process => Register_Mapping);
procedure Iterate_Query is
new Gen.Utils.Iterate_Nodes (T => Gen.Model.Queries.Query_Definition,
Process => Register_Query);
Table : constant Query_Definition_Access := new Query_Definition;
Pkg : constant Unbounded_String := Gen.Model.Get_Attribute (Node, "package");
begin
Table.File_Name := To_Unbounded_String (Ada.Directories.Simple_Name (Path));
Table.Pkg_Name := Pkg;
Iterate_Mapping (Query_Definition (Table.all), Node, "class");
Iterate_Query (Query_Definition (Table.all), Node, "query");
if Length (Table.Pkg_Name) = 0 then
Context.Error ("Missing or empty package attribute");
else
Model.Register_Query (Table);
end if;
Log.Info ("Query hash for {0} is {1}", Path, To_String (Hash));
Table.Sha1 := Util.Encoders.HMAC.SHA1.Sign (Key => "ADO.Queries",
Data => To_String (Hash));
end Register_Mapping;
procedure Iterate is new Gen.Utils.Iterate_Nodes (T => Gen.Model.Packages.Model_Definition,
Process => Register_Mapping);
begin
Log.Debug ("Initializing query artifact for the configuration");
Iterate (Gen.Model.Packages.Model_Definition (Model), Node, "query-mapping");
end Initialize;
-- ------------------------------
-- Prepare the generation of the package:
-- o identify the column types which are used
-- o build a list of package for the with clauses.
-- ------------------------------
overriding
procedure Prepare (Handler : in Artifact;
Model : in out Gen.Model.Packages.Model_Definition'Class;
Context : in out Generator'Class) is
pragma Unreferenced (Handler);
begin
Log.Debug ("Preparing the model for query");
if Model.Has_Packages then
Context.Add_Generation (Name => GEN_PACKAGE_SPEC, Mode => ITERATION_PACKAGE);
Context.Add_Generation (Name => GEN_PACKAGE_BODY, Mode => ITERATION_PACKAGE);
end if;
end Prepare;
end Gen.Artifacts.Query;
|
-----------------------------------------------------------------------
-- gen-artifacts-query -- Query artifact for Code Generator
-- Copyright (C) 2011 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Ada.Directories;
with Gen.Utils;
with Gen.Model.Tables;
with Gen.Model.Queries;
with Util.Log.Loggers;
with Util.Encoders.HMAC.SHA1;
-- The <b>Gen.Artifacts.Query</b> package is an artifact for the generation of
-- data structures returned by queries.
package body Gen.Artifacts.Query is
use Ada.Strings.Unbounded;
use Gen.Model;
use Gen.Model.Tables;
use Gen.Model.Queries;
use type DOM.Core.Node;
use Util.Log;
Log : constant Loggers.Logger := Loggers.Create ("Gen.Artifacts.Query");
-- ------------------------------
-- After the configuration file is read, processes the node whose root
-- is passed in <b>Node</b> and initializes the <b>Model</b> with the information.
-- ------------------------------
procedure Initialize (Handler : in Artifact;
Path : in String;
Node : in DOM.Core.Node;
Model : in out Gen.Model.Packages.Model_Definition'Class;
Context : in out Generator'Class) is
pragma Unreferenced (Handler);
procedure Register_Column (Table : in out Query_Definition;
Column : in DOM.Core.Node);
procedure Register_Columns (Table : in out Query_Definition);
procedure Register_Mapping (Query : in out Gen.Model.Queries.Query_Definition;
Node : in DOM.Core.Node);
procedure Register_Mapping (Model : in out Gen.Model.Packages.Model_Definition;
Node : in DOM.Core.Node);
procedure Register_Query (Query : in out Gen.Model.Queries.Query_Definition;
Node : in DOM.Core.Node);
Hash : Unbounded_String;
-- ------------------------------
-- Register the column definition in the table
-- ------------------------------
procedure Register_Column (Table : in out Query_Definition;
Column : in DOM.Core.Node) is
Name : constant Unbounded_String := Gen.Model.Get_Attribute (Column, "name");
C : constant Column_Definition_Access := new Column_Definition;
begin
C.Node := Column;
C.Number := Table.Members.Get_Count;
Table.Members.Append (C);
C.Type_Name := To_Unbounded_String (Get_Normalized_Type (Column, "type"));
C.Is_Inserted := False;
C.Is_Updated := False;
C.Not_Null := False;
C.Unique := False;
-- Construct the hash for this column mapping.
Append (Hash, ",type=");
Append (Hash, C.Type_Name);
Append (Hash, ",name=");
Append (Hash, Name);
end Register_Column;
-- ------------------------------
-- Register all the columns defined in the table
-- ------------------------------
procedure Register_Columns (Table : in out Query_Definition) is
procedure Iterate is new Gen.Utils.Iterate_Nodes (T => Query_Definition,
Process => Register_Column);
begin
Log.Debug ("Register columns from query {0}", Table.Name);
Iterate (Table, Table.Node, "property");
end Register_Columns;
-- ------------------------------
-- Register a new class definition in the model.
-- ------------------------------
procedure Register_Mapping (Query : in out Gen.Model.Queries.Query_Definition;
Node : in DOM.Core.Node) is
Name : constant Unbounded_String := Gen.Model.Get_Attribute (Node, "name");
begin
Query.Node := Node;
Query.Set_Table_Name (Query.Get_Attribute ("name"));
if Name /= "" then
Query.Name := Name;
else
Query.Name := To_Unbounded_String (Gen.Utils.Get_Query_Name (Path));
end if;
-- Construct the hash for this column mapping.
Append (Hash, "class=");
Append (Hash, Query.Name);
Log.Debug ("Register query {0} with type {0}", Query.Name, Query.Type_Name);
Register_Columns (Query);
end Register_Mapping;
-- ------------------------------
-- Register a new query.
-- ------------------------------
procedure Register_Query (Query : in out Gen.Model.Queries.Query_Definition;
Node : in DOM.Core.Node) is
C : constant Column_Definition_Access := new Column_Definition;
begin
C.Node := Node;
C.Number := Query.Queries.Get_Count;
Query.Queries.Append (C);
end Register_Query;
-- ------------------------------
-- Register a model mapping
-- ------------------------------
procedure Register_Mapping (Model : in out Gen.Model.Packages.Model_Definition;
Node : in DOM.Core.Node) is
procedure Iterate_Mapping is
new Gen.Utils.Iterate_Nodes (T => Gen.Model.Queries.Query_Definition,
Process => Register_Mapping);
procedure Iterate_Query is
new Gen.Utils.Iterate_Nodes (T => Gen.Model.Queries.Query_Definition,
Process => Register_Query);
Table : constant Query_Definition_Access := new Query_Definition;
Pkg : constant Unbounded_String := Gen.Model.Get_Attribute (Node, "package");
begin
Table.File_Name := To_Unbounded_String (Ada.Directories.Simple_Name (Path));
Table.Pkg_Name := Pkg;
Table.Node := Node;
Iterate_Mapping (Query_Definition (Table.all), Node, "class");
Iterate_Query (Query_Definition (Table.all), Node, "query");
if Length (Table.Pkg_Name) = 0 then
Context.Error ("Missing or empty package attribute");
else
Model.Register_Query (Table);
end if;
Log.Info ("Query hash for {0} is {1}", Path, To_String (Hash));
Table.Sha1 := Util.Encoders.HMAC.SHA1.Sign (Key => "ADO.Queries",
Data => To_String (Hash));
end Register_Mapping;
procedure Iterate is new Gen.Utils.Iterate_Nodes (T => Gen.Model.Packages.Model_Definition,
Process => Register_Mapping);
begin
Log.Debug ("Initializing query artifact for the configuration");
Iterate (Gen.Model.Packages.Model_Definition (Model), Node, "query-mapping");
end Initialize;
-- ------------------------------
-- Prepare the generation of the package:
-- o identify the column types which are used
-- o build a list of package for the with clauses.
-- ------------------------------
overriding
procedure Prepare (Handler : in Artifact;
Model : in out Gen.Model.Packages.Model_Definition'Class;
Context : in out Generator'Class) is
pragma Unreferenced (Handler);
begin
Log.Debug ("Preparing the model for query");
if Model.Has_Packages then
Context.Add_Generation (Name => GEN_PACKAGE_SPEC, Mode => ITERATION_PACKAGE);
Context.Add_Generation (Name => GEN_PACKAGE_BODY, Mode => ITERATION_PACKAGE);
end if;
end Prepare;
end Gen.Artifacts.Query;
|
Fix crash when an XML query does not specify a class mapping
|
Fix crash when an XML query does not specify a class mapping
|
Ada
|
apache-2.0
|
Letractively/ada-gen,Letractively/ada-gen,Letractively/ada-gen,Letractively/ada-gen
|
e7aa675c16f22af86fb4f0a56909d82960dcd64c
|
src/el-methods-proc_1.ads
|
src/el-methods-proc_1.ads
|
-----------------------------------------------------------------------
-- EL.Methods.Proc_1 -- Procedure Binding with 1 argument
-- 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 EL.Expressions;
with EL.Contexts;
with Util.Beans.Methods;
with Util.Beans.Basic;
generic
type Param1_Type (<>) is limited private;
package EL.Methods.Proc_1 is
use Util.Beans.Methods;
-- Returns True if the method is a valid method which accepts the arguments
-- defined by the package instantiation.
function Is_Valid (Method : in EL.Expressions.Method_Info) return Boolean;
-- Execute the method describe by the method expression
-- and with the given context. The method signature is:
--
-- procedure F (Obj : in out <Bean>;
-- Param : in out Param1_Type);
--
-- where <Bean> inherits from <b>Readonly_Bean</b>
-- (See <b>Bind</b> package)
--
-- Raises <b>Invalid_Method</b> if the method referenced by
-- the method expression does not exist or does not match
-- the signature.
procedure Execute (Method : in EL.Expressions.Method_Expression'Class;
Param : in out Param1_Type;
Context : in EL.Contexts.ELContext'Class);
-- Execute the method describe by the method binding object.
-- The method signature is:
--
-- procedure F (Obj : in out <Bean>;
-- Param : in out Param1_Type);
--
-- where <Bean> inherits from <b>Readonly_Bean</b>
-- (See <b>Bind</b> package)
--
-- Raises <b>Invalid_Method</b> if the method referenced by
-- the method expression does not exist or does not match
-- the signature.
procedure Execute (Method : in EL.Expressions.Method_Info;
Param : in out Param1_Type);
-- Function access to the proxy.
type Proxy_Access is
access procedure (O : access Util.Beans.Basic.Readonly_Bean'Class;
P : in out Param1_Type);
-- The binding record which links the method name
-- to the proxy function.
type Binding is new Method_Binding with record
Method : Proxy_Access;
end record;
type Binding_Access is access constant Binding;
-- Proxy for the binding.
-- The proxy declares the binding definition that links
-- the name to the function and it implements the necessary
-- object conversion to translate the <b>Readonly_Bean</b>
-- object to the target object type.
generic
-- Name of the method (as exposed in the EL expression)
Name : String;
-- The bean type
type Bean is new Util.Beans.Basic.Readonly_Bean with private;
-- The bean method to invoke
with procedure Method (O : in out Bean;
P1 : in out Param1_Type);
package Bind is
-- Method that <b>Execute</b> will invoke.
procedure Method_Access (O : access Util.Beans.Basic.Readonly_Bean'Class;
P1 : in out Param1_Type);
F_NAME : aliased constant String := Name;
-- The proxy binding that can be exposed through
-- the <b>Method_Bean</b> interface.
Proxy : aliased constant Binding
:= Binding '(Name => F_NAME'Access,
Method => Method_Access'Access);
end Bind;
end EL.Methods.Proc_1;
|
-----------------------------------------------------------------------
-- EL.Methods.Proc_1 -- Procedure Binding with 1 argument
-- 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 EL.Expressions;
with EL.Contexts;
with Util.Beans.Methods;
with Util.Beans.Basic;
generic
type Param1_Type (<>) is limited private;
package EL.Methods.Proc_1 is
use Util.Beans.Methods;
-- Returns True if the method is a valid method which accepts the arguments
-- defined by the package instantiation.
function Is_Valid (Method : in EL.Expressions.Method_Info) return Boolean;
-- Execute the method describe by the method expression
-- and with the given context. The method signature is:
--
-- procedure F (Obj : in out <Bean>;
-- Param : in out Param1_Type);
--
-- where <Bean> inherits from <b>Readonly_Bean</b>
-- (See <b>Bind</b> package)
--
-- Raises <b>Invalid_Method</b> if the method referenced by
-- the method expression does not exist or does not match
-- the signature.
procedure Execute (Method : in EL.Expressions.Method_Expression'Class;
Param : in out Param1_Type;
Context : in EL.Contexts.ELContext'Class);
-- Execute the method describe by the method binding object.
-- The method signature is:
--
-- procedure F (Obj : in out <Bean>;
-- Param : in out Param1_Type);
--
-- where <Bean> inherits from <b>Readonly_Bean</b>
-- (See <b>Bind</b> package)
--
-- Raises <b>Invalid_Method</b> if the method referenced by
-- the method expression does not exist or does not match
-- the signature.
procedure Execute (Method : in EL.Expressions.Method_Info;
Param : in out Param1_Type);
-- Function access to the proxy.
type Proxy_Access is
access procedure (O : access Util.Beans.Basic.Readonly_Bean'Class;
P : in out Param1_Type);
-- The binding record which links the method name
-- to the proxy function.
type Binding is new Method_Binding with record
Method : Proxy_Access;
end record;
type Binding_Access is access constant Binding;
-- Proxy for the binding.
-- The proxy declares the binding definition that links
-- the name to the function and it implements the necessary
-- object conversion to translate the <b>Readonly_Bean</b>
-- object to the target object type.
generic
-- Name of the method (as exposed in the EL expression)
Name : String;
-- The bean type
type Bean is abstract new Util.Beans.Basic.Readonly_Bean with private;
-- The bean method to invoke
with procedure Method (O : in out Bean;
P1 : in out Param1_Type);
package Bind is
-- Method that <b>Execute</b> will invoke.
procedure Method_Access (O : access Util.Beans.Basic.Readonly_Bean'Class;
P1 : in out Param1_Type);
F_NAME : aliased constant String := Name;
-- The proxy binding that can be exposed through
-- the <b>Method_Bean</b> interface.
Proxy : aliased constant Binding
:= Binding '(Name => F_NAME'Access,
Method => Method_Access'Access);
end Bind;
end EL.Methods.Proc_1;
|
Allow the Bean type to be an abstract generic type
|
Allow the Bean type to be an abstract generic type
|
Ada
|
apache-2.0
|
Letractively/ada-el
|
0afeafc3a5ca6e39ad39ee896f83209b9a27825e
|
matp/src/mat-consoles.ads
|
matp/src/mat-consoles.ads
|
-----------------------------------------------------------------------
-- mat-consoles - Console interface
-- Copyright (C) 2014, 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with MAT.Types;
package MAT.Consoles is
type Field_Type is (F_ADDR,
F_SIZE,
F_TOTAL_SIZE,
F_MIN_SIZE,
F_MAX_SIZE,
F_MIN_ADDR,
F_MAX_ADDR,
F_THREAD,
F_COUNT,
F_FILE_NAME,
F_FUNCTION_NAME,
F_LINE_NUMBER,
F_START_TIME,
F_END_TIME,
F_MALLOC_COUNT,
F_REALLOC_COUNT,
F_FREE_COUNT,
F_EVENT_RANGE,
F_ID,
F_OLD_ADDR,
F_TIME,
F_DURATION,
F_EVENT,
F_MODE,
F_FRAME_ID,
F_RANGE_ADDR,
F_FRAME_ADDR);
type Notice_Type is (N_HELP,
N_INFO,
N_EVENT_ID,
N_PID_INFO,
N_DURATION,
N_PATH_INFO);
type Justify_Type is (J_LEFT, -- Justify left |item |
J_RIGHT, -- Justify right | item|
J_CENTER, -- Justify center | item |
J_RIGHT_NO_FILL -- Justify right |item|
);
type Console_Type is abstract tagged limited private;
type Console_Access is access all Console_Type'Class;
-- Report an error message.
procedure Error (Console : in out Console_Type;
Message : in String) is abstract;
-- Report a notice message.
procedure Notice (Console : in out Console_Type;
Kind : in Notice_Type;
Message : in String) is abstract;
-- Print the field value for the given field.
procedure Print_Field (Console : in out Console_Type;
Field : in Field_Type;
Value : in String;
Justify : in Justify_Type := J_LEFT) is abstract;
-- Print the title for the given field.
procedure Print_Title (Console : in out Console_Type;
Field : in Field_Type;
Title : in String) is abstract;
-- Start a new title in a report.
procedure Start_Title (Console : in out Console_Type) is abstract;
-- Finish a new title in a report.
procedure End_Title (Console : in out Console_Type) is abstract;
-- Start a new row in a report.
procedure Start_Row (Console : in out Console_Type) is abstract;
-- Finish a new row in a report.
procedure End_Row (Console : in out Console_Type) is abstract;
-- Print the title for the given field and setup the associated field size.
procedure Print_Title (Console : in out Console_Type;
Field : in Field_Type;
Title : in String;
Length : in Positive);
-- Format the address and print it for the given field.
procedure Print_Field (Console : in out Console_Type;
Field : in Field_Type;
Addr : in MAT.Types.Target_Addr);
-- Format the address range and print it for the given field.
procedure Print_Field (Console : in out Console_Type;
Field : in Field_Type;
From : in MAT.Types.Target_Addr;
To : in MAT.Types.Target_Addr);
-- Format the size and print it for the given field.
procedure Print_Size (Console : in out Console_Type;
Field : in Field_Type;
Size : in MAT.Types.Target_Size);
-- Format the thread information and print it for the given field.
procedure Print_Thread (Console : in out Console_Type;
Field : in Field_Type;
Thread : in MAT.Types.Target_Thread_Ref);
-- Format the time tick as a duration and print it for the given field.
procedure Print_Duration (Console : in out Console_Type;
Field : in Field_Type;
Duration : in MAT.Types.Target_Tick_Ref);
-- Format the integer and print it for the given field.
procedure Print_Field (Console : in out Console_Type;
Field : in Field_Type;
Value : in Integer;
Justify : in Justify_Type := J_LEFT);
-- Format the integer and print it for the given field.
procedure Print_Field (Console : in out Console_Type;
Field : in Field_Type;
Value : in Ada.Strings.Unbounded.Unbounded_String;
Justify : in Justify_Type := J_LEFT);
private
type Field_Size_Array is array (Field_Type) of Natural;
type Field_List_Array is array (1 .. Field_Type'Pos (Field_Type'Last)) of Field_Type;
type Console_Type is abstract tagged limited record
Sizes : Field_Size_Array := (others => 1);
Cols : Field_Size_Array := (others => 1);
Fields : Field_List_Array;
Field_Count : Natural := 0;
end record;
end MAT.Consoles;
|
-----------------------------------------------------------------------
-- mat-consoles - Console interface
-- Copyright (C) 2014, 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with MAT.Types;
package MAT.Consoles is
type Field_Type is (F_ADDR,
F_SIZE,
F_TOTAL_SIZE,
F_MIN_SIZE,
F_MAX_SIZE,
F_MIN_ADDR,
F_MAX_ADDR,
F_THREAD,
F_COUNT,
F_FILE_NAME,
F_FUNCTION_NAME,
F_LINE_NUMBER,
F_START_TIME,
F_END_TIME,
F_MALLOC_COUNT,
F_REALLOC_COUNT,
F_FREE_COUNT,
F_EVENT_RANGE,
F_ID,
F_OLD_ADDR,
F_GROW_SIZE,
F_TIME,
F_DURATION,
F_EVENT,
F_MODE,
F_FRAME_ID,
F_RANGE_ADDR,
F_FRAME_ADDR);
type Notice_Type is (N_HELP,
N_INFO,
N_EVENT_ID,
N_PID_INFO,
N_DURATION,
N_PATH_INFO);
type Justify_Type is (J_LEFT, -- Justify left |item |
J_RIGHT, -- Justify right | item|
J_CENTER, -- Justify center | item |
J_RIGHT_NO_FILL -- Justify right |item|
);
type Console_Type is abstract tagged limited private;
type Console_Access is access all Console_Type'Class;
-- Report an error message.
procedure Error (Console : in out Console_Type;
Message : in String) is abstract;
-- Report a notice message.
procedure Notice (Console : in out Console_Type;
Kind : in Notice_Type;
Message : in String) is abstract;
-- Print the field value for the given field.
procedure Print_Field (Console : in out Console_Type;
Field : in Field_Type;
Value : in String;
Justify : in Justify_Type := J_LEFT) is abstract;
-- Print the title for the given field.
procedure Print_Title (Console : in out Console_Type;
Field : in Field_Type;
Title : in String) is abstract;
-- Start a new title in a report.
procedure Start_Title (Console : in out Console_Type) is abstract;
-- Finish a new title in a report.
procedure End_Title (Console : in out Console_Type) is abstract;
-- Start a new row in a report.
procedure Start_Row (Console : in out Console_Type) is abstract;
-- Finish a new row in a report.
procedure End_Row (Console : in out Console_Type) is abstract;
-- Print the title for the given field and setup the associated field size.
procedure Print_Title (Console : in out Console_Type;
Field : in Field_Type;
Title : in String;
Length : in Positive);
-- Format the address and print it for the given field.
procedure Print_Field (Console : in out Console_Type;
Field : in Field_Type;
Addr : in MAT.Types.Target_Addr);
-- Format the address range and print it for the given field.
procedure Print_Field (Console : in out Console_Type;
Field : in Field_Type;
From : in MAT.Types.Target_Addr;
To : in MAT.Types.Target_Addr);
-- Format the size and print it for the given field.
procedure Print_Size (Console : in out Console_Type;
Field : in Field_Type;
Size : in MAT.Types.Target_Size);
-- Format the thread information and print it for the given field.
procedure Print_Thread (Console : in out Console_Type;
Field : in Field_Type;
Thread : in MAT.Types.Target_Thread_Ref);
-- Format the time tick as a duration and print it for the given field.
procedure Print_Duration (Console : in out Console_Type;
Field : in Field_Type;
Duration : in MAT.Types.Target_Tick_Ref);
-- Format the integer and print it for the given field.
procedure Print_Field (Console : in out Console_Type;
Field : in Field_Type;
Value : in Integer;
Justify : in Justify_Type := J_LEFT);
-- Format the integer and print it for the given field.
procedure Print_Field (Console : in out Console_Type;
Field : in Field_Type;
Value : in Ada.Strings.Unbounded.Unbounded_String;
Justify : in Justify_Type := J_LEFT);
private
type Field_Size_Array is array (Field_Type) of Natural;
type Field_List_Array is array (1 .. Field_Type'Pos (Field_Type'Last)) of Field_Type;
type Console_Type is abstract tagged limited record
Sizes : Field_Size_Array := (others => 1);
Cols : Field_Size_Array := (others => 1);
Fields : Field_List_Array;
Field_Count : Natural := 0;
end record;
end MAT.Consoles;
|
Add F_GROW_SIZE in the console types
|
Add F_GROW_SIZE in the console types
|
Ada
|
apache-2.0
|
stcarrez/mat,stcarrez/mat,stcarrez/mat
|
fee188983652867df873ed972623c9873dd7ee02
|
src/security-policies.adb
|
src/security-policies.adb
|
-----------------------------------------------------------------------
-- security-policies -- Security Policies
-- Copyright (C) 2010, 2011, 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Finalization;
with Ada.Strings.Unbounded;
with Ada.Containers.Hashed_Maps;
with Ada.Containers.Vectors;
with Util.Log.Loggers;
with Util.Strings;
with Util.Refs;
with Util.Beans.Objects;
with Util.Beans.Objects.Vectors;
with Util.Serialize.IO.XML;
with GNAT.Regexp;
with Security.Permissions;
package body Security.Policies is
-- The logger
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Security.Policies");
-- Get the policy name.
function Get_Name (From : in Policy) return String is
begin
return "";
end Get_Name;
-- ------------------------------
-- Permission Manager
-- ------------------------------
-- Add the policy to the policy manager. After a policy is added in the manager,
-- it can participate in the security policy.
procedure Add_Policy (Manager : in out Policy_Manager;
Policy : in Policy_Access) is
begin
null;
end Add_Policy;
-- ------------------------------
-- Add a permission under the given permission name and associated with the controller.
-- To verify the permission, the controller will be called.
-- ------------------------------
procedure Add_Permission (Manager : in out Policy_Manager;
Name : in String;
Permission : in Controller_Access) is
use type Permissions.Permission_Index;
Index : Permission_Index;
begin
Log.Info ("Adding permission {0}", Name);
Permissions.Add_Permission (Name, Index);
if Index >= Manager.Last_Index then
declare
Count : constant Permission_Index := Index + 32;
Perms : constant Controller_Access_Array_Access
:= new Controller_Access_Array (0 .. Count);
begin
if Manager.Permissions /= null then
Perms (Manager.Permissions'Range) := Manager.Permissions.all;
end if;
Manager.Permissions := Perms;
Manager.Last_Index := Count;
end;
end if;
Manager.Permissions (Index) := Permission;
end Add_Permission;
-- Get the security controller associated with the permission index <b>Index</b>.
-- Returns null if there is no such controller.
function Get_Controller (Manager : in Policy_Manager'Class;
Index : in Permissions.Permission_Index) return Controller_Access is
use type Permissions.Permission_Index;
begin
if Index >= Manager.Last_Index then
return null;
else
return Manager.Permissions (Index);
end if;
end Get_Controller;
-- Read the policy file
procedure Read_Policy (Manager : in out Policy_Manager;
File : in String) is
use Util;
Reader : Util.Serialize.IO.XML.Parser;
package Policy_Config is
new Reader_Config (Reader, Manager'Unchecked_Access);
-- package Role_Config is
-- new Security.Controllers.Roles.Reader_Config (Reader, Manager'Unchecked_Access);
pragma Warnings (Off, Policy_Config);
-- pragma Warnings (Off, Role_Config);
begin
Log.Info ("Reading policy file {0}", File);
Reader.Parse (File);
end Read_Policy;
-- Initialize the permission manager.
overriding
procedure Initialize (Manager : in out Policy_Manager) is
begin
null;
end Initialize;
-- Finalize the permission manager.
overriding
procedure Finalize (Manager : in out Policy_Manager) is
begin
null;
end Finalize;
end Security.Policies;
|
-----------------------------------------------------------------------
-- security-policies -- Security Policies
-- Copyright (C) 2010, 2011, 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Finalization;
with Ada.Strings.Unbounded;
with Ada.Containers.Hashed_Maps;
with Ada.Containers.Vectors;
with Util.Log.Loggers;
with Util.Strings;
with Util.Refs;
with Util.Beans.Objects;
with Util.Beans.Objects.Vectors;
with Util.Serialize.IO.XML;
with GNAT.Regexp;
with Security.Permissions;
package body Security.Policies is
-- The logger
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Security.Policies");
-- Get the policy name.
function Get_Name (From : in Policy) return String is
begin
return "";
end Get_Name;
-- ------------------------------
-- Permission Manager
-- ------------------------------
-- ------------------------------
-- Add the policy to the policy manager. After a policy is added in the manager,
-- it can participate in the security policy.
-- Raises Policy_Error if the policy table is full.
-- ------------------------------
procedure Add_Policy (Manager : in out Policy_Manager;
Policy : in Policy_Access) is
Name : constant String := Policy.Get_Name;
begin
Log.Info ("Adding policy {0}", Name);
for I in Manager.Policies'Range loop
if Manager.Policies (I) = null then
Manager.Policies (I) := Policy;
return;
end if;
end loop;
Log.Error ("Policy table is full, increase policy manager table to {0} to add policy {1}",
Positive'Image (Manager.Max_Policies + 1), Name);
raise Policy_Error;
end Add_Policy;
-- ------------------------------
-- Add a permission under the given permission name and associated with the controller.
-- To verify the permission, the controller will be called.
-- ------------------------------
procedure Add_Permission (Manager : in out Policy_Manager;
Name : in String;
Permission : in Controller_Access) is
use type Permissions.Permission_Index;
Index : Permission_Index;
begin
Log.Info ("Adding permission {0}", Name);
Permissions.Add_Permission (Name, Index);
if Index >= Manager.Last_Index then
declare
Count : constant Permission_Index := Index + 32;
Perms : constant Controller_Access_Array_Access
:= new Controller_Access_Array (0 .. Count);
begin
if Manager.Permissions /= null then
Perms (Manager.Permissions'Range) := Manager.Permissions.all;
end if;
Manager.Permissions := Perms;
Manager.Last_Index := Count;
end;
end if;
Manager.Permissions (Index) := Permission;
end Add_Permission;
-- Get the security controller associated with the permission index <b>Index</b>.
-- Returns null if there is no such controller.
function Get_Controller (Manager : in Policy_Manager'Class;
Index : in Permissions.Permission_Index) return Controller_Access is
use type Permissions.Permission_Index;
begin
if Index >= Manager.Last_Index then
return null;
else
return Manager.Permissions (Index);
end if;
end Get_Controller;
-- Read the policy file
procedure Read_Policy (Manager : in out Policy_Manager;
File : in String) is
use Util;
Reader : Util.Serialize.IO.XML.Parser;
package Policy_Config is
new Reader_Config (Reader, Manager'Unchecked_Access);
-- package Role_Config is
-- new Security.Controllers.Roles.Reader_Config (Reader, Manager'Unchecked_Access);
pragma Warnings (Off, Policy_Config);
-- pragma Warnings (Off, Role_Config);
begin
Log.Info ("Reading policy file {0}", File);
Reader.Parse (File);
end Read_Policy;
-- Initialize the permission manager.
overriding
procedure Initialize (Manager : in out Policy_Manager) is
begin
null;
end Initialize;
-- Finalize the permission manager.
overriding
procedure Finalize (Manager : in out Policy_Manager) is
begin
null;
end Finalize;
end Security.Policies;
|
Implement Add_Policy
|
Implement Add_Policy
|
Ada
|
apache-2.0
|
Letractively/ada-security
|
e7bda2bc468c28b2af9ffc7237b2e0cc97b7171c
|
src/security-policies.adb
|
src/security-policies.adb
|
-----------------------------------------------------------------------
-- security-policies -- Security Policies
-- Copyright (C) 2010, 2011, 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Finalization;
with Ada.Strings.Unbounded;
with Ada.Containers.Hashed_Maps;
with Ada.Containers.Vectors;
with Util.Log.Loggers;
with Util.Strings;
with Util.Refs;
with Util.Beans.Objects;
with Util.Beans.Objects.Vectors;
with Util.Serialize.IO.XML;
with GNAT.Regexp;
with Security.Permissions;
package body Security.Policies is
-- The logger
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Security.Policies");
-- Get the policy name.
function Get_Name (From : in Policy) return String is
begin
return "";
end Get_Name;
-- ------------------------------
-- Permission Manager
-- ------------------------------
-- ------------------------------
-- Add the policy to the policy manager. After a policy is added in the manager,
-- it can participate in the security policy.
-- Raises Policy_Error if the policy table is full.
-- ------------------------------
procedure Add_Policy (Manager : in out Policy_Manager;
Policy : in Policy_Access) is
Name : constant String := Policy.Get_Name;
begin
Log.Info ("Adding policy {0}", Name);
for I in Manager.Policies'Range loop
if Manager.Policies (I) = null then
Manager.Policies (I) := Policy;
return;
end if;
end loop;
Log.Error ("Policy table is full, increase policy manager table to {0} to add policy {1}",
Positive'Image (Manager.Max_Policies + 1), Name);
raise Policy_Error;
end Add_Policy;
-- ------------------------------
-- Add a permission under the given permission name and associated with the controller.
-- To verify the permission, the controller will be called.
-- ------------------------------
procedure Add_Permission (Manager : in out Policy_Manager;
Name : in String;
Permission : in Controller_Access) is
use type Permissions.Permission_Index;
Index : Permission_Index;
begin
Log.Info ("Adding permission {0}", Name);
Permissions.Add_Permission (Name, Index);
if Index >= Manager.Last_Index then
declare
Count : constant Permission_Index := Index + 32;
Perms : constant Controller_Access_Array_Access
:= new Controller_Access_Array (0 .. Count);
begin
if Manager.Permissions /= null then
Perms (Manager.Permissions'Range) := Manager.Permissions.all;
end if;
Manager.Permissions := Perms;
Manager.Last_Index := Count;
end;
end if;
Manager.Permissions (Index) := Permission;
end Add_Permission;
-- Get the security controller associated with the permission index <b>Index</b>.
-- Returns null if there is no such controller.
function Get_Controller (Manager : in Policy_Manager'Class;
Index : in Permissions.Permission_Index) return Controller_Access is
use type Permissions.Permission_Index;
begin
if Index >= Manager.Last_Index then
return null;
else
return Manager.Permissions (Index);
end if;
end Get_Controller;
-- Read the policy file
procedure Read_Policy (Manager : in out Policy_Manager;
File : in String) is
use Util;
Reader : Util.Serialize.IO.XML.Parser;
package Policy_Config is
new Reader_Config (Reader, Manager'Unchecked_Access);
-- package Role_Config is
-- new Security.Controllers.Roles.Reader_Config (Reader, Manager'Unchecked_Access);
pragma Warnings (Off, Policy_Config);
-- pragma Warnings (Off, Role_Config);
begin
Log.Info ("Reading policy file {0}", File);
-- Prepare the reader to parse the policy configuration.
for I in Manager.Policies'Range loop
exit when Manager.Policies (I) = null;
Manager.Policies (I).Set_Reader_Config (Reader);
end loop;
-- Read the configuration file.
Reader.Parse (File);
end Read_Policy;
-- Initialize the permission manager.
overriding
procedure Initialize (Manager : in out Policy_Manager) is
begin
null;
end Initialize;
-- Finalize the permission manager.
overriding
procedure Finalize (Manager : in out Policy_Manager) is
begin
null;
end Finalize;
end Security.Policies;
|
-----------------------------------------------------------------------
-- security-policies -- Security Policies
-- Copyright (C) 2010, 2011, 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Finalization;
with Ada.Strings.Unbounded;
with Ada.Containers.Hashed_Maps;
with Ada.Containers.Vectors;
with Util.Log.Loggers;
with Util.Strings;
with Util.Refs;
with Util.Beans.Objects;
with Util.Beans.Objects.Vectors;
with Util.Serialize.IO.XML;
with GNAT.Regexp;
with Security.Permissions;
package body Security.Policies is
-- The logger
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Security.Policies");
-- Get the policy name.
function Get_Name (From : in Policy) return String is
begin
return "";
end Get_Name;
-- ------------------------------
-- Add a permission under the given permission name and associated with the controller.
-- To verify the permission, the controller will be called.
-- ------------------------------
procedure Add_Permission (Manager : in out Policy;
Name : in String;
Permission : in Controller_Access) is
begin
Manager.Manager.Add_Permission (Name, Permission);
end Add_Permission;
-- ------------------------------
-- Permission Manager
-- ------------------------------
-- ------------------------------
-- Add the policy to the policy manager. After a policy is added in the manager,
-- it can participate in the security policy.
-- Raises Policy_Error if the policy table is full.
-- ------------------------------
procedure Add_Policy (Manager : in out Policy_Manager;
Policy : in Policy_Access) is
Name : constant String := Policy.Get_Name;
begin
Log.Info ("Adding policy {0}", Name);
for I in Manager.Policies'Range loop
if Manager.Policies (I) = null then
Manager.Policies (I) := Policy;
Policy.Manager := Manager'Unchecked_Access;
return;
end if;
end loop;
Log.Error ("Policy table is full, increase policy manager table to {0} to add policy {1}",
Positive'Image (Manager.Max_Policies + 1), Name);
raise Policy_Error;
end Add_Policy;
-- ------------------------------
-- Add a permission under the given permission name and associated with the controller.
-- To verify the permission, the controller will be called.
-- ------------------------------
procedure Add_Permission (Manager : in out Policy_Manager;
Name : in String;
Permission : in Controller_Access) is
use type Permissions.Permission_Index;
Index : Permission_Index;
begin
Log.Info ("Adding permission {0}", Name);
Permissions.Add_Permission (Name, Index);
if Index >= Manager.Last_Index then
declare
Count : constant Permission_Index := Index + 32;
Perms : constant Controller_Access_Array_Access
:= new Controller_Access_Array (0 .. Count);
begin
if Manager.Permissions /= null then
Perms (Manager.Permissions'Range) := Manager.Permissions.all;
end if;
Manager.Permissions := Perms;
Manager.Last_Index := Count;
end;
end if;
Manager.Permissions (Index) := Permission;
end Add_Permission;
-- Get the security controller associated with the permission index <b>Index</b>.
-- Returns null if there is no such controller.
function Get_Controller (Manager : in Policy_Manager'Class;
Index : in Permissions.Permission_Index) return Controller_Access is
use type Permissions.Permission_Index;
begin
if Index >= Manager.Last_Index then
return null;
else
return Manager.Permissions (Index);
end if;
end Get_Controller;
-- Read the policy file
procedure Read_Policy (Manager : in out Policy_Manager;
File : in String) is
use Util;
Reader : Util.Serialize.IO.XML.Parser;
package Policy_Config is
new Reader_Config (Reader, Manager'Unchecked_Access);
-- package Role_Config is
-- new Security.Controllers.Roles.Reader_Config (Reader, Manager'Unchecked_Access);
pragma Warnings (Off, Policy_Config);
-- pragma Warnings (Off, Role_Config);
begin
Log.Info ("Reading policy file {0}", File);
-- Prepare the reader to parse the policy configuration.
for I in Manager.Policies'Range loop
exit when Manager.Policies (I) = null;
Manager.Policies (I).Set_Reader_Config (Reader);
end loop;
-- Read the configuration file.
Reader.Parse (File);
end Read_Policy;
-- Initialize the permission manager.
overriding
procedure Initialize (Manager : in out Policy_Manager) is
begin
null;
end Initialize;
-- Finalize the permission manager.
overriding
procedure Finalize (Manager : in out Policy_Manager) is
begin
null;
end Finalize;
end Security.Policies;
|
Implement the Add_Permission on Policy
|
Implement the Add_Permission on Policy
|
Ada
|
apache-2.0
|
stcarrez/ada-security
|
1c8a35727d7948c893e83105d4d7530fae463b36
|
awa/plugins/awa-wikis/regtests/awa-wikis-modules-tests.adb
|
awa/plugins/awa-wikis/regtests/awa-wikis-modules-tests.adb
|
-----------------------------------------------------------------------
-- awa-wikis-modules-tests -- Unit tests for wikis service
-- Copyright (C) 2015, 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Test_Caller;
with Util.Strings;
with ASF.Tests;
with ASF.Requests.Mockup;
with ASF.Responses.Mockup;
with AWA.Tests.Helpers;
with AWA.Tests.Helpers.Users;
with AWA.Services.Contexts;
with Security.Contexts;
package body AWA.Wikis.Modules.Tests is
use ASF.Tests;
use Util.Tests;
package Caller is new Util.Test_Caller (Test, "Wikis.Modules");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test AWA.Wikis.Modules.Create_Wiki_Space",
Test_Create_Wiki_Space'Access);
Caller.Add_Test (Suite, "Test AWA.Wikis.Modules.Create_Wiki_Page",
Test_Create_Wiki_Page'Access);
Caller.Add_Test (Suite, "Test AWA.Wikis.Modules.Create_Wiki_Content",
Test_Create_Wiki_Content'Access);
Caller.Add_Test (Suite, "Test AWA.Wikis.Modules.Wiki_Page",
Test_Wiki_Page'Access);
Caller.Add_Test (Suite, "Test AWA.Wikis.Beans.Save",
Test_Update_Page'Access);
end Add_Tests;
-- ------------------------------
-- Test creation of a wiki space.
-- ------------------------------
procedure Test_Create_Wiki_Space (T : in out Test) is
Sec_Ctx : Security.Contexts.Security_Context;
Context : AWA.Services.Contexts.Service_Context;
W : AWA.Wikis.Models.Wiki_Space_Ref;
W2 : AWA.Wikis.Models.Wiki_Space_Ref;
begin
AWA.Tests.Helpers.Users.Login (Context, Sec_Ctx, "[email protected]");
T.Manager := AWA.Wikis.Modules.Get_Wiki_Module;
T.Assert (T.Manager /= null, "There is no wiki manager");
W.Set_Name ("Test wiki space");
T.Manager.Create_Wiki_Space (W);
T.Assert (W.Is_Inserted, "The new wiki space was not created");
W.Set_Name ("Test wiki space update");
W.Set_Is_Public (True);
T.Manager.Save_Wiki_Space (W);
T.Manager.Load_Wiki_Space (Wiki => W2,
Id => W.Get_Id);
Util.Tests.Assert_Equals (T, "Test wiki space update", String '(W2.Get_Name),
"Invalid wiki space name");
end Test_Create_Wiki_Space;
-- ------------------------------
-- Test creation of a wiki page.
-- ------------------------------
procedure Test_Create_Wiki_Page (T : in out Test) is
Sec_Ctx : Security.Contexts.Security_Context;
Context : AWA.Services.Contexts.Service_Context;
W : AWA.Wikis.Models.Wiki_Space_Ref;
P : AWA.Wikis.Models.Wiki_Page_Ref;
C : AWA.Wikis.Models.Wiki_Content_Ref;
begin
AWA.Tests.Helpers.Users.Login (Context, Sec_Ctx, "[email protected]");
W.Set_Name ("Test wiki space");
T.Manager.Create_Wiki_Space (W);
P.Set_Name ("Private");
P.Set_Title ("The page title");
T.Manager.Create_Wiki_Page (W, P, C);
T.Assert (P.Is_Inserted, "The new wiki page was not created");
C := AWA.Wikis.Models.Null_Wiki_Content;
P := AWA.Wikis.Models.Null_Wiki_Page;
P.Set_Name ("Public");
P.Set_Title ("The page title (public)");
P.Set_Is_Public (True);
T.Manager.Create_Wiki_Page (W, P, C);
T.Assert (P.Is_Inserted, "The new wiki page was not created");
T.Assert (P.Get_Is_Public, "The new wiki page is not public");
end Test_Create_Wiki_Page;
-- ------------------------------
-- Test creation of a wiki page content.
-- ------------------------------
procedure Test_Create_Wiki_Content (T : in out Test) is
Sec_Ctx : Security.Contexts.Security_Context;
Context : AWA.Services.Contexts.Service_Context;
W : AWA.Wikis.Models.Wiki_Space_Ref;
P : AWA.Wikis.Models.Wiki_Page_Ref;
C : AWA.Wikis.Models.Wiki_Content_Ref;
begin
AWA.Tests.Helpers.Users.Login (Context, Sec_Ctx, "[email protected]");
W.Set_Name ("Test wiki space");
T.Manager.Create_Wiki_Space (W);
T.Wiki_Id := W.Get_Id;
P.Set_Name ("PrivatePage");
P.Set_Title ("The page title");
P.Set_Is_Public (False);
T.Manager.Create_Wiki_Page (W, P, C);
T.Private_Id := P.Get_Id;
C := AWA.Wikis.Models.Null_Wiki_Content;
C.Set_Format (AWA.Wikis.Models.FORMAT_MARKDOWN);
C.Set_Content ("-- Title" & ASCII.LF & "A paragraph");
C.Set_Save_Comment ("A first version");
T.Manager.Create_Wiki_Content (P, C);
T.Assert (C.Is_Inserted, "The new wiki content was not created");
T.Assert (not C.Get_Author.Is_Null, "The wiki content has an author");
T.Assert (not C.Get_Page.Is_Null, "The wiki content is associated with the wiki page");
P := AWA.Wikis.Models.Null_Wiki_Page;
C := AWA.Wikis.Models.Null_Wiki_Content;
P.Set_Name ("PublicPage");
P.Set_Title ("The public page title");
P.Set_Is_Public (True);
T.Manager.Create_Wiki_Page (W, P, C);
T.Public_Id := P.Get_Id;
C.Set_Format (AWA.Wikis.Models.FORMAT_MARKDOWN);
C.Set_Content ("-- Title" & ASCII.LF & "A paragraph" & ASCII.LF
& "[Link](http://mylink.com)" & ASCII.LF
& "[Image](my-image.png)");
C.Set_Save_Comment ("A first version");
T.Manager.Create_Wiki_Content (P, C);
T.Assert (C.Is_Inserted, "The new wiki content was not created");
T.Assert (not C.Get_Author.Is_Null, "The wiki content has an author");
T.Assert (not C.Get_Page.Is_Null, "The wiki content is associated with the wiki page");
end Test_Create_Wiki_Content;
-- ------------------------------
-- Test getting the wiki page as well as info, history pages.
-- ------------------------------
procedure Test_Wiki_Page (T : in out Test) is
Request : ASF.Requests.Mockup.Request;
Reply : ASF.Responses.Mockup.Response;
Ident : constant String := Util.Strings.Image (Natural (T.Wiki_Id));
Pub_Ident : constant String := Util.Strings.Image (Natural (T.Public_Id));
begin
ASF.Tests.Do_Get (Request, Reply, "/wikis/view/" & Ident & "/PublicPage",
"wiki-public-1.html");
Assert_Equals (T, ASF.Responses.SC_OK, Reply.Get_Status,
"Invalid response (PublicPage)");
Assert_Matches (T, ".*The public page title.*", Reply,
"Invalid PublicPage page returned",
Status => ASF.Responses.SC_OK);
ASF.Tests.Do_Get (Request, Reply, "/wikis/info/" & Ident & "/" & Pub_Ident,
"wiki-public-info-1.html");
Assert_Equals (T, ASF.Responses.SC_OK, Reply.Get_Status,
"Invalid response (PublicPage info)");
Assert_Matches (T, ".*The public page title.*", Reply,
"Invalid PublicPage info page returned",
Status => ASF.Responses.SC_OK);
ASF.Tests.Do_Get (Request, Reply, "/wikis/history/" & Ident & "/" & Pub_Ident,
"wiki-public-history-1.html");
Assert_Equals (T, ASF.Responses.SC_OK, Reply.Get_Status,
"Invalid response (PublicPage history)");
Assert_Matches (T, ".*The public page title.*", Reply,
"Invalid PublicPage info page returned",
Status => ASF.Responses.SC_OK);
Request.Remove_Attribute ("wikiView");
ASF.Tests.Do_Get (Request, Reply, "/wikis/view/" & Ident & "/PrivatePage",
"wiki-private-1.html");
Assert_Equals (T, ASF.Responses.SC_OK, Reply.Get_Status, "Invalid response (PrivatePage)");
Assert_Matches (T, ".*Protected Wiki Page.*", Reply, "Invalid PrivatePage page returned",
Status => ASF.Responses.SC_OK);
ASF.Tests.Do_Get (Request, Reply, "/wikis/list/" & Ident & "/recent",
"wiki-list-recent-1.html");
Assert_Equals (T, ASF.Responses.SC_OK, Reply.Get_Status,
"Invalid response (list/recent)");
ASF.Tests.Do_Get (Request, Reply, "/wikis/list/" & Ident & "/recent/grid",
"wiki-list-grid-1.html");
Assert_Equals (T, ASF.Responses.SC_OK, Reply.Get_Status,
"Invalid response (list/recent/grid)");
ASF.Tests.Do_Get (Request, Reply, "/wikis/list/" & Ident & "/popular",
"wiki-list-popular-1.html");
Assert_Equals (T, ASF.Responses.SC_OK, Reply.Get_Status,
"Invalid response (list/popular)");
ASF.Tests.Do_Get (Request, Reply, "/wikis/list/" & Ident & "/popular/grid",
"wiki-list-popular-1.html");
Assert_Equals (T, ASF.Responses.SC_OK, Reply.Get_Status,
"Invalid response (list/popular/grid)");
end Test_Wiki_Page;
-- ------------------------------
-- Test updating the wiki page through a POST request.
-- ------------------------------
procedure Test_Update_Page (T : in out Test) is
Request : ASF.Requests.Mockup.Request;
Reply : ASF.Responses.Mockup.Response;
Ident : constant String := Util.Strings.Image (Natural (T.Wiki_Id));
Pub_Ident : constant String := Util.Strings.Image (Natural (T.Public_Id));
begin
AWA.Tests.Helpers.Users.Login ("[email protected]", Request);
Request.Set_Parameter ("title", "The Blog Title");
Request.Set_Parameter ("page-id", Pub_Ident);
Request.Set_Parameter ("page-wiki-id", Ident);
Request.Set_Parameter ("name", "NewPageName");
Request.Set_Parameter ("page-title", "New Page Title");
Request.Set_Parameter ("text", "== Title ==" & ASCII.LF & "A paragraph" & ASCII.LF
& "[[http://mylink.com|Link]]" & ASCII.LF
& "[[Image:my-image.png|My Picture]]" & ASCII.LF
& "== Last header ==" & ASCII.LF);
Request.Set_Parameter ("comment", "Update through test post simulation");
Request.Set_Parameter ("page-is-public", "TRUE");
Request.Set_Parameter ("wiki-format", "FORMAT_MEDIAWIKI");
Request.Set_Parameter ("qtags[1]", "Test-Tag");
Request.Set_Parameter ("save", "1");
Request.Set_Parameter ("post", "1");
ASF.Tests.Do_Post (Request, Reply, "/wikis/edit/" & Ident & "/PublicPage",
"update-wiki.html");
T.Assert (Reply.Get_Status = ASF.Responses.SC_MOVED_TEMPORARILY,
"Invalid response after wiki update");
declare
Result : constant String
:= AWA.Tests.Helpers.Extract_Redirect (Reply, "/asfunit/wikis/view/");
begin
Util.Tests.Assert_Equals (T, Ident & "/NewPageName", Result,
"The page name was not updated");
ASF.Tests.Do_Get (Request, Reply, "/wikis/view/" & Result, "wiki-public-2.html");
Assert_Equals (T, ASF.Responses.SC_OK, Reply.Get_Status,
"Invalid response (NewPageName)");
Assert_Matches (T, ".*Last header.*", Reply,
"Last header is present in the response",
Status => ASF.Responses.SC_OK);
ASF.Tests.Do_Get (Request, Reply, "/wikis/info/" & Ident & "/"
& Pub_Ident, "wiki-info-2.html");
Assert_Equals (T, ASF.Responses.SC_OK, Reply.Get_Status,
"Invalid response (info NewPageName)");
Assert_Matches (T, ".*wiki-image-name.*my-image.png.*", Reply,
"The info page must list the image",
Status => ASF.Responses.SC_OK);
end;
end Test_Update_Page;
end AWA.Wikis.Modules.Tests;
|
-----------------------------------------------------------------------
-- awa-wikis-modules-tests -- Unit tests for wikis service
-- Copyright (C) 2015, 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Test_Caller;
with Util.Strings;
with ASF.Tests;
with ASF.Requests.Mockup;
with ASF.Responses.Mockup;
with AWA.Tests.Helpers;
with AWA.Tests.Helpers.Users;
with AWA.Services.Contexts;
with Security.Contexts;
package body AWA.Wikis.Modules.Tests is
use ASF.Tests;
use Util.Tests;
use type ADO.Identifier;
package Caller is new Util.Test_Caller (Test, "Wikis.Modules");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test AWA.Wikis.Modules.Create_Wiki_Space",
Test_Create_Wiki_Space'Access);
Caller.Add_Test (Suite, "Test AWA.Wikis.Modules.Create_Wiki_Page",
Test_Create_Wiki_Page'Access);
Caller.Add_Test (Suite, "Test AWA.Wikis.Modules.Create_Wiki_Content",
Test_Create_Wiki_Content'Access);
Caller.Add_Test (Suite, "Test AWA.Wikis.Modules.Wiki_Page",
Test_Wiki_Page'Access);
Caller.Add_Test (Suite, "Test AWA.Wikis.Beans.Save",
Test_Update_Page'Access);
end Add_Tests;
-- ------------------------------
-- Test creation of a wiki space.
-- ------------------------------
procedure Test_Create_Wiki_Space (T : in out Test) is
Sec_Ctx : Security.Contexts.Security_Context;
Context : AWA.Services.Contexts.Service_Context;
W : AWA.Wikis.Models.Wiki_Space_Ref;
W2 : AWA.Wikis.Models.Wiki_Space_Ref;
begin
AWA.Tests.Helpers.Users.Login (Context, Sec_Ctx, "[email protected]");
T.Manager := AWA.Wikis.Modules.Get_Wiki_Module;
T.Assert (T.Manager /= null, "There is no wiki manager");
W.Set_Name ("Test wiki space");
T.Manager.Create_Wiki_Space (W);
T.Assert (W.Is_Inserted, "The new wiki space was not created");
W.Set_Name ("Test wiki space update");
W.Set_Is_Public (True);
T.Manager.Save_Wiki_Space (W);
T.Manager.Load_Wiki_Space (Wiki => W2,
Id => W.Get_Id);
Util.Tests.Assert_Equals (T, "Test wiki space update", String '(W2.Get_Name),
"Invalid wiki space name");
end Test_Create_Wiki_Space;
-- ------------------------------
-- Test creation of a wiki page.
-- ------------------------------
procedure Test_Create_Wiki_Page (T : in out Test) is
Sec_Ctx : Security.Contexts.Security_Context;
Context : AWA.Services.Contexts.Service_Context;
W : AWA.Wikis.Models.Wiki_Space_Ref;
P : AWA.Wikis.Models.Wiki_Page_Ref;
C : AWA.Wikis.Models.Wiki_Content_Ref;
begin
AWA.Tests.Helpers.Users.Login (Context, Sec_Ctx, "[email protected]");
T.Manager := AWA.Wikis.Modules.Get_Wiki_Module;
T.Assert (T.Manager /= null, "There is no wiki manager");
W.Set_Name ("Test wiki space");
T.Manager.Create_Wiki_Space (W);
P.Set_Name ("Private");
P.Set_Title ("The page title");
C.Set_Content ("Something");
T.Manager.Create_Wiki_Page (W, P, C);
T.Assert (P.Is_Inserted, "The new wiki page was not created");
P.Set_Content (AWA.Wikis.Models.Null_Wiki_Content);
C := AWA.Wikis.Models.Null_Wiki_Content;
P := AWA.Wikis.Models.Null_Wiki_Page;
P.Set_Name ("Public");
P.Set_Title ("The page title (public)");
P.Set_Is_Public (True);
T.Manager.Create_Wiki_Page (W, P, C);
T.Assert (P.Is_Inserted, "The new wiki page was not created");
T.Assert (P.Get_Is_Public, "The new wiki page is not public");
P.Set_Content (AWA.Wikis.Models.Null_Wiki_Content);
end Test_Create_Wiki_Page;
-- ------------------------------
-- Test creation of a wiki page content.
-- ------------------------------
procedure Test_Create_Wiki_Content (T : in out Test) is
Sec_Ctx : Security.Contexts.Security_Context;
Context : AWA.Services.Contexts.Service_Context;
W : AWA.Wikis.Models.Wiki_Space_Ref;
P : AWA.Wikis.Models.Wiki_Page_Ref;
C : AWA.Wikis.Models.Wiki_Content_Ref;
begin
AWA.Tests.Helpers.Users.Login (Context, Sec_Ctx, "[email protected]");
T.Manager := AWA.Wikis.Modules.Get_Wiki_Module;
T.Assert (T.Manager /= null, "There is no wiki manager");
W.Set_Name ("Test wiki space");
T.Manager.Create_Wiki_Space (W);
T.Wiki_Id := W.Get_Id;
P.Set_Name ("PrivatePage");
P.Set_Title ("The page title");
P.Set_Is_Public (False);
T.Manager.Create_Wiki_Page (W, P, C);
T.Private_Id := P.Get_Id;
C := AWA.Wikis.Models.Null_Wiki_Content;
C.Set_Format (AWA.Wikis.Models.FORMAT_MARKDOWN);
C.Set_Content ("-- Title" & ASCII.LF & "A paragraph");
C.Set_Save_Comment ("A first version");
T.Manager.Create_Wiki_Content (P, C);
T.Assert (C.Is_Inserted, "The new wiki content was not created");
T.Assert (not C.Get_Author.Is_Null, "The wiki content has an author");
T.Assert (C.Get_Page_Id /= ADO.NO_IDENTIFIER,
"The wiki content is associated with the wiki page");
P := AWA.Wikis.Models.Null_Wiki_Page;
C := AWA.Wikis.Models.Null_Wiki_Content;
P.Set_Name ("PublicPage");
P.Set_Title ("The public page title");
P.Set_Is_Public (True);
T.Manager.Create_Wiki_Page (W, P, C);
T.Public_Id := P.Get_Id;
C.Set_Format (AWA.Wikis.Models.FORMAT_MARKDOWN);
C.Set_Content ("-- Title" & ASCII.LF & "A paragraph" & ASCII.LF
& "[Link](http://mylink.com)" & ASCII.LF
& "[Image](my-image.png)");
C.Set_Save_Comment ("A first version");
T.Manager.Create_Wiki_Content (P, C);
T.Assert (C.Is_Inserted, "The new wiki content was not created");
T.Assert (not C.Get_Author.Is_Null, "The wiki content has an author");
T.Assert (C.Get_Page_Id /= ADO.NO_IDENTIFIER,
"The wiki content is associated with the wiki page");
end Test_Create_Wiki_Content;
-- ------------------------------
-- Test getting the wiki page as well as info, history pages.
-- ------------------------------
procedure Test_Wiki_Page (T : in out Test) is
Request : ASF.Requests.Mockup.Request;
Reply : ASF.Responses.Mockup.Response;
Ident : constant String := Util.Strings.Image (Natural (T.Wiki_Id));
Pub_Ident : constant String := Util.Strings.Image (Natural (T.Public_Id));
begin
ASF.Tests.Do_Get (Request, Reply, "/wikis/view/" & Ident & "/PublicPage",
"wiki-public-1.html");
Assert_Equals (T, ASF.Responses.SC_OK, Reply.Get_Status,
"Invalid response (PublicPage)");
Assert_Matches (T, ".*The public page title.*", Reply,
"Invalid PublicPage page returned",
Status => ASF.Responses.SC_OK);
ASF.Tests.Do_Get (Request, Reply, "/wikis/info/" & Ident & "/" & Pub_Ident,
"wiki-public-info-1.html");
Assert_Equals (T, ASF.Responses.SC_OK, Reply.Get_Status,
"Invalid response (PublicPage info)");
Assert_Matches (T, ".*The public page title.*", Reply,
"Invalid PublicPage info page returned",
Status => ASF.Responses.SC_OK);
ASF.Tests.Do_Get (Request, Reply, "/wikis/history/" & Ident & "/" & Pub_Ident,
"wiki-public-history-1.html");
Assert_Equals (T, ASF.Responses.SC_OK, Reply.Get_Status,
"Invalid response (PublicPage history)");
Assert_Matches (T, ".*The public page title.*", Reply,
"Invalid PublicPage info page returned",
Status => ASF.Responses.SC_OK);
Request.Remove_Attribute ("wikiView");
ASF.Tests.Do_Get (Request, Reply, "/wikis/view/" & Ident & "/PrivatePage",
"wiki-private-1.html");
Assert_Equals (T, ASF.Responses.SC_OK, Reply.Get_Status, "Invalid response (PrivatePage)");
Assert_Matches (T, ".*Protected Wiki Page.*", Reply, "Invalid PrivatePage page returned",
Status => ASF.Responses.SC_OK);
ASF.Tests.Do_Get (Request, Reply, "/wikis/list/" & Ident & "/recent",
"wiki-list-recent-1.html");
Assert_Equals (T, ASF.Responses.SC_OK, Reply.Get_Status,
"Invalid response (list/recent)");
ASF.Tests.Do_Get (Request, Reply, "/wikis/list/" & Ident & "/recent/grid",
"wiki-list-grid-1.html");
Assert_Equals (T, ASF.Responses.SC_OK, Reply.Get_Status,
"Invalid response (list/recent/grid)");
ASF.Tests.Do_Get (Request, Reply, "/wikis/list/" & Ident & "/popular",
"wiki-list-popular-1.html");
Assert_Equals (T, ASF.Responses.SC_OK, Reply.Get_Status,
"Invalid response (list/popular)");
ASF.Tests.Do_Get (Request, Reply, "/wikis/list/" & Ident & "/popular/grid",
"wiki-list-popular-1.html");
Assert_Equals (T, ASF.Responses.SC_OK, Reply.Get_Status,
"Invalid response (list/popular/grid)");
end Test_Wiki_Page;
-- ------------------------------
-- Test updating the wiki page through a POST request.
-- ------------------------------
procedure Test_Update_Page (T : in out Test) is
Request : ASF.Requests.Mockup.Request;
Reply : ASF.Responses.Mockup.Response;
Ident : constant String := Util.Strings.Image (Natural (T.Wiki_Id));
Pub_Ident : constant String := Util.Strings.Image (Natural (T.Public_Id));
begin
AWA.Tests.Helpers.Users.Login ("[email protected]", Request);
Request.Set_Parameter ("title", "The Blog Title");
Request.Set_Parameter ("page-id", Pub_Ident);
Request.Set_Parameter ("page-wiki-id", Ident);
Request.Set_Parameter ("name", "NewPageName");
Request.Set_Parameter ("page-title", "New Page Title");
Request.Set_Parameter ("text", "== Title ==" & ASCII.LF & "A paragraph" & ASCII.LF
& "[[http://mylink.com|Link]]" & ASCII.LF
& "[[Image:my-image.png|My Picture]]" & ASCII.LF
& "== Last header ==" & ASCII.LF);
Request.Set_Parameter ("comment", "Update through test post simulation");
Request.Set_Parameter ("page-is-public", "TRUE");
Request.Set_Parameter ("wiki-format", "FORMAT_MEDIAWIKI");
Request.Set_Parameter ("qtags[1]", "Test-Tag");
Request.Set_Parameter ("save", "1");
Request.Set_Parameter ("post", "1");
ASF.Tests.Do_Post (Request, Reply, "/wikis/edit/" & Ident & "/PublicPage",
"update-wiki.html");
T.Assert (Reply.Get_Status = ASF.Responses.SC_MOVED_TEMPORARILY,
"Invalid response after wiki update");
declare
Result : constant String
:= AWA.Tests.Helpers.Extract_Redirect (Reply, "/asfunit/wikis/view/");
begin
Util.Tests.Assert_Equals (T, Ident & "/NewPageName", Result,
"The page name was not updated");
ASF.Tests.Do_Get (Request, Reply, "/wikis/view/" & Result, "wiki-public-2.html");
Assert_Equals (T, ASF.Responses.SC_OK, Reply.Get_Status,
"Invalid response (NewPageName)");
Assert_Matches (T, ".*Last header.*", Reply,
"Last header is present in the response",
Status => ASF.Responses.SC_OK);
ASF.Tests.Do_Get (Request, Reply, "/wikis/info/" & Ident & "/"
& Pub_Ident, "wiki-info-2.html");
Assert_Equals (T, ASF.Responses.SC_OK, Reply.Get_Status,
"Invalid response (info NewPageName)");
Assert_Matches (T, ".*wiki-image-name.*my-image.png.*", Reply,
"The info page must list the image",
Status => ASF.Responses.SC_OK);
end;
end Test_Update_Page;
end AWA.Wikis.Modules.Tests;
|
Update the unit tests for wiki page creation
|
Update the unit tests for wiki page creation
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
30daf48ad10e450bad44d343044475f1d793fd15
|
matp/src/symbols/mat-symbols-targets.adb
|
matp/src/symbols/mat-symbols-targets.adb
|
-----------------------------------------------------------------------
-- mat-symbols-targets - Symbol files management
-- Copyright (C) 2014, 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Bfd.Sections;
with ELF;
with Util.Strings;
with Util.Files;
with Util.Log.Loggers;
with Ada.Directories;
with MAT.Formats;
package body MAT.Symbols.Targets is
-- The logger
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("MAT.Symbols.Targets");
-- ------------------------------
-- Open the binary and load the symbols from that file.
-- ------------------------------
procedure Open (Symbols : in out Target_Symbols;
Path : in String) is
begin
Log.Info ("Loading symbols from {0}", Path);
--
-- Bfd.Files.Open (Symbols.File, Path, "");
-- if Bfd.Files.Check_Format (Symbols.File, Bfd.Files.OBJECT) then
-- Bfd.Symbols.Read_Symbols (Symbols.File, Symbols.Symbols);
-- end if;
end Open;
-- ------------------------------
-- Load the symbol table for the associated region.
-- ------------------------------
procedure Open (Symbols : in out Region_Symbols;
Path : in String;
Search_Path : in String) is
Pos : Natural;
begin
Log.Info ("Loading symbols from {0}", Path);
if Ada.Directories.Exists (Path) then
Bfd.Files.Open (Symbols.File, Path, "");
else
Pos := Util.Strings.Rindex (Path, '/');
if Pos > 0 then
Bfd.Files.Open (Symbols.File,
Util.Files.Find_File_Path (Path (Pos + 1 .. Path'Last), Search_Path));
end if;
end if;
if Bfd.Files.Check_Format (Symbols.File, Bfd.Files.OBJECT) then
Bfd.Symbols.Read_Symbols (Symbols.File, Symbols.Symbols);
end if;
end Open;
-- ------------------------------
-- Load the symbols associated with a shared library described by the memory region.
-- ------------------------------
procedure Load_Symbols (Symbols : in out Target_Symbols;
Region : in MAT.Memory.Region_Info;
Offset_Addr : in MAT.Types.Target_Addr) is
Pos : constant Symbols_Cursor := Symbols.Libraries.Find (Region.Start_Addr);
Syms : Region_Symbols_Ref;
begin
if not Symbols_Maps.Has_Element (Pos) then
Syms := Region_Symbols_Refs.Create;
Syms.Value.Region := Region;
Syms.Value.Offset := Offset_Addr;
Symbols.Libraries.Insert (Region.Start_Addr, Syms);
else
Syms := Symbols_Maps.Element (Pos);
end if;
if Ada.Strings.Unbounded.Length (Region.Path) > 0 then
Open (Syms.Value.all, Ada.Strings.Unbounded.To_String (Region.Path),
Ada.Strings.Unbounded.To_String (Symbols.Search_Path));
end if;
end Load_Symbols;
-- ------------------------------
-- Load the symbols associated with all the shared libraries described by
-- the memory region map.
-- ------------------------------
procedure Load_Symbols (Symbols : in out Target_Symbols;
Regions : in MAT.Memory.Region_Info_Map) is
use type ELF.Elf32_Word;
Iter : MAT.Memory.Region_Info_Cursor := Regions.First;
begin
while MAT.Memory.Region_Info_Maps.Has_Element (Iter) loop
declare
Region : MAT.Memory.Region_Info := MAT.Memory.Region_Info_Maps.Element (Iter);
Offset : MAT.Types.Target_Addr;
begin
if (Region.Flags and ELF.PF_X) /= 0 then
if Ada.Strings.Unbounded.Length (Region.Path) = 0 then
Region.Path := Symbols.Path;
Offset := 0;
else
Offset := Region.Start_Addr;
end if;
MAT.Symbols.Targets.Load_Symbols (Symbols, Region, Offset);
end if;
exception
when Bfd.OPEN_ERROR =>
Symbols.Console.Error ("Cannot open symbol library file '"
& Ada.Strings.Unbounded.To_String (Region.Path) & "'");
end;
MAT.Memory.Region_Info_Maps.Next (Iter);
end loop;
end Load_Symbols;
-- ------------------------------
-- Demangle the symbol.
-- ------------------------------
procedure Demangle (Symbols : in Target_Symbols;
Symbol : in out Symbol_Info) is
use type Bfd.Demangle_Flags;
use Ada.Strings.Unbounded;
Pos : constant Natural := Index (Symbol.File, ".", Ada.Strings.Backward);
begin
if Symbol.Line = 0 or else Pos = 0 or else Symbol.Symbols.Is_Null then
return;
end if;
declare
Mode : Bfd.Demangle_Flags := Symbols.Demangle;
Len : constant Positive := Length (Symbol.File);
Ext : constant String := Slice (Symbol.File, Pos, Len);
Sym : constant String := To_String (Symbol.Name);
begin
if Mode = Bfd.Constants.DMGL_AUTO and then Ext = ".adb" then
Mode := Bfd.Constants.DMGL_GNAT;
end if;
declare
Name : constant String := Bfd.Symbols.Demangle (Symbol.Symbols.Value.File, Sym, Mode);
begin
if Name'Length > 0 then
Symbol.Name := To_Unbounded_String (Name);
end if;
end;
end;
end Demangle;
procedure Find_Nearest_Line (Symbols : in Region_Symbols;
Addr : in MAT.Types.Target_Addr;
Symbol : out Symbol_Info) is
use type Bfd.Vma_Type;
Text_Section : Bfd.Sections.Section;
Pc : constant Bfd.Vma_Type := Bfd.Vma_Type (Addr);
begin
if not Bfd.Files.Is_Open (Symbols.File) then
Symbol.File := Symbols.Region.Path;
return;
end if;
Text_Section := Bfd.Sections.Find_Section (Symbols.File, ".text");
Bfd.Symbols.Find_Nearest_Line (File => Symbols.File,
Sec => Text_Section,
Symbols => Symbols.Symbols,
Addr => Pc,
Name => Symbol.File,
Func => Symbol.Name,
Line => Symbol.Line);
end Find_Nearest_Line;
-- ------------------------------
-- Find the nearest source file and line for the given address.
-- ------------------------------
procedure Find_Nearest_Line (Symbols : in Target_Symbols;
Addr : in MAT.Types.Target_Addr;
Symbol : out Symbol_Info) is
use Ada.Strings.Unbounded;
Pos : constant Symbols_Cursor := Symbols.Libraries.Floor (Addr);
begin
Symbol.Line := 0;
if Symbols_Maps.Has_Element (Pos) then
declare
Syms : constant Region_Symbols_Ref := Symbols_Maps.Element (Pos);
begin
if Syms.Value.Region.End_Addr > Addr then
Symbol.Symbols := Syms;
Find_Nearest_Line (Symbols => Syms.Value.all,
Addr => Addr - Syms.Value.Offset,
Symbol => Symbol);
Demangle (Symbols, Symbol);
return;
end if;
end;
end if;
Symbol.Line := 0;
Symbol.File := Ada.Strings.Unbounded.To_Unbounded_String ("");
Symbol.Name := Ada.Strings.Unbounded.To_Unbounded_String (MAT.Formats.Addr (Addr));
exception
when Bfd.NOT_FOUND =>
Symbol.Line := 0;
Symbol.File := Ada.Strings.Unbounded.To_Unbounded_String ("");
Symbol.Name := Ada.Strings.Unbounded.To_Unbounded_String (MAT.Formats.Addr (Addr));
end Find_Nearest_Line;
-- ------------------------------
-- Find the symbol in the symbol table and return the start and end address.
-- ------------------------------
procedure Find_Symbol_Range (Symbols : in Target_Symbols;
Name : in String;
From : out MAT.Types.Target_Addr;
To : out MAT.Types.Target_Addr) is
use type Bfd.Symbols.Symbol;
Iter : Symbols_Cursor := Symbols.Libraries.First;
begin
while Symbols_Maps.Has_Element (Iter) loop
declare
Syms : constant Region_Symbols_Ref := Symbols_Maps.Element (Iter);
Sym : Bfd.Symbols.Symbol;
Sec : Bfd.Sections.Section;
begin
if not Syms.Is_Null and then Bfd.Files.Is_Open (Syms.Value.File) then
Sym := Bfd.Symbols.Get_Symbol (Syms.Value.Symbols, Name);
if Sym /= Bfd.Symbols.Null_Symbol then
Sec := Bfd.Symbols.Get_Section (Sym);
if not Bfd.Sections.Is_Undefined_Section (Sec) then
From := MAT.Types.Target_Addr (Bfd.Symbols.Get_Value (Sym));
From := From + Syms.Value.Offset;
To := From + MAT.Types.Target_Addr (Bfd.Symbols.Get_Symbol_Size (Sym));
return;
end if;
end if;
end if;
end;
Symbols_Maps.Next (Iter);
end loop;
end Find_Symbol_Range;
end MAT.Symbols.Targets;
|
-----------------------------------------------------------------------
-- mat-symbols-targets - Symbol files management
-- Copyright (C) 2014, 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Bfd.Sections;
with ELF;
with Util.Strings;
with Util.Files;
with Util.Log.Loggers;
with Ada.Directories;
with MAT.Formats;
package body MAT.Symbols.Targets is
-- The logger
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("MAT.Symbols.Targets");
-- ------------------------------
-- Open the binary and load the symbols from that file.
-- ------------------------------
procedure Open (Symbols : in out Target_Symbols;
Path : in String) is
begin
Log.Info ("Loading symbols from {0}", Path);
--
-- Bfd.Files.Open (Symbols.File, Path, "");
-- if Bfd.Files.Check_Format (Symbols.File, Bfd.Files.OBJECT) then
-- Bfd.Symbols.Read_Symbols (Symbols.File, Symbols.Symbols);
-- end if;
end Open;
-- ------------------------------
-- Load the symbol table for the associated region.
-- ------------------------------
procedure Open (Symbols : in out Region_Symbols;
Path : in String;
Search_Path : in String) is
Pos : Natural;
begin
Log.Info ("Loading symbols from {0}", Path);
if Ada.Directories.Exists (Path) then
Bfd.Files.Open (Symbols.File, Path, "");
else
Pos := Util.Strings.Rindex (Path, '/');
if Pos > 0 then
Bfd.Files.Open (Symbols.File,
Util.Files.Find_File_Path (Path (Pos + 1 .. Path'Last), Search_Path));
end if;
end if;
if Bfd.Files.Check_Format (Symbols.File, Bfd.Files.OBJECT) then
Bfd.Symbols.Read_Symbols (Symbols.File, Symbols.Symbols);
end if;
end Open;
-- ------------------------------
-- Load the symbols associated with a shared library described by the memory region.
-- ------------------------------
procedure Load_Symbols (Symbols : in out Target_Symbols;
Region : in MAT.Memory.Region_Info;
Offset_Addr : in MAT.Types.Target_Addr) is
use type Bfd.File_Flags;
Pos : constant Symbols_Cursor := Symbols.Libraries.Find (Region.Start_Addr);
Syms : Region_Symbols_Ref;
begin
if not Symbols_Maps.Has_Element (Pos) then
Syms := Region_Symbols_Refs.Create;
Syms.Value.Region := Region;
Syms.Value.Offset := Offset_Addr;
Symbols.Libraries.Insert (Region.Start_Addr, Syms);
else
Syms := Symbols_Maps.Element (Pos);
end if;
if Ada.Strings.Unbounded.Length (Region.Path) > 0 then
Open (Syms.Value.all, Ada.Strings.Unbounded.To_String (Region.Path),
Ada.Strings.Unbounded.To_String (Symbols.Search_Path));
if (Bfd.Files.Get_File_Flags (Syms.Value.File) and Bfd.Files.EXEC_P) /= 0 then
Syms.Value.Offset := 0;
end if;
end if;
end Load_Symbols;
-- ------------------------------
-- Load the symbols associated with all the shared libraries described by
-- the memory region map.
-- ------------------------------
procedure Load_Symbols (Symbols : in out Target_Symbols;
Regions : in MAT.Memory.Region_Info_Map) is
use type ELF.Elf32_Word;
Iter : MAT.Memory.Region_Info_Cursor := Regions.First;
begin
while MAT.Memory.Region_Info_Maps.Has_Element (Iter) loop
declare
Region : MAT.Memory.Region_Info := MAT.Memory.Region_Info_Maps.Element (Iter);
Offset : MAT.Types.Target_Addr;
begin
if (Region.Flags and ELF.PF_X) /= 0 then
if Ada.Strings.Unbounded.Length (Region.Path) = 0 then
Region.Path := Symbols.Path;
Offset := 0;
else
Offset := Region.Start_Addr;
end if;
MAT.Symbols.Targets.Load_Symbols (Symbols, Region, Offset);
end if;
exception
when Bfd.OPEN_ERROR =>
Symbols.Console.Error ("Cannot open symbol library file '"
& Ada.Strings.Unbounded.To_String (Region.Path) & "'");
end;
MAT.Memory.Region_Info_Maps.Next (Iter);
end loop;
end Load_Symbols;
-- ------------------------------
-- Demangle the symbol.
-- ------------------------------
procedure Demangle (Symbols : in Target_Symbols;
Symbol : in out Symbol_Info) is
use type Bfd.Demangle_Flags;
use Ada.Strings.Unbounded;
Pos : constant Natural := Index (Symbol.File, ".", Ada.Strings.Backward);
begin
if Symbol.Line = 0 or else Pos = 0 or else Symbol.Symbols.Is_Null then
return;
end if;
declare
Mode : Bfd.Demangle_Flags := Symbols.Demangle;
Len : constant Positive := Length (Symbol.File);
Ext : constant String := Slice (Symbol.File, Pos, Len);
Sym : constant String := To_String (Symbol.Name);
begin
if Mode = Bfd.Constants.DMGL_AUTO and then Ext = ".adb" then
Mode := Bfd.Constants.DMGL_GNAT;
end if;
declare
Name : constant String := Bfd.Symbols.Demangle (Symbol.Symbols.Value.File, Sym, Mode);
begin
if Name'Length > 0 then
Symbol.Name := To_Unbounded_String (Name);
end if;
end;
end;
end Demangle;
procedure Find_Nearest_Line (Symbols : in Region_Symbols;
Addr : in MAT.Types.Target_Addr;
Symbol : out Symbol_Info) is
use type Bfd.Vma_Type;
Text_Section : Bfd.Sections.Section;
Pc : constant Bfd.Vma_Type := Bfd.Vma_Type (Addr);
begin
if not Bfd.Files.Is_Open (Symbols.File) then
Symbol.File := Symbols.Region.Path;
return;
end if;
Text_Section := Bfd.Sections.Find_Section (Symbols.File, ".text");
Bfd.Symbols.Find_Nearest_Line (File => Symbols.File,
Sec => Text_Section,
Symbols => Symbols.Symbols,
Addr => Pc,
Name => Symbol.File,
Func => Symbol.Name,
Line => Symbol.Line);
end Find_Nearest_Line;
-- ------------------------------
-- Find the nearest source file and line for the given address.
-- ------------------------------
procedure Find_Nearest_Line (Symbols : in Target_Symbols;
Addr : in MAT.Types.Target_Addr;
Symbol : out Symbol_Info) is
use Ada.Strings.Unbounded;
Pos : constant Symbols_Cursor := Symbols.Libraries.Floor (Addr);
begin
Symbol.Line := 0;
if Symbols_Maps.Has_Element (Pos) then
declare
Syms : constant Region_Symbols_Ref := Symbols_Maps.Element (Pos);
begin
if Syms.Value.Region.End_Addr > Addr then
Symbol.Symbols := Syms;
Find_Nearest_Line (Symbols => Syms.Value.all,
Addr => Addr - Syms.Value.Offset,
Symbol => Symbol);
Demangle (Symbols, Symbol);
return;
end if;
end;
end if;
Symbol.Line := 0;
Symbol.File := Ada.Strings.Unbounded.To_Unbounded_String ("");
Symbol.Name := Ada.Strings.Unbounded.To_Unbounded_String (MAT.Formats.Addr (Addr));
exception
when Bfd.NOT_FOUND =>
Symbol.Line := 0;
Symbol.File := Ada.Strings.Unbounded.To_Unbounded_String ("");
Symbol.Name := Ada.Strings.Unbounded.To_Unbounded_String (MAT.Formats.Addr (Addr));
end Find_Nearest_Line;
-- ------------------------------
-- Find the symbol in the symbol table and return the start and end address.
-- ------------------------------
procedure Find_Symbol_Range (Symbols : in Target_Symbols;
Name : in String;
From : out MAT.Types.Target_Addr;
To : out MAT.Types.Target_Addr) is
use type Bfd.Symbols.Symbol;
Iter : Symbols_Cursor := Symbols.Libraries.First;
begin
while Symbols_Maps.Has_Element (Iter) loop
declare
Syms : constant Region_Symbols_Ref := Symbols_Maps.Element (Iter);
Sym : Bfd.Symbols.Symbol;
Sec : Bfd.Sections.Section;
begin
if not Syms.Is_Null and then Bfd.Files.Is_Open (Syms.Value.File) then
Sym := Bfd.Symbols.Get_Symbol (Syms.Value.Symbols, Name);
if Sym /= Bfd.Symbols.Null_Symbol then
Sec := Bfd.Symbols.Get_Section (Sym);
if not Bfd.Sections.Is_Undefined_Section (Sec) then
From := MAT.Types.Target_Addr (Bfd.Symbols.Get_Value (Sym));
From := From + Syms.Value.Offset;
To := From + MAT.Types.Target_Addr (Bfd.Symbols.Get_Symbol_Size (Sym));
return;
end if;
end if;
end if;
end;
Symbols_Maps.Next (Iter);
end loop;
end Find_Symbol_Range;
end MAT.Symbols.Targets;
|
Check for the BFD flags EXEC_P to decide whether an offset is necessary or not (this is more reliable than the previous method)
|
Check for the BFD flags EXEC_P to decide whether an offset is necessary or not
(this is more reliable than the previous method)
|
Ada
|
apache-2.0
|
stcarrez/mat,stcarrez/mat,stcarrez/mat
|
5ee7baa0bf67e567546beab264aff15751fe1dd2
|
src/gen-commands-info.adb
|
src/gen-commands-info.adb
|
-----------------------------------------------------------------------
-- gen-commands-info -- Collect and give information about the project
-- Copyright (C) 2011, 2012, 2013, 2014, 2015, 2017, 2018 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Text_IO;
with Ada.Directories;
with Gen.Utils;
with Gen.Utils.GNAT;
with Gen.Model.Projects;
with Util.Strings.Sets;
with Util.Files;
package body Gen.Commands.Info is
-- ------------------------------
-- Execute the command with the arguments.
-- ------------------------------
overriding
procedure Execute (Cmd : in out Command;
Name : in String;
Args : in Argument_List'Class;
Generator : in out Gen.Generator.Handler) is
pragma Unreferenced (Cmd, Name, Args);
procedure Collect_Directories (List : in Gen.Utils.String_List.Vector;
Result : out Gen.Utils.String_List.Vector);
procedure Print_Model_File (Name : in String;
File : in String;
Done : out Boolean);
procedure Print_GNAT_Projects (Project : in out Gen.Model.Projects.Project_Definition);
procedure Print_Dynamo_Projects (Project : in out Model.Projects.Root_Project_Definition);
procedure Print_Modules (Project : in out Gen.Model.Projects.Project_Definition'Class;
Indent : in Ada.Text_IO.Positive_Count);
procedure Print_Project (Project : in out Gen.Model.Projects.Root_Project_Definition);
procedure Print_Project_List (Indent : in Ada.Text_IO.Positive_Count;
List : in Gen.Model.Projects.Project_Vectors.Vector);
List : Gen.Utils.String_List.Vector;
Names : Util.Strings.Sets.Set;
procedure Collect_Directories (List : in Gen.Utils.String_List.Vector;
Result : out Gen.Utils.String_List.Vector) is
procedure Add_Model_Dir (Base_Dir : in String;
Dir : in String);
procedure Add_Model_Dir (Base_Dir : in String;
Dir : in String) is
Path : constant String := Util.Files.Compose (Base_Dir, Dir);
begin
if not Result.Contains (Path) and then Ada.Directories.Exists (Path) then
Result.Append (Path);
end if;
end Add_Model_Dir;
Iter : Gen.Utils.String_List.Cursor := List.First;
begin
while Gen.Utils.String_List.Has_Element (Iter) loop
declare
Path : constant String := Gen.Utils.String_List.Element (Iter);
Dir : constant String := Ada.Directories.Containing_Directory (Path);
begin
Add_Model_Dir (Dir, "db");
Add_Model_Dir (Dir, "db/regtests");
Add_Model_Dir (Dir, "db/samples");
end;
Gen.Utils.String_List.Next (Iter);
end loop;
end Collect_Directories;
procedure Print_Model_File (Name : in String;
File : in String;
Done : out Boolean) is
pragma Unreferenced (Name);
begin
Ada.Text_IO.Put (" ");
Ada.Text_IO.Put_Line (File);
Done := False;
end Print_Model_File;
-- ------------------------------
-- Print the list of GNAT projects used by the main project.
-- ------------------------------
procedure Print_GNAT_Projects (Project : in out Gen.Model.Projects.Project_Definition) is
use Gen.Utils.GNAT;
Iter : Project_Info_Vectors.Cursor := Project.Project_Files.First;
Info : Project_Info;
begin
if Project_Info_Vectors.Has_Element (Iter) then
Ada.Text_IO.Put_Line ("GNAT project files:");
while Project_Info_Vectors.Has_Element (Iter) loop
Ada.Text_IO.Put (" ");
Info := Project_Info_Vectors.Element (Iter);
Ada.Text_IO.Put_Line (Ada.Strings.Unbounded.To_String (Info.Path));
Project_Info_Vectors.Next (Iter);
end loop;
end if;
end Print_GNAT_Projects;
-- ------------------------------
-- Print the list of Dynamo modules
-- ------------------------------
procedure Print_Project_List (Indent : in Ada.Text_IO.Positive_Count;
List : in Gen.Model.Projects.Project_Vectors.Vector) is
use Gen.Model.Projects;
use type Ada.Text_IO.Positive_Count;
Iter : Project_Vectors.Cursor := List.First;
Ref : Model.Projects.Project_Reference;
begin
while Project_Vectors.Has_Element (Iter) loop
Ref := Project_Vectors.Element (Iter);
Ada.Text_IO.Set_Col (Indent);
Ada.Text_IO.Put (" ");
Ada.Text_IO.Put (Ada.Strings.Unbounded.To_String (Ref.Name));
Ada.Text_IO.Set_Col (Indent + 30);
if Ref.Project /= null then
Ada.Text_IO.Put_Line (Ada.Strings.Unbounded.To_String (Ref.Project.Path));
else
Ada.Text_IO.Put_Line ("?");
end if;
Project_Vectors.Next (Iter);
end loop;
end Print_Project_List;
-- ------------------------------
-- Print the list of Dynamo modules
-- ------------------------------
procedure Print_Modules (Project : in out Gen.Model.Projects.Project_Definition'Class;
Indent : in Ada.Text_IO.Positive_Count) is
use Gen.Model.Projects;
use type Ada.Text_IO.Positive_Count;
Iter : Project_Vectors.Cursor := Project.Modules.First;
Ref : Model.Projects.Project_Reference;
begin
if not Project.Modules.Is_Empty then
Ada.Text_IO.Set_Col (Indent);
Ada.Text_IO.Put_Line ("Dynamo plugins:");
Print_Project_List (Indent, Project.Modules);
Print_Project_List (Indent, Project.Dependencies);
Iter := Project.Modules.First;
while Project_Vectors.Has_Element (Iter) loop
Ref := Project_Vectors.Element (Iter);
if Ref.Project /= null and then not Ref.Project.Modules.Is_Empty then
declare
Name : constant String := Ada.Strings.Unbounded.To_String (Ref.Name);
begin
Ada.Text_IO.Set_Col (Indent);
if Names.Contains (Name) then
Ada.Text_IO.Put_Line ("!! " & Name);
else
Names.Insert (Name);
Ada.Text_IO.Put_Line ("== " & Name);
Print_Modules (Ref.Project.all, Indent + 4);
Names.Delete (Name);
end if;
end;
end if;
Project_Vectors.Next (Iter);
end loop;
end if;
end Print_Modules;
-- ------------------------------
-- Print the list of Dynamo projects used by the main project.
-- ------------------------------
procedure Print_Dynamo_Projects (Project : in out Model.Projects.Root_Project_Definition) is
Iter : Gen.Utils.String_List.Cursor := Project.Dynamo_Files.First;
begin
if Gen.Utils.String_List.Has_Element (Iter) then
Ada.Text_IO.Put_Line ("Dynamo project files:");
while Gen.Utils.String_List.Has_Element (Iter) loop
Ada.Text_IO.Put (" ");
Ada.Text_IO.Put_Line (Gen.Utils.String_List.Element (Iter));
Gen.Utils.String_List.Next (Iter);
end loop;
end if;
end Print_Dynamo_Projects;
procedure Print_Project (Project : in out Gen.Model.Projects.Root_Project_Definition) is
begin
Print_GNAT_Projects (Gen.Model.Projects.Project_Definition (Project));
Print_Dynamo_Projects (Project);
Print_Modules (Project, 1);
declare
Model_Dirs : Gen.Utils.String_List.Vector;
begin
Collect_Directories (List, Model_Dirs);
declare
Iter : Gen.Utils.String_List.Cursor := Model_Dirs.First;
begin
Ada.Text_IO.Put_Line ("ADO model files:");
while Gen.Utils.String_List.Has_Element (Iter) loop
Ada.Text_IO.Put (" ");
Ada.Text_IO.Put_Line (Gen.Utils.String_List.Element (Iter));
Util.Files.Iterate_Files_Path (Pattern => "*.xml",
Path => Gen.Utils.String_List.Element (Iter),
Process => Print_Model_File'Access);
Gen.Utils.String_List.Next (Iter);
end loop;
end;
end;
end Print_Project;
begin
Generator.Read_Project ("dynamo.xml", True);
Generator.Update_Project (Print_Project'Access);
end Execute;
-- ------------------------------
-- Write the help associated with the command.
-- ------------------------------
overriding
procedure Help (Cmd : in out Command;
Generator : in out Gen.Generator.Handler) is
pragma Unreferenced (Cmd, Generator);
begin
Ada.Text_IO.Put_Line ("info: Print information about the current project");
Ada.Text_IO.Put_Line ("Usage: info");
Ada.Text_IO.New_Line;
end Help;
end Gen.Commands.Info;
|
-----------------------------------------------------------------------
-- gen-commands-info -- Collect and give information about the project
-- Copyright (C) 2011, 2012, 2013, 2014, 2015, 2017, 2018, 2019 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Text_IO;
with Ada.Directories;
with Gen.Utils;
with Gen.Utils.GNAT;
with Gen.Model.Projects;
with Util.Strings.Sets;
with Util.Files;
package body Gen.Commands.Info is
-- ------------------------------
-- Execute the command with the arguments.
-- ------------------------------
overriding
procedure Execute (Cmd : in out Command;
Name : in String;
Args : in Argument_List'Class;
Generator : in out Gen.Generator.Handler) is
pragma Unreferenced (Cmd, Name, Args);
procedure Collect_Directories (List : in Gen.Utils.String_List.Vector;
Result : out Gen.Utils.String_List.Vector);
procedure Print_Model_File (Name : in String;
File : in String;
Done : out Boolean);
procedure Print_GNAT_Projects (Project : in out Gen.Model.Projects.Project_Definition);
procedure Print_Dynamo_Projects (Project : in out Model.Projects.Root_Project_Definition);
procedure Print_Modules (Project : in out Gen.Model.Projects.Project_Definition'Class;
Indent : in Ada.Text_IO.Positive_Count);
procedure Print_Project (Project : in out Gen.Model.Projects.Root_Project_Definition);
procedure Print_Project_List (Indent : in Ada.Text_IO.Positive_Count;
List : in Gen.Model.Projects.Project_Vectors.Vector);
List : Gen.Utils.String_List.Vector;
Names : Util.Strings.Sets.Set;
procedure Collect_Directories (List : in Gen.Utils.String_List.Vector;
Result : out Gen.Utils.String_List.Vector) is
procedure Add_Model_Dir (Base_Dir : in String;
Dir : in String);
procedure Add_Model_Dir (Base_Dir : in String;
Dir : in String) is
Path : constant String := Util.Files.Compose (Base_Dir, Dir);
begin
if not Result.Contains (Path) and then Ada.Directories.Exists (Path) then
Result.Append (Path);
end if;
end Add_Model_Dir;
Iter : Gen.Utils.String_List.Cursor := List.First;
begin
while Gen.Utils.String_List.Has_Element (Iter) loop
declare
Path : constant String := Gen.Utils.String_List.Element (Iter);
Dir : constant String := Ada.Directories.Containing_Directory (Path);
begin
Add_Model_Dir (Dir, "db");
Add_Model_Dir (Dir, "db/regtests");
Add_Model_Dir (Dir, "db/samples");
end;
Gen.Utils.String_List.Next (Iter);
end loop;
end Collect_Directories;
procedure Print_Model_File (Name : in String;
File : in String;
Done : out Boolean) is
pragma Unreferenced (Name);
begin
Ada.Text_IO.Put (" ");
Ada.Text_IO.Put_Line (File);
Done := False;
end Print_Model_File;
-- ------------------------------
-- Print the list of GNAT projects used by the main project.
-- ------------------------------
procedure Print_GNAT_Projects (Project : in out Gen.Model.Projects.Project_Definition) is
use Gen.Utils.GNAT;
Iter : Project_Info_Vectors.Cursor := Project.Project_Files.First;
Info : Project_Info;
begin
if Project_Info_Vectors.Has_Element (Iter) then
Ada.Text_IO.Put_Line ("GNAT project files:");
while Project_Info_Vectors.Has_Element (Iter) loop
Ada.Text_IO.Put (" ");
Info := Project_Info_Vectors.Element (Iter);
Ada.Text_IO.Put_Line (Ada.Strings.Unbounded.To_String (Info.Path));
Project_Info_Vectors.Next (Iter);
end loop;
end if;
end Print_GNAT_Projects;
-- ------------------------------
-- Print the list of Dynamo modules
-- ------------------------------
procedure Print_Project_List (Indent : in Ada.Text_IO.Positive_Count;
List : in Gen.Model.Projects.Project_Vectors.Vector) is
use Gen.Model.Projects;
use type Ada.Text_IO.Positive_Count;
Iter : Project_Vectors.Cursor := List.First;
Ref : Model.Projects.Project_Reference;
begin
while Project_Vectors.Has_Element (Iter) loop
Ref := Project_Vectors.Element (Iter);
Ada.Text_IO.Set_Col (Indent);
Ada.Text_IO.Put (" ");
Ada.Text_IO.Put (Ada.Strings.Unbounded.To_String (Ref.Name));
Ada.Text_IO.Set_Col (Indent + 30);
if Ref.Project /= null then
Ada.Text_IO.Put_Line (Ada.Strings.Unbounded.To_String (Ref.Project.Path));
else
Ada.Text_IO.Put_Line ("?");
end if;
Project_Vectors.Next (Iter);
end loop;
end Print_Project_List;
-- ------------------------------
-- Print the list of Dynamo modules
-- ------------------------------
procedure Print_Modules (Project : in out Gen.Model.Projects.Project_Definition'Class;
Indent : in Ada.Text_IO.Positive_Count) is
use Gen.Model.Projects;
use type Ada.Text_IO.Positive_Count;
Iter : Project_Vectors.Cursor := Project.Modules.First;
Ref : Model.Projects.Project_Reference;
begin
if not Project.Modules.Is_Empty then
Ada.Text_IO.Set_Col (Indent);
Ada.Text_IO.Put_Line ("Dynamo plugins:");
Print_Project_List (Indent, Project.Modules);
Print_Project_List (Indent, Project.Dependencies);
Iter := Project.Modules.First;
while Project_Vectors.Has_Element (Iter) loop
Ref := Project_Vectors.Element (Iter);
if Ref.Project /= null and then not Ref.Project.Modules.Is_Empty then
declare
Name : constant String := Ada.Strings.Unbounded.To_String (Ref.Name);
begin
Ada.Text_IO.Set_Col (Indent);
if Names.Contains (Name) then
Ada.Text_IO.Put_Line ("!! " & Name);
else
Names.Insert (Name);
Ada.Text_IO.Put_Line ("== " & Name);
Print_Modules (Ref.Project.all, Indent + 4);
Names.Delete (Name);
end if;
end;
end if;
Project_Vectors.Next (Iter);
end loop;
end if;
end Print_Modules;
-- ------------------------------
-- Print the list of Dynamo projects used by the main project.
-- ------------------------------
procedure Print_Dynamo_Projects (Project : in out Model.Projects.Root_Project_Definition) is
Iter : Gen.Utils.String_List.Cursor := Project.Dynamo_Files.First;
begin
if Gen.Utils.String_List.Has_Element (Iter) then
Ada.Text_IO.Put_Line ("Dynamo project files:");
while Gen.Utils.String_List.Has_Element (Iter) loop
Ada.Text_IO.Put (" ");
Ada.Text_IO.Put_Line (Gen.Utils.String_List.Element (Iter));
Gen.Utils.String_List.Next (Iter);
end loop;
end if;
end Print_Dynamo_Projects;
procedure Print_Project (Project : in out Gen.Model.Projects.Root_Project_Definition) is
begin
Print_GNAT_Projects (Gen.Model.Projects.Project_Definition (Project));
Print_Dynamo_Projects (Project);
Print_Modules (Project, 1);
declare
Model_Dirs : Gen.Utils.String_List.Vector;
begin
Collect_Directories (List, Model_Dirs);
declare
Iter : Gen.Utils.String_List.Cursor := Model_Dirs.First;
begin
Ada.Text_IO.Put_Line ("ADO model files:");
while Gen.Utils.String_List.Has_Element (Iter) loop
Ada.Text_IO.Put (" ");
Ada.Text_IO.Put_Line (Gen.Utils.String_List.Element (Iter));
Util.Files.Iterate_Files_Path (Pattern => "*.xml",
Path => Gen.Utils.String_List.Element (Iter),
Process => Print_Model_File'Access);
Gen.Utils.String_List.Next (Iter);
end loop;
end;
end;
end Print_Project;
begin
Generator.Read_Project ("dynamo.xml", True);
Generator.Update_Project (Print_Project'Access);
end Execute;
-- ------------------------------
-- Write the help associated with the command.
-- ------------------------------
overriding
procedure Help (Cmd : in out Command;
Name : in String;
Generator : in out Gen.Generator.Handler) is
pragma Unreferenced (Cmd, Name, Generator);
begin
Ada.Text_IO.Put_Line ("info: Print information about the current project");
Ada.Text_IO.Put_Line ("Usage: info");
Ada.Text_IO.New_Line;
end Help;
end Gen.Commands.Info;
|
Add Name parameter to the Help procedure
|
Add Name parameter to the Help procedure
|
Ada
|
apache-2.0
|
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
|
aa2c110c28a0f30f5f52dcd48a43d6dea39f36d1
|
src/gen-model-queries.adb
|
src/gen-model-queries.adb
|
-----------------------------------------------------------------------
-- gen-model-queries -- XML Mapped Database queries representation
-- 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.
-----------------------------------------------------------------------
package body Gen.Model.Queries 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 Sort_Definition;
Name : in String) return Util.Beans.Objects.Object is
begin
if Name = "name" then
return Util.Beans.Objects.To_Object (From.Name);
elsif Name = "sql" then
return Util.Beans.Objects.To_Object (From.Sql);
else
return Definition (From).Get_Value (Name);
end if;
end Get_Value;
-- ------------------------------
-- Get the value identified by the name.
-- If the name cannot be found, the method should return the Null object.
-- ------------------------------
overriding
function Get_Value (From : Query_Definition;
Name : String) return Util.Beans.Objects.Object is
begin
if Name = "sorts" then
return From.Sorts_Bean;
elsif Name = "isBean" then
return Util.Beans.Objects.To_Object (True);
else
return Tables.Table_Definition (From).Get_Value (Name);
end if;
end Get_Value;
-- ------------------------------
-- Prepare the generation of the model.
-- ------------------------------
overriding
procedure Prepare (O : in out Query_Definition) is
begin
Tables.Table_Definition (O).Prepare;
end Prepare;
-- ------------------------------
-- Add a new sort mode for the query definition.
-- ------------------------------
procedure Add_Sort (Into : in out Query_Definition;
Name : in Unbounded_String;
Sql : in Unbounded_String) is
Item : constant Sort_Definition_Access := new Sort_Definition;
begin
Item.Name := Name;
Item.Sql := Sql;
Into.Sorts.Append (Item);
end Add_Sort;
-- ------------------------------
-- Initialize the table definition instance.
-- ------------------------------
overriding
procedure Initialize (O : in out Query_Definition) is
begin
O.Sorts_Bean := Util.Beans.Objects.To_Object (O.Sorts'Unchecked_Access,
Util.Beans.Objects.STATIC);
Tables.Table_Definition (O).Initialize;
end Initialize;
-- 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 Query_File_Definition;
Name : in String) return Util.Beans.Objects.Object is
begin
if Name = "queries" then
return From.Queries_Bean;
elsif Name = "path" then
return Util.Beans.Objects.To_Object (From.File_Name);
elsif Name = "sha1" then
return Util.Beans.Objects.To_Object (From.Sha1);
else
return Query_Definition (From).Get_Value (Name);
end if;
end Get_Value;
-- Prepare the generation of the model.
overriding
procedure Prepare (O : in out Query_File_Definition) is
begin
Tables.Table_Definition (O).Prepare;
end Prepare;
-- ------------------------------
-- Add a new query to the definition.
-- ------------------------------
procedure Add_Query (Into : in out Query_File_Definition;
Name : in Unbounded_String;
Query : out Query_Definition_Access) is
begin
Query := new Query_Definition;
Query.Name := Name;
Into.Queries.Append (Query.all'Access);
-- Query.Number := Into.Queries.Get_Count;
end Add_Query;
-- ------------------------------
-- Initialize the table definition instance.
-- ------------------------------
overriding
procedure Initialize (O : in out Query_File_Definition) is
begin
O.Queries_Bean := Util.Beans.Objects.To_Object (O.Queries'Unchecked_Access,
Util.Beans.Objects.STATIC);
Tables.Table_Definition (O).Initialize;
end Initialize;
end Gen.Model.Queries;
|
-----------------------------------------------------------------------
-- gen-model-queries -- XML Mapped Database queries representation
-- 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.
-----------------------------------------------------------------------
package body Gen.Model.Queries 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 Sort_Definition;
Name : in String) return Util.Beans.Objects.Object is
begin
if Name = "name" then
return Util.Beans.Objects.To_Object (From.Name);
elsif Name = "sql" then
return Util.Beans.Objects.To_Object (From.Sql);
else
return Definition (From).Get_Value (Name);
end if;
end Get_Value;
-- ------------------------------
-- Get the value identified by the name.
-- If the name cannot be found, the method should return the Null object.
-- ------------------------------
overriding
function Get_Value (From : Query_Definition;
Name : String) return Util.Beans.Objects.Object is
begin
if Name = "sorts" then
return From.Sorts_Bean;
elsif Name = "isBean" then
return Util.Beans.Objects.To_Object (True);
else
return Tables.Table_Definition (From).Get_Value (Name);
end if;
end Get_Value;
-- ------------------------------
-- Prepare the generation of the model.
-- ------------------------------
overriding
procedure Prepare (O : in out Query_Definition) is
begin
Tables.Table_Definition (O).Prepare;
end Prepare;
-- ------------------------------
-- Add a new sort mode for the query definition.
-- ------------------------------
procedure Add_Sort (Into : in out Query_Definition;
Name : in Unbounded_String;
Sql : in Unbounded_String) is
Item : constant Sort_Definition_Access := new Sort_Definition;
begin
Item.Set_Name (Name);
Item.Sql := Sql;
Into.Sorts.Append (Item);
end Add_Sort;
-- ------------------------------
-- Initialize the table definition instance.
-- ------------------------------
overriding
procedure Initialize (O : in out Query_Definition) is
begin
O.Sorts_Bean := Util.Beans.Objects.To_Object (O.Sorts'Unchecked_Access,
Util.Beans.Objects.STATIC);
Tables.Table_Definition (O).Initialize;
end Initialize;
-- 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 Query_File_Definition;
Name : in String) return Util.Beans.Objects.Object is
begin
if Name = "queries" then
return From.Queries_Bean;
elsif Name = "path" then
return Util.Beans.Objects.To_Object (From.File_Name);
elsif Name = "sha1" then
return Util.Beans.Objects.To_Object (From.Sha1);
else
return Query_Definition (From).Get_Value (Name);
end if;
end Get_Value;
-- Prepare the generation of the model.
overriding
procedure Prepare (O : in out Query_File_Definition) is
begin
Tables.Table_Definition (O).Prepare;
end Prepare;
-- ------------------------------
-- Add a new query to the definition.
-- ------------------------------
procedure Add_Query (Into : in out Query_File_Definition;
Name : in Unbounded_String;
Query : out Query_Definition_Access) is
begin
Query := new Query_Definition;
Query.Set_Name (Name);
Into.Queries.Append (Query.all'Access);
-- Query.Number := Into.Queries.Get_Count;
end Add_Query;
-- ------------------------------
-- Initialize the table definition instance.
-- ------------------------------
overriding
procedure Initialize (O : in out Query_File_Definition) is
begin
O.Queries_Bean := Util.Beans.Objects.To_Object (O.Queries'Unchecked_Access,
Util.Beans.Objects.STATIC);
Tables.Table_Definition (O).Initialize;
end Initialize;
end Gen.Model.Queries;
|
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
|
404de0a534c310bebd301c8fcb92440de1f63ea1
|
regtests/util-serialize-io-json-tests.adb
|
regtests/util-serialize-io-json-tests.adb
|
-----------------------------------------------------------------------
-- serialize-io-json-tests -- Unit tests for JSON parser
-- 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.Streams.Stream_IO;
with Ada.Characters.Wide_Wide_Latin_1;
with Util.Test_Caller;
with Util.Log.Loggers;
with Util.Streams.Files;
package body Util.Serialize.IO.JSON.Tests is
use Util.Log;
Log : constant Loggers.Logger := Loggers.Create ("Util.Serialize.IO.JSON");
package Caller is new Util.Test_Caller (Test, "Serialize.IO.JSON");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test Util.Serialize.IO.JSON.Parse (parse errors)",
Test_Parse_Error'Access);
Caller.Add_Test (Suite, "Test Util.Serialize.IO.JSON.Parse (parse Ok)",
Test_Parser'Access);
Caller.Add_Test (Suite, "Test Util.Serialize.IO.JSON.Write",
Test_Output'Access);
end Add_Tests;
-- ------------------------------
-- Check various JSON parsing errors.
-- ------------------------------
procedure Test_Parse_Error (T : in out Test) is
pragma Unreferenced (T);
procedure Check_Parse_Error (Content : in String);
procedure Check_Parse_Error (Content : in String) is
P : Parser;
begin
P.Parse_String (Content);
Log.Error ("No exception raised for: {0}", Content);
exception
when Parse_Error =>
null;
end Check_Parse_Error;
begin
Check_Parse_Error ("{ ""person"":23");
Check_Parse_Error ("{ person: 23]");
Check_Parse_Error ("[ }");
Check_Parse_Error ("{[]}");
Check_Parse_Error ("{");
Check_Parse_Error ("{[");
Check_Parse_Error ("{ ""person");
Check_Parse_Error ("{ ""person"":");
Check_Parse_Error ("{ ""person"":""asf");
Check_Parse_Error ("{ ""person"":""asf""");
Check_Parse_Error ("{ ""person"":""asf"",");
Check_Parse_Error ("{ ""person"":""\uze""}");
Check_Parse_Error ("{ ""person"":""\u012-""}");
Check_Parse_Error ("{ ""person"":""\u012G""}");
end Test_Parse_Error;
-- ------------------------------
-- Check various (basic) JSON valid strings (no mapper).
-- ------------------------------
procedure Test_Parser (T : in out Test) is
pragma Unreferenced (T);
procedure Check_Parse (Content : in String);
procedure Check_Parse (Content : in String) is
P : Parser;
begin
P.Parse_String (Content);
exception
when Parse_Error =>
Log.Error ("Parse error for: " & Content);
raise;
end Check_Parse;
begin
Check_Parse ("{ ""person"":23}");
Check_Parse ("{ }");
Check_Parse ("{""person"":""asf""}");
Check_Parse ("{""person"":""asf"",""age"":""2""}");
Check_Parse ("{ ""person"":""\u0123""}");
Check_Parse ("{ ""person"":""\u4567""}");
Check_Parse ("{ ""person"":""\u89ab""}");
Check_Parse ("{ ""person"":""\ucdef""}");
Check_Parse ("{ ""person"":""\u1CDE""}");
Check_Parse ("{ ""person"":""\u2ABF""}");
end Test_Parser;
-- ------------------------------
-- Generate some output stream for the test.
-- ------------------------------
procedure Write_Stream (Stream : in out Util.Serialize.IO.Output_Stream'Class) is
Name : Ada.Strings.Unbounded.Unbounded_String;
Wide : constant Wide_Wide_String :=
Ada.Characters.Wide_Wide_Latin_1.CR &
Ada.Characters.Wide_Wide_Latin_1.LF &
Ada.Characters.Wide_Wide_Latin_1.HT &
Wide_Wide_Character'Val (16#080#) &
Wide_Wide_Character'Val (16#1fC#) &
Wide_Wide_Character'Val (16#2acbf#);
begin
Ada.Strings.Unbounded.Append (Name, "Katniss Everdeen");
Stream.Start_Document;
Stream.Start_Entity ("root");
Stream.Start_Entity ("person");
Stream.Write_Attribute ("id", 1);
Stream.Write_Attribute ("name", Name);
Stream.Write_Entity ("name", Name);
Stream.Write_Entity ("gender", "female");
Stream.Write_Entity ("volunteer", True);
Stream.Write_Entity ("age", 17);
Stream.Write_Wide_Entity ("skin", "olive skin");
Stream.Start_Array ("badges");
Stream.Start_Entity ("badge");
Stream.Write_Entity ("level", "gold");
Stream.Write_Entity ("name", "hunter");
Stream.End_Entity ("badge");
Stream.Start_Entity ("badge");
Stream.Write_Entity ("level", "gold");
Stream.Write_Entity ("name", "archery");
Stream.End_Entity ("badge");
Stream.End_Array ("badges");
Stream.Start_Entity ("district");
Stream.Write_Attribute ("id", 12);
Stream.Write_Wide_Attribute ("industry", "Coal mining");
Stream.Write_Attribute ("state", "<destroyed>");
Stream.Write_Long_Entity ("members", 10_000);
Stream.Write_Entity ("description", "<TBW>&""");
Stream.Write_Wide_Entity ("wescape", "'""<>&;,@!`~[]{}^%*()-+=");
Stream.Write_Entity ("escape", "'""<>&;,@!`~\[]{}^%*()-+=");
Stream.Write_Wide_Entity ("wide", Wide);
Stream.End_Entity ("district");
Stream.End_Entity ("person");
Stream.End_Entity ("root");
Stream.End_Document;
end Write_Stream;
-- ------------------------------
-- Test the JSON output stream generation.
-- ------------------------------
procedure Test_Output (T : in out Test) is
File : aliased Util.Streams.Files.File_Stream;
Stream : Util.Serialize.IO.JSON.Output_Stream;
Expect : constant String := Util.Tests.Get_Path ("regtests/expect/test-stream.json");
Path : constant String := Util.Tests.Get_Test_Path ("regtests/result/test-stream.json");
begin
File.Create (Mode => Ada.Streams.Stream_IO.Out_File, Name => Path);
Stream.Initialize (Output => File'Unchecked_Access, Input => null, Size => 10000);
Write_Stream (Stream);
Stream.Close;
Util.Tests.Assert_Equal_Files (T => T,
Expect => Expect,
Test => Path,
Message => "JSON output serialization");
end Test_Output;
end Util.Serialize.IO.JSON.Tests;
|
-----------------------------------------------------------------------
-- serialize-io-json-tests -- Unit tests for JSON parser
-- 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.Streams.Stream_IO;
with Ada.Characters.Wide_Wide_Latin_1;
with Util.Test_Caller;
with Util.Log.Loggers;
with Util.Streams.Files;
package body Util.Serialize.IO.JSON.Tests is
use Util.Log;
Log : constant Loggers.Logger := Loggers.Create ("Util.Serialize.IO.JSON");
package Caller is new Util.Test_Caller (Test, "Serialize.IO.JSON");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test Util.Serialize.IO.JSON.Parse (parse errors)",
Test_Parse_Error'Access);
Caller.Add_Test (Suite, "Test Util.Serialize.IO.JSON.Parse (parse Ok)",
Test_Parser'Access);
Caller.Add_Test (Suite, "Test Util.Serialize.IO.JSON.Write",
Test_Output'Access);
end Add_Tests;
-- ------------------------------
-- Check various JSON parsing errors.
-- ------------------------------
procedure Test_Parse_Error (T : in out Test) is
pragma Unreferenced (T);
procedure Check_Parse_Error (Content : in String);
procedure Check_Parse_Error (Content : in String) is
P : Parser;
begin
P.Parse_String (Content);
Log.Error ("No exception raised for: {0}", Content);
exception
when Parse_Error =>
null;
end Check_Parse_Error;
begin
Check_Parse_Error ("{ ""person"":23");
Check_Parse_Error ("{ person: 23]");
Check_Parse_Error ("[ }");
Check_Parse_Error ("{[]}");
Check_Parse_Error ("{");
Check_Parse_Error ("{[");
Check_Parse_Error ("{ ""person");
Check_Parse_Error ("{ ""person"":");
Check_Parse_Error ("{ ""person"":""asf");
Check_Parse_Error ("{ ""person"":""asf""");
Check_Parse_Error ("{ ""person"":""asf"",");
Check_Parse_Error ("{ ""person"":""\uze""}");
Check_Parse_Error ("{ ""person"":""\u012-""}");
Check_Parse_Error ("{ ""person"":""\u012G""}");
end Test_Parse_Error;
-- ------------------------------
-- Check various (basic) JSON valid strings (no mapper).
-- ------------------------------
procedure Test_Parser (T : in out Test) is
pragma Unreferenced (T);
procedure Check_Parse (Content : in String);
procedure Check_Parse (Content : in String) is
P : Parser;
begin
P.Parse_String (Content);
exception
when Parse_Error =>
Log.Error ("Parse error for: " & Content);
raise;
end Check_Parse;
begin
Check_Parse ("{ ""person"":23}");
Check_Parse ("{ }");
Check_Parse ("{""person"":""asf""}");
Check_Parse ("{""person"":""asf"",""age"":""2""}");
Check_Parse ("{ ""person"":""\u0123""}");
Check_Parse ("{ ""person"":""\u4567""}");
Check_Parse ("{ ""person"":""\u89ab""}");
Check_Parse ("{ ""person"":""\ucdef""}");
Check_Parse ("{ ""person"":""\u1CDE""}");
Check_Parse ("{ ""person"":""\u2ABF""}");
end Test_Parser;
-- ------------------------------
-- Generate some output stream for the test.
-- ------------------------------
procedure Write_Stream (Stream : in out Util.Serialize.IO.Output_Stream'Class) is
Name : Ada.Strings.Unbounded.Unbounded_String;
Wide : constant Wide_Wide_String :=
Ada.Characters.Wide_Wide_Latin_1.CR &
Ada.Characters.Wide_Wide_Latin_1.LF &
Ada.Characters.Wide_Wide_Latin_1.HT &
Wide_Wide_Character'Val (16#080#) &
Wide_Wide_Character'Val (16#1fC#) &
Wide_Wide_Character'Val (16#20AC#) &
Wide_Wide_Character'Val (16#2acbf#);
begin
Ada.Strings.Unbounded.Append (Name, "Katniss Everdeen");
Stream.Start_Document;
Stream.Start_Entity ("root");
Stream.Start_Entity ("person");
Stream.Write_Attribute ("id", 1);
Stream.Write_Attribute ("name", Name);
Stream.Write_Entity ("name", Name);
Stream.Write_Entity ("gender", "female");
Stream.Write_Entity ("volunteer", True);
Stream.Write_Entity ("age", 17);
Stream.Write_Wide_Entity ("skin", "olive skin");
Stream.Start_Array ("badges");
Stream.Start_Entity ("badge");
Stream.Write_Entity ("level", "gold");
Stream.Write_Entity ("name", "hunter");
Stream.End_Entity ("badge");
Stream.Start_Entity ("badge");
Stream.Write_Entity ("level", "gold");
Stream.Write_Entity ("name", "archery");
Stream.End_Entity ("badge");
Stream.End_Array ("badges");
Stream.Start_Entity ("district");
Stream.Write_Attribute ("id", 12);
Stream.Write_Wide_Attribute ("industry", "Coal mining");
Stream.Write_Attribute ("state", "<destroyed>");
Stream.Write_Long_Entity ("members", 10_000);
Stream.Write_Entity ("description", "<TBW>&""");
Stream.Write_Wide_Entity ("wescape", "'""<>&;,@!`~[]{}^%*()-+=");
Stream.Write_Entity ("escape", "'""<>&;,@!`~\[]{}^%*()-+=");
Stream.Write_Wide_Entity ("wide", Wide);
Stream.End_Entity ("district");
Stream.End_Entity ("person");
Stream.End_Entity ("root");
Stream.End_Document;
end Write_Stream;
-- ------------------------------
-- Test the JSON output stream generation.
-- ------------------------------
procedure Test_Output (T : in out Test) is
File : aliased Util.Streams.Files.File_Stream;
Stream : Util.Serialize.IO.JSON.Output_Stream;
Expect : constant String := Util.Tests.Get_Path ("regtests/expect/test-stream.json");
Path : constant String := Util.Tests.Get_Test_Path ("regtests/result/test-stream.json");
begin
File.Create (Mode => Ada.Streams.Stream_IO.Out_File, Name => Path);
Stream.Initialize (Output => File'Unchecked_Access, Input => null, Size => 10000);
Write_Stream (Stream);
Stream.Close;
Util.Tests.Assert_Equal_Files (T => T,
Expect => Expect,
Test => Path,
Message => "JSON output serialization");
end Test_Output;
end Util.Serialize.IO.JSON.Tests;
|
Update the stream test
|
Update the stream test
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
839a6d0465888e1e0b8b6a61490a902729e62803
|
regtests/util-serialize-io-json-tests.adb
|
regtests/util-serialize-io-json-tests.adb
|
-----------------------------------------------------------------------
-- serialize-io-json-tests -- Unit tests for JSON parser
-- 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.Streams.Stream_IO;
with Ada.Characters.Wide_Wide_Latin_1;
with Util.Test_Caller;
with Util.Log.Loggers;
with Util.Streams.Files;
package body Util.Serialize.IO.JSON.Tests is
use Util.Log;
Log : constant Loggers.Logger := Loggers.Create ("Util.Serialize.IO.JSON");
package Caller is new Util.Test_Caller (Test, "Serialize.IO.JSON");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test Util.Serialize.IO.JSON.Parse (parse errors)",
Test_Parse_Error'Access);
Caller.Add_Test (Suite, "Test Util.Serialize.IO.JSON.Parse (parse Ok)",
Test_Parser'Access);
Caller.Add_Test (Suite, "Test Util.Serialize.IO.JSON.Write",
Test_Output'Access);
end Add_Tests;
-- ------------------------------
-- Check various JSON parsing errors.
-- ------------------------------
procedure Test_Parse_Error (T : in out Test) is
pragma Unreferenced (T);
procedure Check_Parse_Error (Content : in String);
procedure Check_Parse_Error (Content : in String) is
P : Parser;
begin
P.Parse_String (Content);
Log.Error ("No exception raised for: {0}", Content);
exception
when Parse_Error =>
null;
end Check_Parse_Error;
begin
Check_Parse_Error ("{ ""person"":23");
Check_Parse_Error ("{ person: 23]");
Check_Parse_Error ("[ }");
Check_Parse_Error ("{[]}");
Check_Parse_Error ("{");
Check_Parse_Error ("{[");
Check_Parse_Error ("{ ""person");
Check_Parse_Error ("{ ""person"":");
Check_Parse_Error ("{ ""person"":""asf");
Check_Parse_Error ("{ ""person"":""asf""");
Check_Parse_Error ("{ ""person"":""asf"",");
Check_Parse_Error ("{ ""person"":""\uze""}");
Check_Parse_Error ("{ ""person"":""\u012-""}");
Check_Parse_Error ("{ ""person"":""\u012G""}");
end Test_Parse_Error;
-- ------------------------------
-- Check various (basic) JSON valid strings (no mapper).
-- ------------------------------
procedure Test_Parser (T : in out Test) is
pragma Unreferenced (T);
procedure Check_Parse (Content : in String);
procedure Check_Parse (Content : in String) is
P : Parser;
begin
P.Parse_String (Content);
exception
when Parse_Error =>
Log.Error ("Parse error for: " & Content);
raise;
end Check_Parse;
begin
Check_Parse ("{ ""person"":23}");
Check_Parse ("{ }");
Check_Parse ("{""person"":""asf""}");
Check_Parse ("{""person"":""asf"",""age"":""2""}");
Check_Parse ("{ ""person"":""\u0123""}");
Check_Parse ("{ ""person"":""\u4567""}");
Check_Parse ("{ ""person"":""\u89ab""}");
Check_Parse ("{ ""person"":""\ucdef""}");
Check_Parse ("{ ""person"":""\u1CDE""}");
Check_Parse ("{ ""person"":""\u2ABF""}");
end Test_Parser;
-- ------------------------------
-- Generate some output stream for the test.
-- ------------------------------
procedure Write_Stream (Stream : in out Util.Serialize.IO.Output_Stream'Class) is
Name : Ada.Strings.Unbounded.Unbounded_String;
Wide : constant Wide_Wide_String :=
Ada.Characters.Wide_Wide_Latin_1.CR &
Ada.Characters.Wide_Wide_Latin_1.LF &
Ada.Characters.Wide_Wide_Latin_1.HT &
Wide_Wide_Character'Val (16#080#) &
Wide_Wide_Character'Val (16#1fC#) &
Wide_Wide_Character'Val (16#20AC#) &
Wide_Wide_Character'Val (16#2acbf#);
begin
Ada.Strings.Unbounded.Append (Name, "Katniss Everdeen");
Stream.Start_Document;
Stream.Start_Entity ("root");
Stream.Start_Entity ("person");
Stream.Write_Attribute ("id", 1);
Stream.Write_Attribute ("name", Name);
Stream.Write_Entity ("name", Name);
Stream.Write_Entity ("gender", "female");
Stream.Write_Entity ("volunteer", True);
Stream.Write_Entity ("age", 17);
Stream.Write_Wide_Entity ("skin", "olive skin");
Stream.Start_Array ("badges");
Stream.Start_Entity ("badge");
Stream.Write_Entity ("level", "gold");
Stream.Write_Entity ("name", "hunter");
Stream.End_Entity ("badge");
Stream.Start_Entity ("badge");
Stream.Write_Entity ("level", "gold");
Stream.Write_Entity ("name", "archery");
Stream.End_Entity ("badge");
Stream.End_Array ("badges");
Stream.Start_Entity ("district");
Stream.Write_Attribute ("id", 12);
Stream.Write_Wide_Attribute ("industry", "Coal mining");
Stream.Write_Attribute ("state", "<destroyed>");
Stream.Write_Long_Entity ("members", 10_000);
Stream.Write_Entity ("description", "<TBW>&""");
Stream.Write_Wide_Entity ("wescape", "'""<>&;,@!`~[]{}^%*()-+=");
Stream.Write_Entity ("escape", "'""<>&;,@!`~\[]{}^%*()-+=");
Stream.Write_Wide_Entity ("wide", Wide);
Stream.End_Entity ("district");
Stream.End_Entity ("person");
Stream.End_Entity ("root");
Stream.End_Document;
end Write_Stream;
-- ------------------------------
-- Test the JSON output stream generation.
-- ------------------------------
procedure Test_Output (T : in out Test) is
File : aliased Util.Streams.Files.File_Stream;
Stream : Util.Serialize.IO.JSON.Output_Stream;
Expect : constant String := Util.Tests.Get_Path ("regtests/expect/test-stream.json");
Path : constant String := Util.Tests.Get_Test_Path ("regtests/result/test-stream.json");
begin
File.Create (Mode => Ada.Streams.Stream_IO.Out_File, Name => Path);
Stream.Initialize (Output => File'Unchecked_Access, Input => null, Size => 10000);
Write_Stream (Stream);
Stream.Close;
Util.Tests.Assert_Equal_Files (T => T,
Expect => Expect,
Test => Path,
Message => "JSON output serialization");
end Test_Output;
end Util.Serialize.IO.JSON.Tests;
|
-----------------------------------------------------------------------
-- serialize-io-json-tests -- Unit tests for JSON parser
-- 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.Streams.Stream_IO;
with Ada.Characters.Wide_Wide_Latin_1;
with Ada.Calendar.Formatting;
with Util.Test_Caller;
with Util.Log.Loggers;
with Util.Streams.Files;
package body Util.Serialize.IO.JSON.Tests is
use Util.Log;
Log : constant Loggers.Logger := Loggers.Create ("Util.Serialize.IO.JSON");
package Caller is new Util.Test_Caller (Test, "Serialize.IO.JSON");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test Util.Serialize.IO.JSON.Parse (parse errors)",
Test_Parse_Error'Access);
Caller.Add_Test (Suite, "Test Util.Serialize.IO.JSON.Parse (parse Ok)",
Test_Parser'Access);
Caller.Add_Test (Suite, "Test Util.Serialize.IO.JSON.Write",
Test_Output'Access);
end Add_Tests;
-- ------------------------------
-- Check various JSON parsing errors.
-- ------------------------------
procedure Test_Parse_Error (T : in out Test) is
pragma Unreferenced (T);
procedure Check_Parse_Error (Content : in String);
procedure Check_Parse_Error (Content : in String) is
P : Parser;
begin
P.Parse_String (Content);
Log.Error ("No exception raised for: {0}", Content);
exception
when Parse_Error =>
null;
end Check_Parse_Error;
begin
Check_Parse_Error ("{ ""person"":23");
Check_Parse_Error ("{ person: 23]");
Check_Parse_Error ("[ }");
Check_Parse_Error ("{[]}");
Check_Parse_Error ("{");
Check_Parse_Error ("{[");
Check_Parse_Error ("{ ""person");
Check_Parse_Error ("{ ""person"":");
Check_Parse_Error ("{ ""person"":""asf");
Check_Parse_Error ("{ ""person"":""asf""");
Check_Parse_Error ("{ ""person"":""asf"",");
Check_Parse_Error ("{ ""person"":""\uze""}");
Check_Parse_Error ("{ ""person"":""\u012-""}");
Check_Parse_Error ("{ ""person"":""\u012G""}");
end Test_Parse_Error;
-- ------------------------------
-- Check various (basic) JSON valid strings (no mapper).
-- ------------------------------
procedure Test_Parser (T : in out Test) is
pragma Unreferenced (T);
procedure Check_Parse (Content : in String);
procedure Check_Parse (Content : in String) is
P : Parser;
begin
P.Parse_String (Content);
exception
when Parse_Error =>
Log.Error ("Parse error for: " & Content);
raise;
end Check_Parse;
begin
Check_Parse ("{ ""person"":23}");
Check_Parse ("{ }");
Check_Parse ("{""person"":""asf""}");
Check_Parse ("{""person"":""asf"",""age"":""2""}");
Check_Parse ("{ ""person"":""\u0123""}");
Check_Parse ("{ ""person"":""\u4567""}");
Check_Parse ("{ ""person"":""\u89ab""}");
Check_Parse ("{ ""person"":""\ucdef""}");
Check_Parse ("{ ""person"":""\u1CDE""}");
Check_Parse ("{ ""person"":""\u2ABF""}");
end Test_Parser;
-- ------------------------------
-- Generate some output stream for the test.
-- ------------------------------
procedure Write_Stream (Stream : in out Util.Serialize.IO.Output_Stream'Class) is
Name : Ada.Strings.Unbounded.Unbounded_String;
Wide : constant Wide_Wide_String :=
Ada.Characters.Wide_Wide_Latin_1.CR &
Ada.Characters.Wide_Wide_Latin_1.LF &
Ada.Characters.Wide_Wide_Latin_1.HT &
Wide_Wide_Character'Val (16#080#) &
Wide_Wide_Character'Val (16#1fC#) &
Wide_Wide_Character'Val (16#20AC#) & -- Euro sign
Wide_Wide_Character'Val (16#2acbf#);
T : constant Ada.Calendar.Time := Ada.Calendar.Formatting.Time_Of (2011, 11, 19, 23, 0, 0);
begin
Ada.Strings.Unbounded.Append (Name, "Katniss Everdeen");
Stream.Start_Document;
Stream.Start_Entity ("root");
Stream.Start_Entity ("person");
Stream.Write_Attribute ("id", 1);
Stream.Write_Attribute ("name", Name);
Stream.Write_Entity ("name", Name);
Stream.Write_Entity ("gender", "female");
Stream.Write_Entity ("volunteer", True);
Stream.Write_Entity ("age", 17);
Stream.Write_Entity ("date", T);
Stream.Write_Wide_Entity ("skin", "olive skin");
Stream.Start_Array ("badges");
Stream.Start_Entity ("badge");
Stream.Write_Entity ("level", "gold");
Stream.Write_Entity ("name", "hunter");
Stream.End_Entity ("badge");
Stream.Start_Entity ("badge");
Stream.Write_Entity ("level", "gold");
Stream.Write_Entity ("name", "archery");
Stream.End_Entity ("badge");
Stream.End_Array ("badges");
Stream.Start_Entity ("district");
Stream.Write_Attribute ("id", 12);
Stream.Write_Wide_Attribute ("industry", "Coal mining");
Stream.Write_Attribute ("state", "<destroyed>");
Stream.Write_Long_Entity ("members", 10_000);
Stream.Write_Entity ("description", "<TBW>&""");
Stream.Write_Wide_Entity ("wescape", "'""<>&;,@!`~[]{}^%*()-+=");
Stream.Write_Entity ("escape", "'""<>&;,@!`~\[]{}^%*()-+=");
Stream.Write_Wide_Entity ("wide", Wide);
Stream.End_Entity ("district");
Stream.End_Entity ("person");
Stream.End_Entity ("root");
Stream.End_Document;
end Write_Stream;
-- ------------------------------
-- Test the JSON output stream generation.
-- ------------------------------
procedure Test_Output (T : in out Test) is
File : aliased Util.Streams.Files.File_Stream;
Stream : Util.Serialize.IO.JSON.Output_Stream;
Expect : constant String := Util.Tests.Get_Path ("regtests/expect/test-stream.json");
Path : constant String := Util.Tests.Get_Test_Path ("regtests/result/test-stream.json");
begin
File.Create (Mode => Ada.Streams.Stream_IO.Out_File, Name => Path);
Stream.Initialize (Output => File'Unchecked_Access, Input => null, Size => 10000);
Write_Stream (Stream);
Stream.Close;
Util.Tests.Assert_Equal_Files (T => T,
Expect => Expect,
Test => Path,
Message => "JSON output serialization");
end Test_Output;
end Util.Serialize.IO.JSON.Tests;
|
Add a date entry for the JSON/XML/CSV serialization test
|
Add a date entry for the JSON/XML/CSV serialization test
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
f9882b7793e2459ee9a53ca8f07f62eb19bc4c88
|
awa/plugins/awa-workspaces/src/awa-workspaces.ads
|
awa/plugins/awa-workspaces/src/awa-workspaces.ads
|
-----------------------------------------------------------------------
-- awa-workspaces -- Module workspaces
-- 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.
-----------------------------------------------------------------------
-- == Introduction ==
-- The *workspaces* plugin defines a workspace area for other plugins.
--
-- == Data Model ==
-- @include Workspace.hbm.xml
--
package AWA.Workspaces is
end AWA.Workspaces;
|
-----------------------------------------------------------------------
-- awa-workspaces -- Module workspaces
-- 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.
-----------------------------------------------------------------------
-- == Introduction ==
-- The *workspaces* plugin defines a workspace area for other plugins.
--
-- == Ada Beans ==
-- @include workspaces.xml
--
-- == Data Model ==
-- @include Workspace.hbm.xml
--
package AWA.Workspaces is
end AWA.Workspaces;
|
Add the Ada beans in the workspace documentation
|
Add the Ada beans in the workspace documentation
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
10d2b91ba9100211820d59829ff31755038c0e3a
|
awa/src/awa-comments-module.adb
|
awa/src/awa-comments-module.adb
|
-----------------------------------------------------------------------
-- awa-comments-module -- Comments 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.
-----------------------------------------------------------------------
package body AWA.Comments.Module is
overriding
procedure Initialize (Plugin : in out Comment_Module;
App : access ASF.Applications.Main.Application'Class) is
begin
null;
end Initialize;
end AWA.Comments.Module;
|
-----------------------------------------------------------------------
-- awa-comments-module -- Comments 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;
package body AWA.Comments.Module is
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("AWA.Comments.Module");
overriding
procedure Initialize (Plugin : in out Comment_Module;
App : access ASF.Applications.Main.Application'Class) is
begin
Log.Info ("Initializing the comments module");
-- Setup the resource bundles.
App.Register ("userMsg", "users");
-- Plugin.Manager := Plugin.Create_User_Manager;
-- Register.Register (Plugin => Plugin,
-- Name => "AWA.Users.Beans.Authenticate_Bean",
-- Handler => AWA.Users.Beans.Create_Authenticate_Bean'Access);
AWA.Modules.Module (Plugin).Initialize (App);
end Initialize;
end AWA.Comments.Module;
|
Update the comments module
|
Update the comments module
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
5abba26df54552bd5c8a49f16fe885428b56ae9f
|
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.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;
|
-- 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;
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;
Days_Since_Zero : Natural := 0;
begin
while Seconds_Since_Zero > Ada.Calendar.Day_Duration'Last loop
Seconds_Since_Zero := Seconds_Since_Zero - Ada.Calendar.Day_Duration'Last;
Days_Since_Zero := Days_Since_Zero + 1;
end loop;
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;
|
Fix incorrect formatting in function Time_Image
|
orka: Fix incorrect formatting in function Time_Image
If at least 24 hours or 1 day of time has elapsed, then the formatting
would be computed incorrectly because the Days_Since_Zero was
incremented and stored in a global variable.
Signed-off-by: onox <[email protected]>
|
Ada
|
apache-2.0
|
onox/orka
|
e8508778fd53befb0d288d1afcb0b161d3e65c75
|
ravenadm.adb
|
ravenadm.adb
|
-- This file is covered by the Internet Software Consortium (ISC) License
-- Reference: License.txt
with Ada.Command_Line;
with Ada.Text_IO;
with Parameters;
with Pilot;
with Unix;
procedure Ravenadm is
package CLI renames Ada.Command_Line;
package TIO renames Ada.Text_IO;
type mandate_type is (unset, help, dev, build, build_everything, force, test, test_everything,
status, status_everything, configure, locate, purge, changeopts,
checkports, portsnap, repository, list_subpackages, website, purgelogs);
type dev_mandate is (unset, dump, makefile, distinfo, buildsheet, template, genindex, web,
repatch, sort_plist, confinfo, genconspiracy);
procedure scan_first_command_word;
function scan_dev_command_word return dev_mandate;
function get_arg (arg_number : Positive) return String;
mandate : mandate_type := unset;
low_rights : Boolean := False;
reg_user : Boolean;
reg_error : constant String := "This command requires root permissions to execute.";
procedure scan_first_command_word
is
first : constant String := CLI.Argument (1);
begin
if first = "help" then
mandate := help;
elsif first = "dev" then
mandate := dev;
elsif first = "build" then
mandate := build;
elsif first = "build-everything" then
mandate := build_everything;
elsif first = "force" then
mandate := force;
elsif first = "test" then
mandate := test;
elsif first = "test-everything" then
mandate := test_everything;
elsif first = "status" then
mandate := status;
elsif first = "status-everything" then
mandate := status_everything;
elsif first = "configure" then
mandate := configure;
elsif first = "locate" then
mandate := locate;
elsif first = "purge-distfiles" then
mandate := purge;
elsif first = "purge-logs" then
mandate := purgelogs;
elsif first = "set-options" then
mandate := changeopts;
elsif first = "check-ports" then
mandate := checkports;
elsif first = "update-ports" then
mandate := portsnap;
elsif first = "generate-repository" then
mandate := repository;
elsif first = "subpackages" then
mandate := list_subpackages;
elsif first = "generate-website" then
mandate := website;
end if;
end scan_first_command_word;
function scan_dev_command_word return dev_mandate
is
-- Check argument count before calling
second : constant String := CLI.Argument (2);
begin
if second = "dump" then
return dump;
elsif second = "makefile" then
return makefile;
elsif second = "distinfo" then
return distinfo;
elsif second = "buildsheet" then
return buildsheet;
elsif second = "template" then
return template;
elsif second = "generate-index" then
return genindex;
elsif second = "generate-conspiracy" then
return genconspiracy;
elsif second = "web" then
return web;
elsif second = "repatch" then
return repatch;
elsif second = "sort" then
return sort_plist;
elsif second = "info" then
return confinfo;
else
return unset;
end if;
end scan_dev_command_word;
function get_arg (arg_number : Positive) return String is
begin
if CLI.Argument_Count >= arg_number then
return CLI.Argument (arg_number);
else
return "";
end if;
end get_arg;
begin
if CLI.Argument_Count = 0 then
Pilot.display_usage;
return;
end if;
scan_first_command_word;
if mandate = unset then
Pilot.react_to_unknown_first_level_command (CLI.Argument (1));
return;
end if;
--------------------------------------------------------------------------------------------
-- Validation block start
--------------------------------------------------------------------------------------------
if Pilot.already_running then
return;
end if;
reg_user := Pilot.insufficient_privileges;
if not Parameters.configuration_exists and then reg_user then
TIO.Put_Line ("No configuration file found.");
TIO.Put_Line ("Please switch to root permissions and retry the command.");
return;
end if;
if not Parameters.load_configuration then
return;
end if;
case mandate is
when build | force | build_everything | test | status | status_everything =>
-- All commands involving replicant slaves
if Pilot.launch_clash_detected then
return;
end if;
when others => null;
end case;
case mandate is
when build | force | build_everything | test =>
if Parameters.configuration.avec_ncurses and then
not Pilot.TERM_defined_in_environment
then
return;
end if;
when others => null;
end case;
case mandate is
when configure | help => null;
when portsnap =>
if not Parameters.all_paths_valid (skip_mk_check => True) then
return;
end if;
when others =>
if not Parameters.all_paths_valid (skip_mk_check => False) then
return;
end if;
end case;
case mandate is
when help | locate | list_subpackages => null;
low_rights := True;
when dev =>
declare
dev_subcmd : dev_mandate := unset;
begin
if CLI.Argument_Count > 1 then
dev_subcmd := scan_dev_command_word;
end if;
case dev_subcmd is
when template | sort_plist | confinfo | unset =>
low_rights := True;
when dump | makefile | distinfo | buildsheet | web | repatch |
genindex | genconspiracy =>
if reg_user then
TIO.Put_Line (reg_error);
return;
end if;
end case;
end;
when others =>
if reg_user then
TIO.Put_Line (reg_error);
return;
end if;
end case;
if Pilot.previous_run_mounts_detected and then
not Pilot.old_mounts_successfully_removed
then
return;
end if;
if Pilot.previous_realfs_work_detected and then
not Pilot.old_realfs_work_successfully_removed
then
return;
end if;
if Pilot.ravenexec_missing then
return;
end if;
case mandate is
when build | force | test | changeopts | list_subpackages =>
if not Pilot.store_origins (start_from => 2) then
return;
end if;
when status =>
if CLI.Argument_Count > 1 then
if not Pilot.store_origins (start_from => 2) then
return;
end if;
end if;
when others => null;
end case;
case mandate is
when build | build_everything | force |
test | test_everything |
status | status_everything =>
Pilot.check_that_ravenadm_is_modern_enough;
if not Pilot.slave_platform_determined then
return;
end if;
when others => null;
end case;
if not low_rights then
Pilot.create_pidfile;
Unix.ignore_background_tty;
end if;
if mandate /= configure then
Unix.cone_of_silence (deploy => True);
end if;
--------------------------------------------------------------------------------------------
-- Validation block end
--------------------------------------------------------------------------------------------
case mandate is
when status =>
--------------------------------
-- status command
--------------------------------
if CLI.Argument_Count > 1 then
if Pilot.install_compiler_packages and then
Pilot.scan_stack_of_single_ports (always_build => False) and then
Pilot.sanity_check_then_prefail (delete_first => False, dry_run => True)
then
Pilot.display_results_of_dry_run;
end if;
else
null; -- reserved for upgrade_system_everything maybe
end if;
when status_everything =>
--------------------------------
-- status_everything command
--------------------------------
if Pilot.install_compiler_packages and then
Pilot.fully_scan_ports_tree and then
Pilot.sanity_check_then_prefail (delete_first => False, dry_run => True)
then
Pilot.display_results_of_dry_run;
end if;
when build =>
--------------------------------
-- build command
--------------------------------
if Pilot.install_compiler_packages and then
Pilot.scan_stack_of_single_ports (always_build => False) and then
Pilot.sanity_check_then_prefail (delete_first => False, dry_run => False)
then
Pilot.perform_bulk_run (testmode => False);
end if;
when build_everything =>
--------------------------------
-- build-everything command
--------------------------------
if Pilot.install_compiler_packages and then
Pilot.fully_scan_ports_tree and then
Pilot.sanity_check_then_prefail (delete_first => False, dry_run => False)
then
Pilot.perform_bulk_run (testmode => False);
end if;
when test_everything =>
--------------------------------
-- test-everything command
--------------------------------
if Pilot.install_compiler_packages and then
Pilot.fully_scan_ports_tree and then
Pilot.sanity_check_then_prefail (delete_first => True, dry_run => False)
then
Pilot.perform_bulk_run (testmode => True);
end if;
when website =>
--------------------------------
-- generate-website command
--------------------------------
Pilot.generate_website;
when force =>
--------------------------------
-- force command
--------------------------------
if Pilot.install_compiler_packages and then
Pilot.scan_stack_of_single_ports (always_build => False) and then
Pilot.sanity_check_then_prefail (delete_first => True, dry_run => False)
then
Pilot.perform_bulk_run (testmode => False);
end if;
when dev =>
--------------------------------
-- dev command
--------------------------------
if CLI.Argument_Count > 1 then
declare
dev_subcmd : dev_mandate := scan_dev_command_word;
begin
case dev_subcmd is
when unset =>
Pilot.react_to_unknown_second_level_command (CLI.Argument (1),
CLI.Argument (2));
when dump =>
Pilot.dump_ravensource (get_arg (3));
when distinfo =>
Pilot.generate_distinfo;
when buildsheet =>
Pilot.generate_buildsheet (get_arg (3), get_arg (4));
when makefile =>
Pilot.generate_makefile (get_arg (3), get_arg (4));
when web =>
Pilot.generate_webpage (get_arg (3), get_arg (4));
when repatch =>
Pilot.regenerate_patches (get_arg (3), get_arg (4));
when sort_plist =>
Pilot.resort_manifests (get_arg (3));
when template =>
Pilot.print_spec_template (get_arg (3));
when genindex =>
Pilot.generate_ports_index;
when genconspiracy =>
Pilot.generate_conspiracy (get_arg (3));
when confinfo =>
Pilot.show_config_value (get_arg (3));
end case;
end;
else
Pilot.react_to_unknown_second_level_command (CLI.Argument (1), "");
end if;
when help =>
--------------------------------
-- help command
--------------------------------
if CLI.Argument_Count > 1 then
Pilot.launch_man_page (CLI.Argument (2));
else
Pilot.show_short_help;
end if;
when test =>
--------------------------------
-- test command
--------------------------------
if Pilot.install_compiler_packages and then
Pilot.scan_stack_of_single_ports (always_build => True) and then
Pilot.sanity_check_then_prefail (delete_first => True, dry_run => False)
then
if Pilot.interact_with_single_builder then
Pilot.bulk_run_then_interact_with_final_port;
else
Pilot.perform_bulk_run (testmode => True);
end if;
end if;
when configure =>
--------------------------------
-- configure
--------------------------------
Pilot.launch_configure_menu;
when locate =>
--------------------------------
-- locate
--------------------------------
Pilot.locate (get_arg (2));
when list_subpackages =>
--------------------------------
-- subpackages
--------------------------------
Pilot.list_subpackages;
when purge =>
--------------------------------
-- purge-distfiles
--------------------------------
Pilot.purge_distfiles;
when purgelogs =>
--------------------------------
-- purge-logs
--------------------------------
Pilot.purge_logs;
when changeopts =>
--------------------------------
-- set-options
--------------------------------
Pilot.change_options;
when checkports =>
--------------------------------
-- check-ports
--------------------------------
Pilot.check_ravenports_version;
when portsnap =>
--------------------------------
-- update-ports
--------------------------------
Pilot.update_to_latest_ravenports;
when repository =>
--------------------------------
-- generate-repository
--------------------------------
Pilot.generate_repository;
when unset => null;
end case;
Unix.cone_of_silence (deploy => False);
if not low_rights then
Pilot.destroy_pidfile;
end if;
end Ravenadm;
|
-- This file is covered by the Internet Software Consortium (ISC) License
-- Reference: License.txt
with Ada.Command_Line;
with Ada.Text_IO;
with Parameters;
with Pilot;
with Unix;
procedure Ravenadm is
package CLI renames Ada.Command_Line;
package TIO renames Ada.Text_IO;
type mandate_type is (unset, help, dev, build, build_everything, force, test, test_everything,
status, status_everything, configure, locate, purge, changeopts,
checkports, portsnap, repository, list_subpackages, website, purgelogs);
type dev_mandate is (unset, dump, makefile, distinfo, buildsheet, template, genindex, web,
repatch, sort_plist, confinfo, genconspiracy);
procedure scan_first_command_word;
function scan_dev_command_word return dev_mandate;
function get_arg (arg_number : Positive) return String;
mandate : mandate_type := unset;
low_rights : Boolean := False;
reg_user : Boolean;
reg_error : constant String := "This command requires root permissions to execute.";
procedure scan_first_command_word
is
first : constant String := CLI.Argument (1);
begin
if first = "help" then
mandate := help;
elsif first = "dev" then
mandate := dev;
elsif first = "build" then
mandate := build;
elsif first = "build-everything" then
mandate := build_everything;
elsif first = "force" then
mandate := force;
elsif first = "test" then
mandate := test;
elsif first = "test-everything" then
mandate := test_everything;
elsif first = "status" then
mandate := status;
elsif first = "status-everything" then
mandate := status_everything;
elsif first = "configure" then
mandate := configure;
elsif first = "locate" then
mandate := locate;
elsif first = "purge-distfiles" then
mandate := purge;
elsif first = "purge-logs" then
mandate := purgelogs;
elsif first = "set-options" then
mandate := changeopts;
elsif first = "check-ports" then
mandate := checkports;
elsif first = "update-ports" then
mandate := portsnap;
elsif first = "generate-repository" then
mandate := repository;
elsif first = "subpackages" then
mandate := list_subpackages;
elsif first = "generate-website" then
mandate := website;
end if;
end scan_first_command_word;
function scan_dev_command_word return dev_mandate
is
-- Check argument count before calling
second : constant String := CLI.Argument (2);
begin
if second = "dump" then
return dump;
elsif second = "makefile" then
return makefile;
elsif second = "distinfo" then
return distinfo;
elsif second = "buildsheet" then
return buildsheet;
elsif second = "template" then
return template;
elsif second = "generate-index" then
return genindex;
elsif second = "generate-conspiracy" then
return genconspiracy;
elsif second = "web" then
return web;
elsif second = "repatch" then
return repatch;
elsif second = "sort" then
return sort_plist;
elsif second = "info" then
return confinfo;
else
return unset;
end if;
end scan_dev_command_word;
function get_arg (arg_number : Positive) return String is
begin
if CLI.Argument_Count >= arg_number then
return CLI.Argument (arg_number);
else
return "";
end if;
end get_arg;
begin
if CLI.Argument_Count = 0 then
Pilot.display_usage;
return;
end if;
scan_first_command_word;
if mandate = unset then
Pilot.react_to_unknown_first_level_command (CLI.Argument (1));
return;
end if;
--------------------------------------------------------------------------------------------
-- Validation block start
--------------------------------------------------------------------------------------------
case mandate is
when help | locate | list_subpackages =>
low_rights := True;
when others =>
if Pilot.already_running then
return;
end if;
end case;
reg_user := Pilot.insufficient_privileges;
if not Parameters.configuration_exists and then reg_user then
TIO.Put_Line ("No configuration file found.");
TIO.Put_Line ("Please switch to root permissions and retry the command.");
return;
end if;
if not Parameters.load_configuration then
return;
end if;
case mandate is
when build | force | build_everything | test | status | status_everything =>
-- All commands involving replicant slaves
if Pilot.launch_clash_detected then
return;
end if;
when others => null;
end case;
case mandate is
when build | force | build_everything | test =>
if Parameters.configuration.avec_ncurses and then
not Pilot.TERM_defined_in_environment
then
return;
end if;
when others => null;
end case;
case mandate is
when configure | help => null;
when portsnap =>
if not Parameters.all_paths_valid (skip_mk_check => True) then
return;
end if;
when others =>
if not Parameters.all_paths_valid (skip_mk_check => False) then
return;
end if;
end case;
case mandate is
when help | locate | list_subpackages =>
null;
when dev =>
declare
dev_subcmd : dev_mandate := unset;
begin
if CLI.Argument_Count > 1 then
dev_subcmd := scan_dev_command_word;
end if;
case dev_subcmd is
when template | sort_plist | confinfo | unset =>
low_rights := True;
when dump | makefile | distinfo | buildsheet | web | repatch |
genindex | genconspiracy =>
if reg_user then
TIO.Put_Line (reg_error);
return;
end if;
end case;
end;
when others =>
if reg_user then
TIO.Put_Line (reg_error);
return;
end if;
end case;
if not low_rights then
if Pilot.previous_run_mounts_detected and then
not Pilot.old_mounts_successfully_removed
then
return;
end if;
if Pilot.previous_realfs_work_detected and then
not Pilot.old_realfs_work_successfully_removed
then
return;
end if;
if Pilot.ravenexec_missing then
return;
end if;
end if;
case mandate is
when build | force | test | changeopts | list_subpackages =>
if not Pilot.store_origins (start_from => 2) then
return;
end if;
when status =>
if CLI.Argument_Count > 1 then
if not Pilot.store_origins (start_from => 2) then
return;
end if;
end if;
when others => null;
end case;
case mandate is
when build | build_everything | force |
test | test_everything |
status | status_everything =>
Pilot.check_that_ravenadm_is_modern_enough;
if not Pilot.slave_platform_determined then
return;
end if;
when others => null;
end case;
if not low_rights then
Pilot.create_pidfile;
Unix.ignore_background_tty;
end if;
if mandate /= configure then
Unix.cone_of_silence (deploy => True);
end if;
--------------------------------------------------------------------------------------------
-- Validation block end
--------------------------------------------------------------------------------------------
case mandate is
when status =>
--------------------------------
-- status command
--------------------------------
if CLI.Argument_Count > 1 then
if Pilot.install_compiler_packages and then
Pilot.scan_stack_of_single_ports (always_build => False) and then
Pilot.sanity_check_then_prefail (delete_first => False, dry_run => True)
then
Pilot.display_results_of_dry_run;
end if;
else
null; -- reserved for upgrade_system_everything maybe
end if;
when status_everything =>
--------------------------------
-- status_everything command
--------------------------------
if Pilot.install_compiler_packages and then
Pilot.fully_scan_ports_tree and then
Pilot.sanity_check_then_prefail (delete_first => False, dry_run => True)
then
Pilot.display_results_of_dry_run;
end if;
when build =>
--------------------------------
-- build command
--------------------------------
if Pilot.install_compiler_packages and then
Pilot.scan_stack_of_single_ports (always_build => False) and then
Pilot.sanity_check_then_prefail (delete_first => False, dry_run => False)
then
Pilot.perform_bulk_run (testmode => False);
end if;
when build_everything =>
--------------------------------
-- build-everything command
--------------------------------
if Pilot.install_compiler_packages and then
Pilot.fully_scan_ports_tree and then
Pilot.sanity_check_then_prefail (delete_first => False, dry_run => False)
then
Pilot.perform_bulk_run (testmode => False);
end if;
when test_everything =>
--------------------------------
-- test-everything command
--------------------------------
if Pilot.install_compiler_packages and then
Pilot.fully_scan_ports_tree and then
Pilot.sanity_check_then_prefail (delete_first => True, dry_run => False)
then
Pilot.perform_bulk_run (testmode => True);
end if;
when website =>
--------------------------------
-- generate-website command
--------------------------------
Pilot.generate_website;
when force =>
--------------------------------
-- force command
--------------------------------
if Pilot.install_compiler_packages and then
Pilot.scan_stack_of_single_ports (always_build => False) and then
Pilot.sanity_check_then_prefail (delete_first => True, dry_run => False)
then
Pilot.perform_bulk_run (testmode => False);
end if;
when dev =>
--------------------------------
-- dev command
--------------------------------
if CLI.Argument_Count > 1 then
declare
dev_subcmd : dev_mandate := scan_dev_command_word;
begin
case dev_subcmd is
when unset =>
Pilot.react_to_unknown_second_level_command (CLI.Argument (1),
CLI.Argument (2));
when dump =>
Pilot.dump_ravensource (get_arg (3));
when distinfo =>
Pilot.generate_distinfo;
when buildsheet =>
Pilot.generate_buildsheet (get_arg (3), get_arg (4));
when makefile =>
Pilot.generate_makefile (get_arg (3), get_arg (4));
when web =>
Pilot.generate_webpage (get_arg (3), get_arg (4));
when repatch =>
Pilot.regenerate_patches (get_arg (3), get_arg (4));
when sort_plist =>
Pilot.resort_manifests (get_arg (3));
when template =>
Pilot.print_spec_template (get_arg (3));
when genindex =>
Pilot.generate_ports_index;
when genconspiracy =>
Pilot.generate_conspiracy (get_arg (3));
when confinfo =>
Pilot.show_config_value (get_arg (3));
end case;
end;
else
Pilot.react_to_unknown_second_level_command (CLI.Argument (1), "");
end if;
when help =>
--------------------------------
-- help command
--------------------------------
if CLI.Argument_Count > 1 then
Pilot.launch_man_page (CLI.Argument (2));
else
Pilot.show_short_help;
end if;
when test =>
--------------------------------
-- test command
--------------------------------
if Pilot.install_compiler_packages and then
Pilot.scan_stack_of_single_ports (always_build => True) and then
Pilot.sanity_check_then_prefail (delete_first => True, dry_run => False)
then
if Pilot.interact_with_single_builder then
Pilot.bulk_run_then_interact_with_final_port;
else
Pilot.perform_bulk_run (testmode => True);
end if;
end if;
when configure =>
--------------------------------
-- configure
--------------------------------
Pilot.launch_configure_menu;
when locate =>
--------------------------------
-- locate
--------------------------------
Pilot.locate (get_arg (2));
when list_subpackages =>
--------------------------------
-- subpackages
--------------------------------
Pilot.list_subpackages;
when purge =>
--------------------------------
-- purge-distfiles
--------------------------------
Pilot.purge_distfiles;
when purgelogs =>
--------------------------------
-- purge-logs
--------------------------------
Pilot.purge_logs;
when changeopts =>
--------------------------------
-- set-options
--------------------------------
Pilot.change_options;
when checkports =>
--------------------------------
-- check-ports
--------------------------------
Pilot.check_ravenports_version;
when portsnap =>
--------------------------------
-- update-ports
--------------------------------
Pilot.update_to_latest_ravenports;
when repository =>
--------------------------------
-- generate-repository
--------------------------------
Pilot.generate_repository;
when unset => null;
end case;
Unix.cone_of_silence (deploy => False);
if not low_rights then
Pilot.destroy_pidfile;
end if;
end Ravenadm;
|
Allow "ravenadm locate|help|list_subpackages" to work even if ravenadm already running elsewhere.
|
Allow "ravenadm locate|help|list_subpackages" to work even if
ravenadm already running elsewhere.
|
Ada
|
isc
|
jrmarino/ravenadm,jrmarino/ravenadm,jrmarino/ravenadm
|
2032dcf26c22fa56264a92f085396a696655a2d0
|
src/postgresql/ado-schemas-postgresql.adb
|
src/postgresql/ado-schemas-postgresql.adb
|
-----------------------------------------------------------------------
-- ado-schemas-postgresql -- Postgresql Database Schemas
-- Copyright (C) 2018 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with ADO.Statements;
with ADO.Statements.Create;
package body ADO.Schemas.Postgresql is
use ADO.Statements;
procedure Load_Table_Schema (C : in ADO.Drivers.Connections.Database_Connection'Class;
Database : in String;
Table : in Table_Definition);
function String_To_Type (Value : in String) return Column_Type;
function String_To_Type (Value : in String) return Column_Type is
begin
if Value = "date" then
return T_DATE;
elsif Value = "timestamp without time zone" then
return T_DATE_TIME;
elsif Value = "timestamp with time zone" then
return T_DATE_TIME;
elsif Value = "integer" then
return T_INTEGER;
elsif Value = "bigint" then
return T_LONG_INTEGER;
elsif Value = "bytea" then
return T_BLOB;
elsif Value = "character varying" then
return T_VARCHAR;
end if;
return T_UNKNOWN;
end String_To_Type;
-- ------------------------------
-- Load the table definition
-- ------------------------------
procedure Load_Table_Schema (C : in ADO.Drivers.Connections.Database_Connection'Class;
Database : in String;
Table : in Table_Definition) is
Name : constant String := Get_Name (Table);
SQL : constant String
:= "SELECT column_name, column_default, data_type, is_nullable, "
& "character_maximum_length, collation_name FROM information_schema.columns "
& "WHERE table_catalog = ? AND table_name = ?";
Stmt : Query_Statement
:= Create.Create_Statement (C.Create_Statement (SQL));
Last : Column_Definition := null;
Col : Column_Definition;
Value : Unbounded_String;
begin
Stmt.Add_Param (Database);
Stmt.Add_Param (Name);
Stmt.Execute;
while Stmt.Has_Elements loop
Col := new Column;
Col.Name := Stmt.Get_Unbounded_String (0);
if not Stmt.Is_Null (5) then
Col.Collation := Stmt.Get_Unbounded_String (5);
end if;
if not Stmt.Is_Null (1) then
Col.Default := Stmt.Get_Unbounded_String (1);
end if;
if Last /= null then
Last.Next_Column := Col;
else
Table.First_Column := Col;
end if;
Value := Stmt.Get_Unbounded_String (2);
Col.Col_Type := String_To_Type (To_String (Value));
Value := Stmt.Get_Unbounded_String (3);
Col.Is_Null := Value = "YES";
Last := Col;
Stmt.Next;
end loop;
end Load_Table_Schema;
-- ------------------------------
-- Load the database schema
-- ------------------------------
procedure Load_Schema (C : in ADO.Drivers.Connections.Database_Connection'Class;
Schema : out Schema_Definition;
Database : in String) is
SQL : constant String
:= "SELECT tablename FROM pg_catalog.pg_tables "
& "WHERE schemaname != 'pg_catalog' AND schemaname != 'information_schema'";
Stmt : Query_Statement
:= Create.Create_Statement (C.Create_Statement (SQL));
Table : Table_Definition;
Last : Table_Definition := null;
begin
Schema.Schema := new ADO.Schemas.Schema;
Stmt.Execute;
while Stmt.Has_Elements loop
Table := new ADO.Schemas.Table;
Table.Name := Stmt.Get_Unbounded_String (0);
if Last /= null then
Last.Next_Table := Table;
else
Schema.Schema.First_Table := Table;
end if;
Load_Table_Schema (C, Database, Table);
Last := Table;
Stmt.Next;
end loop;
end Load_Schema;
end ADO.Schemas.Postgresql;
|
-----------------------------------------------------------------------
-- ado-schemas-postgresql -- Postgresql Database Schemas
-- Copyright (C) 2018 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with ADO.Statements;
with ADO.Statements.Create;
package body ADO.Schemas.Postgresql is
use ADO.Statements;
procedure Load_Table_Schema (C : in ADO.Drivers.Connections.Database_Connection'Class;
Database : in String;
Table : in Table_Definition);
procedure Load_Table_Keys (C : in ADO.Drivers.Connections.Database_Connection'Class;
Database : in String;
Table : in Table_Definition);
function String_To_Type (Value : in String) return Column_Type;
function String_To_Type (Value : in String) return Column_Type is
begin
if Value = "date" then
return T_DATE;
elsif Value = "timestamp without time zone" then
return T_DATE_TIME;
elsif Value = "timestamp with time zone" then
return T_DATE_TIME;
elsif Value = "integer" then
return T_INTEGER;
elsif Value = "bigint" then
return T_LONG_INTEGER;
elsif Value = "bytea" then
return T_BLOB;
elsif Value = "character varying" then
return T_VARCHAR;
end if;
return T_UNKNOWN;
end String_To_Type;
-- ------------------------------
-- Load the table definition
-- ------------------------------
procedure Load_Table_Schema (C : in ADO.Drivers.Connections.Database_Connection'Class;
Database : in String;
Table : in Table_Definition) is
Name : constant String := Get_Name (Table);
SQL : constant String
:= "SELECT column_name, column_default, data_type, is_nullable, "
& "character_maximum_length, collation_name FROM information_schema.columns "
& "WHERE table_catalog = ? AND table_name = ?";
Stmt : Query_Statement
:= Create.Create_Statement (C.Create_Statement (SQL));
Last : Column_Definition := null;
Col : Column_Definition;
Value : Unbounded_String;
begin
Stmt.Add_Param (Database);
Stmt.Add_Param (Name);
Stmt.Execute;
while Stmt.Has_Elements loop
Col := new Column;
Col.Name := Stmt.Get_Unbounded_String (0);
if not Stmt.Is_Null (5) then
Col.Collation := Stmt.Get_Unbounded_String (5);
end if;
if not Stmt.Is_Null (1) then
Col.Default := Stmt.Get_Unbounded_String (1);
end if;
if Last /= null then
Last.Next_Column := Col;
else
Table.First_Column := Col;
end if;
Value := Stmt.Get_Unbounded_String (2);
Col.Col_Type := String_To_Type (To_String (Value));
Value := Stmt.Get_Unbounded_String (3);
Col.Is_Null := Value = "YES";
Last := Col;
Stmt.Next;
end loop;
end Load_Table_Schema;
-- ------------------------------
-- Load the table definition
-- ------------------------------
procedure Load_Table_Keys (C : in ADO.Drivers.Connections.Database_Connection'Class;
Database : in String;
Table : in Table_Definition) is
Name : constant String := Get_Name (Table);
SQL : constant String
:= "SELECT column_name FROM"
& " information_schema.table_constraints tc, "
& " information_schema.key_column_usage kc "
& "WHERE tc.constraint_type = 'PRIMARY KEY' "
& " AND kc.table_name = tc.table_name "
& " AND kc.table_schema = tc.table_schema "
& " AND kc.constraint_name = tc.constraint_name "
& " AND tc.table_catalog = ? and tc.table_name = ?";
Stmt : Query_Statement
:= Create.Create_Statement (C.Create_Statement (SQL));
Col : Column_Definition;
begin
Stmt.Add_Param (Database);
Stmt.Add_Param (Name);
Stmt.Execute;
while Stmt.Has_Elements loop
declare
Col_Name : constant String := Stmt.Get_String (0);
begin
Col := Find_Column (Table, Col_Name);
if Col /= null then
Col.Is_Primary := True;
end if;
end;
Stmt.Next;
end loop;
end Load_Table_Keys;
-- ------------------------------
-- Load the database schema
-- ------------------------------
procedure Load_Schema (C : in ADO.Drivers.Connections.Database_Connection'Class;
Schema : out Schema_Definition;
Database : in String) is
SQL : constant String
:= "SELECT tablename FROM pg_catalog.pg_tables "
& "WHERE schemaname != 'pg_catalog' AND schemaname != 'information_schema'";
Stmt : Query_Statement
:= Create.Create_Statement (C.Create_Statement (SQL));
Table : Table_Definition;
Last : Table_Definition := null;
begin
Schema.Schema := new ADO.Schemas.Schema;
Stmt.Execute;
while Stmt.Has_Elements loop
Table := new ADO.Schemas.Table;
Table.Name := Stmt.Get_Unbounded_String (0);
if Last /= null then
Last.Next_Table := Table;
else
Schema.Schema.First_Table := Table;
end if;
Load_Table_Schema (C, Database, Table);
Load_Table_Keys (C, Database, Table);
Last := Table;
Stmt.Next;
end loop;
end Load_Schema;
end ADO.Schemas.Postgresql;
|
Declare and implement Load_Table_Keys to find the primary keys and set the Is_Primary attribute for columns
|
Declare and implement Load_Table_Keys to find the primary keys and set the Is_Primary attribute for columns
|
Ada
|
apache-2.0
|
stcarrez/ada-ado
|
93fbd1b1f5db13daacdca3b4662fb5196bf7a0b1
|
regtests/asf-applications-main-tests.adb
|
regtests/asf-applications-main-tests.adb
|
-----------------------------------------------------------------------
-- asf-applications-main-tests - Unit tests for Applications
-- Copyright (C) 2011, 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Test_Caller;
with Util.Beans.Objects;
with Ada.Unchecked_Deallocation;
with EL.Contexts.Default;
with ASF.Applications.Tests;
with ASF.Applications.Main.Configs;
with ASF.Requests.Mockup;
package body ASF.Applications.Main.Tests is
use Util.Tests;
function Create_Form_Bean return Util.Beans.Basic.Readonly_Bean_Access;
package Caller is new Util.Test_Caller (Test, "Applications.Main");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test ASF.Applications.Main.Read_Configuration",
Test_Read_Configuration'Access);
Caller.Add_Test (Suite, "Test ASF.Applications.Main.Create",
Test_Create_Bean'Access);
Caller.Add_Test (Suite, "Test ASF.Applications.Main.Load_Bundle",
Test_Load_Bundle'Access);
Caller.Add_Test (Suite, "Test ASF.Applications.Main.Register,Load_Bundle",
Test_Bundle_Configuration'Access);
Caller.Add_Test (Suite, "Test ASF.Applications.Main.Get_Supported_Locales",
Test_Locales'Access);
end Add_Tests;
-- ------------------------------
-- Initialize the test application
-- ------------------------------
procedure Set_Up (T : in out Test) is
Fact : ASF.Applications.Main.Application_Factory;
C : ASF.Applications.Config;
begin
T.App := new ASF.Applications.Main.Application;
C.Copy (Util.Tests.Get_Properties);
T.App.Initialize (C, Fact);
T.App.Register ("layoutMsg", "layout");
end Set_Up;
-- ------------------------------
-- Deletes the application object
-- ------------------------------
overriding
procedure Tear_Down (T : in out Test) is
procedure Free is
new Ada.Unchecked_Deallocation (Object => ASF.Applications.Main.Application'Class,
Name => ASF.Applications.Main.Application_Access);
begin
Free (T.App);
end Tear_Down;
function Create_Form_Bean return Util.Beans.Basic.Readonly_Bean_Access is
Result : constant Applications.Tests.Form_Bean_Access := new Applications.Tests.Form_Bean;
begin
return Result.all'Access;
end Create_Form_Bean;
-- ------------------------------
-- Test creation of module
-- ------------------------------
procedure Test_Read_Configuration (T : in out Test) is
Path : constant String := Util.Tests.Get_Test_Path ("config/empty.xml");
begin
ASF.Applications.Main.Configs.Read_Configuration (T.App.all, Path);
end Test_Read_Configuration;
-- ------------------------------
-- Test creation of a module and registration in an application.
-- ------------------------------
procedure Test_Create_Bean (T : in out Test) is
use type Util.Beans.Basic.Readonly_Bean_Access;
procedure Check (Name : in String;
Kind : in ASF.Beans.Scope_Type);
procedure Check (Name : in String;
Kind : in ASF.Beans.Scope_Type) is
Value : Util.Beans.Objects.Object;
Bean : Util.Beans.Basic.Readonly_Bean_Access;
Scope : ASF.Beans.Scope_Type;
Context : EL.Contexts.Default.Default_Context;
begin
T.App.Create (Name => Ada.Strings.Unbounded.To_Unbounded_String (Name),
Context => Context,
Result => Bean,
Scope => Scope);
T.Assert (Kind = Scope, "Invalid scope for " & Name);
T.Assert (Bean /= null, "Invalid bean object");
Value := Util.Beans.Objects.To_Object (Bean);
T.Assert (not Util.Beans.Objects.Is_Null (Value), "Invalid bean");
-- Special test for the sessionForm bean which is initialized by configuration properties
if Name = "sessionForm" then
T.Assert_Equals ("[email protected]",
Util.Beans.Objects.To_String (Bean.Get_Value ("email")),
"Session form not initialized");
end if;
end Check;
Path : constant String := Util.Tests.Get_Test_Path ("regtests/config/test-module.xml");
begin
T.App.Register_Class ("ASF.Applications.Tests.Form_Bean", Create_Form_Bean'Access);
ASF.Applications.Main.Configs.Read_Configuration (T.App.all, Path);
-- Check the 'regtests/config/test-module.xml' managed bean configuration.
Check ("applicationForm", ASF.Beans.APPLICATION_SCOPE);
Check ("sessionForm", ASF.Beans.SESSION_SCOPE);
Check ("requestForm", ASF.Beans.REQUEST_SCOPE);
end Test_Create_Bean;
-- ------------------------------
-- Test loading a resource bundle through the application.
-- ------------------------------
procedure Test_Load_Bundle (T : in out Test) is
use type Util.Beans.Basic.Readonly_Bean_Access;
Path : constant String := Util.Tests.Get_Test_Path ("regtests/config/test-bundle.xml");
Bundle : ASF.Locales.Bundle;
begin
ASF.Applications.Main.Configs.Read_Configuration (T.App.all, Path);
T.App.Load_Bundle (Name => "samples",
Locale => "en",
Bundle => Bundle);
Util.Tests.Assert_Equals (T, "Help", String '(Bundle.Get ("layout_help_label")),
"Invalid bundle value");
T.App.Load_Bundle (Name => "asf",
Locale => "en",
Bundle => Bundle);
Util.Tests.Assert_Matches (T, ".*greater than.*",
String '(Bundle.Get ("validators.length.maximum")),
"Invalid bundle value");
end Test_Load_Bundle;
-- ------------------------------
-- Test application configuration and registration of resource bundles.
-- ------------------------------
procedure Test_Bundle_Configuration (T : in out Test) is
use type Util.Beans.Basic.Readonly_Bean_Access;
Path : constant String := Util.Tests.Get_Test_Path ("regtests/config/test-bundle.xml");
Result : Util.Beans.Basic.Readonly_Bean_Access;
Ctx : EL.Contexts.Default.Default_Context;
Scope : Scope_Type;
begin
ASF.Applications.Main.Configs.Read_Configuration (T.App.all, Path);
T.App.Create (Name => Ada.Strings.Unbounded.To_Unbounded_String ("samplesMsg"),
Context => Ctx,
Result => Result,
Scope => Scope);
T.Assert (Result /= null, "The samplesMsg bundle was not created");
T.App.Create (Name => Ada.Strings.Unbounded.To_Unbounded_String ("defaultMsg"),
Context => Ctx,
Result => Result,
Scope => Scope);
T.Assert (Result /= null, "The defaultMsg bundle was not created");
end Test_Bundle_Configuration;
-- ------------------------------
-- Test locales.
-- ------------------------------
procedure Test_Locales (T : in out Test) is
use Util.Locales;
Path : constant String := Util.Tests.Get_Test_Path ("regtests/config/test-locales.xml");
Req : aliased ASF.Requests.Mockup.Request;
View : constant access Applications.Views.View_Handler'Class := T.App.Get_View_Handler;
Context : aliased ASF.Contexts.Faces.Faces_Context;
ELContext : aliased EL.Contexts.Default.Default_Context;
Locale : Util.Locales.Locale;
begin
ASF.Applications.Main.Configs.Read_Configuration (T.App.all, Path);
Util.Tests.Assert_Equals (T, To_String (Util.Locales.FRENCH),
To_String (T.App.Get_Default_Locale),
"Invalid default locale");
Context.Set_ELContext (ELContext'Unchecked_Access);
Context.Set_Request (Req'Unchecked_Access);
Req.Set_Header ("Accept-Language", "da, en-gb;q=0.3, fr;q=0.7");
T.App.Set_Context (Context'Unchecked_Access);
Locale := View.Calculate_Locale (Context);
Util.Tests.Assert_Equals (T, To_String (Util.Locales.FRENCH),
To_String (Locale),
"Invalid calculated locale");
Req.Set_Header ("Accept-Language", "da, en-gb, en;q=0.8, fr;q=0.7");
T.App.Set_Context (Context'Unchecked_Access);
Locale := View.Calculate_Locale (Context);
Util.Tests.Assert_Equals (T, "en_GB",
To_String (Locale),
"Invalid calculated locale");
Req.Set_Header ("Accept-Language", "da, fr;q=0.7, fr-fr;q=0.8");
T.App.Set_Context (Context'Unchecked_Access);
Locale := View.Calculate_Locale (Context);
Util.Tests.Assert_Equals (T, "fr_FR",
To_String (Locale),
"Invalid calculated locale");
Req.Set_Header ("Accept-Language", "da, ru, it;q=0.8, de;q=0.7");
T.App.Set_Context (Context'Unchecked_Access);
Locale := View.Calculate_Locale (Context);
Util.Tests.Assert_Equals (T, To_String (Util.Locales.FRENCH),
To_String (Locale),
"Invalid calculated locale");
end Test_Locales;
end ASF.Applications.Main.Tests;
|
-----------------------------------------------------------------------
-- asf-applications-main-tests - Unit tests for Applications
-- 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 Util.Test_Caller;
with Util.Beans.Objects;
with Ada.Unchecked_Deallocation;
with EL.Contexts.Default;
with ASF.Applications.Tests;
with ASF.Applications.Main.Configs;
with ASF.Requests.Mockup;
package body ASF.Applications.Main.Tests is
use Util.Tests;
function Create_Form_Bean return Util.Beans.Basic.Readonly_Bean_Access;
package Caller is new Util.Test_Caller (Test, "Applications.Main");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test ASF.Applications.Main.Read_Configuration",
Test_Read_Configuration'Access);
Caller.Add_Test (Suite, "Test ASF.Applications.Main.Create",
Test_Create_Bean'Access);
Caller.Add_Test (Suite, "Test ASF.Applications.Main.Load_Bundle",
Test_Load_Bundle'Access);
Caller.Add_Test (Suite, "Test ASF.Applications.Main.Register,Load_Bundle",
Test_Bundle_Configuration'Access);
Caller.Add_Test (Suite, "Test ASF.Applications.Main.Get_Supported_Locales",
Test_Locales'Access);
end Add_Tests;
-- ------------------------------
-- Initialize the test application
-- ------------------------------
procedure Set_Up (T : in out Test) is
Fact : ASF.Applications.Main.Application_Factory;
C : ASF.Applications.Config;
begin
T.App := new ASF.Applications.Main.Application;
C.Copy (Util.Tests.Get_Properties);
T.App.Initialize (C, Fact);
T.App.Register ("layoutMsg", "layout");
end Set_Up;
-- ------------------------------
-- Deletes the application object
-- ------------------------------
overriding
procedure Tear_Down (T : in out Test) is
procedure Free is
new Ada.Unchecked_Deallocation (Object => ASF.Applications.Main.Application'Class,
Name => ASF.Applications.Main.Application_Access);
begin
Free (T.App);
end Tear_Down;
function Create_Form_Bean return Util.Beans.Basic.Readonly_Bean_Access is
Result : constant Applications.Tests.Form_Bean_Access := new Applications.Tests.Form_Bean;
begin
return Result.all'Access;
end Create_Form_Bean;
-- ------------------------------
-- Test creation of module
-- ------------------------------
procedure Test_Read_Configuration (T : in out Test) is
Path : constant String := Util.Tests.Get_Test_Path ("config/empty.xml");
begin
ASF.Applications.Main.Configs.Read_Configuration (T.App.all, Path);
end Test_Read_Configuration;
-- ------------------------------
-- Test creation of a module and registration in an application.
-- ------------------------------
procedure Test_Create_Bean (T : in out Test) is
use type Util.Beans.Basic.Readonly_Bean_Access;
procedure Check (Name : in String;
Kind : in ASF.Beans.Scope_Type);
procedure Check (Name : in String;
Kind : in ASF.Beans.Scope_Type) is
Value : Util.Beans.Objects.Object;
Bean : Util.Beans.Basic.Readonly_Bean_Access;
Scope : ASF.Beans.Scope_Type;
Context : EL.Contexts.Default.Default_Context;
begin
T.App.Create (Name => Ada.Strings.Unbounded.To_Unbounded_String (Name),
Context => Context,
Result => Bean,
Scope => Scope);
T.Assert (Kind = Scope, "Invalid scope for " & Name);
T.Assert (Bean /= null, "Invalid bean object");
Value := Util.Beans.Objects.To_Object (Bean);
T.Assert (not Util.Beans.Objects.Is_Null (Value), "Invalid bean");
-- Special test for the sessionForm bean which is initialized by configuration properties
if Name = "sessionForm" then
T.Assert_Equals ("[email protected]",
Util.Beans.Objects.To_String (Bean.Get_Value ("email")),
"Session form not initialized");
end if;
end Check;
Path : constant String := Util.Tests.Get_Test_Path ("regtests/config/test-module.xml");
begin
T.App.Register_Class ("ASF.Applications.Tests.Form_Bean", Create_Form_Bean'Access);
ASF.Applications.Main.Configs.Read_Configuration (T.App.all, Path);
-- Check the 'regtests/config/test-module.xml' managed bean configuration.
Check ("applicationForm", ASF.Beans.APPLICATION_SCOPE);
Check ("sessionForm", ASF.Beans.SESSION_SCOPE);
Check ("requestForm", ASF.Beans.REQUEST_SCOPE);
end Test_Create_Bean;
-- ------------------------------
-- Test loading a resource bundle through the application.
-- ------------------------------
procedure Test_Load_Bundle (T : in out Test) is
use type Util.Beans.Basic.Readonly_Bean_Access;
Path : constant String := Util.Tests.Get_Test_Path ("regtests/config/test-bundle.xml");
Bundle : ASF.Locales.Bundle;
begin
ASF.Applications.Main.Configs.Read_Configuration (T.App.all, Path);
T.App.Load_Bundle (Name => "samples",
Locale => "en",
Bundle => Bundle);
Util.Tests.Assert_Equals (T, "Help", String '(Bundle.Get ("layout_help_label")),
"Invalid bundle value");
T.App.Load_Bundle (Name => "asf",
Locale => "en",
Bundle => Bundle);
Util.Tests.Assert_Matches (T, ".*greater than.*",
String '(Bundle.Get ("validators.length.maximum")),
"Invalid bundle value");
end Test_Load_Bundle;
-- ------------------------------
-- Test application configuration and registration of resource bundles.
-- ------------------------------
procedure Test_Bundle_Configuration (T : in out Test) is
use type Util.Beans.Basic.Readonly_Bean_Access;
Path : constant String := Util.Tests.Get_Test_Path ("regtests/config/test-bundle.xml");
Result : Util.Beans.Basic.Readonly_Bean_Access;
Context : aliased ASF.Contexts.Faces.Faces_Context;
Ctx : aliased EL.Contexts.Default.Default_Context;
Scope : Scope_Type;
begin
Context.Set_ELContext (Ctx'Unchecked_Access);
ASF.Applications.Main.Configs.Read_Configuration (T.App.all, Path);
T.App.Create (Name => Ada.Strings.Unbounded.To_Unbounded_String ("samplesMsg"),
Context => Ctx,
Result => Result,
Scope => Scope);
T.Assert (Result /= null, "The samplesMsg bundle was not created");
T.App.Create (Name => Ada.Strings.Unbounded.To_Unbounded_String ("defaultMsg"),
Context => Ctx,
Result => Result,
Scope => Scope);
T.Assert (Result /= null, "The defaultMsg bundle was not created");
end Test_Bundle_Configuration;
-- ------------------------------
-- Test locales.
-- ------------------------------
procedure Test_Locales (T : in out Test) is
use Util.Locales;
Path : constant String := Util.Tests.Get_Test_Path ("regtests/config/test-locales.xml");
Req : aliased ASF.Requests.Mockup.Request;
View : constant access Applications.Views.View_Handler'Class := T.App.Get_View_Handler;
Context : aliased ASF.Contexts.Faces.Faces_Context;
ELContext : aliased EL.Contexts.Default.Default_Context;
Locale : Util.Locales.Locale;
begin
ASF.Applications.Main.Configs.Read_Configuration (T.App.all, Path);
Util.Tests.Assert_Equals (T, To_String (Util.Locales.FRENCH),
To_String (T.App.Get_Default_Locale),
"Invalid default locale");
Context.Set_ELContext (ELContext'Unchecked_Access);
Context.Set_Request (Req'Unchecked_Access);
Req.Set_Header ("Accept-Language", "da, en-gb;q=0.3, fr;q=0.7");
T.App.Set_Context (Context'Unchecked_Access);
Locale := View.Calculate_Locale (Context);
Util.Tests.Assert_Equals (T, To_String (Util.Locales.FRENCH),
To_String (Locale),
"Invalid calculated locale");
Req.Set_Header ("Accept-Language", "da, en-gb, en;q=0.8, fr;q=0.7");
T.App.Set_Context (Context'Unchecked_Access);
Locale := View.Calculate_Locale (Context);
Util.Tests.Assert_Equals (T, "en_GB",
To_String (Locale),
"Invalid calculated locale");
Req.Set_Header ("Accept-Language", "da, fr;q=0.7, fr-fr;q=0.8");
T.App.Set_Context (Context'Unchecked_Access);
Locale := View.Calculate_Locale (Context);
Util.Tests.Assert_Equals (T, "fr_FR",
To_String (Locale),
"Invalid calculated locale");
Req.Set_Header ("Accept-Language", "da, ru, it;q=0.8, de;q=0.7");
T.App.Set_Context (Context'Unchecked_Access);
Locale := View.Calculate_Locale (Context);
Util.Tests.Assert_Equals (T, To_String (Util.Locales.FRENCH),
To_String (Locale),
"Invalid calculated locale");
end Test_Locales;
end ASF.Applications.Main.Tests;
|
Fix the Test_Bundle_Configuration that requires a faces context to be executed
|
Fix the Test_Bundle_Configuration that requires a faces context to be executed
|
Ada
|
apache-2.0
|
Letractively/ada-asf,Letractively/ada-asf,Letractively/ada-asf
|
078e59891dd0c00bfde3245e63405323b2992855
|
ada/evaluation.adb
|
ada/evaluation.adb
|
with Ada.Text_IO;
with Ada.Exceptions;
with Envs;
with Smart_Pointers;
package body Evaluation is
use Types;
function Def_Fn (Args : List_Mal_Type; Env : Envs.Env_Handle)
return Mal_Handle is
Name, Fn_Body, Res : Mal_Handle;
begin
Name := Car (Args);
pragma Assert (Deref (Name).Sym_Type = Sym,
"Def_Fn: expected atom as name");
Fn_Body := Car (Deref_List (Cdr (Args)).all);
Res := Eval (Fn_Body, Env);
Envs.Set (Envs.Get_Current, Deref_Sym (Name).Get_Sym, Res);
return Res;
end Def_Fn;
function Def_Macro (Args : List_Mal_Type; Env : Envs.Env_Handle)
return Mal_Handle is
Name, Fn_Body, Res : Mal_Handle;
Lambda_P : Lambda_Ptr;
begin
Name := Car (Args);
pragma Assert (Deref (Name).Sym_Type = Sym,
"Def_Macro: expected atom as name");
Fn_Body := Car (Deref_List (Cdr (Args)).all);
Res := Eval (Fn_Body, Env);
Lambda_P := Deref_Lambda (Res);
Lambda_P.Set_Is_Macro (True);
Envs.Set (Envs.Get_Current, Deref_Sym (Name).Get_Sym, Res);
return Res;
end Def_Macro;
function Macro_Expand (Ast : Mal_Handle; Env : Envs.Env_Handle)
return Mal_Handle is
Res : Mal_Handle;
E : Envs.Env_Handle;
LMT : List_Mal_Type;
LP : Lambda_Ptr;
begin
Res := Ast;
E := Env;
loop
if Deref (Res).Sym_Type /= List then
exit;
end if;
LMT := Deref_List (Res).all;
-- Get the macro in the list from the env
-- or return null if not applicable.
LP := Get_Macro (Res, E);
exit when LP = null or else not LP.Get_Is_Macro;
declare
Fn_List : Mal_Handle := Cdr (LMT);
Params : List_Mal_Type;
begin
E := Envs.New_Env (E);
Params := Deref_List (LP.Get_Params).all;
if Envs.Bind (E, Params, Deref_List (Fn_List).all) then
Res := Eval (LP.Get_Expr, E);
end if;
end;
end loop;
return Res;
end Macro_Expand;
function Let_Processing (Args : List_Mal_Type; Env : Envs.Env_Handle)
return Mal_Handle is
Defs, Expr, Res : Mal_Handle;
E : Envs.Env_Handle;
begin
E := Envs.New_Env (Env);
Defs := Car (Args);
Deref_List_Class (Defs).Add_Defs (E);
Expr := Car (Deref_List (Cdr (Args)).all);
Res := Eval (Expr, E);
return Res;
end Let_Processing;
function Eval_As_Boolean (MH : Mal_Handle) return Boolean is
Res : Boolean;
begin
case Deref (MH).Sym_Type is
when Bool =>
Res := Deref_Bool (MH).Get_Bool;
when Sym =>
return not (Deref_Sym (MH).Get_Sym = "nil");
-- when List =>
-- declare
-- L : List_Mal_Type;
-- begin
-- L := Deref_List (MH).all;
-- Res := not Is_Null (L);
-- end;
when others => -- Everything else
Res := True;
end case;
return Res;
end Eval_As_Boolean;
function Eval_Ast
(Ast : Mal_Handle; Env : Envs.Env_Handle)
return Mal_Handle is
function Call_Eval (A : Mal_Handle) return Mal_Handle is
begin
return Eval (A, Env);
end Call_Eval;
begin
case Deref (Ast).Sym_Type is
when Sym =>
declare
Sym : Mal_String := Deref_Sym (Ast).Get_Sym;
begin
-- if keyword, return it. Otherwise look it up in the environment.
if Sym(1) = ':' then
return Ast;
else
return Envs.Get (Env, Sym);
end if;
exception
when Envs.Not_Found =>
raise Envs.Not_Found with (" '" & Sym & "' not found ");
end;
when List =>
return Map (Call_Eval'Unrestricted_Access, Deref_List_Class (Ast).all);
when Lambda =>
-- Evaluating a lambda in a different Env.
declare
L : Lambda_Ptr;
New_Env : Envs.Env_Handle;
begin
L := Deref_Lambda (Ast);
New_Env := Env;
-- Make the current Lambda's env the outer of the env param.
Envs.Set_Outer (New_Env, L.Get_Env);
-- Make the Lambda's Env.
L.Set_Env (New_Env);
return Ast;
end;
when others => return Ast;
end case;
end Eval_Ast;
function Do_Processing (Do_List : List_Mal_Type; Env : Envs.Env_Handle)
return Mal_Handle is
D : List_Mal_Type;
Res : Mal_Handle := Smart_Pointers.Null_Smart_Pointer;
begin
if Debug then
Ada.Text_IO.Put_Line ("Do-ing " & To_String (Do_List));
end if;
D := Do_List;
while not Is_Null (D) loop
Res := Eval (Car (D), Env);
D := Deref_List (Cdr(D)).all;
end loop;
return Res;
end Do_Processing;
function Quasi_Quote_Processing (Param : Mal_Handle) return Mal_Handle is
Res, First_Elem, FE_0 : Mal_Handle;
D, Ast : List_Mal_Type;
L : List_Ptr;
begin
if Debug then
Ada.Text_IO.Put_Line ("QuasiQt " & Deref (Param).To_String);
end if;
-- Create a New List for the result...
Res := New_List_Mal_Type (List_List);
L := Deref_List (Res);
-- This is the equivalent of Is_Pair
if Deref (Param).Sym_Type /= List or else
Is_Null (Deref_List (Param).all) then
-- return a new list containing: a symbol named "quote" and ast.
L.Append (New_Symbol_Mal_Type ("quote"));
L.Append (Param);
return Res;
end if;
-- Ast is a non-empty list at this point.
Ast := Deref_List (Param).all;
First_Elem := Car (Ast);
-- if the first element of ast is a symbol named "unquote":
if Deref (First_Elem).Sym_Type = Sym and then
Deref_Sym (First_Elem).Get_Sym = "unquote" then
-- return the second element of ast.`
D := Deref_List (Cdr (Ast)).all;
return Car (D);
end if;
-- if the first element of first element of `ast` (`ast[0][0]`)
-- is a symbol named "splice-unquote"
if Deref (First_Elem).Sym_Type = List and then
not Is_Null (Deref_List (First_Elem).all) then
D := Deref_List (First_Elem).all;
FE_0 := Car (D);
if Deref (FE_0).Sym_Type = Sym and then
Deref_Sym (FE_0).Get_Sym = "splice-unquote" then
-- return a new list containing: a symbol named "concat",
L.Append (New_Symbol_Mal_Type ("concat"));
-- the second element of first element of ast (ast[0][1]),
D := Deref_List (Cdr (D)).all;
L.Append (Car (D));
-- and the result of calling quasiquote with
-- the second through last element of ast.
L.Append (Quasi_Quote_Processing (Cdr (Ast)));
return Res;
end if;
end if;
-- otherwise: return a new list containing: a symbol named "cons",
L.Append (New_Symbol_Mal_Type ("cons"));
-- the result of calling quasiquote on first element of ast (ast[0]),
L.Append (Quasi_Quote_Processing (Car (Ast)));
-- and result of calling quasiquote with the second through last element of ast.
L.Append (Quasi_Quote_Processing (Cdr (Ast)));
return Res;
end Quasi_Quote_Processing;
function Catch_Processing
(Try_Line : Mal_Handle;
ExStr : Mal_Handle;
Env : Envs.Env_Handle)
return Mal_Handle is
L, CL, CL2, CL3 : List_Mal_Type;
C : Mal_Handle;
New_Env : Envs.Env_Handle;
begin
L := Deref_List (Try_Line).all;
C := Car (L);
-- CL is the list with the catch in.
CL := Deref_List (C).all;
CL2 := Deref_List (Cdr (CL)).all;
New_Env := Envs.New_Env (Env);
Envs.Set (New_Env, Deref_Sym (Car (CL2)).Get_Sym, ExStr);
CL3 := Deref_List (Cdr (CL2)).all;
return Eval (Car (CL3), New_Env);
end Catch_Processing;
Mal_Exception_Value : Mal_Handle;
procedure Set_Mal_Exception_Value (MEV : Mal_Handle) is
begin
Mal_Exception_Value := MEV;
end Set_Mal_Exception_Value;
function Eval (AParam : Mal_Handle; AnEnv : Envs.Env_Handle)
return Mal_Handle is
Param : Mal_Handle;
Env : Envs.Env_Handle;
First_Elem : Mal_Handle;
begin
Param := AParam;
Env := AnEnv;
<<Tail_Call_Opt>>
if Debug then
Ada.Text_IO.Put_Line ("Evaling " & Deref (Param).To_String);
end if;
Param := Macro_Expand (Param, Env);
if Debug then
Ada.Text_IO.Put_Line ("After expansion " & Deref (Param).To_String);
end if;
if Deref (Param).Sym_Type = List and then
Deref_List (Param).Get_List_Type = List_List then
declare
L : Mal_Handle := Param;
LMT, Rest_List : List_Mal_Type;
First_Elem, Rest_Handle : Mal_Handle;
begin
LMT := Deref_List (L).all;
First_Elem := Car (LMT);
Rest_Handle := Cdr (LMT);
Rest_List := Deref_List (Rest_Handle).all;
case Deref (First_Elem).Sym_Type is
when Int | Floating | Bool | Str =>
return First_Elem;
when Atom =>
return Deref_Atom (First_Elem).Get_Atom;
when Sym =>
declare
Sym_P : Sym_Ptr;
begin
Sym_P := Deref_Sym (First_Elem);
if Sym_P.Get_Sym = "def!" then
return Def_Fn (Rest_List, Env);
elsif Sym_P.Get_Sym = "defmacro!" then
return Def_Macro (Rest_List, Env);
elsif Sym_P.Get_Sym = "macroexpand" then
return Macro_Expand (Car (Rest_List), Env);
elsif Sym_P.Get_Sym = "let*" then
return Let_Processing (Rest_List, Env);
elsif Sym_P.Get_Sym = "do" then
return Do_Processing (Rest_List, Env);
elsif Sym_P.Get_Sym = "if" then
declare
Args : List_Mal_Type := Rest_List;
Cond, True_Part, False_Part : Mal_Handle;
Cond_Bool : Boolean;
pragma Assert (Length (Args) = 2 or Length (Args) = 3,
"If_Processing: not 2 or 3 parameters");
L : List_Mal_Type;
begin
Cond := Eval (Car (Args), Env);
Cond_Bool := Eval_As_Boolean (Cond);
if Cond_Bool then
L := Deref_List (Cdr (Args)).all;
Param := Car (L);
goto Tail_Call_Opt;
-- was: return Eval (Car (L), Env);
else
if Length (Args) = 3 then
L := Deref_List (Cdr (Args)).all;
L := Deref_List (Cdr (L)).all;
Param := Car (L);
goto Tail_Call_Opt;
-- was: return Eval (Car (L), Env);
else
return New_Symbol_Mal_Type ("nil");
end if;
end if;
end;
elsif Sym_P.Get_Sym = "quote" then
return Car (Rest_List);
elsif Sym_P.Get_Sym = "quasiquote" then
Param := Quasi_Quote_Processing (Car (Rest_List));
goto Tail_Call_Opt;
elsif Sym_P.Get_Sym = "try*" then
declare
Res : Mal_Handle;
begin
return Eval (Car (Rest_List), Env);
exception
when Mal_Exception =>
Res := Catch_Processing
(Cdr (Rest_List),
Mal_Exception_Value,
Env);
Mal_Exception_Value := Smart_Pointers.Null_Smart_Pointer;
return Res;
when E : others =>
return Catch_Processing
(Cdr (Rest_List),
New_String_Mal_Type
(Ada.Exceptions.Exception_Message (E)),
Env);
end;
else -- not a special form
-- Apply section
declare
Res : Mal_Handle;
begin
-- Eval the atom.
Res := Eval_Ast (L, Env);
Param := Res;
goto Tail_Call_Opt;
-- was: return Eval (Res, Env);
end;
end if;
end;
when Func =>
return Call_Func
(Deref_Func (First_Elem).all,
Rest_Handle,
Env);
when Lambda =>
declare
LP : Lambda_Ptr := Deref_Lambda (First_Elem);
Fn_List : Mal_Handle := Cdr (LMT);
Params : List_Mal_Type;
E : Envs.Env_Handle;
begin
E := Envs.New_Env (LP.Get_Env);
Params := Deref_List (LP.Get_Params).all;
if Envs.Bind (E, Params, Deref_List (Fn_List).all) then
Param := LP.Get_Expr;
Env := E;
goto Tail_Call_Opt;
-- was: return Eval (LP.Get_Expr, E);
else
return First_Elem;
end if;
end;
when List =>
-- First elem in the list is a list.
-- Eval it and then insert it as first elem in the list and
-- go again.
declare
Evaled_List : Mal_Handle;
E : Envs.Env_Handle;
begin
Evaled_List := Eval (First_Elem, Env);
if Is_Null (Evaled_List) then
return Evaled_List;
elsif Deref (Evaled_List).Sym_Type = Lambda then
E := Deref_Lambda (Evaled_List).Get_Env;
else
E := Env;
end if;
Param := Prepend (Evaled_List, Rest_List);
Env := E;
goto Tail_Call_Opt;
-- was:
-- Evaled_List := Prepend (Evaled_List, Rest_List);
-- return Eval (Evaled_List, E);
end;
when Error => return First_Elem;
when Node => return New_Error_Mal_Type ("Evaluating a node");
end case;
end;
else
return Eval_Ast (Param, Env);
end if;
end Eval;
end Evaluation;
|
with Ada.Text_IO;
with Ada.Exceptions;
with Envs;
with Smart_Pointers;
package body Evaluation is
use Types;
function Def_Fn (Args : List_Mal_Type; Env : Envs.Env_Handle)
return Mal_Handle is
Name, Fn_Body, Res : Mal_Handle;
begin
Name := Car (Args);
pragma Assert (Deref (Name).Sym_Type = Sym,
"Def_Fn: expected atom as name");
Fn_Body := Car (Deref_List (Cdr (Args)).all);
Res := Eval (Fn_Body, Env);
Envs.Set (Envs.Get_Current, Deref_Sym (Name).Get_Sym, Res);
return Res;
end Def_Fn;
function Def_Macro (Args : List_Mal_Type; Env : Envs.Env_Handle)
return Mal_Handle is
Name, Fn_Body, Res : Mal_Handle;
Lambda_P : Lambda_Ptr;
begin
Name := Car (Args);
pragma Assert (Deref (Name).Sym_Type = Sym,
"Def_Macro: expected atom as name");
Fn_Body := Car (Deref_List (Cdr (Args)).all);
Res := Eval (Fn_Body, Env);
Lambda_P := Deref_Lambda (Res);
Lambda_P.Set_Is_Macro (True);
Envs.Set (Envs.Get_Current, Deref_Sym (Name).Get_Sym, Res);
return Res;
end Def_Macro;
function Macro_Expand (Ast : Mal_Handle; Env : Envs.Env_Handle)
return Mal_Handle is
Res : Mal_Handle;
E : Envs.Env_Handle;
LMT : List_Mal_Type;
LP : Lambda_Ptr;
begin
Res := Ast;
E := Env;
loop
if Deref (Res).Sym_Type /= List then
exit;
end if;
LMT := Deref_List (Res).all;
-- Get the macro in the list from the env
-- or return null if not applicable.
LP := Get_Macro (Res, E);
exit when LP = null or else not LP.Get_Is_Macro;
declare
Fn_List : Mal_Handle := Cdr (LMT);
Params : List_Mal_Type;
begin
E := Envs.New_Env (E);
Params := Deref_List (LP.Get_Params).all;
if Envs.Bind (E, Params, Deref_List (Fn_List).all) then
Res := Eval (LP.Get_Expr, E);
end if;
end;
end loop;
return Res;
end Macro_Expand;
function Let_Processing (Args : List_Mal_Type; Env : Envs.Env_Handle)
return Mal_Handle is
Defs, Expr, Res : Mal_Handle;
E : Envs.Env_Handle;
begin
E := Envs.New_Env (Env);
Defs := Car (Args);
Deref_List_Class (Defs).Add_Defs (E);
Expr := Car (Deref_List (Cdr (Args)).all);
Res := Eval (Expr, E);
return Res;
end Let_Processing;
function Eval_As_Boolean (MH : Mal_Handle) return Boolean is
Res : Boolean;
begin
case Deref (MH).Sym_Type is
when Bool =>
Res := Deref_Bool (MH).Get_Bool;
when Sym =>
return not (Deref_Sym (MH).Get_Sym = "nil");
-- when List =>
-- declare
-- L : List_Mal_Type;
-- begin
-- L := Deref_List (MH).all;
-- Res := not Is_Null (L);
-- end;
when others => -- Everything else
Res := True;
end case;
return Res;
end Eval_As_Boolean;
function Eval_Ast
(Ast : Mal_Handle; Env : Envs.Env_Handle)
return Mal_Handle is
function Call_Eval (A : Mal_Handle) return Mal_Handle is
begin
return Eval (A, Env);
end Call_Eval;
begin
case Deref (Ast).Sym_Type is
when Sym =>
declare
Sym : Mal_String := Deref_Sym (Ast).Get_Sym;
begin
-- if keyword, return it. Otherwise look it up in the environment.
if Sym(1) = ':' then
return Ast;
else
return Envs.Get (Env, Sym);
end if;
exception
when Envs.Not_Found =>
raise Envs.Not_Found with (" '" & Sym & "' not found ");
end;
when List =>
return Map (Call_Eval'Unrestricted_Access, Deref_List_Class (Ast).all);
when Lambda =>
-- Evaluating a lambda in a different Env.
declare
L : Lambda_Ptr;
New_Env : Envs.Env_Handle;
begin
L := Deref_Lambda (Ast);
New_Env := Env;
-- Make the current Lambda's env the outer of the env param.
Envs.Set_Outer (New_Env, L.Get_Env);
-- Make the Lambda's Env.
L.Set_Env (New_Env);
return Ast;
end;
when others => return Ast;
end case;
end Eval_Ast;
function Do_Processing (Do_List : List_Mal_Type; Env : Envs.Env_Handle)
return Mal_Handle is
D : List_Mal_Type;
Res : Mal_Handle := Smart_Pointers.Null_Smart_Pointer;
begin
if Debug then
Ada.Text_IO.Put_Line ("Do-ing " & To_String (Do_List));
end if;
D := Do_List;
while not Is_Null (D) loop
Res := Eval (Car (D), Env);
D := Deref_List (Cdr(D)).all;
end loop;
return Res;
end Do_Processing;
function Quasi_Quote_Processing (Param : Mal_Handle) return Mal_Handle is
Res, First_Elem, FE_0 : Mal_Handle;
L : List_Ptr;
D_Ptr, Ast_P : List_Class_Ptr;
begin
if Debug then
Ada.Text_IO.Put_Line ("QuasiQt " & Deref (Param).To_String);
end if;
-- Create a New List for the result...
Res := New_List_Mal_Type (List_List);
L := Deref_List (Res);
-- This is the equivalent of Is_Pair
if Deref (Param).Sym_Type /= List or else
Is_Null (Deref_List_Class (Param).all) then
-- return a new list containing: a symbol named "quote" and ast.
L.Append (New_Symbol_Mal_Type ("quote"));
L.Append (Param);
return Res;
end if;
-- Ast is a non-empty list at this point.
Ast_P := Deref_List_Class (Param);
First_Elem := Car (Ast_P.all);
-- if the first element of ast is a symbol named "unquote":
if Deref (First_Elem).Sym_Type = Sym and then
Deref_Sym (First_Elem).Get_Sym = "unquote" then
-- return the second element of ast.`
D_Ptr := Deref_List_Class (Cdr (Ast_P.all));
return Car (D_Ptr.all);
end if;
-- if the first element of first element of `ast` (`ast[0][0]`)
-- is a symbol named "splice-unquote"
if Deref (First_Elem).Sym_Type = List and then
not Is_Null (Deref_List_Class (First_Elem).all) then
D_Ptr := Deref_List_Class (First_Elem);
FE_0 := Car (D_Ptr.all);
if Deref (FE_0).Sym_Type = Sym and then
Deref_Sym (FE_0).Get_Sym = "splice-unquote" then
-- return a new list containing: a symbol named "concat",
L.Append (New_Symbol_Mal_Type ("concat"));
-- the second element of first element of ast (ast[0][1]),
D_Ptr := Deref_List_Class (Cdr (D_Ptr.all));
L.Append (Car (D_Ptr.all));
-- and the result of calling quasiquote with
-- the second through last element of ast.
L.Append (Quasi_Quote_Processing (Cdr (Ast_P.all)));
return Res;
end if;
end if;
-- otherwise: return a new list containing: a symbol named "cons",
L.Append (New_Symbol_Mal_Type ("cons"));
-- the result of calling quasiquote on first element of ast (ast[0]),
L.Append (Quasi_Quote_Processing (Car (Ast_P.all)));
-- and result of calling quasiquote with the second through last element of ast.
L.Append (Quasi_Quote_Processing (Cdr (Ast_P.all)));
return Res;
end Quasi_Quote_Processing;
function Catch_Processing
(Try_Line : Mal_Handle;
ExStr : Mal_Handle;
Env : Envs.Env_Handle)
return Mal_Handle is
L, CL, CL2, CL3 : List_Mal_Type;
C : Mal_Handle;
New_Env : Envs.Env_Handle;
begin
L := Deref_List (Try_Line).all;
C := Car (L);
-- CL is the list with the catch in.
CL := Deref_List (C).all;
CL2 := Deref_List (Cdr (CL)).all;
New_Env := Envs.New_Env (Env);
Envs.Set (New_Env, Deref_Sym (Car (CL2)).Get_Sym, ExStr);
CL3 := Deref_List (Cdr (CL2)).all;
return Eval (Car (CL3), New_Env);
end Catch_Processing;
Mal_Exception_Value : Mal_Handle;
procedure Set_Mal_Exception_Value (MEV : Mal_Handle) is
begin
Mal_Exception_Value := MEV;
end Set_Mal_Exception_Value;
function Eval (AParam : Mal_Handle; AnEnv : Envs.Env_Handle)
return Mal_Handle is
Param : Mal_Handle;
Env : Envs.Env_Handle;
First_Elem : Mal_Handle;
begin
Param := AParam;
Env := AnEnv;
<<Tail_Call_Opt>>
if Debug then
Ada.Text_IO.Put_Line ("Evaling " & Deref (Param).To_String);
end if;
Param := Macro_Expand (Param, Env);
if Debug then
Ada.Text_IO.Put_Line ("After expansion " & Deref (Param).To_String);
end if;
if Deref (Param).Sym_Type = List and then
Deref_List (Param).Get_List_Type = List_List then
declare
L : Mal_Handle := Param;
LMT, Rest_List : List_Mal_Type;
First_Elem, Rest_Handle : Mal_Handle;
begin
LMT := Deref_List (L).all;
First_Elem := Car (LMT);
Rest_Handle := Cdr (LMT);
Rest_List := Deref_List (Rest_Handle).all;
case Deref (First_Elem).Sym_Type is
when Int | Floating | Bool | Str =>
return First_Elem;
when Atom =>
return Deref_Atom (First_Elem).Get_Atom;
when Sym =>
declare
Sym_P : Sym_Ptr;
begin
Sym_P := Deref_Sym (First_Elem);
if Sym_P.Get_Sym = "def!" then
return Def_Fn (Rest_List, Env);
elsif Sym_P.Get_Sym = "defmacro!" then
return Def_Macro (Rest_List, Env);
elsif Sym_P.Get_Sym = "macroexpand" then
return Macro_Expand (Car (Rest_List), Env);
elsif Sym_P.Get_Sym = "let*" then
return Let_Processing (Rest_List, Env);
elsif Sym_P.Get_Sym = "do" then
return Do_Processing (Rest_List, Env);
elsif Sym_P.Get_Sym = "if" then
declare
Args : List_Mal_Type := Rest_List;
Cond, True_Part, False_Part : Mal_Handle;
Cond_Bool : Boolean;
pragma Assert (Length (Args) = 2 or Length (Args) = 3,
"If_Processing: not 2 or 3 parameters");
L : List_Mal_Type;
begin
Cond := Eval (Car (Args), Env);
Cond_Bool := Eval_As_Boolean (Cond);
if Cond_Bool then
L := Deref_List (Cdr (Args)).all;
Param := Car (L);
goto Tail_Call_Opt;
-- was: return Eval (Car (L), Env);
else
if Length (Args) = 3 then
L := Deref_List (Cdr (Args)).all;
L := Deref_List (Cdr (L)).all;
Param := Car (L);
goto Tail_Call_Opt;
-- was: return Eval (Car (L), Env);
else
return New_Symbol_Mal_Type ("nil");
end if;
end if;
end;
elsif Sym_P.Get_Sym = "quote" then
return Car (Rest_List);
elsif Sym_P.Get_Sym = "quasiquote" then
Param := Quasi_Quote_Processing (Car (Rest_List));
goto Tail_Call_Opt;
elsif Sym_P.Get_Sym = "try*" then
declare
Res : Mal_Handle;
begin
return Eval (Car (Rest_List), Env);
exception
when Mal_Exception =>
Res := Catch_Processing
(Cdr (Rest_List),
Mal_Exception_Value,
Env);
Mal_Exception_Value := Smart_Pointers.Null_Smart_Pointer;
return Res;
when E : others =>
return Catch_Processing
(Cdr (Rest_List),
New_String_Mal_Type
(Ada.Exceptions.Exception_Message (E)),
Env);
end;
else -- not a special form
-- Apply section
declare
Res : Mal_Handle;
begin
-- Eval the atom.
Res := Eval_Ast (L, Env);
Param := Res;
goto Tail_Call_Opt;
-- was: return Eval (Res, Env);
end;
end if;
end;
when Func =>
return Call_Func
(Deref_Func (First_Elem).all,
Rest_Handle,
Env);
when Lambda =>
declare
LP : Lambda_Ptr := Deref_Lambda (First_Elem);
Fn_List : Mal_Handle := Cdr (LMT);
Params : List_Mal_Type;
E : Envs.Env_Handle;
begin
E := Envs.New_Env (LP.Get_Env);
Params := Deref_List (LP.Get_Params).all;
if Envs.Bind (E, Params, Deref_List (Fn_List).all) then
Param := LP.Get_Expr;
Env := E;
goto Tail_Call_Opt;
-- was: return Eval (LP.Get_Expr, E);
else
return First_Elem;
end if;
end;
when List =>
-- First elem in the list is a list.
-- Eval it and then insert it as first elem in the list and
-- go again.
declare
Evaled_List : Mal_Handle;
E : Envs.Env_Handle;
begin
Evaled_List := Eval (First_Elem, Env);
if Is_Null (Evaled_List) then
return Evaled_List;
elsif Deref (Evaled_List).Sym_Type = Lambda then
E := Deref_Lambda (Evaled_List).Get_Env;
else
E := Env;
end if;
Param := Prepend (Evaled_List, Rest_List);
Env := E;
goto Tail_Call_Opt;
-- was:
-- Evaled_List := Prepend (Evaled_List, Rest_List);
-- return Eval (Evaled_List, E);
end;
when Error => return First_Elem;
when Node => return New_Error_Mal_Type ("Evaluating a node");
end case;
end;
else
return Eval_Ast (Param, Env);
end if;
end Eval;
end Evaluation;
|
make quasiquote etc work for vectors
|
Ada: make quasiquote etc work for vectors
|
Ada
|
mpl-2.0
|
foresterre/mal,jwalsh/mal,foresterre/mal,alantsev/mal,hterkelsen/mal,hterkelsen/mal,DomBlack/mal,0gajun/mal,alantsev/mal,0gajun/mal,hterkelsen/mal,0gajun/mal,0gajun/mal,SawyerHood/mal,0gajun/mal,alantsev/mal,DomBlack/mal,foresterre/mal,foresterre/mal,jwalsh/mal,jwalsh/mal,jwalsh/mal,mpwillson/mal,hterkelsen/mal,SawyerHood/mal,foresterre/mal,DomBlack/mal,0gajun/mal,DomBlack/mal,alantsev/mal,mpwillson/mal,alantsev/mal,hterkelsen/mal,foresterre/mal,mpwillson/mal,0gajun/mal,hterkelsen/mal,foresterre/mal,foresterre/mal,jwalsh/mal,mpwillson/mal,mpwillson/mal,hterkelsen/mal,jwalsh/mal,SawyerHood/mal,0gajun/mal,hterkelsen/mal,jwalsh/mal,SawyerHood/mal,SawyerHood/mal,joncol/mal,mpwillson/mal,0gajun/mal,alantsev/mal,alantsev/mal,foresterre/mal,jwalsh/mal,SawyerHood/mal,foresterre/mal,hterkelsen/mal,DomBlack/mal,SawyerHood/mal,joncol/mal,jwalsh/mal,mpwillson/mal,hterkelsen/mal,alantsev/mal,0gajun/mal,DomBlack/mal,alantsev/mal,alantsev/mal,mpwillson/mal,alantsev/mal,SawyerHood/mal,SawyerHood/mal,mpwillson/mal,DomBlack/mal,jwalsh/mal,hterkelsen/mal,0gajun/mal,0gajun/mal,DomBlack/mal,DomBlack/mal,joncol/mal,foresterre/mal,SawyerHood/mal,jwalsh/mal,alantsev/mal,DomBlack/mal,DomBlack/mal,hterkelsen/mal,SawyerHood/mal,foresterre/mal,alantsev/mal,jwalsh/mal,DomBlack/mal,hterkelsen/mal,SawyerHood/mal,hterkelsen/mal,alantsev/mal,hterkelsen/mal,DomBlack/mal,jwalsh/mal,DomBlack/mal,mpwillson/mal,foresterre/mal,foresterre/mal,SawyerHood/mal,0gajun/mal,alantsev/mal,mpwillson/mal,foresterre/mal,hterkelsen/mal,0gajun/mal,0gajun/mal,hterkelsen/mal,0gajun/mal,DomBlack/mal,mpwillson/mal,DomBlack/mal,foresterre/mal,hterkelsen/mal,hterkelsen/mal,alantsev/mal,DomBlack/mal,0gajun/mal,SawyerHood/mal,mpwillson/mal,SawyerHood/mal,SawyerHood/mal,0gajun/mal,jwalsh/mal,SawyerHood/mal,SawyerHood/mal,0gajun/mal,foresterre/mal,jwalsh/mal,jwalsh/mal,DomBlack/mal,DomBlack/mal,DomBlack/mal,0gajun/mal,alantsev/mal,DomBlack/mal,mpwillson/mal,jwalsh/mal
|
eb2e205046ef170f7f23eceafe39f2337a121dfc
|
src/natools-smaz_implementations-base_64.adb
|
src/natools-smaz_implementations-base_64.adb
|
------------------------------------------------------------------------------
-- Copyright (c) 2016, Natacha Porté --
-- --
-- Permission to use, copy, modify, and distribute this software for any --
-- purpose with or without fee is hereby granted, provided that the above --
-- copyright notice and this permission notice appear in all copies. --
-- --
-- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES --
-- WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF --
-- MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR --
-- ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES --
-- WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN --
-- ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF --
-- OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. --
------------------------------------------------------------------------------
package body Natools.Smaz_Implementations.Base_64 is
package Tools renames Natools.Smaz_Implementations.Base_64_Tools;
use type Ada.Streams.Stream_Element_Offset;
use type Tools.Base_64_Digit;
----------------------
-- Public Interface --
----------------------
procedure Read_Code
(Input : in Ada.Streams.Stream_Element_Array;
Offset : in out Ada.Streams.Stream_Element_Offset;
Code : out Natools.Smaz_Implementations.Base_64_Tools.Base_64_Digit;
Verbatim_Length : out Natural;
Last_Code : in Natools.Smaz_Implementations.Base_64_Tools.Base_64_Digit;
Variable_Length_Verbatim : in Boolean)
is
Ignored : String (1 .. 2);
Offset_Backup : Ada.Streams.Stream_Element_Offset;
begin
Tools.Next_Digit (Input, Offset, Code);
if Code <= Last_Code then
Verbatim_Length := 0;
elsif Variable_Length_Verbatim then
if Code < 63 then
Verbatim_Length := 63 - Natural (Code);
else
Tools.Next_Digit (Input, Offset, Code);
Verbatim_Length := Natural (Code) + 63 - Natural (Last_Code);
end if;
Code := 0;
elsif Code = 63 then
Tools.Next_Digit (Input, Offset, Code);
Verbatim_Length := Natural (Code) * 3 + 3;
Code := 0;
elsif Code = 62 then
Offset_Backup := Offset;
Tools.Decode_Single (Input, Offset, Ignored (1), Code);
Verbatim_Length := Natural (Code) * 3 + 1;
Offset := Offset_Backup;
Code := 0;
else
Offset_Backup := Offset;
Verbatim_Length := (61 - Natural (Code)) * 4;
Tools.Decode_Double (Input, Offset, Ignored, Code);
Verbatim_Length := (Verbatim_Length + Natural (Code)) * 3 + 2;
Offset := Offset_Backup;
Code := 0;
end if;
end Read_Code;
procedure Read_Verbatim
(Input : in Ada.Streams.Stream_Element_Array;
Offset : in out Ada.Streams.Stream_Element_Offset;
Output : out String)
is
Ignored : Tools.Base_64_Digit;
Output_Index : Natural := Output'First - 1;
begin
if Output'Length mod 3 = 1 then
Tools.Decode_Single
(Input, Offset, Output (Output_Index + 1), Ignored);
Output_Index := Output_Index + 1;
elsif Output'Length mod 3 = 2 then
Tools.Decode_Double
(Input, Offset,
Output (Output_Index + 1 .. Output_Index + 2), Ignored);
Output_Index := Output_Index + 2;
end if;
if Output_Index < Output'Last then
Tools.Decode
(Input, Offset, Output (Output_Index + 1 .. Output'Last));
end if;
end Read_Verbatim;
procedure Skip_Verbatim
(Input : in Ada.Streams.Stream_Element_Array;
Offset : in out Ada.Streams.Stream_Element_Offset;
Verbatim_Length : in Positive)
is
Code : Tools.Base_64_Digit;
begin
for I in 1 .. Tools.Image_Length (Verbatim_Length) loop
Tools.Next_Digit (Input, Offset, Code);
end loop;
end Skip_Verbatim;
function Verbatim_Size
(Input_Length : in Positive;
Last_Code : in Natools.Smaz_Implementations.Base_64_Tools.Base_64_Digit;
Variable_Length_Verbatim : in Boolean)
return Ada.Streams.Stream_Element_Count is
begin
if Variable_Length_Verbatim then
declare
Largest_Single : constant Positive := 62 - Natural (Last_Code);
Largest_Run : constant Positive := 64 + Largest_Single;
Run_Count : constant Natural
:= (Input_Length + Largest_Run - 1) / Largest_Run;
Last_Run_Size : constant Positive
:= Input_Length - (Run_Count - 1) * Largest_Run;
Last_Run_Header_Size : constant Ada.Streams.Stream_Element_Count
:= (if Last_Run_Size > Largest_Single then 2 else 1);
begin
return Ada.Streams.Stream_Element_Count (Run_Count)
* (Tools.Image_Length (Largest_Run) + 2)
+ Tools.Image_Length (Last_Run_Size) + Last_Run_Header_Size;
end;
else
declare
Largest_Prefix : constant Natural
:= (case Input_Length mod 3 is
when 1 => 15 * 3 + 1,
when 2 => ((62 - Natural (Last_Code)) * 4 - 1) * 3 + 2,
when others => 0);
Prefix_Header_Size : constant Ada.Streams.Stream_Element_Count
:= (if Largest_Prefix > 0 then 1 else 0);
Largest_Run : constant Positive := 64 * 3;
Prefix_Size : constant Natural
:= Natural'Min (Largest_Prefix, Input_Length);
Run_Count : constant Natural
:= (Input_Length - Prefix_Size + Largest_Run - 1) / Largest_Run;
begin
if Run_Count > 0 then
return Prefix_Header_Size + Tools.Image_Length (Prefix_Size)
+ Ada.Streams.Stream_Element_Count (Run_Count - 1)
* (Tools.Image_Length (Largest_Run) + 2)
+ Tools.Image_Length (Input_Length - Prefix_Size
- (Run_Count - 1) * Largest_Run)
+ 2;
else
return Prefix_Header_Size + Tools.Image_Length (Prefix_Size);
end if;
end;
end if;
end Verbatim_Size;
procedure Write_Code
(Output : in out Ada.Streams.Stream_Element_Array;
Offset : in out Ada.Streams.Stream_Element_Offset;
Code : in Natools.Smaz_Implementations.Base_64_Tools.Base_64_Digit) is
begin
Output (Offset) := Tools.Image (Code);
Offset := Offset + 1;
end Write_Code;
procedure Write_Verbatim
(Output : in out Ada.Streams.Stream_Element_Array;
Offset : in out Ada.Streams.Stream_Element_Offset;
Input : in String;
Last_Code : in Natools.Smaz_Implementations.Base_64_Tools.Base_64_Digit;
Variable_Length_Verbatim : in Boolean)
is
Index : Positive := Input'First;
begin
if Variable_Length_Verbatim then
declare
Largest_Single : constant Positive := 62 - Natural (Last_Code);
Largest_Run : constant Positive := 64 + Largest_Single;
Length, Last : Natural;
begin
while Index in Input'Range loop
Length := Positive'Min (Largest_Run, Input'Last + 1 - Index);
if Length > Largest_Single then
Write_Code (Output, Offset, 63);
Write_Code
(Output, Offset,
Tools.Base_64_Digit (Length - Largest_Single - 1));
else
Write_Code
(Output, Offset,
Tools.Base_64_Digit (63 - Length));
end if;
if Length mod 3 = 1 then
Tools.Encode_Single (Input (Index), 0, Output, Offset);
Index := Index + 1;
Length := Length - 1;
elsif Length mod 3 = 2 then
Tools.Encode_Double
(Input (Index .. Index + 1), 0, Output, Offset);
Index := Index + 2;
Length := Length - 2;
end if;
if Length > 0 then
Last := Index + Length - 1;
Tools.Encode (Input (Index .. Last), Output, Offset);
Index := Last + 1;
end if;
end loop;
end;
else
if Input'Length mod 3 = 1 then
declare
Extra_Blocks : constant Natural
:= Natural'Min (15, Input'Length / 3);
begin
Output (Offset) := Tools.Image (62);
Offset := Offset + 1;
Tools.Encode_Single
(Input (Index), Tools.Single_Byte_Padding (Extra_Blocks),
Output, Offset);
Index := Index + 1;
if Extra_Blocks > 0 then
Tools.Encode
(Input (Index .. Index + Extra_Blocks * 3 - 1),
Output, Offset);
Index := Index + Extra_Blocks * 3;
end if;
end;
elsif Input'Length mod 3 = 2 then
declare
Extra_Blocks : constant Natural := Natural'Min
(Input'Length / 3,
(62 - Natural (Last_Code)) * 4 - 1);
begin
Output (Offset)
:= Tools.Image (61 - Tools.Base_64_Digit (Extra_Blocks / 4));
Offset := Offset + 1;
Tools.Encode_Double
(Input (Index .. Index + 1),
Tools.Double_Byte_Padding (Extra_Blocks mod 4),
Output, Offset);
Index := Index + 2;
if Extra_Blocks > 0 then
Tools.Encode
(Input (Index .. Index + Extra_Blocks * 3 - 1),
Output, Offset);
Index := Index + Extra_Blocks * 3;
end if;
end;
end if;
pragma Assert ((Input'Last + 1 - Index) mod 3 = 0);
while Index <= Input'Last loop
declare
Block_Count : constant Natural
:= Natural'Min (64, (Input'Last + 1 - Index) / 3);
begin
Output (Offset) := Tools.Image (63);
Output (Offset + 1)
:= Tools.Image (Tools.Base_64_Digit (Block_Count - 1));
Offset := Offset + 2;
Tools.Encode
(Input (Index .. Index + Block_Count * 3 - 1),
Output, Offset);
Index := Index + Block_Count * 3;
end;
end loop;
end if;
end Write_Verbatim;
end Natools.Smaz_Implementations.Base_64;
|
------------------------------------------------------------------------------
-- Copyright (c) 2016-2017, Natacha Porté --
-- --
-- Permission to use, copy, modify, and distribute this software for any --
-- purpose with or without fee is hereby granted, provided that the above --
-- copyright notice and this permission notice appear in all copies. --
-- --
-- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES --
-- WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF --
-- MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR --
-- ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES --
-- WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN --
-- ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF --
-- OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. --
------------------------------------------------------------------------------
package body Natools.Smaz_Implementations.Base_64 is
package Tools renames Natools.Smaz_Implementations.Base_64_Tools;
use type Ada.Streams.Stream_Element_Offset;
use type Tools.Base_64_Digit;
----------------------
-- Public Interface --
----------------------
procedure Read_Code
(Input : in Ada.Streams.Stream_Element_Array;
Offset : in out Ada.Streams.Stream_Element_Offset;
Code : out Natools.Smaz_Implementations.Base_64_Tools.Base_64_Digit;
Verbatim_Length : out Natural;
Last_Code : in Natools.Smaz_Implementations.Base_64_Tools.Base_64_Digit;
Variable_Length_Verbatim : in Boolean)
is
Ignored : String (1 .. 2);
Offset_Backup : Ada.Streams.Stream_Element_Offset;
Finished : Boolean;
begin
Tools.Next_Digit_Or_End (Input, Offset, Code, Finished);
if Finished then
Code := Base_64_Tools.Base_64_Digit'Last;
Verbatim_Length := 0;
return;
end if;
if Code <= Last_Code then
Verbatim_Length := 0;
elsif Variable_Length_Verbatim then
if Code < 63 then
Verbatim_Length := 63 - Natural (Code);
else
Tools.Next_Digit (Input, Offset, Code);
Verbatim_Length := Natural (Code) + 63 - Natural (Last_Code);
end if;
Code := 0;
elsif Code = 63 then
Tools.Next_Digit (Input, Offset, Code);
Verbatim_Length := Natural (Code) * 3 + 3;
Code := 0;
elsif Code = 62 then
Offset_Backup := Offset;
Tools.Decode_Single (Input, Offset, Ignored (1), Code);
Verbatim_Length := Natural (Code) * 3 + 1;
Offset := Offset_Backup;
Code := 0;
else
Offset_Backup := Offset;
Verbatim_Length := (61 - Natural (Code)) * 4;
Tools.Decode_Double (Input, Offset, Ignored, Code);
Verbatim_Length := (Verbatim_Length + Natural (Code)) * 3 + 2;
Offset := Offset_Backup;
Code := 0;
end if;
end Read_Code;
procedure Read_Verbatim
(Input : in Ada.Streams.Stream_Element_Array;
Offset : in out Ada.Streams.Stream_Element_Offset;
Output : out String)
is
Ignored : Tools.Base_64_Digit;
Output_Index : Natural := Output'First - 1;
begin
if Output'Length mod 3 = 1 then
Tools.Decode_Single
(Input, Offset, Output (Output_Index + 1), Ignored);
Output_Index := Output_Index + 1;
elsif Output'Length mod 3 = 2 then
Tools.Decode_Double
(Input, Offset,
Output (Output_Index + 1 .. Output_Index + 2), Ignored);
Output_Index := Output_Index + 2;
end if;
if Output_Index < Output'Last then
Tools.Decode
(Input, Offset, Output (Output_Index + 1 .. Output'Last));
end if;
end Read_Verbatim;
procedure Skip_Verbatim
(Input : in Ada.Streams.Stream_Element_Array;
Offset : in out Ada.Streams.Stream_Element_Offset;
Verbatim_Length : in Positive)
is
Code : Tools.Base_64_Digit;
begin
for I in 1 .. Tools.Image_Length (Verbatim_Length) loop
Tools.Next_Digit (Input, Offset, Code);
end loop;
end Skip_Verbatim;
function Verbatim_Size
(Input_Length : in Positive;
Last_Code : in Natools.Smaz_Implementations.Base_64_Tools.Base_64_Digit;
Variable_Length_Verbatim : in Boolean)
return Ada.Streams.Stream_Element_Count is
begin
if Variable_Length_Verbatim then
declare
Largest_Single : constant Positive := 62 - Natural (Last_Code);
Largest_Run : constant Positive := 64 + Largest_Single;
Run_Count : constant Natural
:= (Input_Length + Largest_Run - 1) / Largest_Run;
Last_Run_Size : constant Positive
:= Input_Length - (Run_Count - 1) * Largest_Run;
Last_Run_Header_Size : constant Ada.Streams.Stream_Element_Count
:= (if Last_Run_Size > Largest_Single then 2 else 1);
begin
return Ada.Streams.Stream_Element_Count (Run_Count)
* (Tools.Image_Length (Largest_Run) + 2)
+ Tools.Image_Length (Last_Run_Size) + Last_Run_Header_Size;
end;
else
declare
Largest_Prefix : constant Natural
:= (case Input_Length mod 3 is
when 1 => 15 * 3 + 1,
when 2 => ((62 - Natural (Last_Code)) * 4 - 1) * 3 + 2,
when others => 0);
Prefix_Header_Size : constant Ada.Streams.Stream_Element_Count
:= (if Largest_Prefix > 0 then 1 else 0);
Largest_Run : constant Positive := 64 * 3;
Prefix_Size : constant Natural
:= Natural'Min (Largest_Prefix, Input_Length);
Run_Count : constant Natural
:= (Input_Length - Prefix_Size + Largest_Run - 1) / Largest_Run;
begin
if Run_Count > 0 then
return Prefix_Header_Size + Tools.Image_Length (Prefix_Size)
+ Ada.Streams.Stream_Element_Count (Run_Count - 1)
* (Tools.Image_Length (Largest_Run) + 2)
+ Tools.Image_Length (Input_Length - Prefix_Size
- (Run_Count - 1) * Largest_Run)
+ 2;
else
return Prefix_Header_Size + Tools.Image_Length (Prefix_Size);
end if;
end;
end if;
end Verbatim_Size;
procedure Write_Code
(Output : in out Ada.Streams.Stream_Element_Array;
Offset : in out Ada.Streams.Stream_Element_Offset;
Code : in Natools.Smaz_Implementations.Base_64_Tools.Base_64_Digit) is
begin
Output (Offset) := Tools.Image (Code);
Offset := Offset + 1;
end Write_Code;
procedure Write_Verbatim
(Output : in out Ada.Streams.Stream_Element_Array;
Offset : in out Ada.Streams.Stream_Element_Offset;
Input : in String;
Last_Code : in Natools.Smaz_Implementations.Base_64_Tools.Base_64_Digit;
Variable_Length_Verbatim : in Boolean)
is
Index : Positive := Input'First;
begin
if Variable_Length_Verbatim then
declare
Largest_Single : constant Positive := 62 - Natural (Last_Code);
Largest_Run : constant Positive := 64 + Largest_Single;
Length, Last : Natural;
begin
while Index in Input'Range loop
Length := Positive'Min (Largest_Run, Input'Last + 1 - Index);
if Length > Largest_Single then
Write_Code (Output, Offset, 63);
Write_Code
(Output, Offset,
Tools.Base_64_Digit (Length - Largest_Single - 1));
else
Write_Code
(Output, Offset,
Tools.Base_64_Digit (63 - Length));
end if;
if Length mod 3 = 1 then
Tools.Encode_Single (Input (Index), 0, Output, Offset);
Index := Index + 1;
Length := Length - 1;
elsif Length mod 3 = 2 then
Tools.Encode_Double
(Input (Index .. Index + 1), 0, Output, Offset);
Index := Index + 2;
Length := Length - 2;
end if;
if Length > 0 then
Last := Index + Length - 1;
Tools.Encode (Input (Index .. Last), Output, Offset);
Index := Last + 1;
end if;
end loop;
end;
else
if Input'Length mod 3 = 1 then
declare
Extra_Blocks : constant Natural
:= Natural'Min (15, Input'Length / 3);
begin
Output (Offset) := Tools.Image (62);
Offset := Offset + 1;
Tools.Encode_Single
(Input (Index), Tools.Single_Byte_Padding (Extra_Blocks),
Output, Offset);
Index := Index + 1;
if Extra_Blocks > 0 then
Tools.Encode
(Input (Index .. Index + Extra_Blocks * 3 - 1),
Output, Offset);
Index := Index + Extra_Blocks * 3;
end if;
end;
elsif Input'Length mod 3 = 2 then
declare
Extra_Blocks : constant Natural := Natural'Min
(Input'Length / 3,
(62 - Natural (Last_Code)) * 4 - 1);
begin
Output (Offset)
:= Tools.Image (61 - Tools.Base_64_Digit (Extra_Blocks / 4));
Offset := Offset + 1;
Tools.Encode_Double
(Input (Index .. Index + 1),
Tools.Double_Byte_Padding (Extra_Blocks mod 4),
Output, Offset);
Index := Index + 2;
if Extra_Blocks > 0 then
Tools.Encode
(Input (Index .. Index + Extra_Blocks * 3 - 1),
Output, Offset);
Index := Index + Extra_Blocks * 3;
end if;
end;
end if;
pragma Assert ((Input'Last + 1 - Index) mod 3 = 0);
while Index <= Input'Last loop
declare
Block_Count : constant Natural
:= Natural'Min (64, (Input'Last + 1 - Index) / 3);
begin
Output (Offset) := Tools.Image (63);
Output (Offset + 1)
:= Tools.Image (Tools.Base_64_Digit (Block_Count - 1));
Offset := Offset + 2;
Tools.Encode
(Input (Index .. Index + Block_Count * 3 - 1),
Output, Offset);
Index := Index + Block_Count * 3;
end;
end loop;
end if;
end Write_Verbatim;
end Natools.Smaz_Implementations.Base_64;
|
check end-of-input in Read_Code
|
smaz_implementations-base_64: check end-of-input in Read_Code
|
Ada
|
isc
|
faelys/natools
|
6c00c51f33622b4a718f3e981f6cce3895caa955
|
src/asf-filters.ads
|
src/asf-filters.ads
|
-----------------------------------------------------------------------
-- asf.filters -- ASF Filters
-- 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.Requests;
with ASF.Responses;
with ASF.Servlets;
-- The <b>ASF.Filters</b> package defines the servlet filter
-- interface described in Java Servlet Specification, JSR 315, 6. Filtering.
--
package ASF.Filters is
-- ------------------------------
-- Filter interface
-- ------------------------------
-- The <b>Filter</b> interface defines one mandatory procedure through
-- which the request/response pair are passed.
--
-- The <b>Filter</b> instance must be registered in the <b>Servlet_Registry</b>
-- by using the <b>Add_Filter</b> procedure. The same filter instance is used
-- to process multiple requests possibly at the same time.
type Filter is limited interface;
type Filter_Access is access all Filter'Class;
type Filter_List is array (Natural range <>) of Filter_Access;
type Filter_List_Access is access all Filter_List;
-- The Do_Filter method of the Filter is called by the container each time
-- a request/response pair is passed through the chain due to a client request
-- for a resource at the end of the chain. The Filter_Chain passed in to this
-- method allows the Filter to pass on the request and response to the next
-- entity in the chain.
--
-- A typical implementation of this method would follow the following pattern:
-- 1. Examine the request
-- 2. Optionally wrap the request object with a custom implementation to
-- filter content or headers for input filtering
-- 3. Optionally wrap the response object with a custom implementation to
-- filter content or headers for output filtering
-- 4. Either invoke the next entity in the chain using the FilterChain
-- object (chain.Do_Filter()),
-- or, not pass on the request/response pair to the next entity in the
-- filter chain to block the request processing
-- 5. Directly set headers on the response after invocation of the next
-- entity in the filter chain.
procedure Do_Filter (F : in Filter;
Request : in out Requests.Request'Class;
Response : in out Responses.Response'Class;
Chain : in out ASF.Servlets.Filter_Chain) is abstract;
-- Called by the servlet container to indicate to a filter that the filter
-- instance is being placed into service.
procedure Initialize (Server : in out Filter;
Config : in ASF.Servlets.Filter_Config) is null;
end ASF.Filters;
|
-----------------------------------------------------------------------
-- asf-filters -- ASF Filters
-- Copyright (C) 2010, 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 Servlet.Filters;
package ASF.Filters renames Servlet.Filters;
|
Package ASF.Filters moved to Servlet.filters
|
Package ASF.Filters moved to Servlet.filters
|
Ada
|
apache-2.0
|
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
|
e661d4079994fdad61952aed113801c904932d1f
|
regtests/util-serialize-io-csv-tests.ads
|
regtests/util-serialize-io-csv-tests.ads
|
-----------------------------------------------------------------------
-- serialize-io-jcsv-tests -- Unit tests for CSV parser
-- Copyright (C) 2011 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Tests;
package Util.Serialize.IO.CSV.Tests is
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite);
type Test is new Util.Tests.Test with null record;
procedure Test_Parser (T : in out Test);
end Util.Serialize.IO.CSV.Tests;
|
-----------------------------------------------------------------------
-- serialize-io-jcsv-tests -- Unit tests for CSV parser
-- 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 Util.Tests;
package Util.Serialize.IO.CSV.Tests is
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite);
type Test is new Util.Tests.Test with null record;
procedure Test_Parser (T : in out Test);
-- Test the CSV output stream generation.
procedure Test_Output (T : in out Test);
end Util.Serialize.IO.CSV.Tests;
|
Declare the Test_Output procedure
|
Declare the Test_Output procedure
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
ec04a4defbae7c410dbb18d28e5efa2dcaf9b091
|
matp/src/mat-consoles.ads
|
matp/src/mat-consoles.ads
|
-----------------------------------------------------------------------
-- mat-consoles - Console interface
-- Copyright (C) 2014, 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with MAT.Types;
package MAT.Consoles is
type Field_Type is (F_ADDR,
F_SIZE,
F_TOTAL_SIZE,
F_MIN_SIZE,
F_MAX_SIZE,
F_MIN_ADDR,
F_MAX_ADDR,
F_THREAD,
F_COUNT,
F_LEVEL,
F_FILE_NAME,
F_FUNCTION_NAME,
F_LINE_NUMBER,
F_START_TIME,
F_END_TIME,
F_MALLOC_COUNT,
F_REALLOC_COUNT,
F_FREE_COUNT,
F_EVENT_RANGE,
F_ID,
F_OLD_ADDR,
F_GROW_SIZE,
F_TIME,
F_DURATION,
F_EVENT,
F_MODE,
F_FRAME_ID,
F_RANGE_ADDR,
F_FRAME_ADDR);
type Notice_Type is (N_HELP,
N_INFO,
N_EVENT_ID,
N_PID_INFO,
N_DURATION,
N_PATH_INFO);
type Justify_Type is (J_LEFT, -- Justify left |item |
J_RIGHT, -- Justify right | item|
J_CENTER, -- Justify center | item |
J_RIGHT_NO_FILL -- Justify right |item|
);
type Console_Type is abstract tagged limited private;
type Console_Access is access all Console_Type'Class;
-- Report an error message.
procedure Error (Console : in out Console_Type;
Message : in String) is abstract;
-- Report a notice message.
procedure Notice (Console : in out Console_Type;
Kind : in Notice_Type;
Message : in String) is abstract;
-- Print the field value for the given field.
procedure Print_Field (Console : in out Console_Type;
Field : in Field_Type;
Value : in String;
Justify : in Justify_Type := J_LEFT) is abstract;
-- Print the title for the given field.
procedure Print_Title (Console : in out Console_Type;
Field : in Field_Type;
Title : in String) is abstract;
-- Start a new title in a report.
procedure Start_Title (Console : in out Console_Type) is abstract;
-- Finish a new title in a report.
procedure End_Title (Console : in out Console_Type) is abstract;
-- Start a new row in a report.
procedure Start_Row (Console : in out Console_Type) is abstract;
-- Finish a new row in a report.
procedure End_Row (Console : in out Console_Type) is abstract;
-- Print the title for the given field and setup the associated field size.
procedure Print_Title (Console : in out Console_Type;
Field : in Field_Type;
Title : in String;
Length : in Positive);
-- Format the address and print it for the given field.
procedure Print_Field (Console : in out Console_Type;
Field : in Field_Type;
Addr : in MAT.Types.Target_Addr);
-- Format the address range and print it for the given field.
procedure Print_Field (Console : in out Console_Type;
Field : in Field_Type;
From : in MAT.Types.Target_Addr;
To : in MAT.Types.Target_Addr);
-- Format the size and print it for the given field.
procedure Print_Size (Console : in out Console_Type;
Field : in Field_Type;
Size : in MAT.Types.Target_Size);
-- Format the thread information and print it for the given field.
procedure Print_Thread (Console : in out Console_Type;
Field : in Field_Type;
Thread : in MAT.Types.Target_Thread_Ref);
-- Format the time tick as a duration and print it for the given field.
procedure Print_Duration (Console : in out Console_Type;
Field : in Field_Type;
Duration : in MAT.Types.Target_Tick_Ref);
-- Format the integer and print it for the given field.
procedure Print_Field (Console : in out Console_Type;
Field : in Field_Type;
Value : in Integer;
Justify : in Justify_Type := J_LEFT);
-- Format the integer and print it for the given field.
procedure Print_Field (Console : in out Console_Type;
Field : in Field_Type;
Value : in Ada.Strings.Unbounded.Unbounded_String;
Justify : in Justify_Type := J_LEFT);
private
type Field_Size_Array is array (Field_Type) of Natural;
type Field_List_Array is array (1 .. Field_Type'Pos (Field_Type'Last)) of Field_Type;
type Console_Type is abstract tagged limited record
Sizes : Field_Size_Array := (others => 1);
Cols : Field_Size_Array := (others => 1);
Fields : Field_List_Array;
Field_Count : Natural := 0;
end record;
end MAT.Consoles;
|
-----------------------------------------------------------------------
-- mat-consoles - Console interface
-- Copyright (C) 2014, 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with MAT.Types;
package MAT.Consoles is
type Field_Type is (F_ADDR,
F_SIZE,
F_TOTAL_SIZE,
F_MIN_SIZE,
F_MAX_SIZE,
F_MIN_ADDR,
F_MAX_ADDR,
F_THREAD,
F_COUNT,
F_LEVEL,
F_FILE_NAME,
F_FUNCTION_NAME,
F_LINE_NUMBER,
F_START_TIME,
F_END_TIME,
F_MALLOC_COUNT,
F_REALLOC_COUNT,
F_FREE_COUNT,
F_EVENT_RANGE,
F_ID,
F_OLD_ADDR,
F_GROW_SIZE,
F_TIME,
F_DURATION,
F_EVENT,
F_NEXT,
F_PREVIOUS,
F_MODE,
F_FRAME_ID,
F_RANGE_ADDR,
F_FRAME_ADDR);
type Notice_Type is (N_HELP,
N_INFO,
N_EVENT_ID,
N_PID_INFO,
N_DURATION,
N_PATH_INFO);
type Justify_Type is (J_LEFT, -- Justify left |item |
J_RIGHT, -- Justify right | item|
J_CENTER, -- Justify center | item |
J_RIGHT_NO_FILL -- Justify right |item|
);
type Console_Type is abstract tagged limited private;
type Console_Access is access all Console_Type'Class;
-- Report an error message.
procedure Error (Console : in out Console_Type;
Message : in String) is abstract;
-- Report a notice message.
procedure Notice (Console : in out Console_Type;
Kind : in Notice_Type;
Message : in String) is abstract;
-- Print the field value for the given field.
procedure Print_Field (Console : in out Console_Type;
Field : in Field_Type;
Value : in String;
Justify : in Justify_Type := J_LEFT) is abstract;
-- Print the title for the given field.
procedure Print_Title (Console : in out Console_Type;
Field : in Field_Type;
Title : in String) is abstract;
-- Start a new title in a report.
procedure Start_Title (Console : in out Console_Type) is abstract;
-- Finish a new title in a report.
procedure End_Title (Console : in out Console_Type) is abstract;
-- Start a new row in a report.
procedure Start_Row (Console : in out Console_Type) is abstract;
-- Finish a new row in a report.
procedure End_Row (Console : in out Console_Type) is abstract;
-- Print the title for the given field and setup the associated field size.
procedure Print_Title (Console : in out Console_Type;
Field : in Field_Type;
Title : in String;
Length : in Positive);
-- Format the address and print it for the given field.
procedure Print_Field (Console : in out Console_Type;
Field : in Field_Type;
Addr : in MAT.Types.Target_Addr);
-- Format the address range and print it for the given field.
procedure Print_Field (Console : in out Console_Type;
Field : in Field_Type;
From : in MAT.Types.Target_Addr;
To : in MAT.Types.Target_Addr);
-- Format the size and print it for the given field.
procedure Print_Size (Console : in out Console_Type;
Field : in Field_Type;
Size : in MAT.Types.Target_Size);
-- Format the thread information and print it for the given field.
procedure Print_Thread (Console : in out Console_Type;
Field : in Field_Type;
Thread : in MAT.Types.Target_Thread_Ref);
-- Format the time tick as a duration and print it for the given field.
procedure Print_Duration (Console : in out Console_Type;
Field : in Field_Type;
Duration : in MAT.Types.Target_Tick_Ref);
-- Format the integer and print it for the given field.
procedure Print_Field (Console : in out Console_Type;
Field : in Field_Type;
Value : in Integer;
Justify : in Justify_Type := J_LEFT);
-- Format the integer and print it for the given field.
procedure Print_Field (Console : in out Console_Type;
Field : in Field_Type;
Value : in Ada.Strings.Unbounded.Unbounded_String;
Justify : in Justify_Type := J_LEFT);
private
type Field_Size_Array is array (Field_Type) of Natural;
type Field_List_Array is array (1 .. Field_Type'Pos (Field_Type'Last)) of Field_Type;
type Console_Type is abstract tagged limited record
Sizes : Field_Size_Array := (others => 1);
Cols : Field_Size_Array := (others => 1);
Fields : Field_List_Array;
Field_Count : Natural := 0;
end record;
end MAT.Consoles;
|
Declare F_NEXT and F_PREVIOUS
|
Declare F_NEXT and F_PREVIOUS
|
Ada
|
apache-2.0
|
stcarrez/mat,stcarrez/mat,stcarrez/mat
|
f694696185ee566fef48a5fb2d0d14c144340669
|
samples/mapping.adb
|
samples/mapping.adb
|
-----------------------------------------------------------------------
-- mapping -- Example of serialization mappings
-- 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.Serialize.Contexts;
with Util.Beans.Objects;
package body Mapping is
use Util.Beans.Objects;
-- ------------------------------
-- Set the name/value pair on the current object.
-- ------------------------------
procedure Set_Member (P : in out Person;
Field : in Person_Fields;
Value : in Util.Beans.Objects.Object) is
begin
case Field is
when FIELD_FIRST_NAME =>
P.First_Name := To_Unbounded_String (Value);
when FIELD_LAST_NAME =>
P.Last_Name := To_Unbounded_String (Value);
when FIELD_AGE =>
P.Age := To_Integer (Value);
end case;
end Set_Member;
-- ------------------------------
-- Set the name/value pair on the current object.
-- ------------------------------
function Get_Person_Member (From : in Person;
Field : in Person_Fields) return Util.Beans.Objects.Object is
begin
case Field is
when FIELD_FIRST_NAME =>
return Util.Beans.Objects.To_Object (From.First_Name);
when FIELD_LAST_NAME =>
return Util.Beans.Objects.To_Object (From.Last_Name);
when FIELD_AGE =>
return Util.Beans.Objects.To_Object (From.Age);
end case;
end Get_Person_Member;
type Address_Fields is (FIELD_CITY, FIELD_STREET, FIELD_COUNTRY, FIELD_ZIP);
type Address_Access is access all Address;
-- ------------------------------
-- Set the name/value pair on the current object.
-- ------------------------------
procedure Set_Member (Addr : in out Address;
Field : in Address_Fields;
Value : in Util.Beans.Objects.Object) is
begin
case Field is
when FIELD_CITY =>
Addr.City := To_Unbounded_String (Value);
when FIELD_STREET =>
Addr.Street := To_Unbounded_String (Value);
when FIELD_COUNTRY =>
Addr.Country := To_Unbounded_String (Value);
when FIELD_ZIP =>
Addr.Zip := To_Integer (Value);
end case;
end Set_Member;
function Get_Member (Addr : in Address;
Field : in Address_Fields) return Util.Beans.Objects.Object is
begin
case Field is
when FIELD_CITY =>
return Util.Beans.Objects.To_Object (Addr.City);
when FIELD_STREET =>
return Util.Beans.Objects.To_Object (Addr.Street);
when FIELD_COUNTRY =>
return Util.Beans.Objects.To_Object (Addr.Country);
when FIELD_ZIP =>
return Util.Beans.Objects.To_Object (Addr.Zip);
end case;
end Get_Member;
package Address_Mapper is
new Util.Serialize.Mappers.Record_Mapper (Element_Type => Address,
Element_Type_Access => Address_Access,
Fields => Address_Fields,
Set_Member => Set_Member);
-- Mapping for the Address record.
Address_Mapping : aliased Address_Mapper.Mapper;
-- Mapping for the Person record.
Person_Mapping : aliased Person_Mapper.Mapper;
-- Mapping for a list of Person records (stored as a Vector).
Person_Vector_Mapping : aliased Person_Vector_Mapper.Mapper;
-- ------------------------------
-- Get the address mapper which describes how to load an Address.
-- ------------------------------
function Get_Address_Mapper return Util.Serialize.Mappers.Mapper_Access is
begin
return Address_Mapping'Access;
end Get_Address_Mapper;
-- ------------------------------
-- Get the person mapper which describes how to load a Person.
-- ------------------------------
function Get_Person_Mapper return Person_Mapper.Mapper_Access is
begin
return Person_Mapping'Access;
end Get_Person_Mapper;
-- ------------------------------
-- Get the person vector mapper which describes how to load a list of Person.
-- ------------------------------
function Get_Person_Vector_Mapper return Person_Vector_Mapper.Mapper_Access is
begin
return Person_Vector_Mapping'Access;
end Get_Person_Vector_Mapper;
-- ------------------------------
-- Helper to give access to the <b>Address</b> member of a <b>Person</b>.
-- ------------------------------
procedure Person_Address (Ctx : in out Util.Serialize.Contexts.Context'Class;
Process : not null access procedure (Item : in out Address)) is
procedure Process_Person (P : in out Person) is
begin
Process (P.Addr);
end Process_Person;
begin
Person_Mapper.Execute_Object (Ctx, Process_Person'Access);
end Person_Address;
-- ------------------------------
-- Helper to give access to the <b>Address</b> member of a <b>Person</b>.
-- ------------------------------
-- procedure Proxy_Person_Address (Element : in out Person;
-- Process : not null access procedure (Item : in out Address)) is
-- begin
-- Process (Element.Addr);
-- end Proxy_Person_Address;
begin
-- XML: JSON:
-- ---- -----
-- <city>Paris</city> "city" : "Paris"
-- <street>Champs de Mars</street> "street" : "Champs de Mars"
-- <country>France</country> "country" : "France"
-- <zip>75</zip> "zip" : 75
Address_Mapping.Bind (Person_Address'Access);
Address_Mapping.Bind (Get_Member'Access);
Address_Mapping.Add_Default_Mapping;
-- XML:
-- ----
-- <xxx id='23'>
-- <address>
-- <city>...</city>
-- <street number='44'>..</street>
-- <country>..</country>
-- <zip>..</zip>
-- </address>
-- <name>John</name>
-- <last_name>Harry</last_name>
-- <age>23</age>
-- <info><facebook><id>...</id></facebook></info>
-- </xxx>
-- Person_Mapper.Add_Mapping ("@id");
Person_Mapping.Bind (Get_Person_Member'Access);
Person_Mapping.Add_Mapping ("address", Address_Mapping'Access);
Person_Mapping.Add_Mapping ("name", FIELD_FIRST_NAME);
Person_Mapping.Add_Default_Mapping;
-- Person_Mapper.Add_Mapping ("info/*");
-- Person_Mapper.Add_Mapping ("address/street/@number");
Person_Vector_Mapping.Set_Mapping ("person", Person_Mapping);
end Mapping;
|
-----------------------------------------------------------------------
-- mapping -- Example of serialization mappings
-- 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.Serialize.Contexts;
with Util.Beans.Objects;
package body Mapping is
use Util.Beans.Objects;
-- ------------------------------
-- Set the name/value pair on the current object.
-- ------------------------------
procedure Set_Member (P : in out Person;
Field : in Person_Fields;
Value : in Util.Beans.Objects.Object) is
begin
case Field is
when FIELD_FIRST_NAME =>
P.First_Name := To_Unbounded_String (Value);
when FIELD_LAST_NAME =>
P.Last_Name := To_Unbounded_String (Value);
when FIELD_AGE =>
P.Age := To_Integer (Value);
end case;
end Set_Member;
-- ------------------------------
-- Set the name/value pair on the current object.
-- ------------------------------
function Get_Person_Member (From : in Person;
Field : in Person_Fields) return Util.Beans.Objects.Object is
begin
case Field is
when FIELD_FIRST_NAME =>
return Util.Beans.Objects.To_Object (From.First_Name);
when FIELD_LAST_NAME =>
return Util.Beans.Objects.To_Object (From.Last_Name);
when FIELD_AGE =>
return Util.Beans.Objects.To_Object (From.Age);
end case;
end Get_Person_Member;
type Address_Fields is (FIELD_CITY, FIELD_STREET, FIELD_COUNTRY, FIELD_ZIP);
type Address_Access is access all Address;
-- ------------------------------
-- Set the name/value pair on the current object.
-- ------------------------------
procedure Set_Member (Addr : in out Address;
Field : in Address_Fields;
Value : in Util.Beans.Objects.Object) is
begin
case Field is
when FIELD_CITY =>
Addr.City := To_Unbounded_String (Value);
when FIELD_STREET =>
Addr.Street := To_Unbounded_String (Value);
when FIELD_COUNTRY =>
Addr.Country := To_Unbounded_String (Value);
when FIELD_ZIP =>
Addr.Zip := To_Integer (Value);
end case;
end Set_Member;
function Get_Member (Addr : in Address;
Field : in Address_Fields) return Util.Beans.Objects.Object is
begin
case Field is
when FIELD_CITY =>
return Util.Beans.Objects.To_Object (Addr.City);
when FIELD_STREET =>
return Util.Beans.Objects.To_Object (Addr.Street);
when FIELD_COUNTRY =>
return Util.Beans.Objects.To_Object (Addr.Country);
when FIELD_ZIP =>
return Util.Beans.Objects.To_Object (Addr.Zip);
end case;
end Get_Member;
package Address_Mapper is
new Util.Serialize.Mappers.Record_Mapper (Element_Type => Address,
Element_Type_Access => Address_Access,
Fields => Address_Fields,
Set_Member => Set_Member);
-- Mapping for the Address record.
Address_Mapping : aliased Address_Mapper.Mapper;
-- Mapping for the Person record.
Person_Mapping : aliased Person_Mapper.Mapper;
-- Mapping for a list of Person records (stored as a Vector).
Person_Vector_Mapping : aliased Person_Vector_Mapper.Mapper;
-- ------------------------------
-- Get the address mapper which describes how to load an Address.
-- ------------------------------
function Get_Address_Mapper return Util.Serialize.Mappers.Mapper_Access is
begin
return Address_Mapping'Access;
end Get_Address_Mapper;
-- ------------------------------
-- Get the person mapper which describes how to load a Person.
-- ------------------------------
function Get_Person_Mapper return Person_Mapper.Mapper_Access is
begin
return Person_Mapping'Access;
end Get_Person_Mapper;
-- ------------------------------
-- Get the person vector mapper which describes how to load a list of Person.
-- ------------------------------
function Get_Person_Vector_Mapper return Person_Vector_Mapper.Mapper_Access is
begin
return Person_Vector_Mapping'Access;
end Get_Person_Vector_Mapper;
-- ------------------------------
-- Helper to give access to the <b>Address</b> member of a <b>Person</b>.
-- ------------------------------
procedure Proxy_Info (Attr : in Util.Serialize.Mappers.Mapping'Class;
Element : in out Address;
Value : in Util.Beans.Objects.Object) is
begin
-- Info_Mapper.Set_Member (Attr, Element.Info, Value);
null;
end Proxy_Info;
procedure Proxy_Address (Attr : in Util.Serialize.Mappers.Mapping'Class;
Element : in out Person;
Value : in Util.Beans.Objects.Object) is
begin
Address_Mapper.Set_Member (Attr, Element.Addr, Value);
end Proxy_Address;
-- ------------------------------
-- Helper to give access to the <b>Address</b> member of a <b>Person</b>.
-- ------------------------------
-- procedure Proxy_Person_Address (Element : in out Person;
-- Process : not null access procedure (Item : in out Address)) is
-- begin
-- Process (Element.Addr);
-- end Proxy_Person_Address;
begin
-- XML: JSON:
-- ---- -----
-- <city>Paris</city> "city" : "Paris"
-- <street>Champs de Mars</street> "street" : "Champs de Mars"
-- <country>France</country> "country" : "France"
-- <zip>75</zip> "zip" : 75
Address_Mapping.Bind (Get_Member'Access);
-- Address_Mapping.Add_Mapping ("info", Info_Mapping, Proxy_Info'Access);
Address_Mapping.Add_Default_Mapping;
-- XML:
-- ----
-- <xxx id='23'>
-- <address>
-- <city>...</city>
-- <street number='44'>..</street>
-- <country>..</country>
-- <zip>..</zip>
-- </address>
-- <name>John</name>
-- <last_name>Harry</last_name>
-- <age>23</age>
-- <info><facebook><id>...</id></facebook></info>
-- </xxx>
-- Person_Mapper.Add_Mapping ("@id");
Person_Mapping.Bind (Get_Person_Member'Access);
Person_Mapping.Add_Mapping ("address", Address_Mapping'Access, Proxy_Address'Access);
Person_Mapping.Add_Mapping ("name", FIELD_FIRST_NAME);
Person_Mapping.Add_Default_Mapping;
-- Person_Mapper.Add_Mapping ("info/*");
-- Person_Mapper.Add_Mapping ("address/street/@number");
Person_Vector_Mapping.Set_Mapping ("person", Person_Mapping);
end Mapping;
|
Update samples with new mapper
|
Update samples with new mapper
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
41fe560a9bdf0c72be9f413124338a3e89f549a8
|
awa/plugins/awa-workspaces/src/awa-workspaces-beans.adb
|
awa/plugins/awa-workspaces/src/awa-workspaces-beans.adb
|
-----------------------------------------------------------------------
-- awa-workspaces-beans -- Beans for module workspaces
-- Copyright (C) 2011, 2012, 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with ASF.Events.Faces.Actions;
with ADO.Utils;
with ADO.Sessions.Entities;
with ADO.Sessions;
with ADO.Queries;
with ADO.Datasets;
with AWA.Services.Contexts;
with AWA.Workspaces.Models;
with AWA.Events.Action_Method;
with AWA.Services.Contexts;
package body AWA.Workspaces.Beans is
package ASC renames AWA.Services.Contexts;
overriding
procedure Load (Bean : in out Invitation_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
begin
null;
end Load;
overriding
procedure Accept_Invitation (Bean : in out Invitation_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
begin
null;
end Accept_Invitation;
overriding
procedure Send (Bean : in out Invitation_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
begin
null;
end Send;
-- ------------------------------
-- Example of action method.
-- ------------------------------
procedure Action (Bean : in out Workspaces_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
begin
null;
end Action;
-- ------------------------------
-- Event action called to create the workspace when the given event is posted.
-- ------------------------------
procedure Create (Bean : in out Workspaces_Bean;
Event : in AWA.Events.Module_Event'Class) is
pragma Unreferenced (Bean, Event);
WS : AWA.Workspaces.Models.Workspace_Ref;
Ctx : constant AWA.Services.Contexts.Service_Context_Access := AWA.Services.Contexts.Current;
DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx);
begin
Ctx.Start;
AWA.Workspaces.Modules.Get_Workspace (Session => DB,
Context => Ctx,
Workspace => WS);
Ctx.Commit;
end Create;
package Action_Binding is
new ASF.Events.Faces.Actions.Action_Method.Bind (Bean => Workspaces_Bean,
Method => Action,
Name => "action");
package Create_Binding is
new AWA.Events.Action_Method.Bind (Name => "create",
Bean => Workspaces_Bean,
Method => Create);
Workspaces_Bean_Binding : aliased constant Util.Beans.Methods.Method_Binding_Array
:= (Action_Binding.Proxy'Access, Create_Binding.Proxy'Access);
-- ------------------------------
-- Get the value identified by the name.
-- ------------------------------
overriding
function Get_Value (From : in Workspaces_Bean;
Name : in String) return Util.Beans.Objects.Object is
begin
if Name = "count" then
return Util.Beans.Objects.To_Object (From.Count);
else
return Util.Beans.Objects.Null_Object;
end if;
end Get_Value;
-- ------------------------------
-- Set the value identified by the name.
-- ------------------------------
overriding
procedure Set_Value (From : in out Workspaces_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object) is
begin
if Name = "count" then
From.Count := Util.Beans.Objects.To_Integer (Value);
end if;
end Set_Value;
-- ------------------------------
-- This bean provides some methods that can be used in a Method_Expression
-- ------------------------------
overriding
function Get_Method_Bindings (From : in Workspaces_Bean)
return Util.Beans.Methods.Method_Binding_Array_Access is
pragma Unreferenced (From);
begin
return Workspaces_Bean_Binding'Access;
end Get_Method_Bindings;
-- ------------------------------
-- Create the Workspaces_Bean bean instance.
-- ------------------------------
function Create_Workspaces_Bean (Module : in AWA.Workspaces.Modules.Workspace_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access is
Object : constant Workspaces_Bean_Access := new Workspaces_Bean;
begin
Object.Module := Module;
return Object.all'Access;
end Create_Workspaces_Bean;
-- ------------------------------
-- Load the list of members.
-- ------------------------------
overriding
procedure Load (Into : in out Member_List_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
Ctx : constant ASC.Service_Context_Access := ASC.Current;
User : constant ADO.Identifier := Ctx.Get_User_Identifier;
Session : ADO.Sessions.Session := Into.Module.Get_Session;
Query : ADO.Queries.Context;
Count_Query : ADO.Queries.Context;
First : constant Natural := (Into.Page - 1) * Into.Page_Size;
begin
Query.Set_Query (AWA.Workspaces.Models.Query_Workspace_Member_List);
Count_Query.Set_Count_Query (AWA.Workspaces.Models.Query_Workspace_Member_List);
-- ADO.Sessions.Entities.Bind_Param (Params => Query,
-- Name => "page_table",
-- Table => AWA.Wikis.Models.WIKI_PAGE_TABLE,
-- Session => Session);
Query.Bind_Param (Name => "user_id", Value => User);
Count_Query.Bind_Param (Name => "user_id", Value => User);
AWA.Workspaces.Models.List (Into.Members, Session, Query);
Into.Count := ADO.Datasets.Get_Count (Session, Count_Query);
end Load;
end AWA.Workspaces.Beans;
|
-----------------------------------------------------------------------
-- awa-workspaces-beans -- Beans for module workspaces
-- Copyright (C) 2011, 2012, 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with ASF.Events.Faces.Actions;
with ADO.Utils;
with ADO.Sessions.Entities;
with ADO.Sessions;
with ADO.Queries;
with ADO.Datasets;
with AWA.Services.Contexts;
with AWA.Workspaces.Models;
with AWA.Events.Action_Method;
with AWA.Services.Contexts;
package body AWA.Workspaces.Beans is
package ASC renames AWA.Services.Contexts;
overriding
procedure Load (Bean : in out Invitation_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
begin
null;
end Load;
overriding
procedure Accept_Invitation (Bean : in out Invitation_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
begin
null;
end Accept_Invitation;
overriding
procedure Send (Bean : in out Invitation_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
begin
null;
end Send;
-- ------------------------------
-- Example of action method.
-- ------------------------------
procedure Action (Bean : in out Workspaces_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
begin
null;
end Action;
-- ------------------------------
-- Event action called to create the workspace when the given event is posted.
-- ------------------------------
procedure Create (Bean : in out Workspaces_Bean;
Event : in AWA.Events.Module_Event'Class) is
pragma Unreferenced (Bean, Event);
WS : AWA.Workspaces.Models.Workspace_Ref;
Ctx : constant AWA.Services.Contexts.Service_Context_Access := AWA.Services.Contexts.Current;
DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx);
begin
Ctx.Start;
AWA.Workspaces.Modules.Get_Workspace (Session => DB,
Context => Ctx,
Workspace => WS);
Ctx.Commit;
end Create;
package Action_Binding is
new ASF.Events.Faces.Actions.Action_Method.Bind (Bean => Workspaces_Bean,
Method => Action,
Name => "action");
package Create_Binding is
new AWA.Events.Action_Method.Bind (Name => "create",
Bean => Workspaces_Bean,
Method => Create);
Workspaces_Bean_Binding : aliased constant Util.Beans.Methods.Method_Binding_Array
:= (Action_Binding.Proxy'Access, Create_Binding.Proxy'Access);
-- ------------------------------
-- Get the value identified by the name.
-- ------------------------------
overriding
function Get_Value (From : in Workspaces_Bean;
Name : in String) return Util.Beans.Objects.Object is
begin
if Name = "count" then
return Util.Beans.Objects.To_Object (From.Count);
else
return Util.Beans.Objects.Null_Object;
end if;
end Get_Value;
-- ------------------------------
-- Set the value identified by the name.
-- ------------------------------
overriding
procedure Set_Value (From : in out Workspaces_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object) is
begin
if Name = "count" then
From.Count := Util.Beans.Objects.To_Integer (Value);
end if;
end Set_Value;
-- ------------------------------
-- This bean provides some methods that can be used in a Method_Expression
-- ------------------------------
overriding
function Get_Method_Bindings (From : in Workspaces_Bean)
return Util.Beans.Methods.Method_Binding_Array_Access is
pragma Unreferenced (From);
begin
return Workspaces_Bean_Binding'Access;
end Get_Method_Bindings;
-- ------------------------------
-- Create the Workspaces_Bean bean instance.
-- ------------------------------
function Create_Workspaces_Bean (Module : in AWA.Workspaces.Modules.Workspace_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access is
Object : constant Workspaces_Bean_Access := new Workspaces_Bean;
begin
Object.Module := Module;
return Object.all'Access;
end Create_Workspaces_Bean;
-- ------------------------------
-- Load the list of members.
-- ------------------------------
overriding
procedure Load (Into : in out Member_List_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
Ctx : constant ASC.Service_Context_Access := ASC.Current;
User : constant ADO.Identifier := Ctx.Get_User_Identifier;
Session : ADO.Sessions.Session := Into.Module.Get_Session;
Query : ADO.Queries.Context;
Count_Query : ADO.Queries.Context;
First : constant Natural := (Into.Page - 1) * Into.Page_Size;
begin
Query.Set_Query (AWA.Workspaces.Models.Query_Workspace_Member_List);
Count_Query.Set_Count_Query (AWA.Workspaces.Models.Query_Workspace_Member_List);
-- ADO.Sessions.Entities.Bind_Param (Params => Query,
-- Name => "page_table",
-- Table => AWA.Wikis.Models.WIKI_PAGE_TABLE,
-- Session => Session);
Query.Bind_Param (Name => "user_id", Value => User);
Count_Query.Bind_Param (Name => "user_id", Value => User);
AWA.Workspaces.Models.List (Into.Members, Session, Query);
Into.Count := ADO.Datasets.Get_Count (Session, Count_Query);
end Load;
-- ------------------------------
-- Create the Member_List_Bean bean instance.
-- ------------------------------
function Create_Member_List_Bean (Module : in AWA.Workspaces.Modules.Workspace_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access is
Object : constant Member_List_Bean_Access := new Member_List_Bean;
begin
Object.Module := Module;
Object.Members_Bean := Object.Members'Access;
Object.Page_Size := 20;
Object.Page := 1;
Object.Count := 0;
return Object.all'Access;
end Create_Member_List_Bean;
end AWA.Workspaces.Beans;
|
Implement the Create_Member_List_Bean function
|
Implement the Create_Member_List_Bean function
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
05fa720326bde387f06600248de7352910c594bb
|
src/asm-x86/util-concurrent-counters.ads
|
src/asm-x86/util-concurrent-counters.ads
|
-----------------------------------------------------------------------
-- Util.Concurrent -- Concurrent Counters
-- Copyright (C) 2009, 2010 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
-- The <b>Counters</b> package defines the <b>Counter</b> type which provides
-- atomic increment and decrement operations. It is intended to be used to
-- implement reference counting in a multi-threaded environment.
--
-- type Ref is record
-- Cnt : Counter;
-- Data : ...;
-- end record;
--
-- Object : access Ref;
-- Is_Last : Boolean;
-- begin
-- Decrement (Object.Cnt, Is_Last); -- Multi-task safe operation
-- if Is_Last then
-- Free (Object);
-- end if;
--
-- Unlike the Ada portable implementation based on protected type, this implementation
-- does not require that <b>Counter</b> be a limited type.
private with Interfaces;
package Util.Concurrent.Counters is
pragma Preelaborate;
-- ------------------------------
-- Atomic Counter
-- ------------------------------
-- The atomic <b>Counter</b> implements a simple counter that can be
-- incremented or decremented atomically.
type Counter is private;
type Counter_Access is access all Counter;
-- Increment the counter atomically.
procedure Increment (C : in out Counter);
pragma Inline_Always (Increment);
-- Increment the counter atomically and return the value before increment.
procedure Increment (C : in out Counter;
Value : out Integer);
pragma Inline_Always (Increment);
-- Decrement the counter atomically.
procedure Decrement (C : in out Counter);
pragma Inline_Always (Decrement);
-- Decrement the counter atomically and return a status.
procedure Decrement (C : in out Counter;
Is_Zero : out Boolean);
pragma Inline_Always (Decrement);
-- Get the counter value
function Value (C : in Counter) return Integer;
pragma Inline_Always (Value);
ONE : constant Counter;
private
-- This implementation works without an Ada protected type:
-- o The size of the target object is 10 times smaller.
-- o Increment and Decrement operations are 5 times faster.
-- o It works by using special instructions
type Counter is record
Value : Interfaces.Unsigned_32 := 0;
end record;
ONE : constant Counter := Counter '(Value => 1);
end Util.Concurrent.Counters;
|
-----------------------------------------------------------------------
-- Util.Concurrent -- Concurrent Counters
-- Copyright (C) 2009, 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.
-----------------------------------------------------------------------
-- The <b>Counters</b> package defines the <b>Counter</b> type which provides
-- atomic increment and decrement operations. It is intended to be used to
-- implement reference counting in a multi-threaded environment.
--
-- type Ref is record
-- Cnt : Counter;
-- Data : ...;
-- end record;
--
-- Object : access Ref;
-- Is_Last : Boolean;
-- begin
-- Decrement (Object.Cnt, Is_Last); -- Multi-task safe operation
-- if Is_Last then
-- Free (Object);
-- end if;
--
-- Unlike the Ada portable implementation based on protected type, this implementation
-- does not require that <b>Counter</b> be a limited type.
private with Interfaces;
package Util.Concurrent.Counters is
pragma Preelaborate;
-- ------------------------------
-- Atomic Counter
-- ------------------------------
-- The atomic <b>Counter</b> implements a simple counter that can be
-- incremented or decremented atomically.
type Counter is private;
type Counter_Access is access all Counter;
-- Increment the counter atomically.
procedure Increment (C : in out Counter);
pragma Inline_Always (Increment);
-- Increment the counter atomically and return the value before increment.
procedure Increment (C : in out Counter;
Value : out Integer);
pragma Inline_Always (Increment);
-- Decrement the counter atomically.
procedure Decrement (C : in out Counter);
pragma Inline_Always (Decrement);
-- Decrement the counter atomically and return a status.
procedure Decrement (C : in out Counter;
Is_Zero : out Boolean);
pragma Inline_Always (Decrement);
-- Get the counter value
function Value (C : in Counter) return Integer;
pragma Inline_Always (Value);
ONE : constant Counter;
private
-- This implementation works without an Ada protected type:
-- o The size of the target object is 10 times smaller.
-- o Increment and Decrement operations are 5 times faster.
-- o It works by using special instructions
-- o The counter is Atomic to make sure the compiler will use atomic read/write instructions
-- and it prevents optimization (Atomic implies Volatile). The Atomic does not mean
-- that atomic instructions are used.
type Counter is record
Value : Interfaces.Unsigned_32 := 0;
pragma Atomic (Value);
end record;
ONE : constant Counter := Counter '(Value => 1);
end Util.Concurrent.Counters;
|
Declare the counter as Atomic to prevent compiler optimisation on the access of its value
|
Declare the counter as Atomic to prevent compiler optimisation on the access of its value
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
997ceb28f560041e8ca9dd3acf316088860bafbf
|
src/asf-views-facelets.ads
|
src/asf-views-facelets.ads
|
-----------------------------------------------------------------------
-- asf-views-facelets -- Facelets representation and management
-- Copyright (C) 2009, 2010, 2011, 2014, 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Calendar;
with Ada.Strings.Unbounded;
with Ada.Containers.Hashed_Maps;
with Ada.Strings.Unbounded.Hash;
with ASF.Views.Nodes;
with ASF.Contexts.Facelets;
with ASF.Factory;
with ASF.Components.Base;
with Ada.Finalization;
-- The <b>ASF.Views.Facelets</b> package contains the facelet factory
-- responsible for getting the facelet tree from a facelet name.
-- The facelets (or *.xhtml) files are loaded by the reader to form
-- a tag node tree which is cached by the factory. The facelet factory
-- is shared by multiple requests and threads.
package ASF.Views.Facelets is
type Facelet is private;
type Facelet_Access is access all Facelet;
-- Returns True if the facelet is null/empty.
function Is_Null (F : Facelet) return Boolean;
-- ------------------------------
-- Facelet factory
-- ------------------------------
-- The facelet factory allows to retrieve the node tree to build the
-- component tree. The node tree can be shared by several component trees.
-- The node tree is initialized from the <b>XHTML</b> view file. It is put
-- in a cache to avoid loading and parsing the file several times.
type Facelet_Factory is limited private;
-- Get the facelet identified by the given name. If the facelet is already
-- loaded, the cached value is returned. The facelet file is searched in
-- a set of directories configured in the facelet factory.
procedure Find_Facelet (Factory : in out Facelet_Factory;
Name : in String;
Context : in ASF.Contexts.Facelets.Facelet_Context'Class;
Result : out Facelet);
-- Create the component tree from the facelet view.
procedure Build_View (View : in Facelet;
Context : in out ASF.Contexts.Facelets.Facelet_Context'Class;
Root : in ASF.Components.Base.UIComponent_Access);
-- Initialize the facelet factory.
-- Set the search directories for facelet files.
-- Set the ignore white space configuration when reading XHTML files.
-- Set the ignore empty lines configuration when reading XHTML files.
-- Set the escape unknown tags configuration when reading XHTML files.
procedure Initialize (Factory : in out Facelet_Factory;
Components : access ASF.Factory.Component_Factory;
Paths : in String;
Ignore_White_Spaces : in Boolean;
Ignore_Empty_Lines : in Boolean;
Escape_Unknown_Tags : in Boolean);
-- Find the facelet file in one of the facelet directories.
-- Returns the path to be used for reading the facelet file.
function Find_Facelet_Path (Factory : in Facelet_Factory;
Name : in String) return String;
-- Clear the facelet cache
procedure Clear_Cache (Factory : in out Facelet_Factory);
private
use Ada.Strings.Unbounded;
type Facelet is record
Root : ASF.Views.Nodes.Tag_Node_Access;
File : ASF.Views.File_Info_Access;
Modify_Time : Ada.Calendar.Time;
end record;
-- Tag library map indexed on the library namespace.
package Facelet_Maps is new
Ada.Containers.Hashed_Maps (Key_Type => Unbounded_String,
Element_Type => Facelet,
Hash => Ada.Strings.Unbounded.Hash,
Equivalent_Keys => "=");
use Facelet_Maps;
protected type Facelet_Cache is
-- Find the facelet entry associated with the given name.
function Find (Name : in Unbounded_String) return Facelet;
-- Insert or replace the facelet entry associated with the given name.
procedure Insert (Name : in Unbounded_String;
Item : in Facelet);
-- Clear the cache.
procedure Clear;
private
Map : Facelet_Maps.Map;
end Facelet_Cache;
type Facelet_Factory is new Ada.Finalization.Limited_Controlled with record
Paths : Unbounded_String := To_Unbounded_String ("");
-- The facelet cache.
Map : Facelet_Cache;
-- The component factory
Factory : access ASF.Factory.Component_Factory;
-- Whether the unknown tags are escaped using XML escape rules.
Escape_Unknown_Tags : Boolean := True;
-- Whether white spaces can be ignored.
Ignore_White_Spaces : Boolean := True;
-- Whether empty lines should be ignored (when white spaces are kept).
Ignore_Empty_Lines : Boolean := True;
end record;
-- Free the storage held by the factory cache.
overriding
procedure Finalize (Factory : in out Facelet_Factory);
end ASF.Views.Facelets;
|
-----------------------------------------------------------------------
-- asf-views-facelets -- Facelets representation and management
-- Copyright (C) 2009, 2010, 2011, 2014, 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Calendar;
with Ada.Strings.Unbounded;
with Ada.Containers.Hashed_Maps;
with Ada.Strings.Unbounded.Hash;
with ASF.Views.Nodes;
with ASF.Contexts.Facelets;
with ASF.Factory;
with ASF.Components.Base;
with Ada.Finalization;
-- The <b>ASF.Views.Facelets</b> package contains the facelet factory
-- responsible for getting the facelet tree from a facelet name.
-- The facelets (or *.xhtml) files are loaded by the reader to form
-- a tag node tree which is cached by the factory. The facelet factory
-- is shared by multiple requests and threads.
package ASF.Views.Facelets is
type Facelet is private;
type Facelet_Access is access all Facelet;
-- Returns True if the facelet is null/empty.
function Is_Null (F : Facelet) return Boolean;
-- ------------------------------
-- Facelet factory
-- ------------------------------
-- The facelet factory allows to retrieve the node tree to build the
-- component tree. The node tree can be shared by several component trees.
-- The node tree is initialized from the <b>XHTML</b> view file. It is put
-- in a cache to avoid loading and parsing the file several times.
type Facelet_Factory is limited private;
-- Get the facelet identified by the given name. If the facelet is already
-- loaded, the cached value is returned. The facelet file is searched in
-- a set of directories configured in the facelet factory.
procedure Find_Facelet (Factory : in out Facelet_Factory;
Name : in String;
Context : in ASF.Contexts.Facelets.Facelet_Context'Class;
Result : out Facelet);
-- Create the component tree from the facelet view.
procedure Build_View (View : in Facelet;
Context : in out ASF.Contexts.Facelets.Facelet_Context'Class;
Root : in ASF.Components.Base.UIComponent_Access);
-- Initialize the facelet factory.
-- Set the search directories for facelet files.
-- Set the ignore white space configuration when reading XHTML files.
-- Set the ignore empty lines configuration when reading XHTML files.
-- Set the escape unknown tags configuration when reading XHTML files.
procedure Initialize (Factory : in out Facelet_Factory;
Components : access ASF.Factory.Component_Factory;
Paths : in String;
Ignore_White_Spaces : in Boolean;
Ignore_Empty_Lines : in Boolean;
Escape_Unknown_Tags : in Boolean);
-- Find the facelet file in one of the facelet directories.
-- Returns the path to be used for reading the facelet file.
function Find_Facelet_Path (Factory : in Facelet_Factory;
Name : in String) return String;
-- Clear the facelet cache
procedure Clear_Cache (Factory : in out Facelet_Factory);
private
use Ada.Strings.Unbounded;
type Facelet is record
Root : ASF.Views.Nodes.Tag_Node_Access;
File : ASF.Views.File_Info_Access;
Modify_Time : Ada.Calendar.Time;
end record;
Empty : constant Facelet := (others => <>);
-- Tag library map indexed on the library namespace.
package Facelet_Maps is new
Ada.Containers.Hashed_Maps (Key_Type => Unbounded_String,
Element_Type => Facelet,
Hash => Ada.Strings.Unbounded.Hash,
Equivalent_Keys => "=");
use Facelet_Maps;
protected type Facelet_Cache is
-- Find the facelet entry associated with the given name.
function Find (Name : in Unbounded_String) return Facelet;
-- Insert or replace the facelet entry associated with the given name.
procedure Insert (Name : in Unbounded_String;
Item : in Facelet);
-- Clear the cache.
procedure Clear;
private
Map : Facelet_Maps.Map;
end Facelet_Cache;
type Facelet_Factory is new Ada.Finalization.Limited_Controlled with record
Paths : Unbounded_String := To_Unbounded_String ("");
-- The facelet cache.
Map : Facelet_Cache;
-- The component factory
Factory : access ASF.Factory.Component_Factory;
-- Whether the unknown tags are escaped using XML escape rules.
Escape_Unknown_Tags : Boolean := True;
-- Whether white spaces can be ignored.
Ignore_White_Spaces : Boolean := True;
-- Whether empty lines should be ignored (when white spaces are kept).
Ignore_Empty_Lines : Boolean := True;
end record;
-- Free the storage held by the factory cache.
overriding
procedure Finalize (Factory : in out Facelet_Factory);
end ASF.Views.Facelets;
|
Declare the Empty constant to represent an empty facelet
|
Declare the Empty constant to represent an empty facelet
|
Ada
|
apache-2.0
|
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
|
e824079a5a99a01d00d98dfa812931e6231d69c4
|
awa/src/awa-events-queues-persistents.adb
|
awa/src/awa-events-queues-persistents.adb
|
-----------------------------------------------------------------------
-- awa-events-queues-persistents -- AWA Event Queues
-- 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.Calendar;
with Ada.Strings.Unbounded;
with Util.Log.Loggers;
with Util.Serialize.IO.XML;
with Util.Properties;
with Util.Streams.Texts;
with Util.Streams.Buffered;
with Util.Serialize.Tools;
with AWA.Services.Contexts;
with AWA.Users.Models;
with ADO;
with ADO.Queries;
with ADO.Sessions;
with ADO.SQL;
package body AWA.Events.Queues.Persistents is
use Util.Log;
Log : constant Loggers.Logger := Loggers.Create ("AWA.Events.Queues.Persistents");
-- ------------------------------
-- Get the queue name.
-- ------------------------------
overriding
function Get_Name (From : in Persistent_Queue) return String is
begin
return From.Name;
end Get_Name;
-- ------------------------------
-- Get the model queue reference object.
-- Returns a null object if the queue is not persistent.
-- ------------------------------
overriding
function Get_Queue (From : in Persistent_Queue) return AWA.Events.Models.Queue_Ref is
begin
return From.Queue;
end Get_Queue;
-- ------------------------------
-- Queue the event. The event is saved in the database with a relation to
-- the user, the user session, the event queue and the event type.
-- ------------------------------
overriding
procedure Enqueue (Into : in out Persistent_Queue;
Event : in AWA.Events.Module_Event'Class) is
use Ada.Strings.Unbounded;
use Util.Streams;
procedure Add_Property (Name, Value : in Util.Properties.Value);
Ctx : constant Services.Contexts.Service_Context_Access := AWA.Services.Contexts.Current;
DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx);
Msg : AWA.Events.Models.Message_Ref;
Has_Param : Boolean := False;
Output : Util.Serialize.IO.XML.Output_Stream;
procedure Add_Property (Name, Value : in Util.Properties.Value) is
begin
if not Has_Param then
Output.Initialize (Size => 10000);
Has_Param := True;
Output.Start_Entity (Name => "params");
end if;
Output.Start_Entity (Name => "param");
Output.Write_Attribute (Name => "name",
Value => Util.Beans.Objects.To_Object (Name));
Output.Write_String (Value => To_String (Value));
Output.End_Entity (Name => "param");
end Add_Property;
begin
Ctx.Start;
Msg.Set_Queue (Into.Queue);
Msg.Set_User (Ctx.Get_User);
Msg.Set_Session (Ctx.Get_User_Session);
Msg.Set_Create_Date (Event.Get_Time);
Msg.Set_Status (AWA.Events.Models.QUEUED);
-- Collect the event parameters in a string and format the result in XML.
-- If there is no parameter, avoid the overhead of allocating and formatting this.
Event.Props.Iterate (Process => Add_Property'Access);
if Has_Param then
Output.End_Entity (Name => "params");
Msg.Set_Parameters (Util.Streams.Texts.To_String (Buffered.Buffered_Stream (Output)));
end if;
-- Msg.Set_Message_Type
Msg.Save (DB);
Ctx.Commit;
Log.Info ("Event {0} created", ADO.Identifier'Image (Msg.Get_Id));
end Enqueue;
overriding
procedure Dequeue (From : in out Persistent_Queue;
Process : access procedure (Event : in Module_Event'Class)) is
Ctx : constant AWA.Services.Contexts.Service_Context_Access := AWA.Services.Contexts.Current;
DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx);
Messages : Models.Message_Vector;
Query : ADO.Queries.Context;
Task_Id : Integer := 0;
-- Prepare the message by indicating in the database it is going to be processed
-- by the given server and task.
procedure Prepare_Message (Msg : in out Models.Message_Ref) is
begin
Msg.Set_Status (Models.PROCESSING);
Msg.Set_Server_Id (From.Server_Id);
Msg.Set_Task_Id (Task_Id);
Msg.Set_Processing_Date (ADO.Nullable_Time '(Is_Null => False,
Value => Ada.Calendar.Clock));
Msg.Save (DB);
end Prepare_Message;
-- Dispatch the event.
procedure Dispatch_Message (Msg : in out Models.Message_Ref) is
User : constant AWA.Users.Models.User_Ref'Class := Msg.Get_User;
Session : constant AWA.Users.Models.Session_Ref'Class := Msg.Get_Session;
Event : Module_Event;
begin
Process (Event);
end Dispatch_Message;
-- Finish processing the message by marking it as being processed.
procedure Finish_Message (Msg : in out Models.Message_Ref) is
begin
Ctx.Start;
Msg.Set_Status (Models.PROCESSED);
Msg.Set_Finish_Date (ADO.Nullable_Time '(Is_Null => False,
Value => Ada.Calendar.Clock));
Msg.Save (DB);
Ctx.Commit;
end Finish_Message;
Count : Natural;
begin
Ctx.Start;
Query.Set_Query (Models.Query_Queue_Pending_Message);
Query.Bind_Param ("queue", From.Queue.Get_Id);
Query.Bind_Param ("max", From.Max_Batch);
Models.List (Messages, DB, Query);
Count := Natural (Messages.Length);
-- Prepare the event messages by marking them in the database.
-- This makes sure that no other server or task (if any), will process them.
if Count > 0 then
for I in 1 .. Count loop
Messages.Update_Element (Index => I,
Process => Prepare_Message'Access);
end loop;
end if;
Ctx.Commit;
if Count = 0 then
return;
end if;
-- Dispatch each event.
for I in 1 .. Count loop
Messages.Update_Element (Index => I,
Process => Dispatch_Message'Access);
end loop;
-- After having dispatched the events, mark them as dispatched in the queue.
Ctx.Start;
for I in 1 .. Count loop
Messages.Update_Element (Index => I,
Process => Finish_Message'Access);
end loop;
Ctx.Commit;
end Dequeue;
-- ------------------------------
-- Create the queue associated with the given name and configure it by using
-- the configuration properties.
-- ------------------------------
function Create_Queue (Name : in String;
Props : in EL.Beans.Param_Vectors.Vector;
Context : in EL.Contexts.ELContext'Class) return Queue_Access is
package AC renames AWA.Services.Contexts;
Ctx : constant AC.Service_Context_Access := AC.Current;
Session : ADO.Sessions.Master_Session := AC.Get_Master_Session (Ctx);
Queue : AWA.Events.Models.Queue_Ref;
Query : ADO.SQL.Query;
Found : Boolean;
begin
Session.Begin_Transaction;
-- Find the queue instance which matches the name.
Query.Set_Filter ("o.name = ?");
Query.Add_Param (Name);
Queue.Find (Session => Session,
Query => Query,
Found => Found);
-- But create the queue instance if it does not exist.
if not Found then
Queue.Set_Name (Name);
Queue.Save (Session);
end if;
Session.Commit;
declare
Result : constant Persistent_Queue_Access
:= new Persistent_Queue '(Name_Length => Name'Length,
Name => Name,
Queue => Queue,
others => <>);
begin
return Result.all'Access;
end;
end Create_Queue;
end AWA.Events.Queues.Persistents;
|
-----------------------------------------------------------------------
-- awa-events-queues-persistents -- AWA Event Queues
-- 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.Calendar;
with Ada.Strings.Unbounded;
with Util.Log.Loggers;
with Util.Serialize.IO.XML;
with Util.Properties;
with Util.Streams.Texts;
with Util.Streams.Buffered;
with Util.Serialize.Tools;
with AWA.Services.Contexts;
with AWA.Users.Models;
with ADO;
with ADO.Queries;
with ADO.Sessions;
with ADO.SQL;
package body AWA.Events.Queues.Persistents is
use Util.Log;
Log : constant Loggers.Logger := Loggers.Create ("AWA.Events.Queues.Persistents");
-- ------------------------------
-- Get the queue name.
-- ------------------------------
overriding
function Get_Name (From : in Persistent_Queue) return String is
begin
return From.Name;
end Get_Name;
-- ------------------------------
-- Get the model queue reference object.
-- Returns a null object if the queue is not persistent.
-- ------------------------------
overriding
function Get_Queue (From : in Persistent_Queue) return AWA.Events.Models.Queue_Ref is
begin
return From.Queue;
end Get_Queue;
-- ------------------------------
-- Queue the event. The event is saved in the database with a relation to
-- the user, the user session, the event queue and the event type.
-- ------------------------------
overriding
procedure Enqueue (Into : in out Persistent_Queue;
Event : in AWA.Events.Module_Event'Class) is
use Ada.Strings.Unbounded;
use Util.Streams;
procedure Add_Property (Name, Value : in Util.Properties.Value);
Ctx : constant Services.Contexts.Service_Context_Access := AWA.Services.Contexts.Current;
DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx);
Msg : AWA.Events.Models.Message_Ref;
Has_Param : Boolean := False;
Output : Util.Serialize.IO.XML.Output_Stream;
procedure Add_Property (Name, Value : in Util.Properties.Value) is
begin
if not Has_Param then
Output.Initialize (Size => 10000);
Has_Param := True;
Output.Start_Entity (Name => "params");
end if;
Output.Start_Entity (Name => "param");
Output.Write_Attribute (Name => "name",
Value => Util.Beans.Objects.To_Object (Name));
Output.Write_String (Value => To_String (Value));
Output.End_Entity (Name => "param");
end Add_Property;
begin
Ctx.Start;
Msg.Set_Queue (Into.Queue);
Msg.Set_User (Ctx.Get_User);
Msg.Set_Session (Ctx.Get_User_Session);
Msg.Set_Create_Date (Event.Get_Time);
Msg.Set_Status (AWA.Events.Models.QUEUED);
-- Collect the event parameters in a string and format the result in XML.
-- If there is no parameter, avoid the overhead of allocating and formatting this.
Event.Props.Iterate (Process => Add_Property'Access);
if Has_Param then
Output.End_Entity (Name => "params");
Msg.Set_Parameters (Util.Streams.Texts.To_String (Buffered.Buffered_Stream (Output)));
end if;
-- Msg.Set_Message_Type
Msg.Save (DB);
Ctx.Commit;
Log.Info ("Event {0} created", ADO.Identifier'Image (Msg.Get_Id));
end Enqueue;
overriding
procedure Dequeue (From : in out Persistent_Queue;
Process : access procedure (Event : in Module_Event'Class)) is
Ctx : constant AWA.Services.Contexts.Service_Context_Access := AWA.Services.Contexts.Current;
DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx);
Messages : Models.Message_Vector;
Query : ADO.Queries.Context;
Task_Id : Integer := 0;
-- Prepare the message by indicating in the database it is going to be processed
-- by the given server and task.
procedure Prepare_Message (Msg : in out Models.Message_Ref) is
begin
Msg.Set_Status (Models.PROCESSING);
Msg.Set_Server_Id (From.Server_Id);
Msg.Set_Task_Id (Task_Id);
Msg.Set_Processing_Date (ADO.Nullable_Time '(Is_Null => False,
Value => Ada.Calendar.Clock));
Msg.Save (DB);
end Prepare_Message;
-- Dispatch the event.
procedure Dispatch_Message (Msg : in out Models.Message_Ref) is
User : constant AWA.Users.Models.User_Ref'Class := Msg.Get_User;
Session : constant AWA.Users.Models.Session_Ref'Class := Msg.Get_Session;
Event : Module_Event;
begin
Process (Event);
end Dispatch_Message;
-- Finish processing the message by marking it as being processed.
procedure Finish_Message (Msg : in out Models.Message_Ref) is
begin
Ctx.Start;
Msg.Set_Status (Models.PROCESSED);
Msg.Set_Finish_Date (ADO.Nullable_Time '(Is_Null => False,
Value => Ada.Calendar.Clock));
Msg.Save (DB);
Ctx.Commit;
end Finish_Message;
Count : Natural;
begin
Ctx.Start;
Query.Set_Query (Models.Query_Queue_Pending_Message);
Query.Bind_Param ("queue", From.Queue.Get_Id);
Query.Bind_Param ("max", From.Max_Batch);
Models.List (Messages, DB, Query);
Count := Natural (Messages.Length);
-- Prepare the event messages by marking them in the database.
-- This makes sure that no other server or task (if any), will process them.
if Count > 0 then
for I in 1 .. Count loop
Messages.Update_Element (Index => I,
Process => Prepare_Message'Access);
end loop;
end if;
Ctx.Commit;
if Count = 0 then
return;
end if;
-- Dispatch each event.
for I in 1 .. Count loop
Messages.Update_Element (Index => I,
Process => Dispatch_Message'Access);
end loop;
-- After having dispatched the events, mark them as dispatched in the queue.
Ctx.Start;
for I in 1 .. Count loop
Messages.Update_Element (Index => I,
Process => Finish_Message'Access);
end loop;
Ctx.Commit;
end Dequeue;
-- ------------------------------
-- Create the queue associated with the given name and configure it by using
-- the configuration properties.
-- ------------------------------
function Create_Queue (Name : in String;
Props : in EL.Beans.Param_Vectors.Vector;
Context : in EL.Contexts.ELContext'Class) return Queue_Access is
package AC renames AWA.Services.Contexts;
Ctx : constant AC.Service_Context_Access := AC.Current;
Session : ADO.Sessions.Master_Session := AC.Get_Master_Session (Ctx);
Queue : AWA.Events.Models.Queue_Ref;
Query : ADO.SQL.Query;
Found : Boolean;
begin
Session.Begin_Transaction;
-- Find the queue instance which matches the name.
Query.Set_Filter ("o.name = ?");
Query.Add_Param (Name);
Queue.Find (Session => Session,
Query => Query,
Found => Found);
-- But create the queue instance if it does not exist.
if not Found then
Log.Info ("Creating database queue {0}", Name);
Queue.Set_Name (Name);
Queue.Save (Session);
else
Log.Info ("Using database queue {0}", Name);
end if;
Session.Commit;
declare
Result : constant Persistent_Queue_Access
:= new Persistent_Queue '(Name_Length => Name'Length,
Name => Name,
Queue => Queue,
others => <>);
begin
return Result.all'Access;
end;
end Create_Queue;
end AWA.Events.Queues.Persistents;
|
Add some log to report when an event queue is created in the database
|
Add some log to report when an event queue is created in the database
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
1f47e95c0904b01ddd52f68d7644823185d68cdb
|
src/util-stacks.ads
|
src/util-stacks.ads
|
-----------------------------------------------------------------------
-- util-stacks -- Simple stack
-- Copyright (C) 2010, 2011 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Finalization;
generic
type Element_Type is private;
type Element_Type_Access is access all Element_Type;
package Util.Stacks is
type Stack is limited private;
-- Get access to the current stack element.
function Current (Container : in Stack) return Element_Type_Access;
-- Push an element on top of the stack making the new element the current one.
procedure Push (Container : in out Stack);
-- Pop the top element.
procedure Pop (Container : in out Stack);
-- Clear the stack.
procedure Clear (Container : in out Stack);
private
type Element_Type_Array is array (Natural range <>) of aliased Element_Type;
type Element_Type_Array_Access is access all Element_Type_Array;
type Stack is new Ada.Finalization.Limited_Controlled with record
Current : Element_Type_Access := null;
Stack : Element_Type_Array_Access := null;
Pos : Natural := 0;
end record;
-- Release the stack
overriding
procedure Finalize (Obj : in out Stack);
end Util.Stacks;
|
-----------------------------------------------------------------------
-- util-stacks -- Simple stack
-- Copyright (C) 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.
-----------------------------------------------------------------------
with Ada.Finalization;
generic
type Element_Type is private;
type Element_Type_Access is access all Element_Type;
package Util.Stacks is
pragma Preelaborate;
type Stack is limited private;
-- Get access to the current stack element.
function Current (Container : in Stack) return Element_Type_Access;
-- Push an element on top of the stack making the new element the current one.
procedure Push (Container : in out Stack);
-- Pop the top element.
procedure Pop (Container : in out Stack);
-- Clear the stack.
procedure Clear (Container : in out Stack);
private
type Element_Type_Array is array (Natural range <>) of aliased Element_Type;
type Element_Type_Array_Access is access all Element_Type_Array;
type Stack is new Ada.Finalization.Limited_Controlled with record
Current : Element_Type_Access := null;
Stack : Element_Type_Array_Access := null;
Pos : Natural := 0;
end record;
-- Release the stack
overriding
procedure Finalize (Obj : in out Stack);
end Util.Stacks;
|
Make the package Preelaborate
|
Make the package Preelaborate
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
c5a9257cce800a071092bbdfc1e707b02c6dd0b0
|
mat/src/mat-targets.ads
|
mat/src/mat-targets.ads
|
-----------------------------------------------------------------------
-- mat-targets - Representation of target information
-- Copyright (C) 2014 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with MAT.Types;
with MAT.Memory.Targets;
with MAT.Symbols.Targets;
with MAT.Readers;
with MAT.Consoles;
package MAT.Targets is
type Target_Process_Type is tagged limited record
Pid : MAT.Types.Target_Process_Ref;
Memory : MAT.Memory.Targets.Target_Memory;
Console : MAT.Consoles.Console_Access;
end record;
type Target_Process_Type_Access is access all Target_Process_Type'Class;
type Target_Type is tagged limited record
Pid : MAT.Types.Target_Process_Ref;
Memory : MAT.Memory.Targets.Target_Memory;
Symbols : MAT.Symbols.Targets.Target_Symbols;
Console : MAT.Consoles.Console_Access;
end record;
type Target_Type_Access is access all Target_Type'Class;
-- Initialize the target object to manage the memory slots, the stack frames
-- and setup the reader to analyze the memory and other events.
procedure Initialize (Target : in out Target_Type;
Reader : in out MAT.Readers.Manager_Base'Class);
--
-- private
--
-- type Target_Type is tagged limited record
-- Memory : MAT.Memory.Targets.Target_Memory;
-- end record;
end MAT.Targets;
|
-----------------------------------------------------------------------
-- mat-targets - Representation of target information
-- Copyright (C) 2014 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Ada.Containers.Ordered_Maps;
with MAT.Types;
with MAT.Memory.Targets;
with MAT.Symbols.Targets;
with MAT.Readers;
with MAT.Consoles;
package MAT.Targets is
type Target_Process_Type is tagged limited record
Pid : MAT.Types.Target_Process_Ref;
Memory : MAT.Memory.Targets.Target_Memory;
Console : MAT.Consoles.Console_Access;
end record;
type Target_Process_Type_Access is access all Target_Process_Type'Class;
type Target_Type is tagged limited record
Pid : MAT.Types.Target_Process_Ref;
Memory : MAT.Memory.Targets.Target_Memory;
Symbols : MAT.Symbols.Targets.Target_Symbols;
Console : MAT.Consoles.Console_Access;
end record;
type Target_Type_Access is access all Target_Type'Class;
-- Initialize the target object to manage the memory slots, the stack frames
-- and setup the reader to analyze the memory and other events.
procedure Initialize (Target : in out Target_Type;
Reader : in out MAT.Readers.Manager_Base'Class);
private
-- Define a map of <tt>Target_Process_Type_Access</tt> keyed by the process Id.
-- This map allows to retrieve the information about a process.
use type MAT.Types.Target_Process_Ref;
package Process_Maps is
new Ada.Containers.Ordered_Maps (Key_Type => MAT.Types.Target_Process_Ref,
Element_Type => Target_Process_Type_Access);
end MAT.Targets;
|
Declare the Process_Maps package
|
Declare the Process_Maps package
|
Ada
|
apache-2.0
|
stcarrez/mat,stcarrez/mat,stcarrez/mat
|
84fc46f1618e71c6ee9b2556046888a607933d96
|
src/base/dates/util-dates-iso8601.adb
|
src/base/dates/util-dates-iso8601.adb
|
-----------------------------------------------------------------------
-- util-dates-iso8601 -- ISO8601 dates
-- 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.
-----------------------------------------------------------------------
package body Util.Dates.ISO8601 is
-- ------------------------------
-- Parses an ISO8601 date and return it as a calendar time.
-- Raises Constraint_Error if the date format is not recognized.
-- ------------------------------
function Value (Date : in String) return Ada.Calendar.Time is
use Ada.Calendar;
use Ada.Calendar.Formatting;
Result : Date_Record;
Pos : Natural;
pragma Unreferenced (Pos);
begin
if Date'Length < 4 then
raise Constraint_Error with "Invalid date";
end if;
Result.Hour := 0;
Result.Minute := 0;
Result.Second := 0;
Result.Sub_Second := 0.0;
Result.Time_Zone := 0;
Result.Year := Year_Number'Value (Date (Date'First .. Date'First + 3));
if Date'Length = 4 then
-- ISO8601 date: YYYY
Result.Month := 1;
Result.Month_Day := 1;
elsif Date'Length = 7 and Date (Date'First + 4) = '-' then
-- ISO8601 date: YYYY-MM
Result.Month := Month_Number'Value (Date (Date'First + 4 .. Date'Last));
Result.Month_Day := 1;
elsif Date'Length = 8 then
-- ISO8601 date: YYYYMMDD
Result.Month := Month_Number'Value (Date (Date'First + 4 .. Date'First + 5));
Result.Month_Day := Day_Number'Value (Date (Date'First + 6 .. Date'First + 7));
elsif Date'Length >= 9 and then Date (Date'First + 4) = '-'
and then Date (Date'First + 7) = '-'
then
-- ISO8601 date: YYYY-MM-DD
Result.Month := Month_Number'Value (Date (Date'First + 5 .. Date'First + 6));
Result.Month_Day := Day_Number'Value (Date (Date'First + 8 .. Date'First + 9));
-- ISO8601 date: YYYY-MM-DDTHH
if Date'Length > 12 then
if Date (Date'First + 10) /= 'T' then
raise Constraint_Error with "invalid date";
end if;
Result.Hour := Hour_Number'Value (Date (Date'First + 11 .. Date'First + 12));
Pos := Date'First + 13;
end if;
if Date'Length > 15 then
if Date (Date'First + 13) /= ':' then
raise Constraint_Error with "invalid date";
end if;
Result.Minute := Minute_Number'Value (Date (Date'First + 14 .. Date'First + 15));
Pos := Date'First + 16;
end if;
if Date'Length > 18 then
if Date (Date'First + 16) /= ':' then
raise Constraint_Error with "invalid date";
end if;
Result.Second := Second_Number'Value (Date (Date'First + 17 .. Date'First + 18));
Pos := Date'First + 19;
end if;
-- ISO8601 timezone: +hh:mm or -hh:mm
-- if Date'Length > Pos + 4 then
-- if Date (Pos) /= '+' and Date (Pos) /= '-' and Date (Pos + 2) /= ':' then
-- raise Constraint_Error with "invalid date";
-- end if;
-- end if;
else
raise Constraint_Error with "invalid date";
end if;
return Time_Of (Result);
end Value;
-- ------------------------------
-- Return the ISO8601 date.
-- ------------------------------
function Image (Date : in Ada.Calendar.Time) return String is
D : Date_Record;
begin
Split (D, Date);
return Image (D);
end Image;
function Image (Date : in Date_Record) return String is
To_Char : constant array (0 .. 9) of Character := "0123456789";
Result : String (1 .. 10) := "0000-00-00";
begin
Result (1) := To_Char (Date.Year / 1000);
Result (2) := To_Char (Date.Year / 100 mod 10);
Result (3) := To_Char (Date.Year / 10 mod 10);
Result (4) := To_Char (Date.Year mod 10);
Result (6) := To_Char (Date.Month / 10);
Result (7) := To_Char (Date.Month mod 10);
Result (9) := To_Char (Date.Month_Day / 10);
Result (10) := To_Char (Date.Month_Day mod 10);
return Result;
end Image;
function Image (Date : in Ada.Calendar.Time;
Precision : in Precision_Type) return String is
D : Date_Record;
begin
Split (D, Date);
return Image (D, Precision);
end Image;
function Image (Date : in Date_Record;
Precision : in Precision_Type) return String is
use type Ada.Calendar.Time_Zones.Time_Offset;
To_Char : constant array (0 .. 9) of Character := "0123456789";
Result : String (1 .. 29) := "0000-00-00T00:00:00.000-00:00";
N, Tz : Natural;
begin
Result (1) := To_Char (Date.Year / 1000);
Result (2) := To_Char (Date.Year / 100 mod 10);
Result (3) := To_Char (Date.Year / 10 mod 10);
Result (4) := To_Char (Date.Year mod 10);
if Precision = YEAR then
return Result (1 .. 4);
end if;
Result (6) := To_Char (Date.Month / 10);
Result (7) := To_Char (Date.Month mod 10);
if Precision = MONTH then
return Result (1 .. 7);
end if;
Result (9) := To_Char (Date.Month_Day / 10);
Result (10) := To_Char (Date.Month_Day mod 10);
if Precision = DAY then
return Result (1 .. 10);
end if;
Result (12) := To_Char (Date.Hour / 10);
Result (13) := To_Char (Date.Hour mod 10);
if Precision = HOUR then
return Result (1 .. 13);
end if;
Result (15) := To_Char (Date.Minute / 10);
Result (16) := To_Char (Date.Minute mod 10);
if Precision = MINUTE then
return Result (1 .. 16);
end if;
Result (18) := To_Char (Date.Second / 10);
Result (19) := To_Char (Date.Second mod 10);
if Precision = SECOND then
return Result (1 .. 19);
end if;
N := Natural (Date.Sub_Second * 1000.0);
Result (21) := To_Char (N / 100);
Result (22) := To_Char ((N mod 100) / 10);
Result (23) := To_Char (N mod 10);
if Date.Time_Zone < 0 then
Tz := Natural (-Date.Time_Zone);
else
Result (24) := '+';
Tz := Natural (Date.Time_Zone);
end if;
Result (25) := To_Char (Tz / 600);
Result (26) := To_Char ((Tz / 60) mod 10);
Tz := Tz mod 60;
Result (28) := To_Char (Tz / 10);
Result (29) := To_Char (Tz mod 10);
return Result;
end Image;
end Util.Dates.ISO8601;
|
-----------------------------------------------------------------------
-- util-dates-iso8601 -- ISO8601 dates
-- Copyright (C) 2011, 2013, 2015, 2016, 2017, 2018, 2020 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
package body Util.Dates.ISO8601 is
-- ------------------------------
-- Parses an ISO8601 date and return it as a calendar time.
-- Raises Constraint_Error if the date format is not recognized.
-- ------------------------------
function Value (Date : in String) return Ada.Calendar.Time is
use Ada.Calendar;
use Ada.Calendar.Formatting;
use Ada.Calendar.Time_Zones;
Result : Date_Record;
Pos : Natural;
begin
if Date'Length < 4 then
raise Constraint_Error with "Invalid date";
end if;
Result.Hour := 0;
Result.Minute := 0;
Result.Second := 0;
Result.Sub_Second := 0.0;
Result.Time_Zone := 0;
Result.Year := Year_Number'Value (Date (Date'First .. Date'First + 3));
if Date'Length = 4 then
-- ISO8601 date: YYYY
Result.Month := 1;
Result.Month_Day := 1;
elsif Date'Length = 7 and Date (Date'First + 4) = '-' then
-- ISO8601 date: YYYY-MM
Result.Month := Month_Number'Value (Date (Date'First + 5 .. Date'Last));
Result.Month_Day := 1;
elsif Date'Length = 8 then
-- ISO8601 date: YYYYMMDD
Result.Month := Month_Number'Value (Date (Date'First + 4 .. Date'First + 5));
Result.Month_Day := Day_Number'Value (Date (Date'First + 6 .. Date'First + 7));
elsif Date'Length >= 9 and then Date (Date'First + 4) = '-'
and then Date (Date'First + 7) = '-'
then
-- ISO8601 date: YYYY-MM-DD
Result.Month := Month_Number'Value (Date (Date'First + 5 .. Date'First + 6));
Result.Month_Day := Day_Number'Value (Date (Date'First + 8 .. Date'First + 9));
-- ISO8601 date: YYYY-MM-DDTHH
if Date'Length > 12 then
if Date (Date'First + 10) /= 'T' then
raise Constraint_Error with "invalid date";
end if;
Result.Hour := Hour_Number'Value (Date (Date'First + 11 .. Date'First + 12));
Pos := Date'First + 13;
end if;
if Date'Length > 15 then
if Date (Date'First + 13) /= ':' then
raise Constraint_Error with "invalid date";
end if;
Result.Minute := Minute_Number'Value (Date (Date'First + 14 .. Date'First + 15));
Pos := Date'First + 16;
end if;
if Date'Length >= 17 then
if Date (Date'First + 16) /= ':' or else Date'Length <= 18 then
raise Constraint_Error with "invalid date";
end if;
Result.Second := Second_Number'Value (Date (Date'First + 17 .. Date'First + 18));
Pos := Date'First + 19;
if Pos <= Date'Last then
if Date (Pos) = '.' or Date (Pos) = ',' then
if Date'Length < 22 then
raise Constraint_Error with "invalid date";
end if;
declare
Value : constant Natural := Natural'Value (Date (Pos + 1 .. Pos + 3));
begin
Result.Sub_Second := Second_Duration (Duration (Value) / 1000.0);
end;
Pos := Pos + 4;
end if;
if Pos <= Date'Last then
-- ISO8601 timezone: Z
-- ISO8601 timezone: +hh or -hh
-- ISO8601 timezone: +hhmm or -hhmm
-- ISO8601 timezone: +hh:mm or -hh:mm
if Date (Pos) = 'Z' then
if Pos /= Date'Last then
raise Constraint_Error with "invalid date";
end if;
elsif Date (Pos) /= '-' and Date (Pos) /= '+' then
raise Constraint_Error with "invalid date";
elsif Pos + 2 = Date'Last then
Result.Time_Zone := 60 * Time_Offset'Value (Date (Pos + 1 .. Date'Last));
elsif Pos + 4 = Date'Last then
Result.Time_Zone := 60 * Time_Offset'Value (Date (Pos + 1 .. Pos + 2))
+ Time_Offset'Value (Date (Pos + 3 .. Date'Last));
elsif Pos + 5 = Date'Last and then Date (Pos + 3) = ':' then
Result.Time_Zone := 60 * Time_Offset'Value (Date (Pos + 1 .. Pos + 2))
+ Time_Offset'Value (Date (Pos + 4 .. Date'Last));
else
raise Constraint_Error with "invalid date";
end if;
end if;
end if;
end if;
else
raise Constraint_Error with "invalid date";
end if;
return Time_Of (Result);
end Value;
-- ------------------------------
-- Return the ISO8601 date.
-- ------------------------------
function Image (Date : in Ada.Calendar.Time) return String is
D : Date_Record;
begin
Split (D, Date);
return Image (D);
end Image;
function Image (Date : in Date_Record) return String is
To_Char : constant array (0 .. 9) of Character := "0123456789";
Result : String (1 .. 10) := "0000-00-00";
begin
Result (1) := To_Char (Date.Year / 1000);
Result (2) := To_Char (Date.Year / 100 mod 10);
Result (3) := To_Char (Date.Year / 10 mod 10);
Result (4) := To_Char (Date.Year mod 10);
Result (6) := To_Char (Date.Month / 10);
Result (7) := To_Char (Date.Month mod 10);
Result (9) := To_Char (Date.Month_Day / 10);
Result (10) := To_Char (Date.Month_Day mod 10);
return Result;
end Image;
function Image (Date : in Ada.Calendar.Time;
Precision : in Precision_Type) return String is
D : Date_Record;
begin
Split (D, Date);
return Image (D, Precision);
end Image;
function Image (Date : in Date_Record;
Precision : in Precision_Type) return String is
use type Ada.Calendar.Time_Zones.Time_Offset;
To_Char : constant array (0 .. 9) of Character := "0123456789";
Result : String (1 .. 29) := "0000-00-00T00:00:00.000-00:00";
N, Tz : Natural;
begin
Result (1) := To_Char (Date.Year / 1000);
Result (2) := To_Char (Date.Year / 100 mod 10);
Result (3) := To_Char (Date.Year / 10 mod 10);
Result (4) := To_Char (Date.Year mod 10);
if Precision = YEAR then
return Result (1 .. 4);
end if;
Result (6) := To_Char (Date.Month / 10);
Result (7) := To_Char (Date.Month mod 10);
if Precision = MONTH then
return Result (1 .. 7);
end if;
Result (9) := To_Char (Date.Month_Day / 10);
Result (10) := To_Char (Date.Month_Day mod 10);
if Precision = DAY then
return Result (1 .. 10);
end if;
Result (12) := To_Char (Date.Hour / 10);
Result (13) := To_Char (Date.Hour mod 10);
if Precision = HOUR then
return Result (1 .. 13);
end if;
Result (15) := To_Char (Date.Minute / 10);
Result (16) := To_Char (Date.Minute mod 10);
if Precision = MINUTE then
return Result (1 .. 16);
end if;
Result (18) := To_Char (Date.Second / 10);
Result (19) := To_Char (Date.Second mod 10);
if Precision = SECOND then
return Result (1 .. 19);
end if;
N := Natural (Date.Sub_Second * 1000.0);
Result (21) := To_Char (N / 100);
Result (22) := To_Char ((N mod 100) / 10);
Result (23) := To_Char (N mod 10);
if Date.Time_Zone < 0 then
Tz := Natural (-Date.Time_Zone);
else
Result (24) := '+';
Tz := Natural (Date.Time_Zone);
end if;
Result (25) := To_Char (Tz / 600);
Result (26) := To_Char ((Tz / 60) mod 10);
Tz := Tz mod 60;
Result (28) := To_Char (Tz / 10);
Result (29) := To_Char (Tz mod 10);
return Result;
end Image;
end Util.Dates.ISO8601;
|
Add support to parse sub-seconds and timezone
|
Add support to parse sub-seconds and timezone
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
86cf7c78e22e32d9ead7647fb6e56236834ae0b0
|
src/http/aws/util-http-clients-web.adb
|
src/http/aws/util-http-clients-web.adb
|
-----------------------------------------------------------------------
-- util-http-clients-web -- HTTP Clients with AWS implementation
-- 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 AWS.Headers.Set;
with AWS.Client;
with AWS.Messages;
package body Util.Http.Clients.Web is
Manager : aliased AWS_Http_Manager;
-- ------------------------------
-- Register the Http manager.
-- ------------------------------
procedure Register is
begin
Default_Http_Manager := Manager'Access;
end Register;
function To_Status (Code : in AWS.Messages.Status_Code) return Natural;
function To_Status (Code : in AWS.Messages.Status_Code) return Natural is
use AWS.Messages;
begin
case Code is
when S100 =>
return 100;
when S101 =>
return 101;
when S102 =>
return 102;
when S200 =>
return 200;
when S201 =>
return 201;
when S203 =>
return 203;
when S204 =>
return 204;
when S205 =>
return 205;
when S206 =>
return 206;
when S207 =>
return 207;
when S300 =>
return 300;
when S301 =>
return 301;
when S302 =>
return 302;
when S303 =>
return 303;
when S304 =>
return 304;
when S305 =>
return 305;
when S307 =>
return 307;
when S400 =>
return 400;
when S401 =>
return 401;
when S402 =>
return 402;
when S403 =>
return 403;
when S404 =>
return 404;
when S405 =>
return 405;
when S406 =>
return 406;
when S407 =>
return 407;
when S408 =>
return 408;
when S409 =>
return 409;
when S410 =>
return 410;
when S411 =>
return 411;
when S412 =>
return 412;
when S413 =>
return 413;
when S414 =>
return 414;
when S415 =>
return 415;
when S416 =>
return 416;
when S417 =>
return 417;
when S422 =>
return 422;
when S423 =>
return 423;
when S424 =>
return 424;
when S500 =>
return 500;
when S501 =>
return 501;
when S502 =>
return 502;
when S503 =>
return 503;
when S504 =>
return 504;
when S505 =>
return 505;
when S507 =>
return 507;
when others =>
return 500;
end case;
end To_Status;
procedure Create (Manager : in AWS_Http_Manager;
Http : in out Client'Class) is
pragma Unreferenced (Manager);
begin
Http.Delegate := new AWS_Http_Request;
end Create;
procedure Do_Get (Manager : in AWS_Http_Manager;
Http : in Client'Class;
URI : in String;
Reply : out Response'Class) is
pragma Unreferenced (Manager);
Req : constant AWS_Http_Request_Access
:= AWS_Http_Request'Class (Http.Delegate.all)'Access;
Rep : constant AWS_Http_Response_Access := new AWS_Http_Response;
begin
Reply.Delegate := Rep.all'Access;
Rep.Data := AWS.Client.Get (URL => URI, Headers => Req.Headers);
end Do_Get;
procedure Do_Post (Manager : in AWS_Http_Manager;
Http : in Client'Class;
URI : in String;
Data : in String;
Reply : out Response'Class) is
pragma Unreferenced (Manager);
Req : constant AWS_Http_Request_Access
:= AWS_Http_Request'Class (Http.Delegate.all)'Access;
Rep : constant AWS_Http_Response_Access := new AWS_Http_Response;
begin
Reply.Delegate := Rep.all'Access;
Rep.Data := AWS.Client.Post (URL => URI, Data => Data, Headers => Req.Headers);
end Do_Post;
-- ------------------------------
-- Returns a boolean indicating whether the named request header has already
-- been set.
-- ------------------------------
function Contains_Header (Http : in AWS_Http_Request;
Name : in String) return Boolean is
begin
raise Program_Error with "Contains_Header is not implemented";
return False;
end Contains_Header;
-- Returns the value of the specified request header as a String. If the request
-- did not include a header of the specified name, this method returns null.
-- If there are multiple headers with the same name, this method returns the
-- first head in the request. The header name is case insensitive. You can use
-- this method with any response header.
overriding
function Get_Header (Request : in AWS_Http_Request;
Name : in String) return String is
begin
return "";
end Get_Header;
-- ------------------------------
-- Sets a request header with the given name and value. If the header had already
-- been set, the new value overwrites the previous one. The containsHeader
-- method can be used to test for the presence of a header before setting its value.
-- ------------------------------
overriding
procedure Set_Header (Http : in out AWS_Http_Request;
Name : in String;
Value : in String) is
begin
AWS.Headers.Set.Add (Http.Headers, Name, Value);
end Set_Header;
-- ------------------------------
-- Adds a request header with the given name and value.
-- This method allows request headers to have multiple values.
-- ------------------------------
overriding
procedure Add_Header (Http : in out AWS_Http_Request;
Name : in String;
Value : in String) is
begin
AWS.Headers.Set.Add (Http.Headers, Name, Value);
end Add_Header;
-- Iterate over the request headers and executes the <b>Process</b> procedure.
overriding
procedure Iterate_Headers (Request : in AWS_Http_Request;
Process : not null access
procedure (Name : in String;
Value : in String)) is
begin
null;
end Iterate_Headers;
-- ------------------------------
-- Returns a boolean indicating whether the named response header has already
-- been set.
-- ------------------------------
function Contains_Header (Reply : in AWS_Http_Response;
Name : in String) return Boolean is
begin
return AWS.Response.Header (Reply.Data, Name) /= "";
end Contains_Header;
-- ------------------------------
-- Returns the value of the specified response header as a String. If the response
-- did not include a header of the specified name, this method returns null.
-- If there are multiple headers with the same name, this method returns the
-- first head in the request. The header name is case insensitive. You can use
-- this method with any response header.
-- ------------------------------
function Get_Header (Reply : in AWS_Http_Response;
Name : in String) return String is
begin
return AWS.Response.Header (Reply.Data, Name);
end Get_Header;
-- Sets a message header with the given name and value. If the header had already
-- been set, the new value overwrites the previous one. The containsHeader
-- method can be used to test for the presence of a header before setting its value.
overriding
procedure Set_Header (Reply : in out AWS_Http_Response;
Name : in String;
Value : in String) is
begin
null;
end Set_Header;
-- Adds a request header with the given name and value.
-- This method allows request headers to have multiple values.
overriding
procedure Add_Header (Reply : in out AWS_Http_Response;
Name : in String;
Value : in String) is
begin
null;
end Add_Header;
-- Iterate over the response headers and executes the <b>Process</b> procedure.
overriding
procedure Iterate_Headers (Reply : in AWS_Http_Response;
Process : not null access
procedure (Name : in String;
Value : in String)) is
begin
null;
end Iterate_Headers;
-- ------------------------------
-- Get the response body as a string.
-- ------------------------------
function Get_Body (Reply : in AWS_Http_Response) return String is
begin
return AWS.Response.Message_Body (Reply.Data);
end Get_Body;
-- Get the response status code.
overriding
function Get_Status (Reply : in AWS_Http_Response) return Natural is
begin
return To_Status (AWS.Response.Status_Code (Reply.Data));
end Get_Status;
end Util.Http.Clients.Web;
|
-----------------------------------------------------------------------
-- util-http-clients-web -- HTTP Clients with AWS implementation
-- 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 AWS.Headers.Set;
with AWS.Client;
with AWS.Messages;
with Util.Log.Loggers;
package body Util.Http.Clients.Web is
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Util.Http.Clients.Web");
Manager : aliased AWS_Http_Manager;
-- ------------------------------
-- Register the Http manager.
-- ------------------------------
procedure Register is
begin
Default_Http_Manager := Manager'Access;
end Register;
function To_Status (Code : in AWS.Messages.Status_Code) return Natural;
function To_Status (Code : in AWS.Messages.Status_Code) return Natural is
use AWS.Messages;
begin
case Code is
when S100 =>
return 100;
when S101 =>
return 101;
when S102 =>
return 102;
when S200 =>
return 200;
when S201 =>
return 201;
when S203 =>
return 203;
when S204 =>
return 204;
when S205 =>
return 205;
when S206 =>
return 206;
when S207 =>
return 207;
when S300 =>
return 300;
when S301 =>
return 301;
when S302 =>
return 302;
when S303 =>
return 303;
when S304 =>
return 304;
when S305 =>
return 305;
when S307 =>
return 307;
when S400 =>
return 400;
when S401 =>
return 401;
when S402 =>
return 402;
when S403 =>
return 403;
when S404 =>
return 404;
when S405 =>
return 405;
when S406 =>
return 406;
when S407 =>
return 407;
when S408 =>
return 408;
when S409 =>
return 409;
when S410 =>
return 410;
when S411 =>
return 411;
when S412 =>
return 412;
when S413 =>
return 413;
when S414 =>
return 414;
when S415 =>
return 415;
when S416 =>
return 416;
when S417 =>
return 417;
when S422 =>
return 422;
when S423 =>
return 423;
when S424 =>
return 424;
when S500 =>
return 500;
when S501 =>
return 501;
when S502 =>
return 502;
when S503 =>
return 503;
when S504 =>
return 504;
when S505 =>
return 505;
when S507 =>
return 507;
when others =>
return 500;
end case;
end To_Status;
procedure Create (Manager : in AWS_Http_Manager;
Http : in out Client'Class) is
pragma Unreferenced (Manager);
begin
Http.Delegate := new AWS_Http_Request;
end Create;
procedure Do_Get (Manager : in AWS_Http_Manager;
Http : in Client'Class;
URI : in String;
Reply : out Response'Class) is
pragma Unreferenced (Manager);
Req : constant AWS_Http_Request_Access
:= AWS_Http_Request'Class (Http.Delegate.all)'Access;
Rep : constant AWS_Http_Response_Access := new AWS_Http_Response;
begin
Log.Info ("Get {0}", URI);
Reply.Delegate := Rep.all'Access;
Rep.Data := AWS.Client.Get (URL => URI, Headers => Req.Headers);
end Do_Get;
procedure Do_Post (Manager : in AWS_Http_Manager;
Http : in Client'Class;
URI : in String;
Data : in String;
Reply : out Response'Class) is
pragma Unreferenced (Manager);
Req : constant AWS_Http_Request_Access
:= AWS_Http_Request'Class (Http.Delegate.all)'Access;
Rep : constant AWS_Http_Response_Access := new AWS_Http_Response;
begin
Log.Info ("Post {0}", URI);
Reply.Delegate := Rep.all'Access;
Rep.Data := AWS.Client.Post (URL => URI, Data => Data, Headers => Req.Headers);
end Do_Post;
-- ------------------------------
-- Returns a boolean indicating whether the named request header has already
-- been set.
-- ------------------------------
function Contains_Header (Http : in AWS_Http_Request;
Name : in String) return Boolean is
begin
raise Program_Error with "Contains_Header is not implemented";
return False;
end Contains_Header;
-- Returns the value of the specified request header as a String. If the request
-- did not include a header of the specified name, this method returns null.
-- If there are multiple headers with the same name, this method returns the
-- first head in the request. The header name is case insensitive. You can use
-- this method with any response header.
overriding
function Get_Header (Request : in AWS_Http_Request;
Name : in String) return String is
begin
return "";
end Get_Header;
-- ------------------------------
-- Sets a request header with the given name and value. If the header had already
-- been set, the new value overwrites the previous one. The containsHeader
-- method can be used to test for the presence of a header before setting its value.
-- ------------------------------
overriding
procedure Set_Header (Http : in out AWS_Http_Request;
Name : in String;
Value : in String) is
begin
AWS.Headers.Set.Add (Http.Headers, Name, Value);
end Set_Header;
-- ------------------------------
-- Adds a request header with the given name and value.
-- This method allows request headers to have multiple values.
-- ------------------------------
overriding
procedure Add_Header (Http : in out AWS_Http_Request;
Name : in String;
Value : in String) is
begin
AWS.Headers.Set.Add (Http.Headers, Name, Value);
end Add_Header;
-- Iterate over the request headers and executes the <b>Process</b> procedure.
overriding
procedure Iterate_Headers (Request : in AWS_Http_Request;
Process : not null access
procedure (Name : in String;
Value : in String)) is
begin
null;
end Iterate_Headers;
-- ------------------------------
-- Returns a boolean indicating whether the named response header has already
-- been set.
-- ------------------------------
function Contains_Header (Reply : in AWS_Http_Response;
Name : in String) return Boolean is
begin
return AWS.Response.Header (Reply.Data, Name) /= "";
end Contains_Header;
-- ------------------------------
-- Returns the value of the specified response header as a String. If the response
-- did not include a header of the specified name, this method returns null.
-- If there are multiple headers with the same name, this method returns the
-- first head in the request. The header name is case insensitive. You can use
-- this method with any response header.
-- ------------------------------
function Get_Header (Reply : in AWS_Http_Response;
Name : in String) return String is
begin
return AWS.Response.Header (Reply.Data, Name);
end Get_Header;
-- Sets a message header with the given name and value. If the header had already
-- been set, the new value overwrites the previous one. The containsHeader
-- method can be used to test for the presence of a header before setting its value.
overriding
procedure Set_Header (Reply : in out AWS_Http_Response;
Name : in String;
Value : in String) is
begin
null;
end Set_Header;
-- Adds a request header with the given name and value.
-- This method allows request headers to have multiple values.
overriding
procedure Add_Header (Reply : in out AWS_Http_Response;
Name : in String;
Value : in String) is
begin
null;
end Add_Header;
-- Iterate over the response headers and executes the <b>Process</b> procedure.
overriding
procedure Iterate_Headers (Reply : in AWS_Http_Response;
Process : not null access
procedure (Name : in String;
Value : in String)) is
begin
null;
end Iterate_Headers;
-- ------------------------------
-- Get the response body as a string.
-- ------------------------------
function Get_Body (Reply : in AWS_Http_Response) return String is
begin
return AWS.Response.Message_Body (Reply.Data);
end Get_Body;
-- Get the response status code.
overriding
function Get_Status (Reply : in AWS_Http_Response) return Natural is
begin
return To_Status (AWS.Response.Status_Code (Reply.Data));
end Get_Status;
end Util.Http.Clients.Web;
|
Add some log to help solving web issues
|
Add some log to help solving web issues
|
Ada
|
apache-2.0
|
flottokarotto/ada-util,Letractively/ada-util,Letractively/ada-util,flottokarotto/ada-util
|
8640efa9c4edf5946301f4d89cf441858c427455
|
src/base/os-linux32/util-systems-types.ads
|
src/base/os-linux32/util-systems-types.ads
|
-- Generated by utildgen.c from system includes
with Interfaces.C;
package Util.Systems.Types is
subtype dev_t is Long_Long_Integer;
subtype ino_t is Interfaces.C.unsigned;
subtype off_t is Interfaces.C.int;
subtype blksize_t is Interfaces.C.int;
subtype blkcnt_t is Interfaces.C.int;
subtype uid_t is Interfaces.C.unsigned;
subtype gid_t is Interfaces.C.unsigned;
subtype nlink_t is Interfaces.C.unsigned;
subtype mode_t is Interfaces.C.unsigned;
S_IFMT : constant mode_t := 8#00170000#;
S_IFDIR : constant mode_t := 8#00040000#;
S_IFCHR : constant mode_t := 8#00020000#;
S_IFBLK : constant mode_t := 8#00060000#;
S_IFREG : constant mode_t := 8#00100000#;
S_IFIFO : constant mode_t := 8#00010000#;
S_IFLNK : constant mode_t := 8#00120000#;
S_IFSOCK : constant mode_t := 8#00140000#;
S_ISUID : constant mode_t := 8#00004000#;
S_ISGID : constant mode_t := 8#00002000#;
S_IREAD : constant mode_t := 8#00000400#;
S_IWRITE : constant mode_t := 8#00000200#;
S_IEXEC : constant mode_t := 8#00000100#;
type File_Type is new Interfaces.C.int;
subtype Time_Type is Interfaces.C.unsigned;
type Timespec is record
tv_sec : Time_Type;
tv_nsec : Interfaces.C.int;
end record;
pragma Convention (C_Pass_By_Copy, Timespec);
type Seek_Mode is (SEEK_SET, SEEK_CUR, SEEK_END);
for Seek_Mode use (SEEK_SET => 0, SEEK_CUR => 1, SEEK_END => 2);
STAT_NAME : constant String := "stat";
FSTAT_NAME : constant String := "fstat";
type Stat_Type is record
st_dev : dev_t;
pad1 : Interfaces.C.unsigned_short;
st_ino : ino_t;
st_mode : mode_t;
st_nlink : nlink_t;
st_uid : uid_t;
st_gid : gid_t;
st_rdev : dev_t;
pad2 : Interfaces.C.unsigned_short;
st_size : off_t;
st_blksize : blksize_t;
st_blocks : blkcnt_t;
pad3_1 : Interfaces.C.unsigned_long;
st_atim : Timespec;
st_mtim : Timespec;
st_ctim : Timespec;
pad3 : Interfaces.C.unsigned_long;
pad4 : Interfaces.C.unsigned_long;
end record;
pragma Convention (C_Pass_By_Copy, Stat_Type);
end Util.Systems.Types;
|
-- Generated by utildgen.c from system includes
with Interfaces.C;
package Util.Systems.Types is
subtype dev_t is Long_Long_Integer;
subtype ino_t is Interfaces.C.unsigned;
subtype off_t is Interfaces.C.int;
subtype blksize_t is Interfaces.C.int;
subtype blkcnt_t is Interfaces.C.int;
subtype uid_t is Interfaces.C.unsigned;
subtype gid_t is Interfaces.C.unsigned;
subtype nlink_t is Interfaces.C.unsigned;
subtype mode_t is Interfaces.C.unsigned;
S_IFMT : constant mode_t := 8#00170000#;
S_IFDIR : constant mode_t := 8#00040000#;
S_IFCHR : constant mode_t := 8#00020000#;
S_IFBLK : constant mode_t := 8#00060000#;
S_IFREG : constant mode_t := 8#00100000#;
S_IFIFO : constant mode_t := 8#00010000#;
S_IFLNK : constant mode_t := 8#00120000#;
S_IFSOCK : constant mode_t := 8#00140000#;
S_ISUID : constant mode_t := 8#00004000#;
S_ISGID : constant mode_t := 8#00002000#;
S_IREAD : constant mode_t := 8#00000400#;
S_IWRITE : constant mode_t := 8#00000200#;
S_IEXEC : constant mode_t := 8#00000100#;
type File_Type is new Interfaces.C.int;
subtype Time_Type is Interfaces.C.unsigned;
type Timespec is record
tv_sec : Time_Type;
tv_nsec : Interfaces.C.int;
end record;
pragma Convention (C_Pass_By_Copy, Timespec);
type Seek_Mode is (SEEK_SET, SEEK_CUR, SEEK_END);
for Seek_Mode use (SEEK_SET => 0, SEEK_CUR => 1, SEEK_END => 2);
STAT_NAME : constant String := "stat";
FSTAT_NAME : constant String := "fstat";
LSTAT_NAME : constant String := "lstat";
type Stat_Type is record
st_dev : dev_t;
pad1 : Interfaces.C.unsigned_short;
st_ino : ino_t;
st_mode : mode_t;
st_nlink : nlink_t;
st_uid : uid_t;
st_gid : gid_t;
st_rdev : dev_t;
pad2 : Interfaces.C.unsigned_short;
st_size : off_t;
st_blksize : blksize_t;
st_blocks : blkcnt_t;
pad3_1 : Interfaces.C.unsigned_long;
st_atim : Timespec;
st_mtim : Timespec;
st_ctim : Timespec;
pad3 : Interfaces.C.unsigned_long;
pad4 : Interfaces.C.unsigned_long;
end record;
pragma Convention (C_Pass_By_Copy, Stat_Type);
end Util.Systems.Types;
|
Declare the LSTAT_NAME
|
Declare the LSTAT_NAME
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
ca9be93cf0eb6a026144a246d5bb18c7ab6afceb
|
src/sys/streams/util-streams-texts.ads
|
src/sys/streams/util-streams-texts.ads
|
-----------------------------------------------------------------------
-- util-streams-texts -- Text stream utilities
-- Copyright (C) 2010, 2011, 2012, 2015, 2016, 2017, 2018, 2019 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Ada.Strings.Wide_Wide_Unbounded;
with Util.Streams.Buffered;
with Ada.Calendar;
with GNAT.Calendar.Time_IO;
-- == Texts ==
-- The `Util.Streams.Texts` package implements text oriented input and output streams.
-- The `Print_Stream` type extends the `Output_Buffer_Stream` to allow writing
-- text content.
--
-- The `Reader_Stream` type extends the `Input_Buffer_Stream` and allows to
-- read text content.
package Util.Streams.Texts is
-- -----------------------
-- Print stream
-- -----------------------
-- The <b>Print_Stream</b> is an output stream which provides helper methods
-- for writing text streams.
type Print_Stream is new Buffered.Output_Buffer_Stream with private;
type Print_Stream_Access is access all Print_Stream'Class;
procedure Initialize (Stream : in out Print_Stream;
To : access Output_Stream'Class);
-- Write a raw character on the stream.
procedure Write (Stream : in out Print_Stream;
Char : in Character);
-- Write a wide character on the stream doing some conversion if necessary.
-- The default implementation translates the wide character to a UTF-8 sequence.
procedure Write_Wide (Stream : in out Print_Stream;
Item : in Wide_Wide_Character);
-- Write a raw string on the stream.
procedure Write (Stream : in out Print_Stream;
Item : in String);
-- Write a raw string on the stream.
procedure Write (Stream : in out Print_Stream;
Item : in Ada.Strings.Unbounded.Unbounded_String);
-- Write a raw string on the stream.
procedure Write (Stream : in out Print_Stream;
Item : in Ada.Strings.Wide_Wide_Unbounded.Unbounded_Wide_Wide_String);
-- Write an integer on the stream.
procedure Write (Stream : in out Print_Stream;
Item : in Integer);
-- Write an integer on the stream.
procedure Write (Stream : in out Print_Stream;
Item : in Long_Long_Integer);
-- Write a date on the stream.
procedure Write (Stream : in out Print_Stream;
Item : in Ada.Calendar.Time;
Format : in GNAT.Calendar.Time_IO.Picture_String
:= GNAT.Calendar.Time_IO.ISO_Date);
-- Get the output stream content as a string.
function To_String (Stream : in Buffered.Output_Buffer_Stream'Class) return String;
-- Write a character on the stream.
procedure Write_Char (Stream : in out Print_Stream'Class;
Item : in Character);
-- Write a character on the stream.
procedure Write_Char (Stream : in out Print_Stream'Class;
Item : in Wide_Wide_Character);
-- -----------------------
-- Reader stream
-- -----------------------
-- The <b>Reader_Stream</b> is an input stream which provides helper methods
-- for reading text streams.
type Reader_Stream is new Buffered.Input_Buffer_Stream with private;
type Reader_Stream_Access is access all Reader_Stream'Class;
-- Initialize the reader to read the input from the input stream given in <b>From</b>.
procedure Initialize (Stream : in out Reader_Stream;
From : access Input_Stream'Class);
-- Read an input line from the input stream. The line is terminated by ASCII.LF.
-- When <b>Strip</b> is set, the line terminators (ASCII.CR, ASCII.LF) are removed.
procedure Read_Line (Stream : in out Reader_Stream;
Into : out Ada.Strings.Unbounded.Unbounded_String;
Strip : in Boolean := False);
private
type Print_Stream is new Buffered.Output_Buffer_Stream with null record;
type Reader_Stream is new Buffered.Input_Buffer_Stream with null record;
end Util.Streams.Texts;
|
-----------------------------------------------------------------------
-- util-streams-texts -- Text stream utilities
-- Copyright (C) 2010, 2011, 2012, 2015, 2016, 2017, 2018, 2019, 2020 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Ada.Strings.Wide_Wide_Unbounded;
with Util.Streams.Buffered;
with Ada.Calendar;
with GNAT.Calendar.Time_IO;
-- == Texts ==
-- The `Util.Streams.Texts` package implements text oriented input and output streams.
-- The `Print_Stream` type extends the `Output_Buffer_Stream` to allow writing
-- text content.
--
-- The `Reader_Stream` type extends the `Input_Buffer_Stream` and allows to
-- read text content.
package Util.Streams.Texts is
-- -----------------------
-- Print stream
-- -----------------------
-- The <b>Print_Stream</b> is an output stream which provides helper methods
-- for writing text streams.
type Print_Stream is new Buffered.Output_Buffer_Stream with private;
type Print_Stream_Access is access all Print_Stream'Class;
procedure Initialize (Stream : in out Print_Stream;
To : access Output_Stream'Class);
-- Write a raw string on the stream.
procedure Write (Stream : in out Print_Stream;
Item : in Ada.Strings.Unbounded.Unbounded_String);
-- Write a raw string on the stream.
procedure Write (Stream : in out Print_Stream;
Item : in Ada.Strings.Wide_Wide_Unbounded.Unbounded_Wide_Wide_String);
-- Write an integer on the stream.
procedure Write (Stream : in out Print_Stream;
Item : in Integer);
-- Write an integer on the stream.
procedure Write (Stream : in out Print_Stream;
Item : in Long_Long_Integer);
-- Write a date on the stream.
procedure Write (Stream : in out Print_Stream;
Item : in Ada.Calendar.Time;
Format : in GNAT.Calendar.Time_IO.Picture_String
:= GNAT.Calendar.Time_IO.ISO_Date);
-- Get the output stream content as a string.
function To_String (Stream : in Buffered.Output_Buffer_Stream'Class) return String;
-- Write a character on the stream.
procedure Write_Char (Stream : in out Print_Stream'Class;
Item : in Character);
-- Write a character on the stream.
procedure Write_Char (Stream : in out Print_Stream'Class;
Item : in Wide_Wide_Character);
-- -----------------------
-- Reader stream
-- -----------------------
-- The <b>Reader_Stream</b> is an input stream which provides helper methods
-- for reading text streams.
type Reader_Stream is new Buffered.Input_Buffer_Stream with private;
type Reader_Stream_Access is access all Reader_Stream'Class;
-- Initialize the reader to read the input from the input stream given in <b>From</b>.
procedure Initialize (Stream : in out Reader_Stream;
From : access Input_Stream'Class);
-- Read an input line from the input stream. The line is terminated by ASCII.LF.
-- When <b>Strip</b> is set, the line terminators (ASCII.CR, ASCII.LF) are removed.
procedure Read_Line (Stream : in out Reader_Stream;
Into : out Ada.Strings.Unbounded.Unbounded_String;
Strip : in Boolean := False);
private
type Print_Stream is new Buffered.Output_Buffer_Stream with null record;
type Reader_Stream is new Buffered.Input_Buffer_Stream with null record;
end Util.Streams.Texts;
|
Remove Write and Write_Wide procedures because they are now provided by a parent package
|
Remove Write and Write_Wide procedures because they are now provided by a parent package
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
67fcb86581e386e7b8f825e8ff0cb017eed37660
|
src/wiki-documents.ads
|
src/wiki-documents.ads
|
-----------------------------------------------------------------------
-- wiki-documents -- Wiki document
-- Copyright (C) 2011, 2015, 2016, 2018, 2019 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Wiki.Strings;
with Wiki.Attributes;
with Wiki.Nodes.Lists;
-- === Documents ===
-- The <tt>Document</tt> type is used to hold a Wiki document that was parsed by the parser
-- with one of the supported syntax. The <tt>Document</tt> holds two distinct parts:
--
-- * A main document body that represents the Wiki content that was parsed.
-- * A table of contents part that was built while Wiki sections are collected.
--
-- Most of the operations provided by the <tt>Wiki.Documents</tt> package are intended to
-- be used by the wiki parser and filters to build the document. The document is made of
-- nodes whose knowledge is required by the renderer.
--
-- A document instance must be declared before parsing a text:
--
-- Doc : Wiki.Documents.Document;
package Wiki.Documents is
pragma Preelaborate;
-- ------------------------------
-- A Wiki Document
-- ------------------------------
type Document is tagged private;
-- Append a simple node such as N_LINE_BREAK, N_HORIZONTAL_RULE or N_PARAGRAPH.
procedure Append (Into : in out Document;
Kind : in Wiki.Nodes.Simple_Node_Kind);
-- Append a HTML tag start node to the document.
procedure Push_Node (Into : in out Document;
Tag : in Html_Tag;
Attributes : in Wiki.Attributes.Attribute_List);
-- Pop the HTML tag.
procedure Pop_Node (From : in out Document;
Tag : in Html_Tag);
-- Returns True if the current node is the root document node.
function Is_Root_Node (Doc : in Document) return Boolean;
-- Append the text with the given format at end of the document.
procedure Append (Into : in out Document;
Text : in Wiki.Strings.WString;
Format : in Format_Map);
-- Append a section header at end of the document.
procedure Append (Into : in out Document;
Header : in Wiki.Strings.WString;
Level : in Positive);
-- Add a link.
procedure Add_Link (Into : in out Document;
Name : in Wiki.Strings.WString;
Attributes : in out Wiki.Attributes.Attribute_List);
-- Add an image.
procedure Add_Image (Into : in out Document;
Name : in Wiki.Strings.WString;
Attributes : in out Wiki.Attributes.Attribute_List);
-- Add a quote.
procedure Add_Quote (Into : in out Document;
Name : in Wiki.Strings.WString;
Attributes : in out Wiki.Attributes.Attribute_List);
-- Add a list item (<li>). Close the previous paragraph and list item if any.
-- The list item will be closed at the next list item, next paragraph or next header.
procedure Add_List_Item (Into : in out Document;
Level : in Positive;
Ordered : in Boolean);
-- Add a blockquote (<blockquote>). The level indicates the blockquote nested level.
-- The blockquote must be closed at the next header.
procedure Add_Blockquote (Into : in out Document;
Level : in Natural);
-- Add a text block that is pre-formatted.
procedure Add_Preformatted (Into : in out Document;
Text : in Wiki.Strings.WString;
Format : in Wiki.Strings.WString);
-- Iterate over the nodes of the list and call the <tt>Process</tt> procedure with
-- each node instance.
procedure Iterate (Doc : in Document;
Process : not null access procedure (Node : in Wiki.Nodes.Node_Type));
-- Returns True if the document is empty.
function Is_Empty (Doc : in Document) return Boolean;
-- Returns True if the document displays the table of contents by itself.
function Is_Using_TOC (Doc : in Document) return Boolean;
-- Returns True if the table of contents is visible and must be rendered.
function Is_Visible_TOC (Doc : in Document) return Boolean;
-- Hide the table of contents.
procedure Hide_TOC (Doc : in out Document);
-- Get the table of content node associated with the document.
procedure Get_TOC (Doc : in out Document;
TOC : out Wiki.Nodes.Lists.Node_List_Ref);
-- Get the table of content node associated with the document.
function Get_TOC (Doc : in Document) return Wiki.Nodes.Lists.Node_List_Ref;
private
-- Append a node to the document.
procedure Append (Into : in out Document;
Node : in Wiki.Nodes.Node_Type_Access);
type Document is tagged record
Nodes : Wiki.Nodes.Lists.Node_List_Ref;
TOC : Wiki.Nodes.Lists.Node_List_Ref;
Current : Wiki.Nodes.Node_Type_Access;
Using_TOC : Boolean := False;
Visible_TOC : Boolean := True;
end record;
end Wiki.Documents;
|
-----------------------------------------------------------------------
-- wiki-documents -- Wiki document
-- Copyright (C) 2011, 2015, 2016, 2018, 2019, 2020 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Wiki.Strings;
with Wiki.Attributes;
with Wiki.Nodes.Lists;
-- === Documents ===
-- The <tt>Document</tt> type is used to hold a Wiki document that was parsed by the parser
-- with one of the supported syntax. The <tt>Document</tt> holds two distinct parts:
--
-- * A main document body that represents the Wiki content that was parsed.
-- * A table of contents part that was built while Wiki sections are collected.
--
-- Most of the operations provided by the <tt>Wiki.Documents</tt> package are intended to
-- be used by the wiki parser and filters to build the document. The document is made of
-- nodes whose knowledge is required by the renderer.
--
-- A document instance must be declared before parsing a text:
--
-- Doc : Wiki.Documents.Document;
package Wiki.Documents is
pragma Preelaborate;
-- ------------------------------
-- A Wiki Document
-- ------------------------------
type Document is tagged private;
-- Append a simple node such as N_LINE_BREAK, N_HORIZONTAL_RULE or N_PARAGRAPH.
procedure Append (Into : in out Document;
Kind : in Wiki.Nodes.Simple_Node_Kind);
-- Append a HTML tag start node to the document.
procedure Push_Node (Into : in out Document;
Tag : in Html_Tag;
Attributes : in Wiki.Attributes.Attribute_List);
-- Pop the HTML tag.
procedure Pop_Node (From : in out Document;
Tag : in Html_Tag);
-- Returns True if the current node is the root document node.
function Is_Root_Node (Doc : in Document) return Boolean;
-- Append the text with the given format at end of the document.
procedure Append (Into : in out Document;
Text : in Wiki.Strings.WString;
Format : in Format_Map);
-- Append a section header at end of the document.
procedure Append (Into : in out Document;
Header : in Wiki.Strings.WString;
Level : in Positive);
-- Add a link.
procedure Add_Link (Into : in out Document;
Name : in Wiki.Strings.WString;
Attributes : in out Wiki.Attributes.Attribute_List);
-- Add an image.
procedure Add_Image (Into : in out Document;
Name : in Wiki.Strings.WString;
Attributes : in out Wiki.Attributes.Attribute_List);
-- Add a quote.
procedure Add_Quote (Into : in out Document;
Name : in Wiki.Strings.WString;
Attributes : in out Wiki.Attributes.Attribute_List);
-- Add a list item (<li>). Close the previous paragraph and list item if any.
-- The list item will be closed at the next list item, next paragraph or next header.
procedure Add_List_Item (Into : in out Document;
Level : in Positive;
Ordered : in Boolean);
-- Add a blockquote (<blockquote>). The level indicates the blockquote nested level.
-- The blockquote must be closed at the next header.
procedure Add_Blockquote (Into : in out Document;
Level : in Natural);
-- Add a text block that is pre-formatted.
procedure Add_Preformatted (Into : in out Document;
Text : in Wiki.Strings.WString;
Format : in Wiki.Strings.WString);
-- Add a new row to the current table.
procedure Add_Row (Into : in out Document);
-- Add a column to the current table row. The column is configured with the
-- given attributes. The column content is provided through calls to Append.
procedure Add_Column (Into : in out Document;
Attributes : in out Wiki.Attributes.Attribute_List);
-- Finish the creation of the table.
procedure Finish_Table (Into : in out Document);
-- Iterate over the nodes of the list and call the <tt>Process</tt> procedure with
-- each node instance.
procedure Iterate (Doc : in Document;
Process : not null access procedure (Node : in Wiki.Nodes.Node_Type));
-- Returns True if the document is empty.
function Is_Empty (Doc : in Document) return Boolean;
-- Returns True if the document displays the table of contents by itself.
function Is_Using_TOC (Doc : in Document) return Boolean;
-- Returns True if the table of contents is visible and must be rendered.
function Is_Visible_TOC (Doc : in Document) return Boolean;
-- Hide the table of contents.
procedure Hide_TOC (Doc : in out Document);
-- Get the table of content node associated with the document.
procedure Get_TOC (Doc : in out Document;
TOC : out Wiki.Nodes.Lists.Node_List_Ref);
-- Get the table of content node associated with the document.
function Get_TOC (Doc : in Document) return Wiki.Nodes.Lists.Node_List_Ref;
private
-- Append a node to the document.
procedure Append (Into : in out Document;
Node : in Wiki.Nodes.Node_Type_Access);
type Document is tagged record
Nodes : Wiki.Nodes.Lists.Node_List_Ref;
TOC : Wiki.Nodes.Lists.Node_List_Ref;
Current : Wiki.Nodes.Node_Type_Access;
Using_TOC : Boolean := False;
Visible_TOC : Boolean := True;
end record;
end Wiki.Documents;
|
Add support for wiki tables - declare Add_Row, Add_Column and Finish_Table
|
Add support for wiki tables
- declare Add_Row, Add_Column and Finish_Table
|
Ada
|
apache-2.0
|
stcarrez/ada-wiki,stcarrez/ada-wiki
|
6bd90a830795f8f7e14fd0b99881ab7bc7dfc742
|
regtests/util-serialize-io-json-tests.adb
|
regtests/util-serialize-io-json-tests.adb
|
-----------------------------------------------------------------------
-- serialize-io-json-tests -- Unit tests for JSON parser
-- 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.Streams.Stream_IO;
with Ada.Characters.Wide_Wide_Latin_1;
with Ada.Calendar.Formatting;
with Util.Test_Caller;
with Util.Log.Loggers;
with Util.Streams.Files;
package body Util.Serialize.IO.JSON.Tests is
use Util.Log;
Log : constant Loggers.Logger := Loggers.Create ("Util.Serialize.IO.JSON");
package Caller is new Util.Test_Caller (Test, "Serialize.IO.JSON");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test Util.Serialize.IO.JSON.Parse (parse errors)",
Test_Parse_Error'Access);
Caller.Add_Test (Suite, "Test Util.Serialize.IO.JSON.Parse (parse Ok)",
Test_Parser'Access);
Caller.Add_Test (Suite, "Test Util.Serialize.IO.JSON.Write",
Test_Output'Access);
end Add_Tests;
-- ------------------------------
-- Check various JSON parsing errors.
-- ------------------------------
procedure Test_Parse_Error (T : in out Test) is
pragma Unreferenced (T);
procedure Check_Parse_Error (Content : in String);
procedure Check_Parse_Error (Content : in String) is
P : Parser;
begin
P.Parse_String (Content);
Log.Error ("No exception raised for: {0}", Content);
exception
when Parse_Error =>
null;
end Check_Parse_Error;
begin
Check_Parse_Error ("{ ""person"":23");
Check_Parse_Error ("{ person: 23]");
Check_Parse_Error ("[ }");
Check_Parse_Error ("{[]}");
Check_Parse_Error ("{");
Check_Parse_Error ("{[");
Check_Parse_Error ("{ ""person");
Check_Parse_Error ("{ ""person"":");
Check_Parse_Error ("{ ""person"":""asf");
Check_Parse_Error ("{ ""person"":""asf""");
Check_Parse_Error ("{ ""person"":""asf"",");
Check_Parse_Error ("{ ""person"":""\uze""}");
Check_Parse_Error ("{ ""person"":""\u012-""}");
Check_Parse_Error ("{ ""person"":""\u012G""}");
end Test_Parse_Error;
-- ------------------------------
-- Check various (basic) JSON valid strings (no mapper).
-- ------------------------------
procedure Test_Parser (T : in out Test) is
pragma Unreferenced (T);
procedure Check_Parse (Content : in String);
procedure Check_Parse (Content : in String) is
P : Parser;
begin
P.Parse_String (Content);
exception
when Parse_Error =>
Log.Error ("Parse error for: " & Content);
raise;
end Check_Parse;
begin
Check_Parse ("{ ""person"":23}");
Check_Parse ("{ }");
Check_Parse ("{""person"":""asf""}");
Check_Parse ("{""person"":""asf"",""age"":""2""}");
Check_Parse ("{ ""person"":""\u0123""}");
Check_Parse ("{ ""person"":""\u4567""}");
Check_Parse ("{ ""person"":""\u89ab""}");
Check_Parse ("{ ""person"":""\ucdef""}");
Check_Parse ("{ ""person"":""\u1CDE""}");
Check_Parse ("{ ""person"":""\u2ABF""}");
end Test_Parser;
-- ------------------------------
-- Generate some output stream for the test.
-- ------------------------------
procedure Write_Stream (Stream : in out Util.Serialize.IO.Output_Stream'Class) is
Name : Ada.Strings.Unbounded.Unbounded_String;
Wide : constant Wide_Wide_String :=
Ada.Characters.Wide_Wide_Latin_1.CR &
Ada.Characters.Wide_Wide_Latin_1.LF &
Ada.Characters.Wide_Wide_Latin_1.HT &
Wide_Wide_Character'Val (16#080#) &
Wide_Wide_Character'Val (16#1fC#) &
Wide_Wide_Character'Val (16#20AC#) & -- Euro sign
Wide_Wide_Character'Val (16#2acbf#);
T : constant Ada.Calendar.Time := Ada.Calendar.Formatting.Time_Of (2011, 11, 19, 23, 0, 0);
begin
Ada.Strings.Unbounded.Append (Name, "Katniss Everdeen");
Stream.Start_Document;
Stream.Start_Entity ("root");
Stream.Start_Entity ("person");
Stream.Write_Attribute ("id", 1);
Stream.Write_Attribute ("name", Name);
Stream.Write_Entity ("name", Name);
Stream.Write_Entity ("gender", "female");
Stream.Write_Entity ("volunteer", True);
Stream.Write_Entity ("age", 17);
Stream.Write_Entity ("date", T);
Stream.Write_Wide_Entity ("skin", "olive skin");
Stream.Start_Array ("badges");
Stream.Start_Entity ("badge");
Stream.Write_Entity ("level", "gold");
Stream.Write_Entity ("name", "hunter");
Stream.End_Entity ("badge");
Stream.Start_Entity ("badge");
Stream.Write_Entity ("level", "gold");
Stream.Write_Entity ("name", "archery");
Stream.End_Entity ("badge");
Stream.End_Array ("badges");
Stream.Start_Entity ("district");
Stream.Write_Attribute ("id", 12);
Stream.Write_Wide_Attribute ("industry", "Coal mining");
Stream.Write_Attribute ("state", "<destroyed>");
Stream.Write_Long_Entity ("members", 10_000);
Stream.Write_Entity ("description", "<TBW>&""");
Stream.Write_Wide_Entity ("wescape", "'""<>&;,@!`~[]{}^%*()-+=");
Stream.Write_Entity ("escape", "'""<>&;,@!`~\[]{}^%*()-+=");
Stream.Write_Wide_Entity ("wide", Wide);
Stream.End_Entity ("district");
Stream.End_Entity ("person");
Stream.End_Entity ("root");
Stream.End_Document;
end Write_Stream;
-- ------------------------------
-- Test the JSON output stream generation.
-- ------------------------------
procedure Test_Output (T : in out Test) is
File : aliased Util.Streams.Files.File_Stream;
Stream : Util.Serialize.IO.JSON.Output_Stream;
Expect : constant String := Util.Tests.Get_Path ("regtests/expect/test-stream.json");
Path : constant String := Util.Tests.Get_Test_Path ("regtests/result/test-stream.json");
begin
File.Create (Mode => Ada.Streams.Stream_IO.Out_File, Name => Path);
Stream.Initialize (Output => File'Unchecked_Access, Input => null, Size => 10000);
Write_Stream (Stream);
Stream.Close;
Util.Tests.Assert_Equal_Files (T => T,
Expect => Expect,
Test => Path,
Message => "JSON output serialization");
end Test_Output;
end Util.Serialize.IO.JSON.Tests;
|
-----------------------------------------------------------------------
-- serialize-io-json-tests -- Unit tests for JSON parser
-- 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.Streams.Stream_IO;
with Ada.Characters.Wide_Wide_Latin_1;
with Ada.Calendar.Formatting;
with Util.Test_Caller;
with Util.Log.Loggers;
with Util.Streams.Files;
package body Util.Serialize.IO.JSON.Tests is
use Util.Log;
Log : constant Loggers.Logger := Loggers.Create ("Util.Serialize.IO.JSON");
package Caller is new Util.Test_Caller (Test, "Serialize.IO.JSON");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test Util.Serialize.IO.JSON.Parse (parse errors)",
Test_Parse_Error'Access);
Caller.Add_Test (Suite, "Test Util.Serialize.IO.JSON.Parse (parse Ok)",
Test_Parser'Access);
Caller.Add_Test (Suite, "Test Util.Serialize.IO.JSON.Write",
Test_Output'Access);
end Add_Tests;
-- ------------------------------
-- Check various JSON parsing errors.
-- ------------------------------
procedure Test_Parse_Error (T : in out Test) is
pragma Unreferenced (T);
procedure Check_Parse_Error (Content : in String);
procedure Check_Parse_Error (Content : in String) is
P : Parser;
begin
P.Parse_String (Content);
Log.Error ("No exception raised for: {0}", Content);
exception
when Parse_Error =>
null;
end Check_Parse_Error;
begin
Check_Parse_Error ("{ ""person"":23");
Check_Parse_Error ("{ person: 23]");
Check_Parse_Error ("[ }");
Check_Parse_Error ("{[]}");
Check_Parse_Error ("{");
Check_Parse_Error ("{[");
Check_Parse_Error ("{ ""person");
Check_Parse_Error ("{ ""person"":");
Check_Parse_Error ("{ ""person"":""asf");
Check_Parse_Error ("{ ""person"":""asf""");
Check_Parse_Error ("{ ""person"":""asf"",");
Check_Parse_Error ("{ ""person"":""\uze""}");
Check_Parse_Error ("{ ""person"":""\u012-""}");
Check_Parse_Error ("{ ""person"":""\u012G""}");
end Test_Parse_Error;
-- ------------------------------
-- Check various (basic) JSON valid strings (no mapper).
-- ------------------------------
procedure Test_Parser (T : in out Test) is
pragma Unreferenced (T);
procedure Check_Parse (Content : in String);
procedure Check_Parse (Content : in String) is
P : Parser;
begin
P.Parse_String (Content);
exception
when Parse_Error =>
Log.Error ("Parse error for: " & Content);
raise;
end Check_Parse;
begin
Check_Parse ("{ ""person"":23}");
Check_Parse ("{ }");
Check_Parse ("{""person"":""asf""}");
Check_Parse ("{""person"":""asf"",""age"":""2""}");
Check_Parse ("{ ""person"":""\u0123""}");
Check_Parse ("{ ""person"":""\u4567""}");
Check_Parse ("{ ""person"":""\u89ab""}");
Check_Parse ("{ ""person"":""\ucdef""}");
Check_Parse ("{ ""person"":""\u1CDE""}");
Check_Parse ("{ ""person"":""\u2ABF""}");
end Test_Parser;
-- ------------------------------
-- Generate some output stream for the test.
-- ------------------------------
procedure Write_Stream (Stream : in out Util.Serialize.IO.Output_Stream'Class) is
Name : Ada.Strings.Unbounded.Unbounded_String;
Wide : constant Wide_Wide_String :=
Ada.Characters.Wide_Wide_Latin_1.CR &
Ada.Characters.Wide_Wide_Latin_1.LF &
Ada.Characters.Wide_Wide_Latin_1.HT &
Wide_Wide_Character'Val (16#080#) &
Wide_Wide_Character'Val (16#1fC#) &
Wide_Wide_Character'Val (16#20AC#) & -- Euro sign
Wide_Wide_Character'Val (16#2acbf#);
T : constant Ada.Calendar.Time := Ada.Calendar.Formatting.Time_Of (2011, 11, 19, 23, 0, 0);
begin
Ada.Strings.Unbounded.Append (Name, "Katniss Everdeen");
Stream.Start_Document;
Stream.Start_Entity ("root");
Stream.Start_Entity ("person");
Stream.Write_Attribute ("id", 1);
Stream.Write_Attribute ("name", Name);
Stream.Write_Entity ("name", Name);
Stream.Write_Entity ("gender", "female");
Stream.Write_Entity ("volunteer", True);
Stream.Write_Entity ("age", 17);
Stream.Write_Entity ("date", T);
Stream.Write_Wide_Entity ("skin", "olive skin");
Stream.Start_Array ("badges");
Stream.Start_Entity ("badge");
Stream.Write_Entity ("level", "gold");
Stream.Write_Entity ("name", "hunter");
Stream.End_Entity ("badge");
Stream.Start_Entity ("badge");
Stream.Write_Entity ("level", "gold");
Stream.Write_Entity ("name", "archery");
Stream.End_Entity ("badge");
Stream.End_Array ("badges");
Stream.Start_Entity ("district");
Stream.Write_Attribute ("id", 12);
Stream.Write_Wide_Attribute ("industry", "Coal mining");
Stream.Write_Attribute ("state", "<destroyed>");
Stream.Write_Long_Entity ("members", 10_000);
Stream.Write_Entity ("description", "<TBW>&""");
Stream.Write_Wide_Entity ("wescape", "'""<>&;,@!`~[]{}^%*()-+=");
Stream.Write_Entity ("escape", "'""<>&;,@!`~\[]{}^%*()-+=");
Stream.Write_Wide_Entity ("wide", Wide);
Stream.End_Entity ("district");
Stream.End_Entity ("person");
Stream.End_Entity ("root");
Stream.End_Document;
end Write_Stream;
-- ------------------------------
-- Test the JSON output stream generation.
-- ------------------------------
procedure Test_Output (T : in out Test) is
File : aliased Util.Streams.Files.File_Stream;
Buffer : aliased Util.Streams.Texts.Print_Stream;
Stream : Util.Serialize.IO.JSON.Output_Stream;
Expect : constant String := Util.Tests.Get_Path ("regtests/expect/test-stream.json");
Path : constant String := Util.Tests.Get_Test_Path ("regtests/result/test-stream.json");
begin
File.Create (Mode => Ada.Streams.Stream_IO.Out_File, Name => Path);
Buffer.Initialize (Output => File'Unchecked_Access, Input => null, Size => 10000);
Stream.Initialize (Output => Buffer'Unchecked_Access);
Write_Stream (Stream);
Stream.Close;
Util.Tests.Assert_Equal_Files (T => T,
Expect => Expect,
Test => Path,
Message => "JSON output serialization");
end Test_Output;
end Util.Serialize.IO.JSON.Tests;
|
Update Test_Output procedure to configure the text buffer for the JSON output stream
|
Update Test_Output procedure to configure the text buffer for the JSON output stream
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
7de38a74089806fef0008c6249c53d999a661266
|
src/security-policies-roles.ads
|
src/security-policies-roles.ads
|
-----------------------------------------------------------------------
-- security-policies-roles -- Role based policies
-- Copyright (C) 2010, 2011, 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
-- == Role Based Security Policy ==
-- The <tt>Security.Policies.Roles</tt> package implements a role based security policy.
--
-- A role is represented by a name in security configuration files. A role based permission
-- is associated with a list of roles. The permission is granted if the user has one of these
-- roles.
--
-- <security-role>
-- <role-name>admin</role-name>
-- </security-role>
-- <security-role>
-- <role-name>manager</role-name>
-- </security-role>
-- <role-permission>
-- <name>create-workspace</name>
-- <role>admin</role>
-- <role>manager</role>
-- </role-permission>
--
-- This definition declares two roles: <tt>admin</tt> and <tt>manager</tt>
-- It defines a permission <b>create-workspace</b> that will be granted if the
-- user has either the <b>admin</b> or the <b>manager</b> role.
package Security.Policies.Roles is
-- Each role is represented by a <b>Role_Type</b> number to provide a fast
-- and efficient role check.
type Role_Type is new Natural range 0 .. 63;
for Role_Type'Size use 8;
type Role_Type_Array is array (Positive range <>) of Role_Type;
-- The <b>Role_Map</b> represents a set of roles which are assigned to a user.
-- Each role is represented by a boolean in the map. The implementation is limited
-- to 64 roles (the number of different permissions can be higher).
type Role_Map is array (Role_Type'Range) of Boolean;
pragma Pack (Role_Map);
-- ------------------------------
-- Role based policy
-- ------------------------------
type Role_Policy is new Policy with private;
type Role_Policy_Access is access all Role_Policy'Class;
Invalid_Name : exception;
-- Get the policy name.
overriding
function Get_Name (From : in Role_Policy) return String;
-- Find the role type associated with the role name identified by <b>Name</b>.
-- Raises <b>Invalid_Name</b> if there is no role type.
function Find_Role (Manager : in Role_Policy;
Name : in String) return Role_Type;
-- Get the role name.
function Get_Role_Name (Manager : in Role_Policy;
Role : in Role_Type) return String;
-- Create a role
procedure Create_Role (Manager : in out Role_Policy;
Name : in String;
Role : out Role_Type);
-- Get or add a role type for the given name.
procedure Add_Role_Type (Manager : in out Role_Policy;
Name : in String;
Result : out Role_Type);
-- Setup the XML parser to read the <b>role-permission</b> description.
overriding
procedure Set_Reader_Config (Policy : in out Role_Policy;
Reader : in out Util.Serialize.IO.XML.Parser);
private
type Role_Name_Array is
array (Role_Type'Range) of Ada.Strings.Unbounded.String_Access;
type Role_Policy is new Policy with record
Names : Role_Name_Array;
Next_Role : Role_Type := Role_Type'First;
end record;
type Controller_Config is record
Name : Util.Beans.Objects.Object;
Roles : Role_Type_Array (1 .. Integer (Role_Type'Last));
Count : Natural := 0;
Manager : Role_Policy_Access;
end record;
end Security.Policies.Roles;
|
-----------------------------------------------------------------------
-- security-policies-roles -- Role based policies
-- Copyright (C) 2010, 2011, 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
-- == Role Based Security Policy ==
-- The <tt>Security.Policies.Roles</tt> package implements a role based security policy.
--
-- A role is represented by a name in security configuration files. A role based permission
-- is associated with a list of roles. The permission is granted if the user has one of these
-- roles.
--
-- <security-role>
-- <role-name>admin</role-name>
-- </security-role>
-- <security-role>
-- <role-name>manager</role-name>
-- </security-role>
-- <role-permission>
-- <name>create-workspace</name>
-- <role>admin</role>
-- <role>manager</role>
-- </role-permission>
--
-- This definition declares two roles: <tt>admin</tt> and <tt>manager</tt>
-- It defines a permission <b>create-workspace</b> that will be granted if the
-- user has either the <b>admin</b> or the <b>manager</b> role.
package Security.Policies.Roles is
-- Each role is represented by a <b>Role_Type</b> number to provide a fast
-- and efficient role check.
type Role_Type is new Natural range 0 .. 63;
for Role_Type'Size use 8;
type Role_Type_Array is array (Positive range <>) of Role_Type;
-- The <b>Role_Map</b> represents a set of roles which are assigned to a user.
-- Each role is represented by a boolean in the map. The implementation is limited
-- to 64 roles (the number of different permissions can be higher).
type Role_Map is array (Role_Type'Range) of Boolean;
pragma Pack (Role_Map);
-- ------------------------------
-- Role based policy
-- ------------------------------
type Role_Policy is new Policy with private;
type Role_Policy_Access is access all Role_Policy'Class;
Invalid_Name : exception;
-- Get the policy name.
overriding
function Get_Name (From : in Role_Policy) return String;
-- Find the role type associated with the role name identified by <b>Name</b>.
-- Raises <b>Invalid_Name</b> if there is no role type.
function Find_Role (Manager : in Role_Policy;
Name : in String) return Role_Type;
-- Get the role name.
function Get_Role_Name (Manager : in Role_Policy;
Role : in Role_Type) return String;
-- Create a role
procedure Create_Role (Manager : in out Role_Policy;
Name : in String;
Role : out Role_Type);
-- Get or add a role type for the given name.
procedure Add_Role_Type (Manager : in out Role_Policy;
Name : in String;
Result : out Role_Type);
-- Setup the XML parser to read the <b>role-permission</b> description.
overriding
procedure Prepare_Config (Policy : in out Role_Policy;
Reader : in out Util.Serialize.IO.XML.Parser);
private
type Role_Name_Array is
array (Role_Type'Range) of Ada.Strings.Unbounded.String_Access;
type Role_Policy is new Policy with record
Names : Role_Name_Array;
Next_Role : Role_Type := Role_Type'First;
end record;
type Controller_Config is record
Name : Util.Beans.Objects.Object;
Roles : Role_Type_Array (1 .. Integer (Role_Type'Last));
Count : Natural := 0;
Manager : Role_Policy_Access;
end record;
end Security.Policies.Roles;
|
Rename Set_Reader_Config into Prepare_Config
|
Rename Set_Reader_Config into Prepare_Config
|
Ada
|
apache-2.0
|
stcarrez/ada-security
|
828ef18a67684917d8be96ae9b531b9a009897f1
|
src/ado-sequences-hilo.adb
|
src/ado-sequences-hilo.adb
|
-----------------------------------------------------------------------
-- ADO Sequences -- Database sequence generator
-- Copyright (C) 2009, 2010 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Log;
with Util.Log.Loggers;
with ADO.Sessions;
with ADO.Model;
with ADO.Objects;
package body ADO.Sequences.Hilo is
use Util.Log;
use ADO.Sessions;
use Sequence_Maps;
use ADO.Model;
Log : constant Loggers.Logger := Loggers.Create ("ADO.Sequences.Hilo");
type HiLoGenerator_Access is access all HiLoGenerator'Class;
-- ------------------------------
-- Create a high low sequence generator
-- ------------------------------
function Create_HiLo_Generator
(Sess_Factory : access ADO.Sessions.Factory.Session_Factory'Class)
return Generator_Access is
Result : constant HiLoGenerator_Access := new HiLoGenerator;
begin
Result.Factory := Sess_Factory;
return Result.all'Access;
end Create_HiLo_Generator;
-- ------------------------------
-- Allocate an identifier using the generator.
-- The generator allocates blocks of sequences by using a sequence
-- table stored in the database. One database access is necessary
-- every N allocations.
-- ------------------------------
procedure Allocate (Gen : in out HiLoGenerator;
Id : out Identifier) is
begin
-- Get a new sequence range
if Gen.Next_Id >= Gen.Last_Id then
Allocate_Sequence (Gen);
end if;
Id := Gen.Next_Id;
Gen.Next_Id := Gen.Next_Id + 1;
end Allocate;
-- ------------------------------
-- Allocate a new sequence block.
-- ------------------------------
procedure Allocate_Sequence (Gen : in out HiLoGenerator) is
Name : constant String := Get_Sequence_Name (Gen);
Value : Identifier;
Seq_Block : Sequence_Ref;
DB : Master_Session'Class := Gen.Get_Session;
begin
loop
-- Allocate a new sequence within a transaction.
declare
Params : Parameter_List;
Found : Boolean;
begin
Log.Info ("Allocate sequence range for {0}", Name);
DB.Begin_Transaction;
Params.Set_Filter ("name = ?");
Params.Bind_Param (Position => 1, Value => Name);
Seq_Block.Find (Database => DB, Parameters => Params, Found => Found);
begin
if Found then
Value := Seq_Block.Get_Value;
Seq_Block.Set_Value (Value + Seq_Block.Get_Block_Size);
Seq_Block.Save (DB);
else
Value := 1;
Seq_Block.Set_Name (Name);
Seq_Block.Set_Block_Size (Gen.Block_Size);
Seq_Block.Set_Value (Value + Seq_Block.Get_Block_Size);
Seq_Block.Save (DB);
end if;
DB.Commit;
Gen.Next_Id := Value;
Gen.Last_Id := Seq_Block.Get_Value;
return;
exception
when ADO.Objects.LAZY_LOCK =>
Log.Info ("Sequence table modified, retrying");
DB.Rollback;
end;
exception
when E : others =>
Log.Error ("Cannot allocate sequence range", E);
raise;
end;
end loop;
end Allocate_Sequence;
end ADO.Sequences.Hilo;
|
-----------------------------------------------------------------------
-- ADO Sequences -- Database sequence generator
-- Copyright (C) 2009, 2010 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Log;
with Util.Log.Loggers;
with ADO.Sessions;
with ADO.Model;
with ADO.Objects;
with ADO.SQL;
package body ADO.Sequences.Hilo is
use Util.Log;
use ADO.Sessions;
use Sequence_Maps;
use ADO.Model;
Log : constant Loggers.Logger := Loggers.Create ("ADO.Sequences.Hilo");
type HiLoGenerator_Access is access all HiLoGenerator'Class;
-- ------------------------------
-- Create a high low sequence generator
-- ------------------------------
function Create_HiLo_Generator
(Sess_Factory : access ADO.Sessions.Factory.Session_Factory'Class)
return Generator_Access is
Result : constant HiLoGenerator_Access := new HiLoGenerator;
begin
Result.Factory := Sess_Factory;
return Result.all'Access;
end Create_HiLo_Generator;
-- ------------------------------
-- Allocate an identifier using the generator.
-- The generator allocates blocks of sequences by using a sequence
-- table stored in the database. One database access is necessary
-- every N allocations.
-- ------------------------------
procedure Allocate (Gen : in out HiLoGenerator;
Id : out Identifier) is
begin
-- Get a new sequence range
if Gen.Next_Id >= Gen.Last_Id then
Allocate_Sequence (Gen);
end if;
Id := Gen.Next_Id;
Gen.Next_Id := Gen.Next_Id + 1;
end Allocate;
-- ------------------------------
-- Allocate a new sequence block.
-- ------------------------------
procedure Allocate_Sequence (Gen : in out HiLoGenerator) is
Name : constant String := Get_Sequence_Name (Gen);
Value : Identifier;
Seq_Block : Sequence_Ref;
DB : Master_Session'Class := Gen.Get_Session;
begin
loop
-- Allocate a new sequence within a transaction.
declare
Query : ADO.SQL.Query;
Found : Boolean;
begin
Log.Info ("Allocate sequence range for {0}", Name);
DB.Begin_Transaction;
Query.Set_Filter ("name = ?");
Query.Bind_Param (Position => 1, Value => Name);
Seq_Block.Find (Session => DB, Query => Query, Found => Found);
begin
if Found then
Value := Seq_Block.Get_Value;
Seq_Block.Set_Value (Value + Seq_Block.Get_Block_Size);
Seq_Block.Save (DB);
else
Value := 1;
Seq_Block.Set_Name (Name);
Seq_Block.Set_Block_Size (Gen.Block_Size);
Seq_Block.Set_Value (Value + Seq_Block.Get_Block_Size);
Seq_Block.Save (DB);
end if;
DB.Commit;
Gen.Next_Id := Value;
Gen.Last_Id := Seq_Block.Get_Value;
return;
exception
when ADO.Objects.LAZY_LOCK =>
Log.Info ("Sequence table modified, retrying");
DB.Rollback;
end;
exception
when E : others =>
Log.Error ("Cannot allocate sequence range", E);
raise;
end;
end loop;
end Allocate_Sequence;
end ADO.Sequences.Hilo;
|
Update query parameters for the new model
|
Update query parameters for the new model
|
Ada
|
apache-2.0
|
Letractively/ada-ado
|
c887d65c58c79c809bdd5ad2e6a6a3e06dca2a6f
|
src/ado-connections.adb
|
src/ado-connections.adb
|
-----------------------------------------------------------------------
-- ADO Drivers -- Database Drivers
-- Copyright (C) 2010, 2011, 2012, 2013, 2015, 2016, 2017, 2018, 2019 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Log.Loggers;
with Util.Systems.DLLs;
with System;
with Ada.Containers.Doubly_Linked_Lists;
with Ada.Exceptions;
package body ADO.Connections is
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("ADO.Drivers.Connections");
-- Load the database driver.
procedure Load_Driver (Name : in String);
-- ------------------------------
-- Get the driver index that corresponds to the driver for this database connection string.
-- ------------------------------
function Get_Driver (Config : in Configuration) return Driver_Index is
Driver : constant Driver_Access := Get_Driver (Config.Get_Driver);
begin
if Driver = null then
return Driver_Index'First;
else
return Driver.Get_Driver_Index;
end if;
end Get_Driver;
-- ------------------------------
-- Create a new connection using the configuration parameters.
-- ------------------------------
procedure Create_Connection (Config : in Configuration'Class;
Result : in out Ref.Ref'Class) is
Driver : Driver_Access;
Log_URI : constant String := Config.Get_Log_URI;
begin
Driver := Get_Driver (Config.Get_Driver);
if Driver = null then
Log.Error ("No driver found for connection {0}", Log_URI);
raise ADO.Configs.Connection_Error with
"Data source is not initialized: driver '" & Config.Get_Driver & "' not found";
end if;
Driver.Create_Connection (Config, Result);
Log.Info ("Created connection to '{0}' -> {1}", Log_URI, Result.Value.Ident);
exception
when others =>
Log.Info ("Failed to create connection to '{0}'", Log_URI);
raise;
end Create_Connection;
-- ------------------------------
-- Get the database driver index.
-- ------------------------------
function Get_Driver_Index (Database : in Database_Connection) return Driver_Index is
Driver : constant Driver_Access
:= Database_Connection'Class (Database).Get_Driver;
begin
return Driver.Get_Driver_Index;
end Get_Driver_Index;
package Driver_List is
new Ada.Containers.Doubly_Linked_Lists (Element_Type => Driver_Access);
Next_Index : Driver_Index := 1;
Drivers : Driver_List.List;
-- ------------------------------
-- Get the driver unique index.
-- ------------------------------
function Get_Driver_Index (D : in Driver) return Driver_Index is
begin
return D.Index;
end Get_Driver_Index;
-- ------------------------------
-- Get the driver name.
-- ------------------------------
function Get_Driver_Name (D : in Driver) return String is
begin
return D.Name.all;
end Get_Driver_Name;
-- ------------------------------
-- Register a database driver.
-- ------------------------------
procedure Register (Driver : in Driver_Access) is
use type ADO.Configs.Driver_Index;
begin
Log.Info ("Register driver {0}", Driver.Name.all);
Driver_List.Prepend (Container => Drivers, New_Item => Driver);
Driver.Index := Next_Index;
Next_Index := Next_Index + 1;
end Register;
-- ------------------------------
-- Load the database driver.
-- ------------------------------
procedure Load_Driver (Name : in String) is
Lib : constant String := "libada_ado_" & Name & Util.Systems.DLLs.Extension;
Symbol : constant String := "ado__drivers__connections__" & Name & "__initialize";
Handle : Util.Systems.DLLs.Handle;
Addr : System.Address;
begin
if ADO.Configs.Is_On (ADO.Configs.DYNAMIC_DRIVER_LOAD) then
Log.Warn ("Dynamic loading of driver '{0}' is disabled", Name);
return;
end if;
Log.Debug ("Loading driver '{0}' from {1}", Name, Lib);
Handle := Util.Systems.DLLs.Load (Lib);
Addr := Util.Systems.DLLs.Get_Symbol (Handle, Symbol);
declare
procedure Init;
pragma Import (C, Init);
for Init'Address use Addr;
begin
Log.Info ("Initialising driver {0}", Lib);
Init;
end;
exception
when Util.Systems.DLLs.Not_Found =>
Log.Error ("Driver for {0} was loaded but does not define the initialization symbol",
Name);
when E : Util.Systems.DLLs.Load_Error =>
Log.Error ("Driver for {0} was not found: {1}",
Name, Ada.Exceptions.Exception_Message (E));
end Load_Driver;
-- ------------------------------
-- Get a database driver given its name.
-- ------------------------------
function Get_Driver (Name : in String) return Driver_Access is
begin
Log.Debug ("Get driver {0}", Name);
if Name'Length = 0 then
return null;
end if;
for Retry in 0 .. 2 loop
if Retry = 1 then
null;
-- ADO.Drivers.Initialize;
elsif Retry = 2 then
Load_Driver (Name);
end if;
declare
Iter : Driver_List.Cursor := Driver_List.First (Drivers);
begin
while Driver_List.Has_Element (Iter) loop
declare
D : constant Driver_Access := Driver_List.Element (Iter);
begin
if Name = D.Name.all then
return D;
end if;
end;
Driver_List.Next (Iter);
end loop;
end;
end loop;
return null;
end Get_Driver;
end ADO.Connections;
|
-----------------------------------------------------------------------
-- ado-connections -- Database connections
-- Copyright (C) 2010, 2011, 2012, 2013, 2015, 2016, 2017, 2018, 2019 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Log.Loggers;
with Util.Systems.DLLs;
with System;
with Ada.Exceptions;
package body ADO.Connections is
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("ADO.Connections");
type Driver_Array_Access is array (Driver_Index) of Driver_Access;
Driver_List : Driver_Array_Access;
-- Load the database driver.
procedure Load_Driver (Name : in String);
-- ------------------------------
-- Get the driver index that corresponds to the driver for this database connection string.
-- ------------------------------
function Get_Driver (Config : in Configuration) return Driver_Index is
Name : constant String := Config.Get_Driver;
Driver : constant Driver_Access := Get_Driver (Name);
begin
if Driver = null then
raise ADO.Configs.Connection_Error with "Database driver '" & Name & "' not found";
else
return Driver.Get_Driver_Index;
end if;
end Get_Driver;
-- ------------------------------
-- Create a new connection using the configuration parameters.
-- ------------------------------
procedure Create_Connection (Config : in Configuration'Class;
Result : in out Ref.Ref'Class) is
Driver : Driver_Access;
Log_URI : constant String := Config.Get_Log_URI;
begin
Driver := Get_Driver (Config.Get_Driver);
if Driver = null then
Log.Error ("No driver found for connection {0}", Log_URI);
raise ADO.Configs.Connection_Error with
"Data source is not initialized: driver '" & Config.Get_Driver & "' not found";
end if;
Driver.Create_Connection (Config, Result);
Log.Info ("Created connection to '{0}' -> {1}", Log_URI, Result.Value.Ident);
exception
when others =>
Log.Info ("Failed to create connection to '{0}'", Log_URI);
raise;
end Create_Connection;
-- ------------------------------
-- Get the database driver index.
-- ------------------------------
function Get_Driver_Index (Database : in Database_Connection) return Driver_Index is
Driver : constant Driver_Access
:= Database_Connection'Class (Database).Get_Driver;
begin
return Driver.Get_Driver_Index;
end Get_Driver_Index;
-- ------------------------------
-- Get the driver unique index.
-- ------------------------------
function Get_Driver_Index (D : in Driver) return Driver_Index is
begin
return D.Index;
end Get_Driver_Index;
-- ------------------------------
-- Get the driver name.
-- ------------------------------
function Get_Driver_Name (D : in Driver) return String is
begin
return D.Name.all;
end Get_Driver_Name;
-- ------------------------------
-- Register a database driver.
-- ------------------------------
procedure Register (Driver : in Driver_Access) is
begin
Log.Info ("Register driver {0}", Driver.Name.all);
for I in Driver_List'Range loop
if Driver_List (I) = Driver then
return;
end if;
if Driver_List (I) = null then
Driver_List (I) := Driver;
Driver.Index := I;
return;
end if;
end loop;
Log.Error ("The ADO driver table is full: increase ADO.Configs.MAX_DRIVER");
end Register;
-- ------------------------------
-- Load the database driver.
-- ------------------------------
procedure Load_Driver (Name : in String) is
Lib : constant String := "libado_" & Name & Util.Systems.DLLs.Extension;
Symbol : constant String := "ado__connections__" & Name & "__initialize";
Handle : Util.Systems.DLLs.Handle;
Addr : System.Address;
begin
if ADO.Configs.Is_On (ADO.Configs.DYNAMIC_DRIVER_LOAD) then
Log.Warn ("Dynamic loading of driver '{0}' is disabled", Name);
return;
end if;
Log.Debug ("Loading driver '{0}' from {1}", Name, Lib);
Handle := Util.Systems.DLLs.Load (Lib);
Addr := Util.Systems.DLLs.Get_Symbol (Handle, Symbol);
declare
procedure Init;
pragma Import (C, Init);
for Init'Address use Addr;
begin
Log.Info ("Initialising driver {0}", Lib);
Init;
end;
exception
when Util.Systems.DLLs.Not_Found =>
Log.Error ("Driver for {0} was loaded but does not define the initialization symbol",
Name);
when E : Util.Systems.DLLs.Load_Error =>
Log.Error ("Driver for {0} was not found: {1}",
Name, Ada.Exceptions.Exception_Message (E));
end Load_Driver;
-- ------------------------------
-- Get a database driver given its name.
-- ------------------------------
function Get_Driver (Name : in String) return Driver_Access is
begin
Log.Debug ("Get driver {0}", Name);
if Name'Length = 0 then
return null;
end if;
for Retry in 0 .. 1 loop
if Retry = 1 then
Load_Driver (Name);
end if;
for D of Driver_List loop
exit when D = null;
if Name = D.Name.all then
return D;
end if;
end loop;
end loop;
return null;
end Get_Driver;
end ADO.Connections;
|
Refactor the driver management to use a fixed statically allocated table of drivers - Define Driver_Array_Access type and use the Driver_Index range - Allocate static instance Driver_List - In Register, fill the Driver_List table - In Get_Driver, look at the Driver_List table for entries
|
Refactor the driver management to use a fixed statically allocated table of drivers
- Define Driver_Array_Access type and use the Driver_Index range
- Allocate static instance Driver_List
- In Register, fill the Driver_List table
- In Get_Driver, look at the Driver_List table for entries
|
Ada
|
apache-2.0
|
stcarrez/ada-ado
|
bfdcd6d5645719020239b172c1b9c6f9223bca33
|
src/el-methods-proc_2.ads
|
src/el-methods-proc_2.ads
|
-----------------------------------------------------------------------
-- EL.Methods.Proc_2 -- Procedure Binding with 2 arguments
-- 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 EL.Expressions;
with EL.Contexts;
with Util.Beans.Methods;
with Util.Beans.Basic;
generic
type Param1_Type (<>) is limited private;
type Param2_Type (<>) is limited private;
package EL.Methods.Proc_2 is
use Util.Beans.Methods;
-- Returns True if the method is a valid method which accepts the arguments
-- defined by the package instantiation.
function Is_Valid (Method : in EL.Expressions.Method_Info) return Boolean;
-- Execute the method describe by the method expression
-- and with the given context. The method signature is:
--
-- procedure F (Obj : in out <Bean>;
-- Param1 : in Param1_Type;
-- Param2 : in Param2_Type);
--
-- where <Bean> inherits from <b>Readonly_Bean</b>
-- (See <b>Bind</b> package)
--
-- Raises <b>Invalid_Method</b> if the method referenced by
-- the method expression does not exist or does not match
-- the signature.
procedure Execute (Method : in EL.Expressions.Method_Expression'Class;
Param1 : in Param1_Type;
Param2 : in Param2_Type;
Context : in EL.Contexts.ELContext'Class);
-- Function access to the proxy.
type Proxy_Access is
access procedure (O : access Util.Beans.Basic.Readonly_Bean'Class;
P1 : in Param1_Type;
P2 : in Param2_Type);
-- The binding record which links the method name
-- to the proxy function.
type Binding is new Method_Binding with record
Method : Proxy_Access;
end record;
type Binding_Access is access constant Binding;
-- Proxy for the binding.
-- The proxy declares the binding definition that links
-- the name to the function and it implements the necessary
-- object conversion to translate the <b>Readonly_Bean</b>
-- object to the target object type.
generic
-- Name of the method (as exposed in the EL expression)
Name : String;
-- The bean type
type Bean is abstract new Util.Beans.Basic.Readonly_Bean with private;
-- The bean method to invoke
with procedure Method (O : in out Bean;
P1 : in Param1_Type;
P2 : in Param2_Type);
package Bind is
-- Method that <b>Execute</b> will invoke.
procedure Method_Access (O : access Util.Beans.Basic.Readonly_Bean'Class;
P1 : in Param1_Type;
P2 : in Param2_Type);
F_NAME : aliased constant String := Name;
-- The proxy binding that can be exposed through
-- the <b>Method_Bean</b> interface.
Proxy : aliased constant Binding
:= Binding '(Name => F_NAME'Access,
Method => Method_Access'Access);
end Bind;
end EL.Methods.Proc_2;
|
-----------------------------------------------------------------------
-- EL.Methods.Proc_2 -- Procedure Binding with 2 arguments
-- 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 EL.Expressions;
with EL.Contexts;
with Util.Beans.Methods;
with Util.Beans.Basic;
generic
type Param1_Type (<>) is limited private;
type Param2_Type (<>) is limited private;
package EL.Methods.Proc_2 is
use Util.Beans.Methods;
-- Returns True if the method is a valid method which accepts the arguments
-- defined by the package instantiation.
function Is_Valid (Method : in EL.Expressions.Method_Info) return Boolean;
-- Execute the method describe by the method expression
-- and with the given context. The method signature is:
--
-- procedure F (Obj : in out <Bean>;
-- Param1 : in Param1_Type;
-- Param2 : in Param2_Type);
--
-- where <Bean> inherits from <b>Readonly_Bean</b>
-- (See <b>Bind</b> package)
--
-- Raises <b>Invalid_Method</b> if the method referenced by
-- the method expression does not exist or does not match
-- the signature.
procedure Execute (Method : in EL.Expressions.Method_Expression'Class;
Param1 : in Param1_Type;
Param2 : in Param2_Type;
Context : in EL.Contexts.ELContext'Class);
-- Function access to the proxy.
type Proxy_Access is
access procedure (O : access Util.Beans.Basic.Readonly_Bean'Class;
P1 : in Param1_Type;
P2 : in Param2_Type);
-- The binding record which links the method name
-- to the proxy function.
type Binding is new Method_Binding with record
Method : Proxy_Access;
end record;
type Binding_Access is access constant Binding;
-- Proxy for the binding.
-- The proxy declares the binding definition that links
-- the name to the function and it implements the necessary
-- object conversion to translate the <b>Readonly_Bean</b>
-- object to the target object type.
generic
-- Name of the method (as exposed in the EL expression)
Name : String;
-- The bean type
type Bean is abstract limited new Util.Beans.Basic.Readonly_Bean with private;
-- The bean method to invoke
with procedure Method (O : in out Bean;
P1 : in Param1_Type;
P2 : in Param2_Type);
package Bind is
-- Method that <b>Execute</b> will invoke.
procedure Method_Access (O : access Util.Beans.Basic.Readonly_Bean'Class;
P1 : in Param1_Type;
P2 : in Param2_Type);
F_NAME : aliased constant String := Name;
-- The proxy binding that can be exposed through
-- the <b>Method_Bean</b> interface.
Proxy : aliased constant Binding
:= Binding '(Name => F_NAME'Access,
Method => Method_Access'Access);
end Bind;
end EL.Methods.Proc_2;
|
Change the Bean generic parameter to a limited type
|
Change the Bean generic parameter to a limited type
|
Ada
|
apache-2.0
|
stcarrez/ada-el
|
3d97899bc752ed0b56e8420a03a01037add3668c
|
src/definitions.ads
|
src/definitions.ads
|
-- This file is covered by the Internet Software Consortium (ISC) License
-- Reference: ../License.txt
package Definitions is
pragma Pure;
synth_version_major : constant String := "1";
synth_version_minor : constant String := "67";
copyright_years : constant String := "2015-2016";
host_localbase : constant String := "/usr/local";
host_make : constant String := "/usr/bin/make";
host_pkg8 : constant String := host_localbase & "/sbin/pkg";
host_bmake : constant String := host_localbase & "/bin/bmake";
host_make_program : constant String := host_make;
chroot_make : constant String := "/usr/bin/make";
chroot_bmake : constant String := "/usr/pkg/bin/bmake -m /usr/pkg/share/mk";
chroot_make_program : constant String := chroot_make;
jobs_per_cpu : constant := 2;
type cpu_range is range 1 .. 32;
type scanners is range cpu_range'First .. cpu_range'Last;
type builders is range cpu_range'First .. cpu_range'Last * jobs_per_cpu;
type package_system is (ports_collection, pkgsrc);
software_framework : constant package_system := ports_collection;
-- Notes for tailoring Synth. Use sed to:
-- 1. Modify host_localbase to value of LOCALBASE
-- 2. Change software_framework to "pkgsrc" for pkgsrc version
-- 3. Change host_make_program to "host_bmake" for Non-NetBSD pkgsrc platforms
-- 4. Change chroot_make_program to "chroot_bmake" for pkgsrc version
-- 5. On replicant.ads, change "/usr/local" to "/usr/pkg" on pkgsrc
end Definitions;
|
-- This file is covered by the Internet Software Consortium (ISC) License
-- Reference: ../License.txt
package Definitions is
pragma Pure;
synth_version_major : constant String := "1";
synth_version_minor : constant String := "68";
copyright_years : constant String := "2015-2017";
host_localbase : constant String := "/usr/local";
host_make : constant String := "/usr/bin/make";
host_pkg8 : constant String := host_localbase & "/sbin/pkg";
host_bmake : constant String := host_localbase & "/bin/bmake";
host_make_program : constant String := host_make;
chroot_make : constant String := "/usr/bin/make";
chroot_bmake : constant String := "/usr/pkg/bin/bmake -m /usr/pkg/share/mk";
chroot_make_program : constant String := chroot_make;
jobs_per_cpu : constant := 2;
type cpu_range is range 1 .. 32;
type scanners is range cpu_range'First .. cpu_range'Last;
type builders is range cpu_range'First .. cpu_range'Last * jobs_per_cpu;
type package_system is (ports_collection, pkgsrc);
software_framework : constant package_system := ports_collection;
-- Notes for tailoring Synth. Use sed to:
-- 1. Modify host_localbase to value of LOCALBASE
-- 2. Change software_framework to "pkgsrc" for pkgsrc version
-- 3. Change host_make_program to "host_bmake" for Non-NetBSD pkgsrc platforms
-- 4. Change chroot_make_program to "chroot_bmake" for pkgsrc version
-- 5. On replicant.ads, change "/usr/local" to "/usr/pkg" on pkgsrc
end Definitions;
|
Bump version and copyright years
|
Bump version and copyright years
|
Ada
|
isc
|
jrmarino/synth,jrmarino/synth,jrmarino/synth,jrmarino/synth
|
a9bc4066e3c59cc41879d9e9535bc13c49f9d9a9
|
orka/src/gl/implementation/gl-drawing.adb
|
orka/src/gl/implementation/gl-drawing.adb
|
-- SPDX-License-Identifier: Apache-2.0
--
-- Copyright (c) 2016 onox <[email protected]>
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
with System;
with GL.API;
with GL.Low_Level;
with GL.Types.Indirect;
package body GL.Drawing is
procedure Draw_Arrays
(Mode : Connection_Mode;
Offset, Count : Size;
Instances : Size := 1;
Base_Instance : Size := 0) is
begin
API.Draw_Arrays_Instanced_Base_Instance.Ref
(Mode, Offset, Count, Instances, UInt (Base_Instance));
end Draw_Arrays;
procedure Draw_Multiple_Arrays_Indirect
(Mode : Connection_Mode;
Count : Size;
Offset : Size := 0)
is
use GL.Types.Indirect;
Offset_In_Bytes : constant Size
:= Offset * Arrays_Indirect_Command'Size / System.Storage_Unit;
begin
API.Multi_Draw_Arrays_Indirect.Ref (Mode, Offset_In_Bytes, Count, 0);
end Draw_Multiple_Arrays_Indirect;
procedure Draw_Multiple_Arrays_Indirect_Count
(Mode : Connection_Mode;
Max_Count : Size;
Offset, Count_Offset : Size := 0)
is
use GL.Types.Indirect;
Offset_In_Bytes : constant Size
:= Offset * Arrays_Indirect_Command'Size / System.Storage_Unit;
Count_Offset_In_Bytes : constant Size
:= Offset * Size'Size / System.Storage_Unit;
pragma Assert (Count_Offset_In_Bytes mod 4 = 0);
begin
API.Multi_Draw_Arrays_Indirect_Count.Ref
(Mode, Offset_In_Bytes, Low_Level.IntPtr (Count_Offset), Max_Count, 0);
end Draw_Multiple_Arrays_Indirect_Count;
procedure Draw_Elements
(Mode : Connection_Mode;
Count : Size;
Index_Kind : Index_Type;
Index_Offset : Natural;
Instances : Size := 1;
Base_Instance : Size := 0;
Base_Vertex : Size := 0)
is
Element_Bytes : Natural;
begin
case Index_Kind is
when UShort_Type => Element_Bytes := 2;
when UInt_Type => Element_Bytes := 4;
end case;
API.Draw_Elements_Instanced_Base_Vertex_Base_Instance.Ref
(Mode, Count, Index_Kind, Low_Level.IntPtr (Element_Bytes * Index_Offset),
Instances, Int (Base_Vertex), UInt (Base_Instance));
end Draw_Elements;
procedure Draw_Multiple_Elements_Indirect
(Mode : Connection_Mode;
Index_Kind : Index_Type;
Count : Size;
Offset : Size := 0)
is
use GL.Types.Indirect;
Offset_In_Bytes : constant Size
:= Offset * Elements_Indirect_Command'Size / System.Storage_Unit;
begin
API.Multi_Draw_Elements_Indirect.Ref
(Mode, Index_Kind, Offset_In_Bytes, Count, 0);
end Draw_Multiple_Elements_Indirect;
procedure Draw_Multiple_Elements_Indirect_Count
(Mode : Connection_Mode;
Index_Kind : Index_Type;
Max_Count : Size;
Offset, Count_Offset : Size := 0)
is
use GL.Types.Indirect;
Offset_In_Bytes : constant Size
:= Offset * Elements_Indirect_Command'Size / System.Storage_Unit;
Count_Offset_In_Bytes : constant Size
:= Offset * Size'Size / System.Storage_Unit;
pragma Assert (Count_Offset_In_Bytes mod 4 = 0);
begin
API.Multi_Draw_Elements_Indirect_Count.Ref
(Mode, Index_Kind, Offset_In_Bytes,
Low_Level.IntPtr (Count_Offset_In_Bytes), Max_Count, 0);
end Draw_Multiple_Elements_Indirect_Count;
end GL.Drawing;
|
-- SPDX-License-Identifier: Apache-2.0
--
-- Copyright (c) 2016 onox <[email protected]>
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
with System;
with GL.API;
with GL.Low_Level;
with GL.Types.Indirect;
package body GL.Drawing is
procedure Draw_Arrays
(Mode : Connection_Mode;
Offset, Count : Size;
Instances : Size := 1;
Base_Instance : Size := 0) is
begin
API.Draw_Arrays_Instanced_Base_Instance.Ref
(Mode, Offset, Count, Instances, UInt (Base_Instance));
end Draw_Arrays;
procedure Draw_Multiple_Arrays_Indirect
(Mode : Connection_Mode;
Count : Size;
Offset : Size := 0)
is
use GL.Types.Indirect;
Offset_In_Bytes : constant Size
:= Offset * Arrays_Indirect_Command'Size / System.Storage_Unit;
begin
API.Multi_Draw_Arrays_Indirect.Ref (Mode, Offset_In_Bytes, Count, 0);
end Draw_Multiple_Arrays_Indirect;
procedure Draw_Multiple_Arrays_Indirect_Count
(Mode : Connection_Mode;
Max_Count : Size;
Offset, Count_Offset : Size := 0)
is
use GL.Types.Indirect;
Offset_In_Bytes : constant Size
:= Offset * Arrays_Indirect_Command'Size / System.Storage_Unit;
Count_Offset_In_Bytes : constant Size
:= Offset * Size'Size / System.Storage_Unit;
pragma Assert (Count_Offset_In_Bytes mod 4 = 0);
begin
API.Multi_Draw_Arrays_Indirect_Count.Ref
(Mode, Offset_In_Bytes, Low_Level.IntPtr (Count_Offset), Max_Count, 0);
end Draw_Multiple_Arrays_Indirect_Count;
procedure Draw_Elements
(Mode : Connection_Mode;
Count : Size;
Index_Kind : Index_Type;
Index_Offset : Natural;
Instances : Size := 1;
Base_Instance : Size := 0;
Base_Vertex : Size := 0)
is
Element_Bytes : Natural;
begin
case Index_Kind is
when UShort_Type => Element_Bytes := 2;
when UInt_Type => Element_Bytes := 4;
end case;
API.Draw_Elements_Instanced_Base_Vertex_Base_Instance.Ref
(Mode, Count, Index_Kind, Low_Level.IntPtr (Element_Bytes * Index_Offset),
Instances, Int (Base_Vertex), UInt (Base_Instance));
end Draw_Elements;
procedure Draw_Multiple_Elements_Indirect
(Mode : Connection_Mode;
Index_Kind : Index_Type;
Count : Size;
Offset : Size := 0)
is
use GL.Types.Indirect;
Offset_In_Bytes : constant Size
:= Offset * Elements_Indirect_Command'Size / System.Storage_Unit;
begin
API.Multi_Draw_Elements_Indirect.Ref
(Mode, Index_Kind, Offset_In_Bytes, Count, 0);
end Draw_Multiple_Elements_Indirect;
procedure Draw_Multiple_Elements_Indirect_Count
(Mode : Connection_Mode;
Index_Kind : Index_Type;
Max_Count : Size;
Offset, Count_Offset : Size := 0)
is
use GL.Types.Indirect;
Offset_In_Bytes : constant Size
:= Offset * Elements_Indirect_Command'Size / System.Storage_Unit;
Count_Offset_In_Bytes : constant Size
:= Count_Offset * Size'Size / System.Storage_Unit;
pragma Assert (Count_Offset_In_Bytes mod 4 = 0);
begin
API.Multi_Draw_Elements_Indirect_Count.Ref
(Mode, Index_Kind, Offset_In_Bytes,
Low_Level.IntPtr (Count_Offset_In_Bytes), Max_Count, 0);
end Draw_Multiple_Elements_Indirect_Count;
end GL.Drawing;
|
Fix unused formal parameter of a procedure in package GL.Drawing
|
gl: Fix unused formal parameter of a procedure in package GL.Drawing
Signed-off-by: onox <[email protected]>
|
Ada
|
apache-2.0
|
onox/orka
|
a9c2d4939f4bb3af645d8eb2fed15690030e90b8
|
src/sys/streams/util-streams-buffered.ads
|
src/sys/streams/util-streams-buffered.ads
|
-----------------------------------------------------------------------
-- util-streams-buffered -- Buffered streams utilities
-- Copyright (C) 2010, 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.Strings.Unbounded;
with Ada.Finalization;
-- == Buffered Streams ==
-- The `Output_Buffer_Stream` and `Input_Buffer_Stream` implement an output
-- and input stream respectively which manages an output or input buffer. The data is
-- first written to the buffer and when the buffer is full or flushed, it gets written
-- to the target output stream.
--
-- The `Output_Buffer_Stream` must be initialized to indicate the buffer size as well
-- as the target output stream onto which the data will be flushed. For example, a
-- pipe stream could be created and configured to use the buffer as follows:
--
-- with Util.Streams.Buffered;
-- with Util.Streams.Pipes;
-- ...
-- Pipe : aliased Util.Streams.Pipes.Pipe_Stream;
-- Buffer : Util.Streams.Buffered.Output_Buffer_Stream;
-- ...
-- Buffer.Initialize (Output => Pipe'Unchecked_Access,
-- Size => 1024);
--
-- In this example, the buffer of 1024 bytes is configured to flush its content to the
-- pipe input stream so that what is written to the buffer will be received as input by
-- the program.
-- The `Output_Buffer_Stream` provides write operation that deal only with binary data
-- (`Stream_Element`). To write text, it is best to use the `Print_Stream` type from
-- the `Util.Streams.Texts` package as it extends the `Output_Buffer_Stream` and provides
-- several operations to write character and strings.
--
-- The `Input_Buffer_Stream` must also be initialized to also indicate the buffer size
-- and either an input stream or an input content. When configured, the input stream is used
-- to fill the input stream buffer. The buffer configuration is very similar as the
-- output stream:
--
-- with Util.Streams.Buffered;
-- with Util.Streams.Pipes;
-- ...
-- Pipe : aliased Util.Streams.Pipes.Pipe_Stream;
-- Buffer : Util.Streams.Buffered.Input_Buffer_Stream;
-- ...
-- Buffer.Initialize (Input => Pipe'Unchecked_Access, Size => 1024);
--
-- In this case, the buffer of 1024 bytes is filled by reading the pipe stream, and thus
-- getting the program's output.
package Util.Streams.Buffered is
pragma Preelaborate;
type Buffer_Access is access Ada.Streams.Stream_Element_Array;
-- -----------------------
-- Output buffer stream
-- -----------------------
-- The <b>Output_Buffer_Stream</b> is an output stream which uses
-- an intermediate buffer to write the data.
--
-- It is necessary to call <b>Flush</b> to make sure the data
-- is written to the target stream. The <b>Flush</b> operation will
-- be called when finalizing the output buffer stream.
type Output_Buffer_Stream is limited new Output_Stream with private;
-- Initialize the stream to write on the given streams.
-- An internal buffer is allocated for writing the stream.
procedure Initialize (Stream : in out Output_Buffer_Stream;
Output : access Output_Stream'Class;
Size : in Positive);
-- Initialize the stream with a buffer of <b>Size</b> bytes.
procedure Initialize (Stream : in out Output_Buffer_Stream;
Size : in Positive);
-- Close the sink.
overriding
procedure Close (Stream : in out Output_Buffer_Stream);
-- Get the direct access to the buffer.
function Get_Buffer (Stream : in Output_Buffer_Stream) return Buffer_Access;
-- Write the buffer array to the output stream.
overriding
procedure Write (Stream : in out Output_Buffer_Stream;
Buffer : in Ada.Streams.Stream_Element_Array);
-- Flush the buffer by writing on the output stream.
-- Raises Data_Error if there is no output stream.
overriding
procedure Flush (Stream : in out Output_Buffer_Stream);
-- Flush the buffer in the <tt>Into</tt> array and return the index of the
-- last element (inclusive) in <tt>Last</tt>.
procedure Flush (Stream : in out Output_Buffer_Stream;
Into : out Ada.Streams.Stream_Element_Array;
Last : out Ada.Streams.Stream_Element_Offset);
-- Flush the buffer stream to the unbounded string.
procedure Flush (Stream : in out Output_Buffer_Stream;
Into : out Ada.Strings.Unbounded.Unbounded_String);
-- Get the number of element in the stream.
function Get_Size (Stream : in Output_Buffer_Stream) return Natural;
type Input_Buffer_Stream is limited new Input_Stream with private;
-- Initialize the stream to read from the string.
procedure Initialize (Stream : in out Input_Buffer_Stream;
Content : in String);
-- Initialize the stream to read the given streams.
procedure Initialize (Stream : in out Input_Buffer_Stream;
Input : access Input_Stream'Class;
Size : in Positive);
-- Fill the buffer by reading the input stream.
-- Raises Data_Error if there is no input stream;
procedure Fill (Stream : in out Input_Buffer_Stream);
-- Read one character from the input stream.
procedure Read (Stream : in out Input_Buffer_Stream;
Char : out Character);
-- Read into the buffer as many bytes as possible and return in
-- <b>last</b> the position of the last byte read.
overriding
procedure Read (Stream : in out Input_Buffer_Stream;
Into : out Ada.Streams.Stream_Element_Array;
Last : out Ada.Streams.Stream_Element_Offset);
-- Read into the buffer as many bytes as possible and return in
-- <b>last</b> the position of the last byte read.
procedure Read (Stream : in out Input_Buffer_Stream;
Into : in out Ada.Strings.Unbounded.Unbounded_String);
-- Returns True if the end of the stream is reached.
function Is_Eof (Stream : in Input_Buffer_Stream) return Boolean;
private
use Ada.Streams;
type Output_Buffer_Stream is limited new Ada.Finalization.Limited_Controlled
and Output_Stream with record
-- The buffer where the data is written before being flushed.
Buffer : Buffer_Access := null;
-- The next write position within the buffer.
Write_Pos : Stream_Element_Offset := 0;
-- The next read position within the buffer.
Read_Pos : Stream_Element_Offset := 1;
-- The last valid write position within the buffer.
Last : Stream_Element_Offset := 0;
-- The output stream to use for flushing the buffer.
Output : access Output_Stream'Class;
No_Flush : Boolean := False;
end record;
-- Flush the stream and release the buffer.
overriding
procedure Finalize (Object : in out Output_Buffer_Stream);
type Input_Buffer_Stream is limited new Ada.Finalization.Limited_Controlled
and Input_Stream with record
-- The buffer where the data is written before being flushed.
Buffer : Buffer_Access := null;
-- The next write position within the buffer.
Write_Pos : Stream_Element_Offset := 0;
-- The next read position within the buffer.
Read_Pos : Stream_Element_Offset := 1;
-- The last valid write position within the buffer.
Last : Stream_Element_Offset := 0;
-- The input stream to use to fill the buffer.
Input : access Input_Stream'Class;
-- Reached end of file when reading.
Eof : Boolean := False;
end record;
-- Release the buffer.
overriding
procedure Finalize (Object : in out Input_Buffer_Stream);
end Util.Streams.Buffered;
|
-----------------------------------------------------------------------
-- util-streams-buffered -- Buffered streams utilities
-- Copyright (C) 2010, 2013, 2015, 2016, 2017, 2018, 2019 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Ada.Finalization;
-- == Buffered Streams ==
-- The `Output_Buffer_Stream` and `Input_Buffer_Stream` implement an output
-- and input stream respectively which manages an output or input buffer. The data is
-- first written to the buffer and when the buffer is full or flushed, it gets written
-- to the target output stream.
--
-- The `Output_Buffer_Stream` must be initialized to indicate the buffer size as well
-- as the target output stream onto which the data will be flushed. For example, a
-- pipe stream could be created and configured to use the buffer as follows:
--
-- with Util.Streams.Buffered;
-- with Util.Streams.Pipes;
-- ...
-- Pipe : aliased Util.Streams.Pipes.Pipe_Stream;
-- Buffer : Util.Streams.Buffered.Output_Buffer_Stream;
-- ...
-- Buffer.Initialize (Output => Pipe'Unchecked_Access,
-- Size => 1024);
--
-- In this example, the buffer of 1024 bytes is configured to flush its content to the
-- pipe input stream so that what is written to the buffer will be received as input by
-- the program.
-- The `Output_Buffer_Stream` provides write operation that deal only with binary data
-- (`Stream_Element`). To write text, it is best to use the `Print_Stream` type from
-- the `Util.Streams.Texts` package as it extends the `Output_Buffer_Stream` and provides
-- several operations to write character and strings.
--
-- The `Input_Buffer_Stream` must also be initialized to also indicate the buffer size
-- and either an input stream or an input content. When configured, the input stream is used
-- to fill the input stream buffer. The buffer configuration is very similar as the
-- output stream:
--
-- with Util.Streams.Buffered;
-- with Util.Streams.Pipes;
-- ...
-- Pipe : aliased Util.Streams.Pipes.Pipe_Stream;
-- Buffer : Util.Streams.Buffered.Input_Buffer_Stream;
-- ...
-- Buffer.Initialize (Input => Pipe'Unchecked_Access, Size => 1024);
--
-- In this case, the buffer of 1024 bytes is filled by reading the pipe stream, and thus
-- getting the program's output.
package Util.Streams.Buffered is
pragma Preelaborate;
type Buffer_Access is access Ada.Streams.Stream_Element_Array;
-- -----------------------
-- Output buffer stream
-- -----------------------
-- The <b>Output_Buffer_Stream</b> is an output stream which uses
-- an intermediate buffer to write the data.
--
-- It is necessary to call <b>Flush</b> to make sure the data
-- is written to the target stream. The <b>Flush</b> operation will
-- be called when finalizing the output buffer stream.
type Output_Buffer_Stream is limited new Output_Stream with private;
-- Initialize the stream to write on the given streams.
-- An internal buffer is allocated for writing the stream.
procedure Initialize (Stream : in out Output_Buffer_Stream;
Output : access Output_Stream'Class;
Size : in Positive);
-- Initialize the stream with a buffer of <b>Size</b> bytes.
procedure Initialize (Stream : in out Output_Buffer_Stream;
Size : in Positive);
-- Close the sink.
overriding
procedure Close (Stream : in out Output_Buffer_Stream);
-- Get the direct access to the buffer.
function Get_Buffer (Stream : in Output_Buffer_Stream) return Buffer_Access;
-- Write the buffer array to the output stream.
overriding
procedure Write (Stream : in out Output_Buffer_Stream;
Buffer : in Ada.Streams.Stream_Element_Array);
-- Flush the buffer by writing on the output stream.
-- Raises Data_Error if there is no output stream.
overriding
procedure Flush (Stream : in out Output_Buffer_Stream);
-- Flush the buffer in the <tt>Into</tt> array and return the index of the
-- last element (inclusive) in <tt>Last</tt>.
procedure Flush (Stream : in out Output_Buffer_Stream;
Into : out Ada.Streams.Stream_Element_Array;
Last : out Ada.Streams.Stream_Element_Offset);
-- Flush the buffer stream to the unbounded string.
procedure Flush (Stream : in out Output_Buffer_Stream;
Into : out Ada.Strings.Unbounded.Unbounded_String);
-- Get the number of element in the stream.
function Get_Size (Stream : in Output_Buffer_Stream) return Natural;
type Input_Buffer_Stream is limited new Input_Stream with private;
-- Initialize the stream to read from the string.
procedure Initialize (Stream : in out Input_Buffer_Stream;
Content : in String);
-- Initialize the stream to read the given streams.
procedure Initialize (Stream : in out Input_Buffer_Stream;
Input : access Input_Stream'Class;
Size : in Positive);
-- Initialize the stream from the buffer created for an output stream.
procedure Initialize (Stream : in out Input_Buffer_Stream;
From : in out Output_Buffer_Stream'Class);
-- Fill the buffer by reading the input stream.
-- Raises Data_Error if there is no input stream;
procedure Fill (Stream : in out Input_Buffer_Stream);
-- Read one character from the input stream.
procedure Read (Stream : in out Input_Buffer_Stream;
Char : out Character);
-- Read into the buffer as many bytes as possible and return in
-- <b>last</b> the position of the last byte read.
overriding
procedure Read (Stream : in out Input_Buffer_Stream;
Into : out Ada.Streams.Stream_Element_Array;
Last : out Ada.Streams.Stream_Element_Offset);
-- Read into the buffer as many bytes as possible and return in
-- <b>last</b> the position of the last byte read.
procedure Read (Stream : in out Input_Buffer_Stream;
Into : in out Ada.Strings.Unbounded.Unbounded_String);
-- Returns True if the end of the stream is reached.
function Is_Eof (Stream : in Input_Buffer_Stream) return Boolean;
private
use Ada.Streams;
type Output_Buffer_Stream is limited new Ada.Finalization.Limited_Controlled
and Output_Stream with record
-- The buffer where the data is written before being flushed.
Buffer : Buffer_Access := null;
-- The next write position within the buffer.
Write_Pos : Stream_Element_Offset := 0;
-- The next read position within the buffer.
Read_Pos : Stream_Element_Offset := 1;
-- The last valid write position within the buffer.
Last : Stream_Element_Offset := 0;
-- The output stream to use for flushing the buffer.
Output : access Output_Stream'Class;
No_Flush : Boolean := False;
end record;
-- Flush the stream and release the buffer.
overriding
procedure Finalize (Object : in out Output_Buffer_Stream);
type Input_Buffer_Stream is limited new Ada.Finalization.Limited_Controlled
and Input_Stream with record
-- The buffer where the data is written before being flushed.
Buffer : Buffer_Access := null;
-- The next write position within the buffer.
Write_Pos : Stream_Element_Offset := 0;
-- The next read position within the buffer.
Read_Pos : Stream_Element_Offset := 1;
-- The last valid write position within the buffer.
Last : Stream_Element_Offset := 0;
-- The input stream to use to fill the buffer.
Input : access Input_Stream'Class;
-- Reached end of file when reading.
Eof : Boolean := False;
end record;
-- Release the buffer.
overriding
procedure Finalize (Object : in out Input_Buffer_Stream);
end Util.Streams.Buffered;
|
Declare a new Initialize procedure to setup an Input_Stream from the content of an Output_Stream
|
Declare a new Initialize procedure to setup an Input_Stream from the content of an Output_Stream
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
bc938f423ca0321ee2ae90e05809c44d55132da6
|
src/sys/processes/util-processes-tools.adb
|
src/sys/processes/util-processes-tools.adb
|
-----------------------------------------------------------------------
-- util-processes-tools -- System specific and low level operations
-- 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.Systems.Os;
with Util.Streams.Texts;
package body Util.Processes.Tools is
procedure Execute (Command : in String;
Process : in out Util.Streams.Pipes.Pipe_Stream;
Output : in out Util.Strings.Vectors.Vector;
Status : out Integer) is
Text : Util.Streams.Texts.Reader_Stream;
begin
Text.Initialize (Process'Unchecked_Access);
Process.Open (Command, Util.Processes.READ);
while not Text.Is_Eof loop
declare
Line : Ada.Strings.Unbounded.Unbounded_String;
begin
Text.Read_Line (Line, Strip => True);
if Ada.Strings.Unbounded.Length (Line) > 0 then
Output.Append (Ada.Strings.Unbounded.To_String (Line));
end if;
end;
end loop;
Process.Close;
Status := Process.Get_Exit_Status;
end Execute;
-- ------------------------------
-- Execute the command and append the output in the vector array.
-- The program output is read line by line and the standard input is closed.
-- Return the program exit status.
-- ------------------------------
procedure Execute (Command : in String;
Output : in out Util.Strings.Vectors.Vector;
Status : out Integer) is
Proc : Util.Streams.Pipes.Pipe_Stream;
begin
Proc.Add_Close (Util.Systems.Os.STDIN_FILENO);
Execute (Command, Proc, Output, Status);
end Execute;
procedure Execute (Command : in String;
Input_Path : in String;
Output : in out Util.Strings.Vectors.Vector;
Status : out Integer) is
Proc : Util.Streams.Pipes.Pipe_Stream;
begin
Proc.Set_Input_Stream (Input_Path);
Execute (Command, Proc, Output, Status);
end Execute;
end Util.Processes.Tools;
|
-----------------------------------------------------------------------
-- util-processes-tools -- System specific and low level operations
-- 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.Systems.Os;
with Util.Streams.Texts;
package body Util.Processes.Tools is
procedure Execute (Command : in String;
Process : in out Util.Streams.Pipes.Pipe_Stream;
Output : in out Util.Strings.Vectors.Vector;
Status : out Integer) is
Text : Util.Streams.Texts.Reader_Stream;
begin
Text.Initialize (Process'Unchecked_Access);
Process.Open (Command, Util.Processes.READ);
while not Text.Is_Eof loop
declare
Line : Ada.Strings.Unbounded.Unbounded_String;
begin
Text.Read_Line (Line, Strip => True);
if Ada.Strings.Unbounded.Length (Line) > 0 then
Output.Append (Ada.Strings.Unbounded.To_String (Line));
end if;
end;
end loop;
Process.Close;
Status := Process.Get_Exit_Status;
end Execute;
-- ------------------------------
-- Execute the command and append the output in the vector array.
-- The program output is read line by line and the standard input is closed.
-- Return the program exit status.
-- ------------------------------
procedure Execute (Command : in String;
Output : in out Util.Strings.Vectors.Vector;
Status : out Integer) is
Proc : Util.Streams.Pipes.Pipe_Stream;
begin
Proc.Add_Close (Util.Systems.Os.STDIN_FILENO);
Execute (Command, Proc, Output, Status);
end Execute;
procedure Execute (Command : in String;
Input_Path : in String;
Output : in out Util.Strings.Vectors.Vector;
Status : out Integer) is
Proc : Util.Streams.Pipes.Pipe_Stream;
begin
Proc.Set_Input_Stream (Input_Path);
Execute (Command, Proc, Output, Status);
end Execute;
end Util.Processes.Tools;
|
Replace tabs by spaces
|
Replace tabs by spaces
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
f4f09ba0b3e2ab1a2c31742912798fae05aa8ab4
|
regtests/util-serialize-io-form-tests.adb
|
regtests/util-serialize-io-form-tests.adb
|
-----------------------------------------------------------------------
-- util-serialize-io-form-tests -- Unit tests for form parser
-- Copyright (C) 2018 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Streams.Stream_IO;
with Ada.Characters.Wide_Wide_Latin_1;
with Ada.Calendar.Formatting;
with Util.Test_Caller;
with Util.Log.Loggers;
with Util.Streams.Files;
with Util.Beans.Objects.Readers;
package body Util.Serialize.IO.Form.Tests is
use Util.Log;
Log : constant Loggers.Logger := Loggers.Create ("Util.Serialize.IO.Form");
package Caller is new Util.Test_Caller (Test, "Serialize.IO.Form");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test Util.Serialize.IO.Form.Parse (parse errors)",
Test_Parse_Error'Access);
Caller.Add_Test (Suite, "Test Util.Serialize.IO.Form.Parse (parse Ok)",
Test_Parser'Access);
Caller.Add_Test (Suite, "Test Util.Serialize.IO.Form.Write",
Test_Output'Access);
Caller.Add_Test (Suite, "Test Util.Serialize.IO.Form.Read",
Test_Read'Access);
end Add_Tests;
-- ------------------------------
-- Check various form parsing errors.
-- ------------------------------
procedure Test_Parse_Error (T : in out Test) is
procedure Check_Parse_Error (Content : in String);
procedure Check_Parse_Error (Content : in String) is
P : Parser;
R : Util.Beans.Objects.Readers.Reader;
begin
P.Parse_String (Content, R);
Log.Error ("No exception raised for: {0}", Content);
T.Fail ("No exception for " & Content);
exception
when Parse_Error =>
null;
end Check_Parse_Error;
begin
Check_Parse_Error ("bad");
Check_Parse_Error ("bad=%rw%ad");
end Test_Parse_Error;
-- ------------------------------
-- Check various (basic) JSformON valid strings (no mapper).
-- ------------------------------
procedure Test_Parser (T : in out Test) is
procedure Check_Parse (Content : in String);
procedure Check_Parse (Content : in String) is
P : Parser;
R : Util.Beans.Objects.Readers.Reader;
begin
P.Parse_String (Content, R);
exception
when Parse_Error =>
Log.Error ("Parse error for: " & Content);
T.Fail ("Parse error for: " & Content);
end Check_Parse;
begin
Check_Parse ("name=value");
Check_Parse ("name=value¶m=value");
Check_Parse ("name+name=value+value");
Check_Parse ("name%20%30=value%23%ce");
end Test_Parser;
-- ------------------------------
-- Generate some output stream for the test.
-- ------------------------------
procedure Write_Stream (Stream : in out Util.Serialize.IO.Output_Stream'Class) is
Name : Ada.Strings.Unbounded.Unbounded_String;
Wide : constant Wide_Wide_String :=
Ada.Characters.Wide_Wide_Latin_1.CR &
Ada.Characters.Wide_Wide_Latin_1.LF &
Ada.Characters.Wide_Wide_Latin_1.HT &
Wide_Wide_Character'Val (16#080#) &
Wide_Wide_Character'Val (16#1fC#) &
Wide_Wide_Character'Val (16#20AC#) & -- Euro sign
Wide_Wide_Character'Val (16#2acbf#);
T : constant Ada.Calendar.Time := Ada.Calendar.Formatting.Time_Of (2011, 11, 19, 23, 0, 0);
begin
Ada.Strings.Unbounded.Append (Name, "Katniss Everdeen");
Stream.Start_Document;
Stream.Start_Entity ("root");
Stream.Start_Entity ("person");
Stream.Write_Attribute ("id", 1);
Stream.Write_Attribute ("name", Name);
Stream.Write_Entity ("name", Name);
Stream.Write_Entity ("gender", "female");
Stream.Write_Entity ("volunteer", True);
Stream.Write_Entity ("age", 17);
Stream.Write_Entity ("date", T);
Stream.Write_Wide_Entity ("skin", "olive skin");
Stream.Start_Array ("badges");
Stream.Start_Entity ("badge");
Stream.Write_Entity ("level", "gold");
Stream.Write_Entity ("name", "hunter");
Stream.End_Entity ("badge");
Stream.Start_Entity ("badge");
Stream.Write_Entity ("level", "gold");
Stream.Write_Entity ("name", "archery");
Stream.End_Entity ("badge");
Stream.End_Array ("badges");
Stream.Start_Entity ("district");
Stream.Write_Attribute ("id", 12);
Stream.Write_Wide_Attribute ("industry", "Coal mining");
Stream.Write_Attribute ("state", "<destroyed>");
Stream.Write_Long_Entity ("members", 10_000);
Stream.Write_Entity ("description", "<TBW>&""");
Stream.Write_Wide_Entity ("wescape", "'""<>&;,@!`~[]{}^%*()-+=");
Stream.Write_Entity ("escape", "'""<>&;,@!`~\[]{}^%*()-+=");
Stream.Write_Wide_Entity ("wide", Wide);
Stream.End_Entity ("district");
Stream.End_Entity ("person");
Stream.End_Entity ("root");
Stream.End_Document;
end Write_Stream;
-- ------------------------------
-- Test the JSON output stream generation.
-- ------------------------------
procedure Test_Output (T : in out Test) is
File : aliased Util.Streams.Files.File_Stream;
Buffer : aliased Util.Streams.Texts.Print_Stream;
Stream : Util.Serialize.IO.Form.Output_Stream;
Expect : constant String := Util.Tests.Get_Path ("regtests/expect/test-stream.form");
Path : constant String := Util.Tests.Get_Test_Path ("regtests/result/test-stream.form");
begin
File.Create (Mode => Ada.Streams.Stream_IO.Out_File, Name => Path);
Buffer.Initialize (Output => File'Unchecked_Access, Size => 10000);
Stream.Initialize (Output => Buffer'Unchecked_Access);
Write_Stream (Stream);
Stream.Close;
Util.Tests.Assert_Equal_Files (T => T,
Expect => Expect,
Test => Path,
Message => "Form output serialization");
end Test_Output;
-- ------------------------------
-- Test reading a form content into an Object tree.
-- ------------------------------
procedure Test_Read (T : in out Test) is
use Util.Beans.Objects;
Path : constant String := Util.Tests.Get_Test_Path ("regtests/files/pass-01.form");
Root : Util.Beans.Objects.Object;
Value : Util.Beans.Objects.Object;
begin
Root := Read (Path);
T.Assert (not Util.Beans.Objects.Is_Null (Root), "Read should not return null object");
T.Assert (not Util.Beans.Objects.Is_Array (Root), "Root object is not an array");
Value := Util.Beans.Objects.Get_Value (Root, "home");
Util.Tests.Assert_Equals (T, "Cosby",
Util.Beans.Objects.To_String (Value),
"Invalid first parameter");
Value := Util.Beans.Objects.Get_Value (Root, "favorite flavor");
Util.Tests.Assert_Equals (T, "flies",
Util.Beans.Objects.To_String (Value),
"Invalid second parameter");
end Test_Read;
end Util.Serialize.IO.Form.Tests;
|
-----------------------------------------------------------------------
-- util-serialize-io-form-tests -- Unit tests for form parser
-- Copyright (C) 2018 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Streams.Stream_IO;
with Ada.Characters.Wide_Wide_Latin_1;
with Ada.Calendar.Formatting;
with Util.Test_Caller;
with Util.Log.Loggers;
with Util.Streams.Files;
with Util.Beans.Objects.Readers;
package body Util.Serialize.IO.Form.Tests is
use Util.Log;
Log : constant Loggers.Logger := Loggers.Create ("Util.Serialize.IO.Form");
package Caller is new Util.Test_Caller (Test, "Serialize.IO.Form");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test Util.Serialize.IO.Form.Parse (parse errors)",
Test_Parse_Error'Access);
Caller.Add_Test (Suite, "Test Util.Serialize.IO.Form.Parse (parse Ok)",
Test_Parser'Access);
Caller.Add_Test (Suite, "Test Util.Serialize.IO.Form.Write",
Test_Output'Access);
Caller.Add_Test (Suite, "Test Util.Serialize.IO.Form.Read",
Test_Read'Access);
end Add_Tests;
-- ------------------------------
-- Check various form parsing errors.
-- ------------------------------
procedure Test_Parse_Error (T : in out Test) is
procedure Check_Parse_Error (Content : in String);
procedure Check_Parse_Error (Content : in String) is
P : Parser;
R : Util.Beans.Objects.Readers.Reader;
begin
P.Parse_String (Content, R);
Log.Error ("No exception raised for: {0}", Content);
T.Fail ("No exception for " & Content);
exception
when Parse_Error =>
null;
end Check_Parse_Error;
begin
-- Check_Parse_Error ("bad");
Check_Parse_Error ("bad=%rw%ad");
end Test_Parse_Error;
-- ------------------------------
-- Check various (basic) JSformON valid strings (no mapper).
-- ------------------------------
procedure Test_Parser (T : in out Test) is
procedure Check_Parse (Content : in String);
procedure Check_Parse (Content : in String) is
P : Parser;
R : Util.Beans.Objects.Readers.Reader;
begin
P.Parse_String (Content, R);
exception
when Parse_Error =>
Log.Error ("Parse error for: " & Content);
T.Fail ("Parse error for: " & Content);
end Check_Parse;
begin
Check_Parse ("name=value");
Check_Parse ("name=value¶m=value");
Check_Parse ("name+name=value+value");
Check_Parse ("name%20%30=value%23%ce");
end Test_Parser;
-- ------------------------------
-- Generate some output stream for the test.
-- ------------------------------
procedure Write_Stream (Stream : in out Util.Serialize.IO.Output_Stream'Class) is
Name : Ada.Strings.Unbounded.Unbounded_String;
Wide : constant Wide_Wide_String :=
Ada.Characters.Wide_Wide_Latin_1.CR &
Ada.Characters.Wide_Wide_Latin_1.LF &
Ada.Characters.Wide_Wide_Latin_1.HT &
Wide_Wide_Character'Val (16#080#) &
Wide_Wide_Character'Val (16#1fC#) &
Wide_Wide_Character'Val (16#20AC#) & -- Euro sign
Wide_Wide_Character'Val (16#2acbf#);
T : constant Ada.Calendar.Time := Ada.Calendar.Formatting.Time_Of (2011, 11, 19, 23, 0, 0);
begin
Ada.Strings.Unbounded.Append (Name, "Katniss Everdeen");
Stream.Start_Document;
Stream.Start_Entity ("root");
Stream.Start_Entity ("person");
Stream.Write_Attribute ("id", 1);
Stream.Write_Attribute ("name", Name);
Stream.Write_Entity ("name", Name);
Stream.Write_Entity ("gender", "female");
Stream.Write_Entity ("volunteer", True);
Stream.Write_Entity ("age", 17);
Stream.Write_Entity ("date", T);
Stream.Write_Wide_Entity ("skin", "olive skin");
Stream.Start_Array ("badges");
Stream.Start_Entity ("badge");
Stream.Write_Entity ("level", "gold");
Stream.Write_Entity ("name", "hunter");
Stream.End_Entity ("badge");
Stream.Start_Entity ("badge");
Stream.Write_Entity ("level", "gold");
Stream.Write_Entity ("name", "archery");
Stream.End_Entity ("badge");
Stream.End_Array ("badges");
Stream.Start_Entity ("district");
Stream.Write_Attribute ("id", 12);
Stream.Write_Wide_Attribute ("industry", "Coal mining");
Stream.Write_Attribute ("state", "<destroyed>");
Stream.Write_Long_Entity ("members", 10_000);
Stream.Write_Entity ("description", "<TBW>&""");
Stream.Write_Wide_Entity ("wescape", "'""<>&;,@!`~[]{}^%*()-+=");
Stream.Write_Entity ("escape", "'""<>&;,@!`~\[]{}^%*()-+=");
Stream.Write_Wide_Entity ("wide", Wide);
Stream.End_Entity ("district");
Stream.End_Entity ("person");
Stream.End_Entity ("root");
Stream.End_Document;
end Write_Stream;
-- ------------------------------
-- Test the JSON output stream generation.
-- ------------------------------
procedure Test_Output (T : in out Test) is
File : aliased Util.Streams.Files.File_Stream;
Buffer : aliased Util.Streams.Texts.Print_Stream;
Stream : Util.Serialize.IO.Form.Output_Stream;
Expect : constant String := Util.Tests.Get_Path ("regtests/expect/test-stream.form");
Path : constant String := Util.Tests.Get_Test_Path ("regtests/result/test-stream.form");
begin
File.Create (Mode => Ada.Streams.Stream_IO.Out_File, Name => Path);
Buffer.Initialize (Output => File'Unchecked_Access, Size => 10000);
Stream.Initialize (Output => Buffer'Unchecked_Access);
Write_Stream (Stream);
Stream.Close;
Util.Tests.Assert_Equal_Files (T => T,
Expect => Expect,
Test => Path,
Message => "Form output serialization");
end Test_Output;
-- ------------------------------
-- Test reading a form content into an Object tree.
-- ------------------------------
procedure Test_Read (T : in out Test) is
use Util.Beans.Objects;
Path : constant String := Util.Tests.Get_Test_Path ("regtests/files/pass-01.form");
Root : Util.Beans.Objects.Object;
Value : Util.Beans.Objects.Object;
begin
Root := Read (Path);
T.Assert (not Util.Beans.Objects.Is_Null (Root), "Read should not return null object");
T.Assert (not Util.Beans.Objects.Is_Array (Root), "Root object is not an array");
Value := Util.Beans.Objects.Get_Value (Root, "home");
Util.Tests.Assert_Equals (T, "Cosby",
Util.Beans.Objects.To_String (Value),
"Invalid first parameter");
Value := Util.Beans.Objects.Get_Value (Root, "favorite flavor");
Util.Tests.Assert_Equals (T, "flies",
Util.Beans.Objects.To_String (Value),
"Invalid second parameter");
end Test_Read;
end Util.Serialize.IO.Form.Tests;
|
Disable possibly wrong test
|
Disable possibly wrong test
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
2166858836bc3d0d50ed177bc00f5ff4b0bd3d7b
|
samples/upload_servlet.adb
|
samples/upload_servlet.adb
|
-----------------------------------------------------------------------
-- upload_servlet -- Servlet example to upload files on the server
-- 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.Streams;
with Util.Streams.Pipes;
with Util.Strings;
with ASF.Parts;
package body Upload_Servlet is
-- ------------------------------
-- Write the upload form page with an optional response message.
-- ------------------------------
procedure Write (Response : in out Responses.Response'Class;
Message : in String) is
Output : ASF.Streams.Print_Stream := Response.Get_Output_Stream;
begin
Output.Write ("<html><head><title>Upload servlet example</title></head>"
& "<style></style>"
& "<body>"
& "<h1>Upload files to identify them</h1>");
-- Display the response or some error.
if Message /= "" then
Output.Write ("<h2>" & Message & "</h2>");
end if;
-- Render the form. If we have some existing Radius or Height
-- use them to set the initial values.
Output.Write ("<p>Enter the height and radius of the cylinder</p>"
& "<form method='post' enctype='multipart/form-data'>"
& "<table>"
& "<tr><td>File 1</td>"
& "<td><input type='file' size='50' name='file1' maxlength='100000'/></td>"
& "</tr><tr><td>File 2</td>"
& "<td><input type='file' size='50' name='file2' maxlength='100000'/></td>"
& "</tr><tr><td>File 3</td>"
& "<td><input type='file' size='50' name='file3' maxlength='100000'/></td>"
& "</tr>"
& "<tr><td></td><td><input type='submit' value='Compute'></input></td></tr>"
& "</table></form>"
& "</body></html>");
Response.Set_Status (Responses.SC_OK);
end Write;
-- ------------------------------
-- Called by the servlet container when a GET request is received.
-- Display the volume form page.
-- ------------------------------
procedure Do_Get (Server : in Servlet;
Request : in out Requests.Request'Class;
Response : in out Responses.Response'Class) is
pragma Unreferenced (Server, Request);
begin
Write (Response, "");
end Do_Get;
-- ------------------------------
-- Execute a command and write the result to the output stream.
-- ------------------------------
procedure Execute (Command : in String;
Output : in out ASF.Streams.Print_Stream) is
use type Ada.Streams.Stream_Element_Offset;
Proc : Util.Streams.Pipes.Pipe_Stream;
Content : Ada.Streams.Stream_Element_Array (0 .. 1024);
Pos : Ada.Streams.Stream_Element_Offset;
begin
Proc.Open (Command);
loop
Proc.Read (Into => Content,
Last => Pos);
exit when Pos < 0;
Output.Write (Content (0 .. Pos));
end loop;
Proc.Close;
if Proc.Get_Exit_Status /= 0 then
Output.Write ("Command '" & Command & "' exited with code "
& Integer'Image (Proc.Get_Exit_Status));
end if;
end Execute;
-- ------------------------------
-- Guess a file type depending on a content type or a file name.
-- ------------------------------
function Get_File_Type (Content_Type : in String;
Name : in String) return File_Type is
begin
if Content_Type = "application/pdf" then
return PDF;
elsif Content_Type = "image/png" or Content_Type = "image/jpeg" then
return IMAGE;
elsif Content_Type = "image/gif" then
return IMAGE;
elsif Content_Type = "application/zip" then
return ZIP;
end if;
declare
Ext_Pos : constant Natural := Util.Strings.Rindex (Name, '.');
begin
if Ext_Pos > 0 then
if Name (Ext_Pos .. Name'Last) = ".gz" or Name (Ext_Pos .. Name'Last) = ".tgz" then
return TAR_GZ;
elsif Name (Ext_Pos .. Name'Last) = ".tar" then
return TAR;
elsif Name (Ext_Pos .. Name'Last) = ".jpg"
or Name (Ext_Pos .. Name'Last) = ".gif"
or Name (Ext_Pos .. Name'Last) = ".xbm"
or Name (Ext_Pos .. Name'Last) = ".png" then
return IMAGE;
elsif Name (Ext_Pos .. Name'Last) = ".zip" then
return ZIP;
elsif Name (Ext_Pos .. Name'Last) = ".pdf" then
return PDF;
end if;
end if;
return UNKNOWN;
end;
end Get_File_Type;
-- ------------------------------
-- Called by the servlet container when a POST request is received.
-- Receives the uploaded files and identify them using some external command.
-- ------------------------------
procedure Do_Post (Server : in Servlet;
Request : in out Requests.Request'Class;
Response : in out Responses.Response'Class) is
pragma Unreferenced (Server);
procedure Process_Part (Part : in ASF.Parts.Part'Class);
Output : ASF.Streams.Print_Stream := Response.Get_Output_Stream;
procedure Process_Part (Part : in ASF.Parts.Part'Class) is
Name : constant String := Part.Get_Name;
Content_Type : constant String := Part.Get_Content_Type;
Path : constant String := Part.Get_Local_Filename;
Kind : constant File_Type := Get_File_Type (Content_Type, Name);
begin
Output.Write ("<tr><td>Name: " & Name);
Output.Write ("</td><td>Content_Type: " & Content_Type & "</td>");
Output.Write ("<td>Path: " & Path & "</td>");
Output.Write ("<td>Length: " & Natural'Image (Part.Get_Size) & "</td>");
Output.Write ("</tr><tr><td></td><td colspan='3'><pre>");
case Kind is
when TAR_GZ =>
Execute ("tar tvzf " & Path, Output);
when TAR =>
Execute ("tar tvf " & Path, Output);
when IMAGE =>
Execute ("identify " & Path, Output);
when ZIP =>
Execute ("zipinfo " & Path, Output);
when PDF =>
Execute ("pdfinfo " & Path, Output);
when others =>
Output.Write ("Unknown file type");
end case;
Output.Write ("</pre></td></tr>");
end Process_Part;
begin
Response.Set_Content_Type ("text/html");
Output.Write ("<html><body>");
Output.Write ("<table style='width: 100%;'>");
for I in 1 .. Request.Get_Part_Count loop
Request.Process_Part (I, Process_Part'Access);
end loop;
Output.Write ("</table>");
Output.Write ("</body></html>");
end Do_Post;
end Upload_Servlet;
|
-----------------------------------------------------------------------
-- upload_servlet -- Servlet example to upload files on the server
-- 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.Streams;
with Util.Streams.Pipes;
with Util.Strings;
with ASF.Parts;
package body Upload_Servlet is
-- ------------------------------
-- Write the upload form page with an optional response message.
-- ------------------------------
procedure Write (Response : in out Responses.Response'Class;
Message : in String) is
Output : ASF.Streams.Print_Stream := Response.Get_Output_Stream;
begin
Output.Write ("<html><head><title>Upload servlet example</title></head>"
& "<style></style>"
& "<body>"
& "<h1>Upload files to identify them</h1>");
-- Display the response or some error.
if Message /= "" then
Output.Write ("<h2>" & Message & "</h2>");
end if;
-- Render the form. If we have some existing Radius or Height
-- use them to set the initial values.
Output.Write ("<p>Identifies images, PDF, tar, tar.gz, zip</p>"
& "<form method='post' enctype='multipart/form-data'>"
& "<table>"
& "<tr><td>File 1</td>"
& "<td><input type='file' size='50' name='file1' maxlength='100000'/></td>"
& "</tr><tr><td>File 2</td>"
& "<td><input type='file' size='50' name='file2' maxlength='100000'/></td>"
& "</tr><tr><td>File 3</td>"
& "<td><input type='file' size='50' name='file3' maxlength='100000'/></td>"
& "</tr>"
& "<tr><td></td><td><input type='submit' value='Identify'></input></td></tr>"
& "</table></form>"
& "</body></html>");
Response.Set_Status (Responses.SC_OK);
end Write;
-- ------------------------------
-- Called by the servlet container when a GET request is received.
-- Display the volume form page.
-- ------------------------------
procedure Do_Get (Server : in Servlet;
Request : in out Requests.Request'Class;
Response : in out Responses.Response'Class) is
pragma Unreferenced (Server, Request);
begin
Write (Response, "");
end Do_Get;
-- ------------------------------
-- Execute a command and write the result to the output stream.
-- ------------------------------
procedure Execute (Command : in String;
Output : in out ASF.Streams.Print_Stream) is
use type Ada.Streams.Stream_Element_Offset;
Proc : Util.Streams.Pipes.Pipe_Stream;
Content : Ada.Streams.Stream_Element_Array (0 .. 1024);
Pos : Ada.Streams.Stream_Element_Offset;
begin
Proc.Open (Command);
loop
Proc.Read (Into => Content,
Last => Pos);
exit when Pos < 0;
Output.Write (Content (0 .. Pos));
end loop;
Proc.Close;
if Proc.Get_Exit_Status /= 0 then
Output.Write ("Command '" & Command & "' exited with code "
& Integer'Image (Proc.Get_Exit_Status));
end if;
end Execute;
-- ------------------------------
-- Guess a file type depending on a content type or a file name.
-- ------------------------------
function Get_File_Type (Content_Type : in String;
Name : in String) return File_Type is
begin
if Content_Type = "application/pdf" then
return PDF;
elsif Content_Type = "image/png" or Content_Type = "image/jpeg" then
return IMAGE;
elsif Content_Type = "image/gif" then
return IMAGE;
elsif Content_Type = "application/zip" then
return ZIP;
end if;
declare
Ext_Pos : constant Natural := Util.Strings.Rindex (Name, '.');
begin
if Ext_Pos > 0 then
if Name (Ext_Pos .. Name'Last) = ".gz" or Name (Ext_Pos .. Name'Last) = ".tgz" then
return TAR_GZ;
elsif Name (Ext_Pos .. Name'Last) = ".tar" then
return TAR;
elsif Name (Ext_Pos .. Name'Last) = ".jpg"
or Name (Ext_Pos .. Name'Last) = ".gif"
or Name (Ext_Pos .. Name'Last) = ".xbm"
or Name (Ext_Pos .. Name'Last) = ".png" then
return IMAGE;
elsif Name (Ext_Pos .. Name'Last) = ".zip"
or Name (Ext_Pos .. Name'Last) = ".jar" then
return ZIP;
elsif Name (Ext_Pos .. Name'Last) = ".pdf" then
return PDF;
end if;
end if;
return UNKNOWN;
end;
end Get_File_Type;
-- ------------------------------
-- Called by the servlet container when a POST request is received.
-- Receives the uploaded files and identify them using some external command.
-- ------------------------------
procedure Do_Post (Server : in Servlet;
Request : in out Requests.Request'Class;
Response : in out Responses.Response'Class) is
pragma Unreferenced (Server);
procedure Process_Part (Part : in ASF.Parts.Part'Class);
Output : ASF.Streams.Print_Stream := Response.Get_Output_Stream;
procedure Process_Part (Part : in ASF.Parts.Part'Class) is
Name : constant String := Part.Get_Name;
Content_Type : constant String := Part.Get_Content_Type;
Path : constant String := Part.Get_Local_Filename;
Kind : constant File_Type := Get_File_Type (Content_Type, Name);
begin
Output.Write ("<tr><td>Name: " & Name);
Output.Write ("</td><td>Content_Type: " & Content_Type & "</td>");
Output.Write ("<td>Path: " & Path & "</td>");
Output.Write ("<td>Length: " & Natural'Image (Part.Get_Size) & "</td>");
Output.Write ("</tr><tr><td></td><td colspan='3'><pre>");
case Kind is
when TAR_GZ =>
Execute ("tar tvzf " & Path, Output);
when TAR =>
Execute ("tar tvf " & Path, Output);
when IMAGE =>
Execute ("identify " & Path, Output);
when ZIP =>
Execute ("zipinfo " & Path, Output);
when PDF =>
Execute ("pdfinfo " & Path, Output);
when others =>
Output.Write ("Unknown file type");
end case;
Output.Write ("</pre></td></tr>");
end Process_Part;
begin
Response.Set_Content_Type ("text/html");
Output.Write ("<html><body>");
Output.Write ("<table style='width: 100%;'>");
for I in 1 .. Request.Get_Part_Count loop
Request.Process_Part (I, Process_Part'Access);
end loop;
Output.Write ("<tr><td colspan='5'><a href='upload.html'>Upload new files</a></td></tr>");
Output.Write ("</table>");
Output.Write ("</body></html>");
end Do_Post;
end Upload_Servlet;
|
Update the page description and recognize JAR files (as a ZIP)
|
Update the page description and recognize JAR files (as a ZIP)
|
Ada
|
apache-2.0
|
Letractively/ada-asf,Letractively/ada-asf,Letractively/ada-asf
|
028d6975b5530abd5b084823a07e39c866d5a9c4
|
src/sqlite/ado-sqlite.ads
|
src/sqlite/ado-sqlite.ads
|
-----------------------------------------------------------------------
-- ado-sqlite -- SQLite Database Drivers
-- Copyright (C) 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.Properties;
-- === SQLite Database Driver ===
-- The SQLite database driver can be initialize explicitly by using the `ado_mysql`
-- GNAT project and calling the initialization procedure.
--
-- ADO.Sqlite.Initialize ("db.properties");
--
-- The set of configuration properties can be set programatically and passed to the
-- `Initialize` operation.
--
-- Config : Util.Properties.Manager;
-- ...
-- Config.Set ("ado.database", "sqlite:///regtests.db?synchronous=OFF&encoding=UTF-8");
-- Config.Set ("ado.queries.path", ".;db");
-- ADO.Sqlite.Initialize (Config);
--
-- The SQLite database driver will pass all the properties as SQLite `pragma` allowing
-- the configuration of the SQLite database.
--
package ADO.Sqlite is
-- 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);
end ADO.Sqlite;
|
-----------------------------------------------------------------------
-- ado-sqlite -- SQLite Database Drivers
-- Copyright (C) 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.Properties;
-- === SQLite Database Driver ===
-- The SQLite database driver can be initialize explicitly by using the `ado_mysql`
-- GNAT project and calling the initialization procedure.
--
-- ADO.Sqlite.Initialize ("db.properties");
--
-- The set of configuration properties can be set programatically and passed to the
-- `Initialize` operation.
--
-- Config : Util.Properties.Manager;
-- ...
-- Config.Set ("ado.database", "sqlite:///regtests.db?synchronous=OFF&encoding=UTF-8");
-- Config.Set ("ado.queries.path", ".;db");
-- ADO.Sqlite.Initialize (Config);
--
-- The SQLite database driver will pass all the properties as SQLite `pragma` allowing
-- the configuration of the SQLite database.
--
package ADO.Sqlite is
-- Initialize the SQLite driver.
procedure Initialize;
-- 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);
end ADO.Sqlite;
|
Declare the Initialize procedure
|
Declare the Initialize procedure
|
Ada
|
apache-2.0
|
stcarrez/ada-ado
|
c6b0f3c1677b8ec6d31dedf1e1e1a65b67ef29b3
|
src/wiki-streams-html.ads
|
src/wiki-streams-html.ads
|
-----------------------------------------------------------------------
-- 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.Strings.Wide_Wide_Unbounded;
with Wiki.Strings;
-- == Writer interfaces ==
-- The <tt>Wiki.Writers</tt> package defines the interfaces used by the renderer to write
-- their outputs.
--
-- The <tt>Input_Stream</tt> interface defines the interface that must be implemented to
-- read the source Wiki content. The <tt>Read</tt> procedure is called by the parser
-- repeatedly while scanning the Wiki content.
package Wiki.Streams.Html is
use Ada.Strings.Wide_Wide_Unbounded;
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 element using the given name and with the content.
-- This is similar to calling <b>Start_Element</b>, <b>Write_Text</b>
-- and <b>End_Element</b>.
procedure Write_Wide_Element (Writer : in out Html_Output_Stream;
Name : in String;
Content : in Wiki.Strings.WString) 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 Unbounded_Wide_Wide_String) 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 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 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR 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.Strings;
-- === HTML Output Stream ===
-- The <tt>Wiki.Writers</tt> package defines the interfaces used by the renderer to write
-- their outputs.
--
-- The <tt>Input_Stream</tt> interface defines the interface that must be implemented to
-- read the source Wiki content. The <tt>Read</tt> procedure is called by the parser
-- repeatedly while scanning the Wiki content.
package Wiki.Streams.Html is
use Ada.Strings.Wide_Wide_Unbounded;
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 element using the given name and with the content.
-- This is similar to calling <b>Start_Element</b>, <b>Write_Text</b>
-- and <b>End_Element</b>.
procedure Write_Wide_Element (Writer : in out Html_Output_Stream;
Name : in String;
Content : in Wiki.Strings.WString) 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 Unbounded_Wide_Wide_String) 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 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 some documentation
|
Add some documentation
|
Ada
|
apache-2.0
|
stcarrez/ada-wiki,stcarrez/ada-wiki
|
fec671fba334683a0b811f51bcfb876f184506c5
|
src/base/beans/util-beans-objects-maps.adb
|
src/base/beans/util-beans-objects-maps.adb
|
-----------------------------------------------------------------------
-- util-beans-objects-maps -- Object maps
-- Copyright (C) 2010, 2011, 2012, 2017, 2018, 2019 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
package body Util.Beans.Objects.Maps is
-- ------------------------------
-- Get the value identified by the name.
-- If the name cannot be found, the method should return the Null object.
-- ------------------------------
function Get_Value (From : in Map_Bean;
Name : in String) return Object is
Pos : constant Cursor := From.Find (Name);
begin
if Has_Element (Pos) then
return Element (Pos);
else
return Null_Object;
end if;
end Get_Value;
-- ------------------------------
-- Set the value identified by the name.
-- If the map contains the given name, the value changed.
-- Otherwise name is added to the map and the value associated with it.
-- ------------------------------
procedure Set_Value (From : in out Map_Bean;
Name : in String;
Value : in Object) is
begin
From.Include (Name, Value);
end Set_Value;
-- ------------------------------
-- Iterate over the members of the map.
-- ------------------------------
procedure Iterate (From : in Object;
Process : not null access procedure (Name : in String;
Item : in Object)) is
procedure Process_One (Pos : in Maps.Cursor);
procedure Process_One (Pos : in Maps.Cursor) is
begin
Process (Maps.Key (Pos), Maps.Element (Pos));
end Process_One;
Bean : constant access Util.Beans.Basic.Readonly_Bean'Class := To_Bean (From);
begin
if Bean /= null and then Bean.all in Util.Beans.Objects.Maps.Map_Bean'Class then
Map_Bean'Class (Bean.all).Iterate (Process_One'Access);
end if;
end Iterate;
-- ------------------------------
-- Create an object that contains a <tt>Map_Bean</tt> instance.
-- ------------------------------
function Create return Object is
M : constant Map_Bean_Access := new Map_Bean;
begin
return To_Object (Value => M, Storage => DYNAMIC);
end Create;
end Util.Beans.Objects.Maps;
|
-----------------------------------------------------------------------
-- util-beans-objects-maps -- Object maps
-- Copyright (C) 2010, 2011, 2012, 2017, 2018, 2019 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
package body Util.Beans.Objects.Maps is
-- ------------------------------
-- Get the value identified by the name.
-- If the name cannot be found, the method should return the Null object.
-- ------------------------------
overriding
function Get_Value (From : in Map_Bean;
Name : in String) return Object is
Pos : constant Cursor := From.Find (Name);
begin
if Has_Element (Pos) then
return Element (Pos);
else
return Null_Object;
end if;
end Get_Value;
-- ------------------------------
-- Set the value identified by the name.
-- If the map contains the given name, the value changed.
-- Otherwise name is added to the map and the value associated with it.
-- ------------------------------
overriding
procedure Set_Value (From : in out Map_Bean;
Name : in String;
Value : in Object) is
begin
From.Include (Name, Value);
end Set_Value;
-- ------------------------------
-- Get an iterator to iterate starting with the first element.
-- ------------------------------
overriding
function First (From : in Map_Bean) return Iterators.Proxy_Iterator_Access is
Iter : constant Map_Iterator_Access := new Map_Iterator;
begin
Iter.Pos := From.First;
return Iter.all'Access;
end First;
-- ------------------------------
-- Get an iterator to iterate starting with the last element.
-- ------------------------------
overriding
function Last (From : in Map_Bean) return Iterators.Proxy_Iterator_Access is
begin
return null;
end Last;
-- ------------------------------
-- Iterate over the members of the map.
-- ------------------------------
procedure Iterate (From : in Object;
Process : not null access procedure (Name : in String;
Item : in Object)) is
procedure Process_One (Pos : in Maps.Cursor);
procedure Process_One (Pos : in Maps.Cursor) is
begin
Process (Maps.Key (Pos), Maps.Element (Pos));
end Process_One;
Bean : constant access Util.Beans.Basic.Readonly_Bean'Class := To_Bean (From);
begin
if Bean /= null and then Bean.all in Util.Beans.Objects.Maps.Map_Bean'Class then
Map_Bean'Class (Bean.all).Iterate (Process_One'Access);
end if;
end Iterate;
-- ------------------------------
-- Create an object that contains a <tt>Map_Bean</tt> instance.
-- ------------------------------
function Create return Object is
M : constant Map_Bean_Access := new Map_Bean;
begin
return To_Object (Value => M, Storage => DYNAMIC);
end Create;
function Get_Map is
new Util.Beans.Objects.Iterators.Get_Bean (Map_Bean, Map_Bean_Access);
overriding
function Has_Element (Iter : in Map_Iterator) return Boolean is
Map : constant Map_Bean_Access := Get_Map (Iter);
begin
return Map /= null and then Has_Element (Iter.Pos);
end Has_Element;
overriding
procedure Next (Iter : in out Map_Iterator) is
begin
Next (Iter.Pos);
end Next;
overriding
procedure Previous (Iter : in out Map_Iterator) is
begin
null;
end Previous;
overriding
function Element (Iter : in Map_Iterator) return Object is
begin
return Element (Iter.Pos);
end Element;
overriding
function Key (Iter : in Map_Iterator) return String is
begin
return Key (Iter.Pos);
end Key;
end Util.Beans.Objects.Maps;
|
Implement the Map_Iterator operations
|
Implement the Map_Iterator operations
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
e31d6d9cd7acb3f76bbdf2445ae501b802a7b89e
|
src/gen-commands-project.adb
|
src/gen-commands-project.adb
|
-----------------------------------------------------------------------
-- gen-commands-project -- Project creation command for dynamo
-- Copyright (C) 2011, 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Directories;
with Ada.Text_IO;
with Gen.Artifacts;
with GNAT.Command_Line;
with GNAT.OS_Lib;
with Util.Log.Loggers;
with Util.Strings.Transforms;
package body Gen.Commands.Project is
use Util.Log;
Log : constant Loggers.Logger := Loggers.Create ("Gen.Commands.Project");
-- ------------------------------
-- Generator Command
-- ------------------------------
function Get_Name_From_Email (Email : in String) return String;
-- ------------------------------
-- Get the user name from the email address.
-- Returns the possible user name from his email address.
-- ------------------------------
function Get_Name_From_Email (Email : in String) return String is
Pos : Natural := Util.Strings.Index (Email, '<');
begin
if Pos > 0 then
return Email (Email'First .. Pos - 1);
end if;
Pos := Util.Strings.Index (Email, '@');
if Pos > 0 then
return Email (Email'First .. Pos - 1);
else
return Email;
end if;
end Get_Name_From_Email;
-- Execute the command with the arguments.
procedure Execute (Cmd : in Command;
Generator : in out Gen.Generator.Handler) is
pragma Unreferenced (Cmd);
use GNAT.Command_Line;
Web_Flag : aliased Boolean := False;
Tool_Flag : aliased Boolean := False;
Ado_Flag : aliased Boolean := False;
begin
-- If a dynamo.xml file exists, read it.
if Ada.Directories.Exists ("dynamo.xml") then
Generator.Read_Project ("dynamo.xml");
else
Generator.Set_Project_Property ("license", "apache");
Generator.Set_Project_Property ("author", "unknown");
Generator.Set_Project_Property ("author_email", "[email protected]");
end if;
-- Parse the command line
loop
case Getopt ("l: -web -tool -ado") is
when ASCII.NUL => exit;
when '-' =>
if Full_Switch = "-web" then
Web_Flag := True;
elsif Full_Switch = "-tool" then
Tool_Flag := True;
elsif Full_Switch = "-ado" then
Ado_Flag := True;
end if;
when 'l' =>
declare
L : constant String := Util.Strings.Transforms.To_Lower_Case (Parameter);
begin
Log.Info ("License {0}", L);
if L = "apache" then
Generator.Set_Project_Property ("license", "apache");
elsif L = "gpl" then
Generator.Set_Project_Property ("license", "gpl");
elsif L = "proprietary" then
Generator.Set_Project_Property ("license", "proprietary");
else
Generator.Error ("Invalid license: {0}", L);
Generator.Error ("Valid licenses: apache, gpl, proprietary");
return;
end if;
end;
when others =>
null;
end case;
end loop;
if not Web_Flag and not Ado_Flag and not Tool_Flag then
Web_Flag := True;
end if;
declare
Name : constant String := Get_Argument;
Arg2 : constant String := Get_Argument;
Arg3 : constant String := Get_Argument;
begin
if Name'Length = 0 then
Generator.Error ("Missing project name");
Gen.Commands.Usage;
return;
end if;
if Util.Strings.Index (Arg2, '@') > Arg2'First then
Generator.Set_Project_Property ("author_email", Arg2);
if Arg3'Length = 0 then
Generator.Set_Project_Property ("author", Get_Name_From_Email (Arg2));
else
Generator.Set_Project_Property ("author", Arg3);
end if;
elsif Util.Strings.Index (Arg3, '@') > Arg3'First then
Generator.Set_Project_Property ("author", Arg2);
Generator.Set_Project_Property ("author_email", Arg3);
elsif Arg3'Length > 0 then
Generator.Error ("The last argument should be the author's email address.");
Gen.Commands.Usage;
return;
end if;
Generator.Set_Project_Name (Name);
Generator.Set_Force_Save (False);
Gen.Generator.Generate_All (Generator, Gen.Artifacts.ITERATION_TABLE, "project");
Generator.Save_Project;
declare
use type GNAT.OS_Lib.String_Access;
Path : constant GNAT.OS_Lib.String_Access
:= GNAT.OS_Lib.Locate_Exec_On_Path ("autoconf");
Args : GNAT.OS_Lib.Argument_List (1 .. 0);
Status : Boolean;
begin
if Path = null then
Generator.Error ("The 'autoconf' tool was not found. It is necessary to "
& "generate the configure script.");
Generator.Error ("Install 'autoconf' or launch it manually.");
else
Ada.Directories.Set_Directory (Generator.Get_Result_Directory);
Log.Info ("Executing {0}", Path.all);
GNAT.OS_Lib.Spawn (Path.all, Args, Status);
if not Status then
Generator.Error ("Execution of {0} failed", Path.all);
end if;
end if;
end;
end;
end Execute;
-- ------------------------------
-- Write the help associated with the command.
-- ------------------------------
procedure Help (Cmd : in Command;
Generator : in out Gen.Generator.Handler) is
pragma Unreferenced (Cmd, Generator);
use Ada.Text_IO;
begin
Put_Line ("create-project: Create a new Ada Web Application project");
Put_Line ("Usage: create-project [-l apache|gpl|proprietary] [-web] [-tool] [-ado] "
& "NAME [AUTHOR] [EMAIL]");
New_Line;
Put_Line (" Creates a new AWA application with the name passed in NAME.");
Put_Line (" The application license is controlled with the -l option. ");
Put_Line (" License headers can use either the Apache, the GNU license or");
Put_Line (" a proprietary license. The author's name and email addresses");
Put_Line (" are also reported in generated files.");
New_Line;
Put_Line (" -web Generate a Web application");
Put_Line (" -tool Generate a command line tool");
Put_Line (" -ado Generate a database tool operation for ADO");
end Help;
end Gen.Commands.Project;
|
-----------------------------------------------------------------------
-- gen-commands-project -- Project creation command for dynamo
-- Copyright (C) 2011, 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Directories;
with Ada.Text_IO;
with Gen.Artifacts;
with GNAT.Command_Line;
with GNAT.OS_Lib;
with Util.Log.Loggers;
with Util.Strings.Transforms;
package body Gen.Commands.Project is
use Util.Log;
Log : constant Loggers.Logger := Loggers.Create ("Gen.Commands.Project");
-- ------------------------------
-- Generator Command
-- ------------------------------
function Get_Name_From_Email (Email : in String) return String;
-- ------------------------------
-- Get the user name from the email address.
-- Returns the possible user name from his email address.
-- ------------------------------
function Get_Name_From_Email (Email : in String) return String is
Pos : Natural := Util.Strings.Index (Email, '<');
begin
if Pos > 0 then
return Email (Email'First .. Pos - 1);
end if;
Pos := Util.Strings.Index (Email, '@');
if Pos > 0 then
return Email (Email'First .. Pos - 1);
else
return Email;
end if;
end Get_Name_From_Email;
-- Execute the command with the arguments.
procedure Execute (Cmd : in Command;
Generator : in out Gen.Generator.Handler) is
pragma Unreferenced (Cmd);
use GNAT.Command_Line;
Web_Flag : aliased Boolean := False;
Tool_Flag : aliased Boolean := False;
Ado_Flag : aliased Boolean := False;
begin
-- If a dynamo.xml file exists, read it.
if Ada.Directories.Exists ("dynamo.xml") then
Generator.Read_Project ("dynamo.xml");
else
Generator.Set_Project_Property ("license", "apache");
Generator.Set_Project_Property ("author", "unknown");
Generator.Set_Project_Property ("author_email", "[email protected]");
end if;
-- Parse the command line
loop
case Getopt ("l: ? -web -tool -ado") is
when ASCII.NUL => exit;
when '-' =>
if Full_Switch = "-web" then
Web_Flag := True;
elsif Full_Switch = "-tool" then
Tool_Flag := True;
elsif Full_Switch = "-ado" then
Ado_Flag := True;
end if;
when 'l' =>
declare
L : constant String := Util.Strings.Transforms.To_Lower_Case (Parameter);
begin
Log.Info ("License {0}", L);
if L = "apache" then
Generator.Set_Project_Property ("license", "apache");
elsif L = "gpl" then
Generator.Set_Project_Property ("license", "gpl");
elsif L = "proprietary" then
Generator.Set_Project_Property ("license", "proprietary");
else
Generator.Error ("Invalid license: {0}", L);
Generator.Error ("Valid licenses: apache, gpl, proprietary");
return;
end if;
end;
when others =>
null;
end case;
end loop;
if not Web_Flag and not Ado_Flag and not Tool_Flag then
Web_Flag := True;
end if;
declare
Name : constant String := Get_Argument;
Arg2 : constant String := Get_Argument;
Arg3 : constant String := Get_Argument;
begin
if Name'Length = 0 then
Generator.Error ("Missing project name");
Gen.Commands.Usage;
return;
end if;
if Util.Strings.Index (Arg2, '@') > Arg2'First then
Generator.Set_Project_Property ("author_email", Arg2);
if Arg3'Length = 0 then
Generator.Set_Project_Property ("author", Get_Name_From_Email (Arg2));
else
Generator.Set_Project_Property ("author", Arg3);
end if;
elsif Util.Strings.Index (Arg3, '@') > Arg3'First then
Generator.Set_Project_Property ("author", Arg2);
Generator.Set_Project_Property ("author_email", Arg3);
elsif Arg3'Length > 0 then
Generator.Error ("The last argument should be the author's email address.");
Gen.Commands.Usage;
return;
end if;
Generator.Set_Project_Property ("is_web", Boolean'Image (Web_Flag));
Generator.Set_Project_Property ("is_tool", Boolean'Image (Tool_Flag));
Generator.Set_Project_Property ("is_ado", Boolean'Image (Ado_Flag));
Generator.Set_Project_Name (Name);
Generator.Set_Force_Save (False);
if Ado_Flag then
Gen.Generator.Generate_All (Generator, Gen.Artifacts.ITERATION_TABLE, "project-ado");
else
Gen.Generator.Generate_All (Generator, Gen.Artifacts.ITERATION_TABLE, "project");
end if;
Generator.Save_Project;
declare
use type GNAT.OS_Lib.String_Access;
Path : constant GNAT.OS_Lib.String_Access
:= GNAT.OS_Lib.Locate_Exec_On_Path ("autoconf");
Args : GNAT.OS_Lib.Argument_List (1 .. 0);
Status : Boolean;
begin
if Path = null then
Generator.Error ("The 'autoconf' tool was not found. It is necessary to "
& "generate the configure script.");
Generator.Error ("Install 'autoconf' or launch it manually.");
else
Ada.Directories.Set_Directory (Generator.Get_Result_Directory);
Log.Info ("Executing {0}", Path.all);
GNAT.OS_Lib.Spawn (Path.all, Args, Status);
if not Status then
Generator.Error ("Execution of {0} failed", Path.all);
end if;
end if;
end;
end;
end Execute;
-- ------------------------------
-- Write the help associated with the command.
-- ------------------------------
procedure Help (Cmd : in Command;
Generator : in out Gen.Generator.Handler) is
pragma Unreferenced (Cmd, Generator);
use Ada.Text_IO;
begin
Put_Line ("create-project: Create a new Ada Web Application project");
Put_Line ("Usage: create-project [-l apache|gpl|proprietary] [-web] [-tool] [-ado] "
& "NAME [AUTHOR] [EMAIL]");
New_Line;
Put_Line (" Creates a new AWA application with the name passed in NAME.");
Put_Line (" The application license is controlled with the -l option. ");
Put_Line (" License headers can use either the Apache, the GNU license or");
Put_Line (" a proprietary license. The author's name and email addresses");
Put_Line (" are also reported in generated files.");
New_Line;
Put_Line (" -web Generate a Web application");
Put_Line (" -tool Generate a command line tool");
Put_Line (" -ado Generate a database tool operation for ADO");
end Help;
end Gen.Commands.Project;
|
Use another project template for Ado utilities
|
Use another project template for Ado utilities
|
Ada
|
apache-2.0
|
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
|
4f9c3ad2785d5ac9427841882f7f2d590289046f
|
regtests/util-beans-objects-record_tests.adb
|
regtests/util-beans-objects-record_tests.adb
|
-----------------------------------------------------------------------
-- util-beans-objects-record_tests -- Unit tests for objects.records package
-- 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.Test_Caller;
with Util.Strings;
with Util.Beans.Basic;
with Util.Beans.Objects.Vectors;
with Util.Beans.Objects.Records;
package body Util.Beans.Objects.Record_Tests is
use Util.Tests;
package Caller is new Util.Test_Caller (Test, "Objects.Records");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test Util.Beans.Objects.Records",
Test_Record'Access);
Caller.Add_Test (Suite, "Test Util.Beans.Basic",
Test_Bean'Access);
end Add_Tests;
type Data is record
Name : Unbounded_String;
Value : Util.Beans.Objects.Object;
end record;
package Data_Bean is new Util.Beans.Objects.Records (Data);
use type Data_Bean.Element_Type_Access;
subtype Data_Access is Data_Bean.Element_Type_Access;
procedure Test_Record (T : in out Test) is
D : Data;
begin
D.Name := To_Unbounded_String ("testing");
D.Value := To_Object (Integer (23));
declare
V : Object := Data_Bean.To_Object (D);
P : constant Data_Access := Data_Bean.To_Element_Access (V);
V2 : constant Object := V;
begin
T.Assert (not Is_Empty (V), "Object with data record should not be empty");
T.Assert (not Is_Null (V), "Object with data record should not be null");
T.Assert (P /= null, "To_Element_Access returned null");
Assert_Equals (T, "testing", To_String (P.Name), "Data name is not the same");
Assert_Equals (T, 23, To_Integer (P.Value), "Data value is not the same");
V := Data_Bean.Create;
declare
D2 : constant Data_Access := Data_Bean.To_Element_Access (V);
begin
T.Assert (D2 /= null, "Null element");
D2.Name := To_Unbounded_String ("second test");
D2.Value := V2;
end;
V := Data_Bean.To_Object (D);
end;
end Test_Record;
type Bean_Type is new Util.Beans.Basic.Readonly_Bean with record
Name : Unbounded_String;
end record;
type Bean_Type_Access is access all Bean_Type'Class;
overriding
function Get_Value (Bean : in Bean_Type;
Name : in String) return Util.Beans.Objects.Object;
overriding
function Get_Value (Bean : in Bean_Type;
Name : in String) return Util.Beans.Objects.Object is
begin
if Name = "name" then
return Util.Beans.Objects.To_Object (Bean.Name);
elsif Name = "length" then
return Util.Beans.Objects.To_Object (Length (Bean.Name));
else
return Util.Beans.Objects.Null_Object;
end if;
end Get_Value;
procedure Test_Bean (T : in out Test) is
use Basic;
Static : aliased Bean_Type;
begin
Static.Name := To_Unbounded_String ("Static");
-- Allocate dynamically several Bean_Type objects and drop the list.
-- The memory held by internal proxy as well as the Bean_Type must be freed.
-- The static bean should never be freed!
for I in 1 .. 10 loop
declare
List : Util.Beans.Objects.Vectors.Vector;
Value : Util.Beans.Objects.Object;
Bean : Bean_Type_Access;
P : access Readonly_Bean'Class;
begin
for J in 1 .. 1_000 loop
if I = J then
Value := To_Object (Static'Unchecked_Access, Objects.STATIC);
List.Append (Value);
end if;
Bean := new Bean_Type;
Bean.Name := To_Unbounded_String ("B" & Util.Strings.Image (J));
Value := To_Object (Bean);
List.Append (Value);
end loop;
-- Verify each bean of the list
for J in 1 .. 1_000 + 1 loop
Value := List.Element (J - 1);
-- Check some common status.
T.Assert (not Is_Null (Value), "The value should hold a bean");
T.Assert (Get_Type (Value) = TYPE_BEAN, "The value should hold a bean");
T.Assert (not Is_Empty (Value), "The value should not be empty");
-- Check the bean access.
P := To_Bean (Value);
T.Assert (P /= null, "To_Bean returned null");
Bean := Bean_Type'Class (P.all)'Access;
-- Check we have the good bean object.
if I = J then
Assert_Equals (T, "Static", To_String (Bean.Name),
"Bean at" & Integer'Image (J) & " is invalid");
elsif J > I then
Assert_Equals (T, "B" & Util.Strings.Image (J - 1), To_String (Bean.Name),
"Bean at" & Integer'Image (J) & " is invalid");
else
Assert_Equals (T, "B" & Util.Strings.Image (J), To_String (Bean.Name),
"Bean at" & Integer'Image (J) & " is invalid");
end if;
end loop;
end;
end loop;
end Test_Bean;
end Util.Beans.Objects.Record_Tests;
|
-----------------------------------------------------------------------
-- util-beans-objects-record_tests -- Unit tests for objects.records package
-- 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.Test_Caller;
with Util.Strings;
with Util.Beans.Basic;
with Util.Beans.Objects.Vectors;
with Util.Beans.Objects.Records;
package body Util.Beans.Objects.Record_Tests is
use Util.Tests;
package Caller is new Util.Test_Caller (Test, "Objects.Records");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test Util.Beans.Objects.Records",
Test_Record'Access);
Caller.Add_Test (Suite, "Test Util.Beans.Basic",
Test_Bean'Access);
end Add_Tests;
type Data is record
Name : Unbounded_String;
Value : Util.Beans.Objects.Object;
end record;
package Data_Bean is new Util.Beans.Objects.Records (Data);
use type Data_Bean.Element_Type_Access;
subtype Data_Access is Data_Bean.Element_Type_Access;
procedure Test_Record (T : in out Test) is
D : Data;
begin
D.Name := To_Unbounded_String ("testing");
D.Value := To_Object (Integer (23));
declare
V : Object := Data_Bean.To_Object (D);
P : constant Data_Access := Data_Bean.To_Element_Access (V);
V2 : constant Object := V;
begin
T.Assert (not Is_Empty (V), "Object with data record should not be empty");
T.Assert (not Is_Null (V), "Object with data record should not be null");
T.Assert (P /= null, "To_Element_Access returned null");
Assert_Equals (T, "testing", To_String (P.Name), "Data name is not the same");
Assert_Equals (T, 23, To_Integer (P.Value), "Data value is not the same");
V := Data_Bean.Create;
declare
D2 : constant Data_Access := Data_Bean.To_Element_Access (V);
begin
T.Assert (D2 /= null, "Null element");
D2.Name := To_Unbounded_String ("second test");
D2.Value := V2;
end;
V := Data_Bean.To_Object (D);
end;
end Test_Record;
type Bean_Type is new Util.Beans.Basic.Readonly_Bean with record
Name : Unbounded_String;
end record;
type Bean_Type_Access is access all Bean_Type'Class;
overriding
function Get_Value (Bean : in Bean_Type;
Name : in String) return Util.Beans.Objects.Object;
overriding
function Get_Value (Bean : in Bean_Type;
Name : in String) return Util.Beans.Objects.Object is
begin
if Name = "name" then
return Util.Beans.Objects.To_Object (Bean.Name);
elsif Name = "length" then
return Util.Beans.Objects.To_Object (Length (Bean.Name));
else
return Util.Beans.Objects.Null_Object;
end if;
end Get_Value;
procedure Test_Bean (T : in out Test) is
use Basic;
Static : aliased Bean_Type;
begin
Static.Name := To_Unbounded_String ("Static");
-- Allocate dynamically several Bean_Type objects and drop the list.
-- The memory held by internal proxy as well as the Bean_Type must be freed.
-- The static bean should never be freed!
for I in 1 .. 10 loop
declare
List : Util.Beans.Objects.Vectors.Vector;
Value : Util.Beans.Objects.Object;
Bean : Bean_Type_Access;
P : access Readonly_Bean'Class;
begin
for J in 1 .. 1_000 loop
if I = J then
Value := To_Object (Static'Unchecked_Access, Objects.STATIC);
List.Append (Value);
end if;
Bean := new Bean_Type;
Bean.Name := To_Unbounded_String ("B" & Util.Strings.Image (J));
Value := To_Object (Bean);
List.Append (Value);
end loop;
-- Verify each bean of the list
for J in 1 .. 1_000 + 1 loop
Value := List.Element (J - 1);
-- Check some common status.
T.Assert (not Is_Null (Value), "The value should hold a bean");
T.Assert (Get_Type (Value) = TYPE_BEAN, "The value should hold a bean");
T.Assert (not Is_Empty (Value), "The value should not be empty");
-- Check the bean access.
P := To_Bean (Value);
T.Assert (P /= null, "To_Bean returned null");
Bean := Bean_Type'Class (P.all)'Unchecked_Access;
-- Check we have the good bean object.
if I = J then
Assert_Equals (T, "Static", To_String (Bean.Name),
"Bean at" & Integer'Image (J) & " is invalid");
elsif J > I then
Assert_Equals (T, "B" & Util.Strings.Image (J - 1), To_String (Bean.Name),
"Bean at" & Integer'Image (J) & " is invalid");
else
Assert_Equals (T, "B" & Util.Strings.Image (J), To_String (Bean.Name),
"Bean at" & Integer'Image (J) & " is invalid");
end if;
end loop;
end;
end loop;
end Test_Bean;
end Util.Beans.Objects.Record_Tests;
|
Fix compilation error
|
Fix compilation error
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
8a448ccc919c9815f2b803b5f1d499338752c8b1
|
awa/plugins/awa-mail/src/aws/awa-mail-clients-aws_smtp.adb
|
awa/plugins/awa-mail/src/aws/awa-mail-clients-aws_smtp.adb
|
-----------------------------------------------------------------------
-- awa-mail-clients-aws_smtp -- Mail client implementation on top of AWS SMTP client
-- Copyright (C) 2012, 2016, 2017, 2020 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Unchecked_Deallocation;
with AWS.SMTP.Client;
with Util.Log.Loggers;
package body AWA.Mail.Clients.AWS_SMTP is
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("AWA.Mail.Clients.AWS_SMTP");
procedure Free is
new Ada.Unchecked_Deallocation (Object => AWS.SMTP.Recipients,
Name => Recipients_Access);
-- Get a printable representation of the email recipients.
function Image (Recipients : in AWS.SMTP.Recipients) return String;
-- ------------------------------
-- Set the <tt>From</tt> part of the message.
-- ------------------------------
overriding
procedure Set_From (Message : in out AWS_Mail_Message;
Name : in String;
Address : in String) is
begin
Message.From := AWS.SMTP.E_Mail (Name => Name,
Address => Address);
end Set_From;
-- ------------------------------
-- Add a recipient for the message.
-- ------------------------------
overriding
procedure Add_Recipient (Message : in out AWS_Mail_Message;
Kind : in Recipient_Type;
Name : in String;
Address : in String) is
pragma Unreferenced (Kind);
begin
if Message.To = null then
Message.To := new AWS.SMTP.Recipients (1 .. 1);
else
declare
To : constant Recipients_Access := new AWS.SMTP.Recipients (1 .. Message.To'Last + 1);
begin
To (Message.To'Range) := Message.To.all;
Free (Message.To);
Message.To := To;
end;
end if;
Message.To (Message.To'Last) := AWS.SMTP.E_Mail (Name => Name,
Address => Address);
end Add_Recipient;
-- ------------------------------
-- Set the subject of the message.
-- ------------------------------
overriding
procedure Set_Subject (Message : in out AWS_Mail_Message;
Subject : in String) is
begin
Message.Subject := To_Unbounded_String (Subject);
end Set_Subject;
-- ------------------------------
-- Set the body of the message.
-- ------------------------------
overriding
procedure Set_Body (Message : in out AWS_Mail_Message;
Content : in Unbounded_String;
Alternative : in Unbounded_String;
Content_Type : in String) is
begin
if Length (Alternative) = 0 then
AWS.Attachments.Add (Message.Attachments, "",
AWS.Attachments.Value (To_String (Content)));
else
AWS.Attachments.Add (Message.Attachments, "",
AWS.Attachments.Value (To_String (Content),
Content_Type => Content_Type));
end if;
end Set_Body;
-- ------------------------------
-- Add an attachment with the given content.
-- ------------------------------
overriding
procedure Add_Attachment (Message : in out AWS_Mail_Message;
Content : in Unbounded_String;
Content_Id : in String;
Content_Type : in String) is
Data : constant AWS.Attachments.Content
:= AWS.Attachments.Value (Data => To_String (Content),
Content_Id => Content_Id,
Content_Type => Content_Type);
begin
AWS.Attachments.Add (Attachments => Message.Attachments,
Name => Content_Id,
Data => Data);
end Add_Attachment;
-- ------------------------------
-- Get a printable representation of the email recipients.
-- ------------------------------
function Image (Recipients : in AWS.SMTP.Recipients) return String is
Result : Unbounded_String;
begin
for I in Recipients'Range loop
Append (Result, AWS.SMTP.Image (Recipients (I)));
end loop;
return To_String (Result);
end Image;
-- ------------------------------
-- Send the email message.
-- ------------------------------
overriding
procedure Send (Message : in out AWS_Mail_Message) is
Result : AWS.SMTP.Status;
begin
if Message.To = null then
return;
end if;
if Message.Manager.Enable then
Log.Info ("Send email from {0} to {1}",
AWS.SMTP.Image (Message.From), Image (Message.To.all));
AWS.SMTP.Client.Send (Server => Message.Manager.Server,
From => Message.From,
To => Message.To.all,
Subject => To_String (Message.Subject),
Attachments => Message.Attachments,
Status => Result);
if not AWS.SMTP.Is_Ok (Result) then
Log.Error ("Cannot send email: {0}",
AWS.SMTP.Status_Message (Result));
end if;
else
Log.Info ("Disable send email from {0} to {1}",
AWS.SMTP.Image (Message.From), Image (Message.To.all));
end if;
end Send;
-- ------------------------------
-- Deletes the mail message.
-- ------------------------------
overriding
procedure Finalize (Message : in out AWS_Mail_Message) is
begin
Log.Info ("Finalize mail message");
Free (Message.To);
end Finalize;
procedure Initialize (Client : in out AWS_Mail_Manager'Class;
Props : in Util.Properties.Manager'Class) is separate;
-- ------------------------------
-- Create a SMTP based mail manager and configure it according to the properties.
-- ------------------------------
function Create_Manager (Props : in Util.Properties.Manager'Class) return Mail_Manager_Access is
Server : constant String := Props.Get (Name => "smtp.host", Default => "localhost");
Port : constant String := Props.Get (Name => "smtp.port", Default => "25");
Enable : constant String := Props.Get (Name => "smtp.enable", Default => "1");
Result : constant AWS_Mail_Manager_Access := new AWS_Mail_Manager;
begin
Log.Info ("Creating SMTP mail manager to server {0}:{1}", Server, Port);
Result.Port := Positive'Value (Port);
Result.Enable := Enable = "1" or Enable = "yes" or Enable = "true";
Result.Self := Result;
Initialize (Result.all, Props);
return Result.all'Access;
end Create_Manager;
-- ------------------------------
-- Create a new mail message.
-- ------------------------------
overriding
function Create_Message (Manager : in AWS_Mail_Manager) return Mail_Message_Access is
Result : constant AWS_Mail_Message_Access := new AWS_Mail_Message;
begin
Result.Manager := Manager.Self;
return Result.all'Access;
end Create_Message;
end AWA.Mail.Clients.AWS_SMTP;
|
-----------------------------------------------------------------------
-- awa-mail-clients-aws_smtp -- Mail client implementation on top of AWS SMTP client
-- Copyright (C) 2012, 2016, 2017, 2020 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Unchecked_Deallocation;
with AWS.SMTP.Client;
with Util.Log.Loggers;
package body AWA.Mail.Clients.AWS_SMTP is
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("AWA.Mail.Clients.AWS_SMTP");
procedure Free is
new Ada.Unchecked_Deallocation (Object => AWS.SMTP.Recipients,
Name => Recipients_Access);
-- Get a printable representation of the email recipients.
function Image (Recipients : in AWS.SMTP.Recipients) return String;
-- ------------------------------
-- Set the <tt>From</tt> part of the message.
-- ------------------------------
overriding
procedure Set_From (Message : in out AWS_Mail_Message;
Name : in String;
Address : in String) is
begin
Message.From := AWS.SMTP.E_Mail (Name => Name,
Address => Address);
end Set_From;
-- ------------------------------
-- Add a recipient for the message.
-- ------------------------------
overriding
procedure Add_Recipient (Message : in out AWS_Mail_Message;
Kind : in Recipient_Type;
Name : in String;
Address : in String) is
pragma Unreferenced (Kind);
begin
if Message.To = null then
Message.To := new AWS.SMTP.Recipients (1 .. 1);
else
declare
To : constant Recipients_Access := new AWS.SMTP.Recipients (1 .. Message.To'Last + 1);
begin
To (Message.To'Range) := Message.To.all;
Free (Message.To);
Message.To := To;
end;
end if;
Message.To (Message.To'Last) := AWS.SMTP.E_Mail (Name => Name,
Address => Address);
end Add_Recipient;
-- ------------------------------
-- Set the subject of the message.
-- ------------------------------
overriding
procedure Set_Subject (Message : in out AWS_Mail_Message;
Subject : in String) is
begin
Message.Subject := To_Unbounded_String (Subject);
end Set_Subject;
-- ------------------------------
-- Set the body of the message.
-- ------------------------------
overriding
procedure Set_Body (Message : in out AWS_Mail_Message;
Content : in Unbounded_String;
Alternative : in Unbounded_String;
Content_Type : in String) is
begin
if Length (Alternative) = 0 then
AWS.Attachments.Add (Message.Attachments, "",
AWS.Attachments.Value (To_String (Content)));
else
declare
Parts : AWS.Attachments.Alternatives;
begin
AWS.Attachments.Add (Parts,
AWS.Attachments.Value (To_String (Content),
Content_Type => Content_Type));
AWS.Attachments.Add (Parts,
AWS.Attachments.Value (To_String (Alternative),
Content_Type => "text/plain"));
AWS.Attachments.Add (Message.Attachments, Parts);
end;
end if;
end Set_Body;
-- ------------------------------
-- Add an attachment with the given content.
-- ------------------------------
overriding
procedure Add_Attachment (Message : in out AWS_Mail_Message;
Content : in Unbounded_String;
Content_Id : in String;
Content_Type : in String) is
Data : constant AWS.Attachments.Content
:= AWS.Attachments.Value (Data => To_String (Content),
Content_Id => Content_Id,
Content_Type => Content_Type);
begin
AWS.Attachments.Add (Attachments => Message.Attachments,
Name => Content_Id,
Data => Data);
end Add_Attachment;
-- ------------------------------
-- Get a printable representation of the email recipients.
-- ------------------------------
function Image (Recipients : in AWS.SMTP.Recipients) return String is
Result : Unbounded_String;
begin
for I in Recipients'Range loop
Append (Result, AWS.SMTP.Image (Recipients (I)));
end loop;
return To_String (Result);
end Image;
-- ------------------------------
-- Send the email message.
-- ------------------------------
overriding
procedure Send (Message : in out AWS_Mail_Message) is
Result : AWS.SMTP.Status;
begin
if Message.To = null then
return;
end if;
if Message.Manager.Enable then
Log.Info ("Send email from {0} to {1}",
AWS.SMTP.Image (Message.From), Image (Message.To.all));
AWS.SMTP.Client.Send (Server => Message.Manager.Server,
From => Message.From,
To => Message.To.all,
Subject => To_String (Message.Subject),
Attachments => Message.Attachments,
Status => Result);
if not AWS.SMTP.Is_Ok (Result) then
Log.Error ("Cannot send email: {0}",
AWS.SMTP.Status_Message (Result));
end if;
else
Log.Info ("Disable send email from {0} to {1}",
AWS.SMTP.Image (Message.From), Image (Message.To.all));
end if;
end Send;
-- ------------------------------
-- Deletes the mail message.
-- ------------------------------
overriding
procedure Finalize (Message : in out AWS_Mail_Message) is
begin
Log.Info ("Finalize mail message");
Free (Message.To);
end Finalize;
procedure Initialize (Client : in out AWS_Mail_Manager'Class;
Props : in Util.Properties.Manager'Class) is separate;
-- ------------------------------
-- Create a SMTP based mail manager and configure it according to the properties.
-- ------------------------------
function Create_Manager (Props : in Util.Properties.Manager'Class) return Mail_Manager_Access is
Server : constant String := Props.Get (Name => "smtp.host", Default => "localhost");
Port : constant String := Props.Get (Name => "smtp.port", Default => "25");
Enable : constant String := Props.Get (Name => "smtp.enable", Default => "1");
Result : constant AWS_Mail_Manager_Access := new AWS_Mail_Manager;
begin
Log.Info ("Creating SMTP mail manager to server {0}:{1}", Server, Port);
Result.Port := Positive'Value (Port);
Result.Enable := Enable = "1" or Enable = "yes" or Enable = "true";
Result.Self := Result;
Initialize (Result.all, Props);
return Result.all'Access;
end Create_Manager;
-- ------------------------------
-- Create a new mail message.
-- ------------------------------
overriding
function Create_Message (Manager : in AWS_Mail_Manager) return Mail_Message_Access is
Result : constant AWS_Mail_Message_Access := new AWS_Mail_Message;
begin
Result.Manager := Manager.Self;
return Result.all'Access;
end Create_Message;
end AWA.Mail.Clients.AWS_SMTP;
|
Fix the creation of the multipart/alternative mail
|
Fix the creation of the multipart/alternative mail
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
8802488687979817a31fdfcf1d7c75b905e52aa5
|
src/el-methods-proc_in.ads
|
src/el-methods-proc_in.ads
|
-----------------------------------------------------------------------
-- EL.Methods.Proc_in -- Procedure Binding with 1 in argument
-- 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 EL.Expressions;
with EL.Contexts;
with Util.Beans.Methods;
with Util.Beans.Basic;
generic
type Param1_Type (<>) is limited private;
package EL.Methods.Proc_In is
use Util.Beans.Methods;
-- Returns True if the method is a valid method which accepts the arguments
-- defined by the package instantiation.
function Is_Valid (Method : in EL.Expressions.Method_Info) return Boolean;
-- Execute the method describe by the method expression
-- and with the given context. The method signature is:
--
-- procedure F (Obj : in out <Bean>;
-- Param : in out Param1_Type);
--
-- where <Bean> inherits from <b>Readonly_Bean</b>
-- (See <b>Bind</b> package)
--
-- Raises <b>Invalid_Method</b> if the method referenced by
-- the method expression does not exist or does not match
-- the signature.
procedure Execute (Method : in EL.Expressions.Method_Expression'Class;
Param : in Param1_Type;
Context : in EL.Contexts.ELContext'Class);
-- Execute the method describe by the method binding object.
-- The method signature is:
--
-- procedure F (Obj : in out <Bean>;
-- Param : in out Param1_Type);
--
-- where <Bean> inherits from <b>Readonly_Bean</b>
-- (See <b>Bind</b> package)
--
-- Raises <b>Invalid_Method</b> if the method referenced by
-- the method expression does not exist or does not match
-- the signature.
procedure Execute (Method : in EL.Expressions.Method_Info;
Param : in Param1_Type);
-- Function access to the proxy.
type Proxy_Access is
access procedure (O : access Util.Beans.Basic.Readonly_Bean'Class;
P : in Param1_Type);
-- The binding record which links the method name
-- to the proxy function.
type Binding is new Method_Binding with record
Method : Proxy_Access;
end record;
type Binding_Access is access constant Binding;
-- Proxy for the binding.
-- The proxy declares the binding definition that links
-- the name to the function and it implements the necessary
-- object conversion to translate the <b>Readonly_Bean</b>
-- object to the target object type.
generic
-- Name of the method (as exposed in the EL expression)
Name : String;
-- The bean type
type Bean is abstract new Util.Beans.Basic.Readonly_Bean with private;
-- The bean method to invoke
with procedure Method (O : in out Bean;
P1 : in Param1_Type);
package Bind is
-- Method that <b>Execute</b> will invoke.
procedure Method_Access (O : access Util.Beans.Basic.Readonly_Bean'Class;
P1 : in Param1_Type);
F_NAME : aliased constant String := Name;
-- The proxy binding that can be exposed through
-- the <b>Method_Bean</b> interface.
Proxy : aliased constant Binding
:= Binding '(Name => F_NAME'Access,
Method => Method_Access'Access);
end Bind;
end EL.Methods.Proc_In;
|
-----------------------------------------------------------------------
-- EL.Methods.Proc_in -- Procedure Binding with 1 in argument
-- 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 EL.Expressions;
with EL.Contexts;
with Util.Beans.Methods;
with Util.Beans.Basic;
generic
type Param1_Type (<>) is limited private;
package EL.Methods.Proc_In is
use Util.Beans.Methods;
-- Returns True if the method is a valid method which accepts the arguments
-- defined by the package instantiation.
function Is_Valid (Method : in EL.Expressions.Method_Info) return Boolean;
-- Execute the method describe by the method expression
-- and with the given context. The method signature is:
--
-- procedure F (Obj : in out <Bean>;
-- Param : in out Param1_Type);
--
-- where <Bean> inherits from <b>Readonly_Bean</b>
-- (See <b>Bind</b> package)
--
-- Raises <b>Invalid_Method</b> if the method referenced by
-- the method expression does not exist or does not match
-- the signature.
procedure Execute (Method : in EL.Expressions.Method_Expression'Class;
Param : in Param1_Type;
Context : in EL.Contexts.ELContext'Class);
-- Execute the method describe by the method binding object.
-- The method signature is:
--
-- procedure F (Obj : in out <Bean>;
-- Param : in out Param1_Type);
--
-- where <Bean> inherits from <b>Readonly_Bean</b>
-- (See <b>Bind</b> package)
--
-- Raises <b>Invalid_Method</b> if the method referenced by
-- the method expression does not exist or does not match
-- the signature.
procedure Execute (Method : in EL.Expressions.Method_Info;
Param : in Param1_Type);
-- Function access to the proxy.
type Proxy_Access is
access procedure (O : access Util.Beans.Basic.Readonly_Bean'Class;
P : in Param1_Type);
-- The binding record which links the method name
-- to the proxy function.
type Binding is new Method_Binding with record
Method : Proxy_Access;
end record;
type Binding_Access is access constant Binding;
-- Proxy for the binding.
-- The proxy declares the binding definition that links
-- the name to the function and it implements the necessary
-- object conversion to translate the <b>Readonly_Bean</b>
-- object to the target object type.
generic
-- Name of the method (as exposed in the EL expression)
Name : String;
-- The bean type
type Bean is abstract limited new Util.Beans.Basic.Readonly_Bean with private;
-- The bean method to invoke
with procedure Method (O : in out Bean;
P1 : in Param1_Type);
package Bind is
-- Method that <b>Execute</b> will invoke.
procedure Method_Access (O : access Util.Beans.Basic.Readonly_Bean'Class;
P1 : in Param1_Type);
F_NAME : aliased constant String := Name;
-- The proxy binding that can be exposed through
-- the <b>Method_Bean</b> interface.
Proxy : aliased constant Binding
:= Binding '(Name => F_NAME'Access,
Method => Method_Access'Access);
end Bind;
end EL.Methods.Proc_In;
|
Change the Bean generic parameter to be a limited type
|
Change the Bean generic parameter to be a limited type
|
Ada
|
apache-2.0
|
stcarrez/ada-el
|
e6bacc8217e896b0cac41bcc62033e7e2e573e59
|
src/base/commands/util-commands-drivers.ads
|
src/base/commands/util-commands-drivers.ads
|
-----------------------------------------------------------------------
-- util-commands-drivers -- Support to make command line tools
-- Copyright (C) 2017, 2018, 2019 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Log;
with Util.Commands.Parsers;
private with Ada.Strings.Unbounded;
private with Ada.Containers.Ordered_Sets;
-- == Command line driver ==
-- The `Util.Commands.Drivers` generic package provides a support to build command line
-- tools that have different commands identified by a name. It defines the `Driver_Type`
-- tagged record that provides a registry of application commands. It gives entry points
-- to register commands and execute them.
--
-- The `Context_Type` package parameter defines the type for the `Context` parameter
-- that is passed to the command when it is executed. It can be used to provide
-- application specific context to the command.
--
-- The `Config_Parser` describes the parser package that will handle the analysis of
-- command line options. To use the GNAT options parser, it is possible to use the
-- `Util.Commands.Parsers.GNAT_Parser` package.
generic
-- The command execution context.
type Context_Type (<>) is limited private;
with package Config_Parser is new Util.Commands.Parsers.Config_Parser (<>);
Driver_Name : String := "Drivers";
package Util.Commands.Drivers is
subtype Config_Type is Config_Parser.Config_Type;
-- A simple command handler executed when the command with the given name is executed.
type Command_Handler is not null access procedure (Name : in String;
Args : in Argument_List'Class;
Context : in out Context_Type);
-- A more complex command handler that has a command instance as context.
type Command_Type is abstract tagged limited private;
type Command_Access is access all Command_Type'Class;
-- Get the description associated with the command.
function Get_Description (Command : in Command_Type) return String;
-- Get the name used to register the command.
function Get_Name (Command : in Command_Type) return String;
-- Execute the command with the arguments. The command name is passed with the command
-- arguments.
procedure Execute (Command : in out Command_Type;
Name : in String;
Args : in Argument_List'Class;
Context : in out Context_Type) is abstract;
-- Setup the command before parsing the arguments and executing it.
procedure Setup (Command : in out Command_Type;
Config : in out Config_Type;
Context : in out Context_Type) is null;
-- Write the help associated with the command.
procedure Help (Command : in out Command_Type;
Name : in String;
Context : in out Context_Type) is abstract;
-- Write the command usage.
procedure Usage (Command : in out Command_Type;
Name : in String;
Context : in out Context_Type);
-- Print a message for the command. The level indicates whether the message is an error,
-- warning or informational. The command name can be used to known the originator.
-- The <tt>Log</tt> operation is redirected to the driver's <tt>Log</tt> procedure.
procedure Log (Command : in Command_Type;
Level : in Util.Log.Level_Type;
Name : in String;
Message : in String);
type Help_Command_Type is new Command_Type with private;
-- Execute the help command with the arguments.
-- Print the help for every registered command.
overriding
procedure Execute (Command : in out Help_Command_Type;
Name : in String;
Args : in Argument_List'Class;
Context : in out Context_Type);
-- Write the help associated with the command.
overriding
procedure Help (Command : in out Help_Command_Type;
Name : in String;
Context : in out Context_Type);
type Driver_Type is tagged limited private;
-- Report the command usage.
procedure Usage (Driver : in Driver_Type;
Args : in Argument_List'Class;
Context : in out Context_Type;
Name : in String := "");
-- Set the driver description printed in the usage.
procedure Set_Description (Driver : in out Driver_Type;
Description : in String);
-- Set the driver usage printed in the usage.
procedure Set_Usage (Driver : in out Driver_Type;
Usage : in String);
-- Register the command under the given name.
procedure Add_Command (Driver : in out Driver_Type;
Name : in String;
Command : in Command_Access);
procedure Add_Command (Driver : in out Driver_Type;
Name : in String;
Description : in String;
Command : in Command_Access);
-- Register the command under the given name.
procedure Add_Command (Driver : in out Driver_Type;
Name : in String;
Description : in String;
Handler : in Command_Handler);
-- Find the command having the given name.
-- Returns null if the command was not found.
function Find_Command (Driver : in Driver_Type;
Name : in String) return Command_Access;
-- Execute the command registered under the given name.
procedure Execute (Driver : in Driver_Type;
Name : in String;
Args : in Argument_List'Class;
Context : in out Context_Type);
-- Print a message for the command. The level indicates whether the message is an error,
-- warning or informational. The command name can be used to known the originator.
procedure Log (Driver : in Driver_Type;
Level : in Util.Log.Level_Type;
Name : in String;
Message : in String);
private
type Command_Type is abstract tagged limited record
Driver : access Driver_Type'Class;
Name : Ada.Strings.Unbounded.Unbounded_String;
Description : Ada.Strings.Unbounded.Unbounded_String;
end record;
function "<" (Left, Right : in Command_Access) return Boolean is
(Ada.Strings.Unbounded."<" (Left.Name, Right.Name));
package Command_Sets is
new Ada.Containers.Ordered_Sets (Element_Type => Command_Access,
"<" => "<",
"=" => "=");
type Help_Command_Type is new Command_Type with null record;
type Handler_Command_Type is new Command_Type with record
Handler : Command_Handler;
end record;
-- Execute the command with the arguments.
overriding
procedure Execute (Command : in out Handler_Command_Type;
Name : in String;
Args : in Argument_List'Class;
Context : in out Context_Type);
-- Write the help associated with the command.
overriding
procedure Help (Command : in out Handler_Command_Type;
Name : in String;
Context : in out Context_Type);
type Driver_Type is tagged limited record
List : Command_Sets.Set;
Desc : Ada.Strings.Unbounded.Unbounded_String;
Usage : Ada.Strings.Unbounded.Unbounded_String;
end record;
end Util.Commands.Drivers;
|
-----------------------------------------------------------------------
-- util-commands-drivers -- Support to make command line tools
-- Copyright (C) 2017, 2018, 2019 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Log;
with Util.Commands.Parsers;
private with Ada.Strings.Unbounded;
private with Ada.Containers.Ordered_Sets;
-- == Command line driver ==
-- The `Util.Commands.Drivers` generic package provides a support to build command line
-- tools that have different commands identified by a name. It defines the `Driver_Type`
-- tagged record that provides a registry of application commands. It gives entry points
-- to register commands and execute them.
--
-- The `Context_Type` package parameter defines the type for the `Context` parameter
-- that is passed to the command when it is executed. It can be used to provide
-- application specific context to the command.
--
-- The `Config_Parser` describes the parser package that will handle the analysis of
-- command line options. To use the GNAT options parser, it is possible to use the
-- `Util.Commands.Parsers.GNAT_Parser` package.
generic
-- The command execution context.
type Context_Type (<>) is limited private;
with package Config_Parser is new Util.Commands.Parsers.Config_Parser (<>);
with function Translate (Message : in String) return String is No_Translate;
Driver_Name : String := "Drivers";
package Util.Commands.Drivers is
subtype Config_Type is Config_Parser.Config_Type;
-- A simple command handler executed when the command with the given name is executed.
type Command_Handler is not null access procedure (Name : in String;
Args : in Argument_List'Class;
Context : in out Context_Type);
-- A more complex command handler that has a command instance as context.
type Command_Type is abstract tagged limited private;
type Command_Access is access all Command_Type'Class;
-- Get the description associated with the command.
function Get_Description (Command : in Command_Type) return String;
-- Get the name used to register the command.
function Get_Name (Command : in Command_Type) return String;
-- Execute the command with the arguments. The command name is passed with the command
-- arguments.
procedure Execute (Command : in out Command_Type;
Name : in String;
Args : in Argument_List'Class;
Context : in out Context_Type) is abstract;
-- Setup the command before parsing the arguments and executing it.
procedure Setup (Command : in out Command_Type;
Config : in out Config_Type;
Context : in out Context_Type) is null;
-- Write the help associated with the command.
procedure Help (Command : in out Command_Type;
Name : in String;
Context : in out Context_Type) is abstract;
-- Write the command usage.
procedure Usage (Command : in out Command_Type;
Name : in String;
Context : in out Context_Type);
-- Print a message for the command. The level indicates whether the message is an error,
-- warning or informational. The command name can be used to known the originator.
-- The <tt>Log</tt> operation is redirected to the driver's <tt>Log</tt> procedure.
procedure Log (Command : in Command_Type;
Level : in Util.Log.Level_Type;
Name : in String;
Message : in String);
type Help_Command_Type is new Command_Type with private;
-- Execute the help command with the arguments.
-- Print the help for every registered command.
overriding
procedure Execute (Command : in out Help_Command_Type;
Name : in String;
Args : in Argument_List'Class;
Context : in out Context_Type);
-- Write the help associated with the command.
overriding
procedure Help (Command : in out Help_Command_Type;
Name : in String;
Context : in out Context_Type);
type Driver_Type is tagged limited private;
-- Report the command usage.
procedure Usage (Driver : in Driver_Type;
Args : in Argument_List'Class;
Context : in out Context_Type;
Name : in String := "");
-- Set the driver description printed in the usage.
procedure Set_Description (Driver : in out Driver_Type;
Description : in String);
-- Set the driver usage printed in the usage.
procedure Set_Usage (Driver : in out Driver_Type;
Usage : in String);
-- Register the command under the given name.
procedure Add_Command (Driver : in out Driver_Type;
Name : in String;
Command : in Command_Access);
procedure Add_Command (Driver : in out Driver_Type;
Name : in String;
Description : in String;
Command : in Command_Access);
-- Register the command under the given name.
procedure Add_Command (Driver : in out Driver_Type;
Name : in String;
Description : in String;
Handler : in Command_Handler);
-- Find the command having the given name.
-- Returns null if the command was not found.
function Find_Command (Driver : in Driver_Type;
Name : in String) return Command_Access;
-- Execute the command registered under the given name.
procedure Execute (Driver : in Driver_Type;
Name : in String;
Args : in Argument_List'Class;
Context : in out Context_Type);
-- Print a message for the command. The level indicates whether the message is an error,
-- warning or informational. The command name can be used to known the originator.
procedure Log (Driver : in Driver_Type;
Level : in Util.Log.Level_Type;
Name : in String;
Message : in String);
private
type Command_Type is abstract tagged limited record
Driver : access Driver_Type'Class;
Name : Ada.Strings.Unbounded.Unbounded_String;
Description : Ada.Strings.Unbounded.Unbounded_String;
end record;
function "<" (Left, Right : in Command_Access) return Boolean is
(Ada.Strings.Unbounded."<" (Left.Name, Right.Name));
package Command_Sets is
new Ada.Containers.Ordered_Sets (Element_Type => Command_Access,
"<" => "<",
"=" => "=");
type Help_Command_Type is new Command_Type with null record;
type Handler_Command_Type is new Command_Type with record
Handler : Command_Handler;
end record;
-- Execute the command with the arguments.
overriding
procedure Execute (Command : in out Handler_Command_Type;
Name : in String;
Args : in Argument_List'Class;
Context : in out Context_Type);
-- Write the help associated with the command.
overriding
procedure Help (Command : in out Handler_Command_Type;
Name : in String;
Context : in out Context_Type);
type Driver_Type is tagged limited record
List : Command_Sets.Set;
Desc : Ada.Strings.Unbounded.Unbounded_String;
Usage : Ada.Strings.Unbounded.Unbounded_String;
end record;
end Util.Commands.Drivers;
|
Add Translate function with optional No_Translate default to allow i18n/l10n
|
Add Translate function with optional No_Translate default to allow i18n/l10n
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
4bb1beec12c4152646ab71a0d66afd10fc97e708
|
src/security-permissions.ads
|
src/security-permissions.ads
|
-----------------------------------------------------------------------
-- security-permissions -- Definition of permissions
-- Copyright (C) 2010, 2011 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Finalization;
with Ada.Strings.Unbounded;
with Ada.Containers.Hashed_Maps;
with Ada.Containers.Vectors;
with Util.Strings;
with Util.Refs;
with Util.Beans.Objects;
with Util.Beans.Objects.Vectors;
with Util.Serialize.IO.XML;
with GNAT.Regexp;
limited with Security.Controllers;
limited with Security.Contexts;
-- == Permissions ==
-- The <b>Security.Permissions</b> package defines the different permissions that can be
-- checked by the access control manager.
--
-- === Principal ===
-- The <tt>Principal</tt> is the entity that can be authenticated. A principal is obtained
-- after successful authentication of a user or of a system through an authorization process.
-- The OpenID or OAuth authentication processes generate such security principal.
--
-- === Permission ===
-- The <tt>Permission</tt> represents an access to a system or application resource.
--
package Security.Permissions is
-- EL function name exposed by Set_Functions.
HAS_PERMISSION_FN : constant String := "hasPermission";
-- URI for the EL functions exposed by the security package (See Set_Functions).
AUTH_NAMESPACE_URI : constant String := "http://code.google.com/p/ada-asf/auth";
Invalid_Name : exception;
type Security_Context_Access is access all Contexts.Security_Context'Class;
type Permission_Index is new Natural;
type Controller_Access is access all Security.Controllers.Controller'Class;
type Controller_Access_Array is array (Permission_Index range <>) of Controller_Access;
-- Get the permission index associated with the name.
function Get_Permission_Index (Name : in String) return Permission_Index;
-- Get the last permission index registered in the global permission map.
function Get_Last_Permission_Index return Permission_Index;
-- Add the permission name and allocate a unique permission index.
procedure Add_Permission (Name : in String;
Index : out Permission_Index);
-- The permission root class.
type Abstract_Permission is abstract tagged limited null record;
-- Each role is represented by a <b>Role_Type</b> number to provide a fast
-- and efficient role check.
type Role_Type is new Natural range 0 .. 63;
type Role_Type_Array is array (Positive range <>) of Role_Type;
-- The <b>Role_Map</b> represents a set of roles which are assigned to a user.
-- Each role is represented by a boolean in the map. The implementation is limited
-- to 64 roles (the number of different permissions can be higher).
type Role_Map is array (Role_Type'Range) of Boolean;
pragma Pack (Role_Map);
-- Each permission is represented by a <b>Permission_Type</b> number to provide a fast
-- and efficient permission check.
type Permission_Type is new Natural range 0 .. 63;
-- The <b>Permission_Map</b> represents a set of permissions which are granted to a user.
-- Each permission is represented by a boolean in the map. The implementation is limited
-- to 64 permissions.
type Permission_Map is array (Permission_Type'Range) of Boolean;
pragma Pack (Permission_Map);
-- ------------------------------
-- Principal
-- ------------------------------
type Principal is limited interface;
type Principal_Access is access all Principal'Class;
-- Returns true if the given role is stored in the user principal.
function Has_Role (User : in Principal;
Role : in Role_Type) return Boolean is abstract;
-- Get the principal name.
function Get_Name (From : in Principal) return String is abstract;
-- ------------------------------
-- Permission
-- ------------------------------
-- Represents a permission for a given role.
type Permission (Role : Permission_Type) is new Abstract_Permission with null record;
-- ------------------------------
-- URI Permission
-- ------------------------------
-- Represents a permission to access a given URI.
type URI_Permission (Len : Natural) is new Abstract_Permission with record
URI : String (1 .. Len);
end record;
-- ------------------------------
-- File Permission
-- ------------------------------
type File_Mode is (READ, WRITE);
-- Represents a permission to access a given file.
type File_Permission (Len : Natural;
Mode : File_Mode) is new Abstract_Permission with record
Path : String (1 .. Len);
end record;
-- ------------------------------
-- Permission Manager
-- ------------------------------
-- The <b>Permission_Manager</b> verifies through some policy that a permission
-- is granted to a user.
type Permission_Manager is new Ada.Finalization.Limited_Controlled with private;
type Permission_Manager_Access is access all Permission_Manager'Class;
procedure Add_Permission (Manager : in out Permission_Manager;
Name : in String;
Permission : in Controller_Access);
-- Find the role type associated with the role name identified by <b>Name</b>.
-- Raises <b>Invalid_Name</b> if there is no role type.
function Find_Role (Manager : in Permission_Manager;
Name : in String) return Role_Type;
-- Returns True if the user has the permission to access the given URI permission.
function Has_Permission (Manager : in Permission_Manager;
Context : in Security_Context_Access;
Permission : in URI_Permission'Class) return Boolean;
-- Returns True if the user has the given role permission.
function Has_Permission (Manager : in Permission_Manager;
User : in Principal'Class;
Permission : in Permission_Type) return Boolean;
-- Get the security controller associated with the permission index <b>Index</b>.
-- Returns null if there is no such controller.
function Get_Controller (Manager : in Permission_Manager'Class;
Index : in Permission_Index) return Controller_Access;
pragma Inline_Always (Get_Controller);
-- Get the role name.
function Get_Role_Name (Manager : in Permission_Manager;
Role : in Role_Type) return String;
-- Create a role
procedure Create_Role (Manager : in out Permission_Manager;
Name : in String;
Role : out Role_Type);
-- Get or add a role type for the given name.
procedure Add_Role_Type (Manager : in out Permission_Manager;
Name : in String;
Result : out Role_Type);
-- Grant the permission to access to the given <b>URI</b> to users having the <b>To</b>
-- permissions.
procedure Grant_URI_Permission (Manager : in out Permission_Manager;
URI : in String;
To : in String);
-- Grant the permission to access to the given <b>Path</b> to users having the <b>To</b>
-- permissions.
procedure Grant_File_Permission (Manager : in out Permission_Manager;
Path : in String;
To : in String);
-- Read the policy file
procedure Read_Policy (Manager : in out Permission_Manager;
File : in String);
-- Initialize the permission manager.
overriding
procedure Initialize (Manager : in out Permission_Manager);
-- Finalize the permission manager.
overriding
procedure Finalize (Manager : in out Permission_Manager);
generic
Name : String;
package Permission_ACL is
function Permission return Permission_Index;
pragma Inline_Always (Permission);
end Permission_ACL;
-- ------------------------------
-- Policy Configuration
-- ------------------------------
type Policy_Config is record
Id : Natural := 0;
Permissions : Util.Beans.Objects.Vectors.Vector;
Patterns : Util.Beans.Objects.Vectors.Vector;
Manager : Permission_Manager_Access;
end record;
type Policy_Config_Access is access all Policy_Config;
-- Setup the XML parser to read the <b>policy</b> description. For example:
--
-- <policy id='1'>
-- <permission>create-workspace</permission>
-- <permission>admin</permission>
-- <url-pattern>/workspace/create</url-pattern>
-- <url-pattern>/workspace/setup/*</url-pattern>
-- </policy>
--
-- This policy gives access to the URL that match one of the URL pattern if the
-- security context has the permission <b>create-workspace</b> or <b>admin</b>.
generic
Reader : in out Util.Serialize.IO.XML.Parser;
Manager : in Security.Permissions.Permission_Manager_Access;
package Reader_Config is
Config : aliased Policy_Config;
end Reader_Config;
-- Register a set of functions in the namespace
-- xmlns:fn="http://code.google.com/p/ada-asf/auth"
-- Functions:
-- hasPermission(NAME) -- Returns True if the permission NAME is granted
-- procedure Set_Functions (Mapper : in out EL.Functions.Function_Mapper'Class);
private
use Util.Strings;
type Role_Name_Array is
array (Role_Type'Range) of Ada.Strings.Unbounded.String_Access;
type Permission_Type_Array is array (1 .. 10) of Permission_Type;
type Permission_Index_Array is array (Positive range <>) of Permission_Index;
-- The <b>Access_Rule</b> represents a list of permissions to verify to grant
-- access to the resource. To make it simple, the user must have one of the
-- permission from the list. Each permission will refer to a specific permission
-- controller.
type Access_Rule (Count : Natural) is new Util.Refs.Ref_Entity with record
Permissions : Permission_Index_Array (1 .. Count);
end record;
type Access_Rule_Access is access all Access_Rule;
package Access_Rule_Refs is
new Util.Refs.Indefinite_References (Element_Type => Access_Rule,
Element_Access => Access_Rule_Access);
subtype Access_Rule_Ref is Access_Rule_Refs.Ref;
-- No rule
-- No_Rule : constant Access_Rule := (Count => 0,
-- Permissions => (others => Permission_Index'First));
-- Find the access rule of the policy that matches the given URI.
-- Returns the No_Rule value (disable access) if no rule is found.
function Find_Access_Rule (Manager : in Permission_Manager;
URI : in String) return Access_Rule_Ref;
-- The <b>Policy</b> defines the access rules that are applied on a given
-- URL, set of URLs or files.
type Policy is record
Id : Natural;
Pattern : GNAT.Regexp.Regexp;
Rule : Access_Rule_Ref;
end record;
-- The <b>Policy_Vector</b> represents the whole permission policy. The order of
-- policy in the list is important as policies can override each other.
package Policy_Vector is new Ada.Containers.Vectors (Index_Type => Positive,
Element_Type => Policy);
package Rules_Maps is new Ada.Containers.Hashed_Maps (Key_Type => String_Ref,
Element_Type => Access_Rule_Ref,
Hash => Hash,
Equivalent_Keys => Equivalent_Keys,
"=" => Access_Rule_Refs."=");
type Rules is new Util.Refs.Ref_Entity with record
Map : Rules_Maps.Map;
end record;
type Rules_Access is access all Rules;
package Rules_Ref is new Util.Refs.References (Rules, Rules_Access);
type Rules_Ref_Access is access Rules_Ref.Atomic_Ref;
type Controller_Access_Array_Access is access all Controller_Access_Array;
type Permission_Manager is new Ada.Finalization.Limited_Controlled with record
Names : Role_Name_Array;
Cache : Rules_Ref_Access;
Next_Role : Role_Type := Role_Type'First;
Policies : Policy_Vector.Vector;
Permissions : Controller_Access_Array_Access;
Last_Index : Permission_Index := Permission_Index'First;
end record;
-- EL function to check if the given permission name is granted by the current
-- security context.
function Has_Permission (Value : in Util.Beans.Objects.Object)
return Util.Beans.Objects.Object;
end Security.Permissions;
|
-----------------------------------------------------------------------
-- security-permissions -- Definition of permissions
-- Copyright (C) 2010, 2011, 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Finalization;
with Ada.Strings.Unbounded;
with Ada.Containers.Hashed_Maps;
with Ada.Containers.Vectors;
with Util.Strings;
with Util.Refs;
with Util.Beans.Objects;
with Util.Beans.Objects.Vectors;
with Util.Serialize.IO.XML;
with GNAT.Regexp;
limited with Security.Controllers;
limited with Security.Contexts;
-- == Permissions ==
-- The <b>Security.Permissions</b> package defines the different permissions that can be
-- checked by the access control manager.
--
-- === Principal ===
-- The <tt>Principal</tt> is the entity that can be authenticated. A principal is obtained
-- after successful authentication of a user or of a system through an authorization process.
-- The OpenID or OAuth authentication processes generate such security principal.
--
-- === Permission ===
-- The <tt>Permission</tt> represents an access to a system or application resource.
-- A permission is checked by using the security manager. The security manager uses a
-- security controller to enforce the permission.
--
package Security.Permissions is
-- EL function name exposed by Set_Functions.
HAS_PERMISSION_FN : constant String := "hasPermission";
-- URI for the EL functions exposed by the security package (See Set_Functions).
AUTH_NAMESPACE_URI : constant String := "http://code.google.com/p/ada-asf/auth";
Invalid_Name : exception;
type Security_Context_Access is access all Contexts.Security_Context'Class;
type Permission_Index is new Natural;
type Controller_Access is access all Security.Controllers.Controller'Class;
type Controller_Access_Array is array (Permission_Index range <>) of Controller_Access;
-- Get the permission index associated with the name.
function Get_Permission_Index (Name : in String) return Permission_Index;
-- Get the last permission index registered in the global permission map.
function Get_Last_Permission_Index return Permission_Index;
-- Add the permission name and allocate a unique permission index.
procedure Add_Permission (Name : in String;
Index : out Permission_Index);
-- The permission root class.
type Abstract_Permission is abstract tagged limited null record;
-- Each role is represented by a <b>Role_Type</b> number to provide a fast
-- and efficient role check.
type Role_Type is new Natural range 0 .. 63;
type Role_Type_Array is array (Positive range <>) of Role_Type;
-- The <b>Role_Map</b> represents a set of roles which are assigned to a user.
-- Each role is represented by a boolean in the map. The implementation is limited
-- to 64 roles (the number of different permissions can be higher).
type Role_Map is array (Role_Type'Range) of Boolean;
pragma Pack (Role_Map);
-- Each permission is represented by a <b>Permission_Type</b> number to provide a fast
-- and efficient permission check.
type Permission_Type is new Natural range 0 .. 63;
-- The <b>Permission_Map</b> represents a set of permissions which are granted to a user.
-- Each permission is represented by a boolean in the map. The implementation is limited
-- to 64 permissions.
type Permission_Map is array (Permission_Type'Range) of Boolean;
pragma Pack (Permission_Map);
-- ------------------------------
-- Principal
-- ------------------------------
type Principal is limited interface;
type Principal_Access is access all Principal'Class;
-- Returns true if the given role is stored in the user principal.
function Has_Role (User : in Principal;
Role : in Role_Type) return Boolean is abstract;
-- Get the principal name.
function Get_Name (From : in Principal) return String is abstract;
-- ------------------------------
-- Permission
-- ------------------------------
-- Represents a permission for a given role.
type Permission (Role : Permission_Type) is new Abstract_Permission with null record;
-- ------------------------------
-- URI Permission
-- ------------------------------
-- Represents a permission to access a given URI.
type URI_Permission (Len : Natural) is new Abstract_Permission with record
URI : String (1 .. Len);
end record;
-- ------------------------------
-- File Permission
-- ------------------------------
type File_Mode is (READ, WRITE);
-- Represents a permission to access a given file.
type File_Permission (Len : Natural;
Mode : File_Mode) is new Abstract_Permission with record
Path : String (1 .. Len);
end record;
-- ------------------------------
-- Permission Manager
-- ------------------------------
-- The <b>Permission_Manager</b> verifies through some policy that a permission
-- is granted to a user.
type Permission_Manager is new Ada.Finalization.Limited_Controlled with private;
type Permission_Manager_Access is access all Permission_Manager'Class;
procedure Add_Permission (Manager : in out Permission_Manager;
Name : in String;
Permission : in Controller_Access);
-- Find the role type associated with the role name identified by <b>Name</b>.
-- Raises <b>Invalid_Name</b> if there is no role type.
function Find_Role (Manager : in Permission_Manager;
Name : in String) return Role_Type;
-- Returns True if the user has the permission to access the given URI permission.
function Has_Permission (Manager : in Permission_Manager;
Context : in Security_Context_Access;
Permission : in URI_Permission'Class) return Boolean;
-- Returns True if the user has the given role permission.
function Has_Permission (Manager : in Permission_Manager;
User : in Principal'Class;
Permission : in Permission_Type) return Boolean;
-- Get the security controller associated with the permission index <b>Index</b>.
-- Returns null if there is no such controller.
function Get_Controller (Manager : in Permission_Manager'Class;
Index : in Permission_Index) return Controller_Access;
pragma Inline_Always (Get_Controller);
-- Get the role name.
function Get_Role_Name (Manager : in Permission_Manager;
Role : in Role_Type) return String;
-- Create a role
procedure Create_Role (Manager : in out Permission_Manager;
Name : in String;
Role : out Role_Type);
-- Get or add a role type for the given name.
procedure Add_Role_Type (Manager : in out Permission_Manager;
Name : in String;
Result : out Role_Type);
-- Grant the permission to access to the given <b>URI</b> to users having the <b>To</b>
-- permissions.
procedure Grant_URI_Permission (Manager : in out Permission_Manager;
URI : in String;
To : in String);
-- Grant the permission to access to the given <b>Path</b> to users having the <b>To</b>
-- permissions.
procedure Grant_File_Permission (Manager : in out Permission_Manager;
Path : in String;
To : in String);
-- Read the policy file
procedure Read_Policy (Manager : in out Permission_Manager;
File : in String);
-- Initialize the permission manager.
overriding
procedure Initialize (Manager : in out Permission_Manager);
-- Finalize the permission manager.
overriding
procedure Finalize (Manager : in out Permission_Manager);
generic
Name : String;
package Permission_ACL is
function Permission return Permission_Index;
pragma Inline_Always (Permission);
end Permission_ACL;
-- ------------------------------
-- Policy Configuration
-- ------------------------------
type Policy_Config is record
Id : Natural := 0;
Permissions : Util.Beans.Objects.Vectors.Vector;
Patterns : Util.Beans.Objects.Vectors.Vector;
Manager : Permission_Manager_Access;
end record;
type Policy_Config_Access is access all Policy_Config;
-- Setup the XML parser to read the <b>policy</b> description. For example:
--
-- <policy id='1'>
-- <permission>create-workspace</permission>
-- <permission>admin</permission>
-- <url-pattern>/workspace/create</url-pattern>
-- <url-pattern>/workspace/setup/*</url-pattern>
-- </policy>
--
-- This policy gives access to the URL that match one of the URL pattern if the
-- security context has the permission <b>create-workspace</b> or <b>admin</b>.
generic
Reader : in out Util.Serialize.IO.XML.Parser;
Manager : in Security.Permissions.Permission_Manager_Access;
package Reader_Config is
Config : aliased Policy_Config;
end Reader_Config;
-- Register a set of functions in the namespace
-- xmlns:fn="http://code.google.com/p/ada-asf/auth"
-- Functions:
-- hasPermission(NAME) -- Returns True if the permission NAME is granted
-- procedure Set_Functions (Mapper : in out EL.Functions.Function_Mapper'Class);
private
use Util.Strings;
type Role_Name_Array is
array (Role_Type'Range) of Ada.Strings.Unbounded.String_Access;
type Permission_Type_Array is array (1 .. 10) of Permission_Type;
type Permission_Index_Array is array (Positive range <>) of Permission_Index;
-- The <b>Access_Rule</b> represents a list of permissions to verify to grant
-- access to the resource. To make it simple, the user must have one of the
-- permission from the list. Each permission will refer to a specific permission
-- controller.
type Access_Rule (Count : Natural) is new Util.Refs.Ref_Entity with record
Permissions : Permission_Index_Array (1 .. Count);
end record;
type Access_Rule_Access is access all Access_Rule;
package Access_Rule_Refs is
new Util.Refs.Indefinite_References (Element_Type => Access_Rule,
Element_Access => Access_Rule_Access);
subtype Access_Rule_Ref is Access_Rule_Refs.Ref;
-- No rule
-- No_Rule : constant Access_Rule := (Count => 0,
-- Permissions => (others => Permission_Index'First));
-- Find the access rule of the policy that matches the given URI.
-- Returns the No_Rule value (disable access) if no rule is found.
function Find_Access_Rule (Manager : in Permission_Manager;
URI : in String) return Access_Rule_Ref;
-- The <b>Policy</b> defines the access rules that are applied on a given
-- URL, set of URLs or files.
type Policy is record
Id : Natural;
Pattern : GNAT.Regexp.Regexp;
Rule : Access_Rule_Ref;
end record;
-- The <b>Policy_Vector</b> represents the whole permission policy. The order of
-- policy in the list is important as policies can override each other.
package Policy_Vector is new Ada.Containers.Vectors (Index_Type => Positive,
Element_Type => Policy);
package Rules_Maps is new Ada.Containers.Hashed_Maps (Key_Type => String_Ref,
Element_Type => Access_Rule_Ref,
Hash => Hash,
Equivalent_Keys => Equivalent_Keys,
"=" => Access_Rule_Refs."=");
type Rules is new Util.Refs.Ref_Entity with record
Map : Rules_Maps.Map;
end record;
type Rules_Access is access all Rules;
package Rules_Ref is new Util.Refs.References (Rules, Rules_Access);
type Rules_Ref_Access is access Rules_Ref.Atomic_Ref;
type Controller_Access_Array_Access is access all Controller_Access_Array;
type Permission_Manager is new Ada.Finalization.Limited_Controlled with record
Names : Role_Name_Array;
Cache : Rules_Ref_Access;
Next_Role : Role_Type := Role_Type'First;
Policies : Policy_Vector.Vector;
Permissions : Controller_Access_Array_Access;
Last_Index : Permission_Index := Permission_Index'First;
end record;
-- EL function to check if the given permission name is granted by the current
-- security context.
function Has_Permission (Value : in Util.Beans.Objects.Object)
return Util.Beans.Objects.Object;
end Security.Permissions;
|
Document the permission
|
Document the permission
|
Ada
|
apache-2.0
|
Letractively/ada-security
|
7413363f3e929215e8832e1d01e5be8e29b497f6
|
src/asf-models-selects.adb
|
src/asf-models-selects.adb
|
-----------------------------------------------------------------------
-- asf-models-selects -- Data model for UISelectOne and UISelectMany
-- Copyright (C) 2011, 2012, 2013, 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.UTF_Encoding.Wide_Wide_Strings;
package body ASF.Models.Selects is
function UTF8_Decode (S : in String) return Wide_Wide_String
renames Ada.Strings.UTF_Encoding.Wide_Wide_Strings.Decode;
-- ------------------------------
-- Return an Object from the select item record.
-- Returns a NULL object if the item is empty.
-- ------------------------------
function To_Object (Item : in Select_Item) return Util.Beans.Objects.Object is
begin
if Item.Item.Is_Null then
return Util.Beans.Objects.Null_Object;
else
declare
Bean : constant Select_Item_Access := new Select_Item;
begin
Bean.all := Item;
return Util.Beans.Objects.To_Object (Bean.all'Access);
end;
end if;
end To_Object;
-- ------------------------------
-- Return the <b>Select_Item</b> instance from a generic bean object.
-- Returns an empty item if the object does not hold a <b>Select_Item</b>.
-- ------------------------------
function To_Select_Item (Object : in Util.Beans.Objects.Object) return Select_Item is
Bean : constant access Util.Beans.Basic.Readonly_Bean'Class
:= Util.Beans.Objects.To_Bean (Object);
Result : Select_Item;
begin
if Bean = null then
return Result;
end if;
if not (Bean.all in Select_Item'Class) then
return Result;
end if;
Result := Select_Item (Bean.all);
return Result;
end To_Select_Item;
-- ------------------------------
-- Creates a <b>Select_Item</b> with the specified label and value.
-- ------------------------------
function Create_Select_Item (Label : in String;
Value : in String;
Description : in String := "";
Disabled : in Boolean := False;
Escaped : in Boolean := True) return Select_Item is
Result : Select_Item;
begin
Result.Item := Select_Item_Refs.Create;
declare
Item : constant Select_Item_Record_Access := Result.Item.Value;
begin
Item.Label := To_Unbounded_Wide_Wide_String (UTF8_Decode (Label));
Item.Value := To_Unbounded_Wide_Wide_String (UTF8_Decode (Value));
Item.Description := To_Unbounded_Wide_Wide_String (UTF8_Decode (Description));
Item.Disabled := Disabled;
Item.Escape := Escaped;
end;
return Result;
end Create_Select_Item;
-- ------------------------------
-- Creates a <b>Select_Item</b> with the specified label and value.
-- ------------------------------
function Create_Select_Item_Wide (Label : in Wide_Wide_String;
Value : in Wide_Wide_String;
Description : in Wide_Wide_String := "";
Disabled : in Boolean := False;
Escaped : in Boolean := True) return Select_Item is
Result : Select_Item;
begin
Result.Item := Select_Item_Refs.Create;
declare
Item : constant Select_Item_Record_Access := Result.Item.Value;
begin
Item.Label := To_Unbounded_Wide_Wide_String (Label);
Item.Value := To_Unbounded_Wide_Wide_String (Value);
Item.Description := To_Unbounded_Wide_Wide_String (Description);
Item.Disabled := Disabled;
Item.Escape := Escaped;
end;
return Result;
end Create_Select_Item_Wide;
-- ------------------------------
-- Creates a <b>Select_Item</b> with the specified label, value and description.
-- The objects are converted to a wide wide string. The empty string is used if they
-- are null.
-- ------------------------------
function Create_Select_Item (Label : in Util.Beans.Objects.Object;
Value : in Util.Beans.Objects.Object;
Description : in Util.Beans.Objects.Object;
Disabled : in Boolean := False;
Escaped : in Boolean := True) return Select_Item is
use Util.Beans.Objects;
Result : Select_Item;
begin
Result.Item := Select_Item_Refs.Create;
declare
Item : constant Select_Item_Record_Access := Result.Item.Value;
begin
if not Is_Null (Label) then
Item.Label := To_Unbounded_Wide_Wide_String (Label);
end if;
if not Is_Null (Value) then
Item.Value := To_Unbounded_Wide_Wide_String (Value);
end if;
if not Is_Null (Description) then
Item.Description := To_Unbounded_Wide_Wide_String (Description);
end if;
Item.Disabled := Disabled;
Item.Escape := Escaped;
end;
return Result;
end Create_Select_Item;
-- ------------------------------
-- Get the item label.
-- ------------------------------
function Get_Label (Item : in Select_Item) return Wide_Wide_String is
begin
if Item.Item.Is_Null then
return "";
else
return To_Wide_Wide_String (Item.Item.Value.Label);
end if;
end Get_Label;
-- ------------------------------
-- Get the item value.
-- ------------------------------
function Get_Value (Item : in Select_Item) return Wide_Wide_String is
begin
if Item.Item.Is_Null then
return "";
else
return To_Wide_Wide_String (Item.Item.Value.Value);
end if;
end Get_Value;
-- ------------------------------
-- Get the item description.
-- ------------------------------
function Get_Description (Item : in Select_Item) return Wide_Wide_String is
begin
if Item.Item.Is_Null then
return "";
else
return To_Wide_Wide_String (Item.Item.Value.Description);
end if;
end Get_Description;
-- ------------------------------
-- Returns true if the item is disabled.
-- ------------------------------
function Is_Disabled (Item : in Select_Item) return Boolean is
begin
if Item.Item.Is_Null then
return False;
else
return Item.Item.Value.Disabled;
end if;
end Is_Disabled;
-- ------------------------------
-- Returns true if the label must be escaped using HTML escape rules.
-- ------------------------------
function Is_Escaped (Item : in Select_Item) return Boolean is
begin
if Item.Item.Is_Null then
return False;
else
return Item.Item.Value.Escape;
end if;
end Is_Escaped;
-- ------------------------------
-- Returns true if the select item component is empty.
-- ------------------------------
function Is_Empty (Item : in Select_Item) return Boolean is
begin
return Item.Item.Is_Null;
end Is_Empty;
-- ------------------------------
-- 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 Select_Item;
Name : in String) return Util.Beans.Objects.Object is
begin
if From.Item.Is_Null then
return Util.Beans.Objects.Null_Object;
end if;
declare
Item : constant Select_Item_Record_Access := From.Item.Value;
begin
if Name = "name" then
return Util.Beans.Objects.To_Object (Item.Label);
elsif Name = "value" then
return Util.Beans.Objects.To_Object (Item.Value);
elsif Name = "description" then
return Util.Beans.Objects.To_Object (Item.Description);
elsif Name = "disabled" then
return Util.Beans.Objects.To_Object (Item.Disabled);
elsif Name = "escaped" then
return Util.Beans.Objects.To_Object (Item.Escape);
else
return Util.Beans.Objects.Null_Object;
end if;
end;
end Get_Value;
-- ------------------------------
-- Select Item List
-- ------------------------------
-- ------------------------------
-- Return an Object from the select item list.
-- Returns a NULL object if the list is empty.
-- ------------------------------
function To_Object (Item : in Select_Item_List) return Util.Beans.Objects.Object is
begin
if Item.List.Is_Null then
return Util.Beans.Objects.Null_Object;
else
declare
Bean : constant Select_Item_List_Access := new Select_Item_List;
begin
Bean.all := Item;
return Util.Beans.Objects.To_Object (Bean.all'Access);
end;
end if;
end To_Object;
-- ------------------------------
-- Return the <b>Select_Item_List</b> instance from a generic bean object.
-- Returns an empty list if the object does not hold a <b>Select_Item_List</b>.
-- ------------------------------
function To_Select_Item_List (Object : in Util.Beans.Objects.Object) return Select_Item_List is
Bean : constant access Util.Beans.Basic.Readonly_Bean'Class
:= Util.Beans.Objects.To_Bean (Object);
Result : Select_Item_List;
begin
if Bean = null then
return Result;
end if;
if not (Bean.all in Select_Item_List'Class) then
return Result;
end if;
Result := Select_Item_List (Bean.all);
return Result;
end To_Select_Item_List;
-- ------------------------------
-- Get the number of elements in the list.
-- ------------------------------
overriding
function Get_Count (From : in Select_Item_List) return Natural is
begin
return From.Length;
end Get_Count;
-- ------------------------------
-- Set the current row index. Valid row indexes start at 1.
-- ------------------------------
overriding
procedure Set_Row_Index (From : in out Select_Item_List;
Index : in Natural) is
begin
From.Current := From.Get_Select_Item (Index);
From.Row := Util.Beans.Objects.To_Object (From.Current'Unchecked_Access,
Util.Beans.Objects.STATIC);
end Set_Row_Index;
-- ------------------------------
-- Get the element at the current row index.
-- ------------------------------
overriding
function Get_Row (From : in Select_Item_List) return Util.Beans.Objects.Object is
begin
return From.Row;
end Get_Row;
-- ------------------------------
-- Get the number of items in the list.
-- ------------------------------
function Length (List : in Select_Item_List) return Natural is
begin
if List.List.Is_Null then
return 0;
else
return Natural (List.List.Value.List.Length);
end if;
end Length;
-- ------------------------------
-- Get the select item from the list
-- ------------------------------
function Get_Select_Item (List : in Select_Item_List'Class;
Pos : in Positive) return Select_Item is
begin
if List.List.Is_Null then
raise Constraint_Error with "Select item list is empty";
end if;
return List.List.Value.List.Element (Pos);
end Get_Select_Item;
-- ------------------------------
-- Add the item at the end of the list.
-- ------------------------------
procedure Append (List : in out Select_Item_List;
Item : in Select_Item'Class) is
begin
if List.List.Is_Null then
List.List := Select_Item_Vector_Refs.Create;
end if;
List.List.Value.all.List.Append (Select_Item (Item));
end Append;
-- ------------------------------
-- Add the item at the end of the list. This is a shortcut for
-- Append (Create_List_Item (Label, Value))
-- ------------------------------
procedure Append (List : in out Select_Item_List;
Label : in String;
Value : in String) is
begin
List.Append (Create_Select_Item (Label, Value));
end Append;
-- ------------------------------
-- 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 Select_Item_List;
Name : in String) return Util.Beans.Objects.Object is
pragma Unreferenced (From, Name);
begin
return Util.Beans.Objects.Null_Object;
end Get_Value;
end ASF.Models.Selects;
|
-----------------------------------------------------------------------
-- asf-models-selects -- Data model for UISelectOne and UISelectMany
-- Copyright (C) 2011, 2012, 2013, 2017, 2019 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.UTF_Encoding.Wide_Wide_Strings;
package body ASF.Models.Selects is
function UTF8_Decode (S : in String) return Wide_Wide_String
renames Ada.Strings.UTF_Encoding.Wide_Wide_Strings.Decode;
-- ------------------------------
-- Return an Object from the select item record.
-- Returns a NULL object if the item is empty.
-- ------------------------------
function To_Object (Item : in Select_Item) return Util.Beans.Objects.Object is
begin
if Item.Item.Is_Null then
return Util.Beans.Objects.Null_Object;
else
declare
Bean : constant Select_Item_Access := new Select_Item;
begin
Bean.all := Item;
return Util.Beans.Objects.To_Object (Bean.all'Access);
end;
end if;
end To_Object;
-- ------------------------------
-- Return the <b>Select_Item</b> instance from a generic bean object.
-- Returns an empty item if the object does not hold a <b>Select_Item</b>.
-- ------------------------------
function To_Select_Item (Object : in Util.Beans.Objects.Object) return Select_Item is
Bean : constant access Util.Beans.Basic.Readonly_Bean'Class
:= Util.Beans.Objects.To_Bean (Object);
Result : Select_Item;
begin
if Bean = null then
return Result;
end if;
if not (Bean.all in Select_Item'Class) then
return Result;
end if;
Result := Select_Item (Bean.all);
return Result;
end To_Select_Item;
-- ------------------------------
-- Creates a <b>Select_Item</b> with the specified label and value.
-- ------------------------------
function Create_Select_Item (Label : in String;
Value : in String;
Description : in String := "";
Disabled : in Boolean := False;
Escaped : in Boolean := True) return Select_Item is
Result : Select_Item;
begin
Result.Item := Select_Item_Refs.Create;
declare
Item : constant Select_Item_Record_Accessor := Result.Item.Value;
begin
Item.Label := To_Unbounded_Wide_Wide_String (UTF8_Decode (Label));
Item.Value := To_Unbounded_Wide_Wide_String (UTF8_Decode (Value));
Item.Description := To_Unbounded_Wide_Wide_String (UTF8_Decode (Description));
Item.Disabled := Disabled;
Item.Escape := Escaped;
end;
return Result;
end Create_Select_Item;
-- ------------------------------
-- Creates a <b>Select_Item</b> with the specified label and value.
-- ------------------------------
function Create_Select_Item_Wide (Label : in Wide_Wide_String;
Value : in Wide_Wide_String;
Description : in Wide_Wide_String := "";
Disabled : in Boolean := False;
Escaped : in Boolean := True) return Select_Item is
Result : Select_Item;
begin
Result.Item := Select_Item_Refs.Create;
declare
Item : constant Select_Item_Record_Accessor := Result.Item.Value;
begin
Item.Label := To_Unbounded_Wide_Wide_String (Label);
Item.Value := To_Unbounded_Wide_Wide_String (Value);
Item.Description := To_Unbounded_Wide_Wide_String (Description);
Item.Disabled := Disabled;
Item.Escape := Escaped;
end;
return Result;
end Create_Select_Item_Wide;
-- ------------------------------
-- Creates a <b>Select_Item</b> with the specified label, value and description.
-- The objects are converted to a wide wide string. The empty string is used if they
-- are null.
-- ------------------------------
function Create_Select_Item (Label : in Util.Beans.Objects.Object;
Value : in Util.Beans.Objects.Object;
Description : in Util.Beans.Objects.Object;
Disabled : in Boolean := False;
Escaped : in Boolean := True) return Select_Item is
use Util.Beans.Objects;
Result : Select_Item;
begin
Result.Item := Select_Item_Refs.Create;
declare
Item : constant Select_Item_Record_Accessor := Result.Item.Value;
begin
if not Is_Null (Label) then
Item.Label := To_Unbounded_Wide_Wide_String (Label);
end if;
if not Is_Null (Value) then
Item.Value := To_Unbounded_Wide_Wide_String (Value);
end if;
if not Is_Null (Description) then
Item.Description := To_Unbounded_Wide_Wide_String (Description);
end if;
Item.Disabled := Disabled;
Item.Escape := Escaped;
end;
return Result;
end Create_Select_Item;
-- ------------------------------
-- Get the item label.
-- ------------------------------
function Get_Label (Item : in Select_Item) return Wide_Wide_String is
begin
if Item.Item.Is_Null then
return "";
else
return To_Wide_Wide_String (Item.Item.Value.Label);
end if;
end Get_Label;
-- ------------------------------
-- Get the item value.
-- ------------------------------
function Get_Value (Item : in Select_Item) return Wide_Wide_String is
begin
if Item.Item.Is_Null then
return "";
else
return To_Wide_Wide_String (Item.Item.Value.Value);
end if;
end Get_Value;
-- ------------------------------
-- Get the item description.
-- ------------------------------
function Get_Description (Item : in Select_Item) return Wide_Wide_String is
begin
if Item.Item.Is_Null then
return "";
else
return To_Wide_Wide_String (Item.Item.Value.Description);
end if;
end Get_Description;
-- ------------------------------
-- Returns true if the item is disabled.
-- ------------------------------
function Is_Disabled (Item : in Select_Item) return Boolean is
begin
if Item.Item.Is_Null then
return False;
else
return Item.Item.Value.Disabled;
end if;
end Is_Disabled;
-- ------------------------------
-- Returns true if the label must be escaped using HTML escape rules.
-- ------------------------------
function Is_Escaped (Item : in Select_Item) return Boolean is
begin
if Item.Item.Is_Null then
return False;
else
return Item.Item.Value.Escape;
end if;
end Is_Escaped;
-- ------------------------------
-- Returns true if the select item component is empty.
-- ------------------------------
function Is_Empty (Item : in Select_Item) return Boolean is
begin
return Item.Item.Is_Null;
end Is_Empty;
-- ------------------------------
-- 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 Select_Item;
Name : in String) return Util.Beans.Objects.Object is
begin
if From.Item.Is_Null then
return Util.Beans.Objects.Null_Object;
end if;
declare
Item : constant Select_Item_Record_Accessor := From.Item.Value;
begin
if Name = "name" then
return Util.Beans.Objects.To_Object (Item.Label);
elsif Name = "value" then
return Util.Beans.Objects.To_Object (Item.Value);
elsif Name = "description" then
return Util.Beans.Objects.To_Object (Item.Description);
elsif Name = "disabled" then
return Util.Beans.Objects.To_Object (Item.Disabled);
elsif Name = "escaped" then
return Util.Beans.Objects.To_Object (Item.Escape);
else
return Util.Beans.Objects.Null_Object;
end if;
end;
end Get_Value;
-- ------------------------------
-- Select Item List
-- ------------------------------
-- ------------------------------
-- Return an Object from the select item list.
-- Returns a NULL object if the list is empty.
-- ------------------------------
function To_Object (Item : in Select_Item_List) return Util.Beans.Objects.Object is
begin
if Item.List.Is_Null then
return Util.Beans.Objects.Null_Object;
else
declare
Bean : constant Select_Item_List_Access := new Select_Item_List;
begin
Bean.all := Item;
return Util.Beans.Objects.To_Object (Bean.all'Access);
end;
end if;
end To_Object;
-- ------------------------------
-- Return the <b>Select_Item_List</b> instance from a generic bean object.
-- Returns an empty list if the object does not hold a <b>Select_Item_List</b>.
-- ------------------------------
function To_Select_Item_List (Object : in Util.Beans.Objects.Object) return Select_Item_List is
Bean : constant access Util.Beans.Basic.Readonly_Bean'Class
:= Util.Beans.Objects.To_Bean (Object);
Result : Select_Item_List;
begin
if Bean = null then
return Result;
end if;
if not (Bean.all in Select_Item_List'Class) then
return Result;
end if;
Result := Select_Item_List (Bean.all);
return Result;
end To_Select_Item_List;
-- ------------------------------
-- Get the number of elements in the list.
-- ------------------------------
overriding
function Get_Count (From : in Select_Item_List) return Natural is
begin
return From.Length;
end Get_Count;
-- ------------------------------
-- Set the current row index. Valid row indexes start at 1.
-- ------------------------------
overriding
procedure Set_Row_Index (From : in out Select_Item_List;
Index : in Natural) is
begin
From.Current := From.Get_Select_Item (Index);
From.Row := Util.Beans.Objects.To_Object (From.Current'Unchecked_Access,
Util.Beans.Objects.STATIC);
end Set_Row_Index;
-- ------------------------------
-- Get the element at the current row index.
-- ------------------------------
overriding
function Get_Row (From : in Select_Item_List) return Util.Beans.Objects.Object is
begin
return From.Row;
end Get_Row;
-- ------------------------------
-- Get the number of items in the list.
-- ------------------------------
function Length (List : in Select_Item_List) return Natural is
begin
if List.List.Is_Null then
return 0;
else
return Natural (List.List.Value.List.Length);
end if;
end Length;
-- ------------------------------
-- Get the select item from the list
-- ------------------------------
function Get_Select_Item (List : in Select_Item_List'Class;
Pos : in Positive) return Select_Item is
begin
if List.List.Is_Null then
raise Constraint_Error with "Select item list is empty";
end if;
return List.List.Value.List.Element (Pos);
end Get_Select_Item;
-- ------------------------------
-- Add the item at the end of the list.
-- ------------------------------
procedure Append (List : in out Select_Item_List;
Item : in Select_Item'Class) is
begin
if List.List.Is_Null then
List.List := Select_Item_Vector_Refs.Create;
end if;
List.List.Value.List.Append (Select_Item (Item));
end Append;
-- ------------------------------
-- Add the item at the end of the list. This is a shortcut for
-- Append (Create_List_Item (Label, Value))
-- ------------------------------
procedure Append (List : in out Select_Item_List;
Label : in String;
Value : in String) is
begin
List.Append (Create_Select_Item (Label, Value));
end Append;
-- ------------------------------
-- 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 Select_Item_List;
Name : in String) return Util.Beans.Objects.Object is
pragma Unreferenced (From, Name);
begin
return Util.Beans.Objects.Null_Object;
end Get_Value;
end ASF.Models.Selects;
|
Update to use Implicit_Deference
|
Update to use Implicit_Deference
|
Ada
|
apache-2.0
|
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
|
37a277b7fe2943e5d70ed4a91ae4fed3c42e7700
|
src/sys/encoders/util-encoders-hmac-sha256.ads
|
src/sys/encoders/util-encoders-hmac-sha256.ads
|
-----------------------------------------------------------------------
-- util-encoders-hmac-sha256 -- Compute HMAC-SHA256 authentication code
-- Copyright (C) 2017, 2019 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Streams;
with Ada.Finalization;
with Util.Encoders.SHA256;
-- The <b>Util.Encodes.HMAC.SHA256</b> package generates HMAC-SHA256 authentication
-- (See RFC 2104 - HMAC: Keyed-Hashing for Message Authentication).
package Util.Encoders.HMAC.SHA256 is
-- Sign the data string with the key and return the HMAC-SHA256 code in binary.
function Sign (Key : in String;
Data : in String) return Util.Encoders.SHA256.Hash_Array;
-- Sign the data string with the key and return the HMAC-SHA256 code as hexadecimal string.
function Sign (Key : in String;
Data : in String) return Util.Encoders.SHA256.Digest;
-- Sign the data array with the key and return the HMAC-SHA256 code in the result.
procedure Sign (Key : in Ada.Streams.Stream_Element_Array;
Data : in Ada.Streams.Stream_Element_Array;
Result : out Util.Encoders.SHA256.Hash_Array);
-- Sign the data string with the key and return the HMAC-SHA256 code as base64 string.
-- When <b>URL</b> is True, use the base64 URL alphabet to encode in base64.
function Sign_Base64 (Key : in String;
Data : in String;
URL : in Boolean := False) return Util.Encoders.SHA256.Base64_Digest;
-- ------------------------------
-- HMAC-SHA256 Context
-- ------------------------------
type Context is limited private;
-- Set the hmac private key. The key must be set before calling any <b>Update</b>
-- procedure.
procedure Set_Key (E : in out Context;
Key : in String);
-- Set the hmac private key. The key must be set before calling any <b>Update</b>
-- procedure.
procedure Set_Key (E : in out Context;
Key : in Ada.Streams.Stream_Element_Array);
-- Update the hash with the string.
procedure Update (E : in out Context;
S : in String);
-- Update the hash with the string.
procedure Update (E : in out Context;
S : in Ada.Streams.Stream_Element_Array);
-- Computes the HMAC-SHA256 with the private key and the data collected by
-- the <b>Update</b> procedures. Returns the raw binary hash in <b>Hash</b>.
procedure Finish (E : in out Context;
Hash : out Util.Encoders.SHA256.Hash_Array);
-- Computes the HMAC-SHA256 with the private key and the data collected by
-- the <b>Update</b> procedures. Returns the hexadecimal hash in <b>Hash</b>.
procedure Finish (E : in out Context;
Hash : out Util.Encoders.SHA256.Digest);
-- Computes the HMAC-SHA256 with the private key and the data collected by
-- the <b>Update</b> procedures. Returns the base64 hash in <b>Hash</b>.
-- When <b>URL</b> is True, use the base64 URL alphabet to encode in base64.
procedure Finish_Base64 (E : in out Context;
Hash : out Util.Encoders.SHA256.Base64_Digest;
URL : in Boolean := False);
private
type Context is new Ada.Finalization.Limited_Controlled with record
SHA : Util.Encoders.SHA256.Context;
Key : Ada.Streams.Stream_Element_Array (0 .. 63);
Key_Len : Ada.Streams.Stream_Element_Offset;
end record;
-- Initialize the SHA-1 context.
overriding
procedure Initialize (E : in out Context);
end Util.Encoders.HMAC.SHA256;
|
-----------------------------------------------------------------------
-- util-encoders-hmac-sha256 -- Compute HMAC-SHA256 authentication code
-- Copyright (C) 2017, 2019 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Streams;
with Ada.Finalization;
with Util.Encoders.SHA256;
-- The <b>Util.Encodes.HMAC.SHA256</b> package generates HMAC-SHA256 authentication
-- (See RFC 2104 - HMAC: Keyed-Hashing for Message Authentication).
package Util.Encoders.HMAC.SHA256 is
HASH_SIZE : constant := Util.Encoders.SHA256.HASH_SIZE;
-- Sign the data string with the key and return the HMAC-SHA256 code in binary.
function Sign (Key : in String;
Data : in String) return Util.Encoders.SHA256.Hash_Array;
-- Sign the data string with the key and return the HMAC-SHA256 code as hexadecimal string.
function Sign (Key : in String;
Data : in String) return Util.Encoders.SHA256.Digest;
-- Sign the data array with the key and return the HMAC-SHA256 code in the result.
procedure Sign (Key : in Ada.Streams.Stream_Element_Array;
Data : in Ada.Streams.Stream_Element_Array;
Result : out Util.Encoders.SHA256.Hash_Array);
-- Sign the data string with the key and return the HMAC-SHA256 code as base64 string.
-- When <b>URL</b> is True, use the base64 URL alphabet to encode in base64.
function Sign_Base64 (Key : in String;
Data : in String;
URL : in Boolean := False) return Util.Encoders.SHA256.Base64_Digest;
-- ------------------------------
-- HMAC-SHA256 Context
-- ------------------------------
type Context is limited private;
-- Set the hmac private key. The key must be set before calling any <b>Update</b>
-- procedure.
procedure Set_Key (E : in out Context;
Key : in String);
-- Set the hmac private key. The key must be set before calling any <b>Update</b>
-- procedure.
procedure Set_Key (E : in out Context;
Key : in Ada.Streams.Stream_Element_Array);
-- Update the hash with the string.
procedure Update (E : in out Context;
S : in String);
-- Update the hash with the string.
procedure Update (E : in out Context;
S : in Ada.Streams.Stream_Element_Array);
-- Computes the HMAC-SHA256 with the private key and the data collected by
-- the <b>Update</b> procedures. Returns the raw binary hash in <b>Hash</b>.
procedure Finish (E : in out Context;
Hash : out Util.Encoders.SHA256.Hash_Array);
-- Computes the HMAC-SHA256 with the private key and the data collected by
-- the <b>Update</b> procedures. Returns the hexadecimal hash in <b>Hash</b>.
procedure Finish (E : in out Context;
Hash : out Util.Encoders.SHA256.Digest);
-- Computes the HMAC-SHA256 with the private key and the data collected by
-- the <b>Update</b> procedures. Returns the base64 hash in <b>Hash</b>.
-- When <b>URL</b> is True, use the base64 URL alphabet to encode in base64.
procedure Finish_Base64 (E : in out Context;
Hash : out Util.Encoders.SHA256.Base64_Digest;
URL : in Boolean := False);
private
type Context is new Ada.Finalization.Limited_Controlled with record
SHA : Util.Encoders.SHA256.Context;
Key : Ada.Streams.Stream_Element_Array (0 .. 63);
Key_Len : Ada.Streams.Stream_Element_Offset;
end record;
-- Initialize the SHA-1 context.
overriding
procedure Initialize (E : in out Context);
end Util.Encoders.HMAC.SHA256;
|
Declare the HASH_SIZE constant
|
Declare the HASH_SIZE constant
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
f0afa4bf521540236c6aac268521c77cdea4017e
|
src/base/commands/util-commands-drivers.ads
|
src/base/commands/util-commands-drivers.ads
|
-----------------------------------------------------------------------
-- util-commands-drivers -- Support to make command line tools
-- Copyright (C) 2017, 2018, 2019 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Log;
with Util.Commands.Parsers;
private with Ada.Strings.Unbounded;
private with Ada.Containers.Indefinite_Ordered_Maps;
-- == Command line driver ==
-- The <tt>Util.Commands.Drivers</tt> generic package provides a support to build command line
-- tools that have different commands identified by a name.
generic
-- The command execution context.
type Context_Type (<>) is limited private;
with package Config_Parser is new Util.Commands.Parsers.Config_Parser (<>);
Driver_Name : String := "Drivers";
package Util.Commands.Drivers is
subtype Config_Type is Config_Parser.Config_Type;
-- A simple command handler executed when the command with the given name is executed.
type Command_Handler is not null access procedure (Name : in String;
Args : in Argument_List'Class;
Context : in out Context_Type);
-- A more complex command handler that has a command instance as context.
type Command_Type is abstract tagged limited private;
type Command_Access is access all Command_Type'Class;
-- Execute the command with the arguments. The command name is passed with the command
-- arguments.
procedure Execute (Command : in out Command_Type;
Name : in String;
Args : in Argument_List'Class;
Context : in out Context_Type) is abstract;
-- Setup the command before parsing the arguments and executing it.
procedure Setup (Command : in out Command_Type;
Config : in out Config_Type;
Context : in out Context_Type) is null;
-- Write the help associated with the command.
procedure Help (Command : in out Command_Type;
Context : in out Context_Type) is abstract;
-- Write the command usage.
procedure Usage (Command : in out Command_Type;
Name : in String;
Context : in out Context_Type);
-- Print a message for the command. The level indicates whether the message is an error,
-- warning or informational. The command name can be used to known the originator.
-- The <tt>Log</tt> operation is redirected to the driver's <tt>Log</tt> procedure.
procedure Log (Command : in Command_Type;
Level : in Util.Log.Level_Type;
Name : in String;
Message : in String);
type Help_Command_Type is new Command_Type with private;
-- Execute the help command with the arguments.
-- Print the help for every registered command.
overriding
procedure Execute (Command : in out Help_Command_Type;
Name : in String;
Args : in Argument_List'Class;
Context : in out Context_Type);
-- Write the help associated with the command.
procedure Help (Command : in out Help_Command_Type;
Context : in out Context_Type);
type Driver_Type is tagged limited private;
-- Report the command usage.
procedure Usage (Driver : in Driver_Type;
Args : in Argument_List'Class;
Context : in out Context_Type;
Name : in String := "");
-- Set the driver description printed in the usage.
procedure Set_Description (Driver : in out Driver_Type;
Description : in String);
-- Set the driver usage printed in the usage.
procedure Set_Usage (Driver : in out Driver_Type;
Usage : in String);
-- Register the command under the given name.
procedure Add_Command (Driver : in out Driver_Type;
Name : in String;
Command : in Command_Access);
procedure Add_Command (Driver : in out Driver_Type;
Name : in String;
Description : in String;
Command : in Command_Access);
-- Register the command under the given name.
procedure Add_Command (Driver : in out Driver_Type;
Name : in String;
Description : in String;
Handler : in Command_Handler);
-- Find the command having the given name.
-- Returns null if the command was not found.
function Find_Command (Driver : in Driver_Type;
Name : in String) return Command_Access;
-- Execute the command registered under the given name.
procedure Execute (Driver : in Driver_Type;
Name : in String;
Args : in Argument_List'Class;
Context : in out Context_Type);
-- Print a message for the command. The level indicates whether the message is an error,
-- warning or informational. The command name can be used to known the originator.
procedure Log (Driver : in Driver_Type;
Level : in Util.Log.Level_Type;
Name : in String;
Message : in String);
private
package Command_Maps is
new Ada.Containers.Indefinite_Ordered_Maps (Key_Type => String,
Element_Type => Command_Access,
"<" => "<");
type Command_Type is abstract tagged limited record
Driver : access Driver_Type'Class;
Description : Ada.Strings.Unbounded.Unbounded_String;
end record;
type Help_Command_Type is new Command_Type with null record;
type Handler_Command_Type is new Command_Type with record
Handler : Command_Handler;
end record;
-- Execute the command with the arguments.
overriding
procedure Execute (Command : in out Handler_Command_Type;
Name : in String;
Args : in Argument_List'Class;
Context : in out Context_Type);
-- Write the help associated with the command.
overriding
procedure Help (Command : in out Handler_Command_Type;
Context : in out Context_Type);
type Driver_Type is tagged limited record
List : Command_Maps.Map;
Desc : Ada.Strings.Unbounded.Unbounded_String;
Usage : Ada.Strings.Unbounded.Unbounded_String;
end record;
end Util.Commands.Drivers;
|
-----------------------------------------------------------------------
-- util-commands-drivers -- Support to make command line tools
-- Copyright (C) 2017, 2018, 2019 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Log;
with Util.Commands.Parsers;
private with Ada.Strings.Unbounded;
private with Ada.Containers.Indefinite_Ordered_Maps;
-- == Command line driver ==
-- The <tt>Util.Commands.Drivers</tt> generic package provides a support to build command line
-- tools that have different commands identified by a name.
generic
-- The command execution context.
type Context_Type (<>) is limited private;
with package Config_Parser is new Util.Commands.Parsers.Config_Parser (<>);
Driver_Name : String := "Drivers";
package Util.Commands.Drivers is
subtype Config_Type is Config_Parser.Config_Type;
-- A simple command handler executed when the command with the given name is executed.
type Command_Handler is not null access procedure (Name : in String;
Args : in Argument_List'Class;
Context : in out Context_Type);
-- A more complex command handler that has a command instance as context.
type Command_Type is abstract tagged limited private;
type Command_Access is access all Command_Type'Class;
-- Execute the command with the arguments. The command name is passed with the command
-- arguments.
procedure Execute (Command : in out Command_Type;
Name : in String;
Args : in Argument_List'Class;
Context : in out Context_Type) is abstract;
-- Setup the command before parsing the arguments and executing it.
procedure Setup (Command : in out Command_Type;
Config : in out Config_Type;
Context : in out Context_Type) is null;
-- Write the help associated with the command.
procedure Help (Command : in out Command_Type;
Name : in String;
Context : in out Context_Type) is abstract;
-- Write the command usage.
procedure Usage (Command : in out Command_Type;
Name : in String;
Context : in out Context_Type);
-- Print a message for the command. The level indicates whether the message is an error,
-- warning or informational. The command name can be used to known the originator.
-- The <tt>Log</tt> operation is redirected to the driver's <tt>Log</tt> procedure.
procedure Log (Command : in Command_Type;
Level : in Util.Log.Level_Type;
Name : in String;
Message : in String);
type Help_Command_Type is new Command_Type with private;
-- Execute the help command with the arguments.
-- Print the help for every registered command.
overriding
procedure Execute (Command : in out Help_Command_Type;
Name : in String;
Args : in Argument_List'Class;
Context : in out Context_Type);
-- Write the help associated with the command.
overriding
procedure Help (Command : in out Help_Command_Type;
Name : in String;
Context : in out Context_Type);
type Driver_Type is tagged limited private;
-- Report the command usage.
procedure Usage (Driver : in Driver_Type;
Args : in Argument_List'Class;
Context : in out Context_Type;
Name : in String := "");
-- Set the driver description printed in the usage.
procedure Set_Description (Driver : in out Driver_Type;
Description : in String);
-- Set the driver usage printed in the usage.
procedure Set_Usage (Driver : in out Driver_Type;
Usage : in String);
-- Register the command under the given name.
procedure Add_Command (Driver : in out Driver_Type;
Name : in String;
Command : in Command_Access);
procedure Add_Command (Driver : in out Driver_Type;
Name : in String;
Description : in String;
Command : in Command_Access);
-- Register the command under the given name.
procedure Add_Command (Driver : in out Driver_Type;
Name : in String;
Description : in String;
Handler : in Command_Handler);
-- Find the command having the given name.
-- Returns null if the command was not found.
function Find_Command (Driver : in Driver_Type;
Name : in String) return Command_Access;
-- Execute the command registered under the given name.
procedure Execute (Driver : in Driver_Type;
Name : in String;
Args : in Argument_List'Class;
Context : in out Context_Type);
-- Print a message for the command. The level indicates whether the message is an error,
-- warning or informational. The command name can be used to known the originator.
procedure Log (Driver : in Driver_Type;
Level : in Util.Log.Level_Type;
Name : in String;
Message : in String);
private
package Command_Maps is
new Ada.Containers.Indefinite_Ordered_Maps (Key_Type => String,
Element_Type => Command_Access,
"<" => "<");
type Command_Type is abstract tagged limited record
Driver : access Driver_Type'Class;
Description : Ada.Strings.Unbounded.Unbounded_String;
end record;
type Help_Command_Type is new Command_Type with null record;
type Handler_Command_Type is new Command_Type with record
Handler : Command_Handler;
end record;
-- Execute the command with the arguments.
overriding
procedure Execute (Command : in out Handler_Command_Type;
Name : in String;
Args : in Argument_List'Class;
Context : in out Context_Type);
-- Write the help associated with the command.
overriding
procedure Help (Command : in out Handler_Command_Type;
Name : in String;
Context : in out Context_Type);
type Driver_Type is tagged limited record
List : Command_Maps.Map;
Desc : Ada.Strings.Unbounded.Unbounded_String;
Usage : Ada.Strings.Unbounded.Unbounded_String;
end record;
end Util.Commands.Drivers;
|
Add Name parameter to the Help procedure
|
Add Name parameter to the Help procedure
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
87a91f7863f8b0855d503f32280f2ddcd395cffe
|
awa/plugins/awa-wikis/src/awa-wikis-beans.ads
|
awa/plugins/awa-wikis/src/awa-wikis-beans.ads
|
-----------------------------------------------------------------------
-- awa-wikis-beans -- Beans for module wikis
-- Copyright (C) 2015, 2016 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Ada.Strings.Wide_Wide_Unbounded;
with Util.Beans.Basic;
with Util.Beans.Objects;
with ADO;
with ADO.Objects;
with ASF.Helpers.Beans;
with Wiki.Strings;
with Wiki.Attributes;
with Wiki.Plugins.Templates;
with AWA.Wikis.Modules;
with AWA.Wikis.Models;
with AWA.Tags.Beans;
with AWA.Counters.Beans;
with AWA.Components.Wikis;
-- == Wiki Beans ==
-- Several bean types are provided to represent and manage the blogs and their posts.
-- The blog module registers the bean constructors when it is initialized.
-- To use them, one must declare a bean definition in the application XML configuration.
--
-- == Ada Beans ==
-- @include wikis.xml
package AWA.Wikis.Beans is
use Ada.Strings.Wide_Wide_Unbounded;
type Wiki_Links_Bean is new AWA.Components.Wikis.Link_Renderer_Bean with record
-- The wiki space identifier.
Wiki_Space_Id : ADO.Identifier;
end record;
-- Get the image link that must be rendered from the wiki image link.
overriding
procedure Make_Image_Link (Renderer : in Wiki_Links_Bean;
Link : in Wiki.Strings.WString;
URI : out Unbounded_Wide_Wide_String;
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 Wiki_Links_Bean;
Link : in Wiki.Strings.WString;
URI : out Unbounded_Wide_Wide_String;
Exists : out Boolean);
-- The Wiki template plugin that retrieves the template content from the Wiki space.
type Wiki_Template_Bean is new Wiki.Plugins.Templates.Template_Plugin
and Util.Beans.Basic.Readonly_Bean with record
-- The wiki space identifier.
Wiki_Space_Id : ADO.Identifier;
end record;
-- Get the value identified by the name.
overriding
function Get_Value (From : in Wiki_Template_Bean;
Name : in String) return Util.Beans.Objects.Object;
-- Get the template content for the plugin evaluation.
overriding
procedure Get_Template (Plugin : in out Wiki_Template_Bean;
Params : in out Wiki.Attributes.Attribute_List;
Template : out Wiki.Strings.UString);
type Wiki_View_Bean is new AWA.Wikis.Models.Wiki_View_Info with record
-- The wiki module instance.
Module : Modules.Wiki_Module_Access := null;
-- The wiki space identifier.
Wiki_Space_Id : ADO.Identifier;
-- List of tags associated with the wiki page.
Tags : aliased AWA.Tags.Beans.Tag_List_Bean;
Tags_Bean : Util.Beans.Basic.Readonly_Bean_Access;
-- The read page counter associated with the wiki page.
Counter : aliased AWA.Counters.Beans.Counter_Bean (Of_Type => ADO.Objects.KEY_INTEGER,
Of_Class => Models.WIKI_PAGE_TABLE);
Counter_Bean : Util.Beans.Basic.Readonly_Bean_Access;
-- The wiki page links.
Links : aliased Wiki_Links_Bean;
Links_Bean : Util.Beans.Basic.Readonly_Bean_Access;
-- The wiki plugins.
Plugins : aliased Wiki_Template_Bean;
Plugins_Bean : Util.Beans.Basic.Readonly_Bean_Access;
end record;
type Wiki_View_Bean_Access is access all Wiki_View_Bean'Class;
-- Get the value identified by the name.
overriding
function Get_Value (From : in Wiki_View_Bean;
Name : in String) return Util.Beans.Objects.Object;
-- Set the value identified by the name.
overriding
procedure Set_Value (From : in out Wiki_View_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object);
-- Load the information about the wiki page to display it.
overriding
procedure Load (Bean : in out Wiki_View_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String);
-- Create the Wiki_View_Bean bean instance.
function Create_Wiki_View_Bean (Module : in AWA.Wikis.Modules.Wiki_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access;
function Get_Wiki_View_Bean is
new ASF.Helpers.Beans.Get_Bean (Element_Type => Wiki_View_Bean,
Element_Access => Wiki_View_Bean_Access);
-- Get a select item list which contains a list of wiki formats.
function Create_Format_List_Bean (Module : in AWA.Wikis.Modules.Wiki_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access;
type Wiki_Space_Bean is new AWA.Wikis.Models.Wiki_Space_Bean with record
Module : Modules.Wiki_Module_Access := null;
-- List of tags associated with the question.
Tags : aliased AWA.Tags.Beans.Tag_List_Bean;
Tags_Bean : Util.Beans.Basic.Readonly_Bean_Access;
end record;
type Wiki_Space_Bean_Access is access all Wiki_Space_Bean'Class;
-- Get the value identified by the name.
overriding
function Get_Value (From : in Wiki_Space_Bean;
Name : in String) return Util.Beans.Objects.Object;
-- Set the value identified by the name.
overriding
procedure Set_Value (From : in out Wiki_Space_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object);
-- Create or save the wiki space.
overriding
procedure Save (Bean : in out Wiki_Space_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String);
-- Load the wiki space information.
overriding
procedure Load (Bean : in out Wiki_Space_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String);
-- Delete the wiki space.
procedure Delete (Bean : in out Wiki_Space_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String);
-- Create the Wiki_Space_Bean bean instance.
function Create_Wiki_Space_Bean (Module : in AWA.Wikis.Modules.Wiki_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access;
-- ------------------------------
-- Wiki Page Bean
-- ------------------------------
-- The <tt>Wiki_Page_Bean</tt> is used to edit a wiki page. The model type inherit from
-- the <tt>Wiki_Page</tt> and the wiki page text is hold in the <tt>Content</tt> member.
-- When a new content is updated, the <tt>Set_Value</tt> procedure sets it in the
-- <tt>New_Content</tt> member. It is compared to the current wiki text to decide whether
-- we have to create a new version or not.
type Wiki_Page_Bean is new AWA.Wikis.Models.Wiki_Page_Bean with record
Module : Modules.Wiki_Module_Access := null;
-- The page content.
Content : Models.Wiki_Content_Ref;
Has_Content : Boolean := False;
Format : AWA.Wikis.Models.Format_Type := AWA.Wikis.Models.FORMAT_CREOLE;
New_Content : Ada.Strings.Unbounded.Unbounded_String;
New_Comment : Ada.Strings.Unbounded.Unbounded_String;
Wiki_Space : Wiki_Space_Bean;
-- List of tags associated with the wiki page.
Tags : aliased AWA.Tags.Beans.Tag_List_Bean;
Tags_Bean : Util.Beans.Basic.Readonly_Bean_Access;
end record;
type Wiki_Page_Bean_Access is access all Wiki_Page_Bean'Class;
-- Returns True if the wiki page has a new text content and requires
-- a new version to be created.
function Has_New_Content (Bean : in Wiki_Page_Bean) return Boolean;
-- Get the value identified by the name.
overriding
function Get_Value (From : in Wiki_Page_Bean;
Name : in String) return Util.Beans.Objects.Object;
-- Set the value identified by the name.
overriding
procedure Set_Value (From : in out Wiki_Page_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object);
-- Create or save the wiki page.
overriding
procedure Save (Bean : in out Wiki_Page_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String);
-- Load the wiki page.
overriding
procedure Load (Bean : in out Wiki_Page_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String);
-- Setup the wiki page for the creation.
overriding
procedure Setup (Bean : in out Wiki_Page_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String);
-- Delete the wiki page.
overriding
procedure Delete (Bean : in out Wiki_Page_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String);
-- Create the Wiki_Page_Bean bean instance.
function Create_Wiki_Page_Bean (Module : in AWA.Wikis.Modules.Wiki_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access;
-- ------------------------------
-- Wiki List Bean
-- ------------------------------
-- The <b>Wiki_List_Bean</b> gives a list of visible wikis to be displayed to users.
-- The list can be filtered by a given tag. The list pagination is supported.
type Wiki_List_Bean is new AWA.Wikis.Models.Wiki_Page_List_Bean with record
Module : Modules.Wiki_Module_Access := null;
Pages : aliased AWA.Wikis.Models.Wiki_Page_Info_List_Bean;
Tags : AWA.Tags.Beans.Entity_Tag_Map;
Pages_Bean : AWA.Wikis.Models.Wiki_Page_Info_List_Bean_Access;
end record;
type Wiki_List_Bean_Access is access all Wiki_List_Bean'Class;
-- Get the value identified by the name.
overriding
function Get_Value (From : in Wiki_List_Bean;
Name : in String) return Util.Beans.Objects.Object;
-- Set the value identified by the name.
overriding
procedure Set_Value (From : in out Wiki_List_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object);
overriding
procedure Load (From : in out Wiki_List_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String);
-- Load the list of pages. If a tag was set, filter the list of pages with the tag.
procedure Load_List (Into : in out Wiki_List_Bean);
-- Create the Post_List_Bean bean instance.
function Create_Wiki_List_Bean (Module : in AWA.Wikis.Modules.Wiki_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access;
-- ------------------------------
-- Wiki Version List Bean
-- ------------------------------
type Wiki_Version_List_Bean is new AWA.Wikis.Models.Wiki_Version_List_Bean with record
Module : Modules.Wiki_Module_Access := null;
Versions : aliased AWA.Wikis.Models.Wiki_Version_Info_List_Bean;
Versions_Bean : AWA.Wikis.Models.Wiki_Version_Info_List_Bean_Access;
end record;
type Wiki_Version_List_Bean_Access is access all Wiki_Version_List_Bean'Class;
-- Get the value identified by the name.
overriding
function Get_Value (From : in Wiki_Version_List_Bean;
Name : in String) return Util.Beans.Objects.Object;
-- Set the value identified by the name.
overriding
procedure Set_Value (From : in out Wiki_Version_List_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object);
overriding
procedure Load (Into : in out Wiki_Version_List_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String);
-- Create the Post_List_Bean bean instance.
function Create_Wiki_Version_List_Bean (Module : in AWA.Wikis.Modules.Wiki_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access;
type Init_Flag is (INIT_WIKI_LIST);
type Init_Map is array (Init_Flag) of Boolean;
-- ------------------------------
-- Admin List Bean
-- ------------------------------
-- The <b>Wiki_Admin_Bean</b> is used for the administration of a wiki. It gives the
-- list of wikis and pages that are created, published or not.
type Wiki_Admin_Bean is new Util.Beans.Basic.Bean with record
Module : AWA.Wikis.Modules.Wiki_Module_Access := null;
-- The wiki space identifier.
Wiki_Id : ADO.Identifier := ADO.NO_IDENTIFIER;
-- List of blogs.
Wiki_List : aliased AWA.Wikis.Models.Wiki_Info_List_Bean;
Wiki_List_Bean : AWA.Wikis.Models.Wiki_Info_List_Bean_Access;
-- Initialization flags.
Init_Flags : aliased Init_Map := (others => False);
Flags : access Init_Map;
end record;
type Wiki_Admin_Bean_Access is access all Wiki_Admin_Bean;
-- Get the wiki space identifier.
function Get_Wiki_Id (List : in Wiki_Admin_Bean) return ADO.Identifier;
overriding
function Get_Value (List : in Wiki_Admin_Bean;
Name : in String) return Util.Beans.Objects.Object;
-- Set the value identified by the name.
overriding
procedure Set_Value (From : in out Wiki_Admin_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object);
-- Load the list of wikis.
procedure Load_Wikis (List : in Wiki_Admin_Bean);
-- Create the Wiki_Admin_Bean bean instance.
function Create_Wiki_Admin_Bean (Module : in AWA.Wikis.Modules.Wiki_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access;
end AWA.Wikis.Beans;
|
-----------------------------------------------------------------------
-- awa-wikis-beans -- Beans for module wikis
-- Copyright (C) 2015, 2016 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Ada.Strings.Wide_Wide_Unbounded;
with Util.Beans.Basic;
with Util.Beans.Objects;
with ADO;
with ADO.Objects;
with ASF.Helpers.Beans;
with Wiki.Strings;
with Wiki.Attributes;
with Wiki.Plugins.Templates;
with AWA.Wikis.Modules;
with AWA.Wikis.Models;
with AWA.Tags.Beans;
with AWA.Counters.Beans;
with AWA.Components.Wikis;
-- == Wiki Beans ==
-- Several bean types are provided to represent and manage the blogs and their posts.
-- The blog module registers the bean constructors when it is initialized.
-- To use them, one must declare a bean definition in the application XML configuration.
--
-- == Ada Beans ==
-- @include wikis.xml
package AWA.Wikis.Beans is
use Ada.Strings.Wide_Wide_Unbounded;
type Wiki_Links_Bean is new AWA.Components.Wikis.Link_Renderer_Bean with record
-- The wiki space identifier.
Wiki_Space_Id : ADO.Identifier;
end record;
-- Get the image link that must be rendered from the wiki image link.
overriding
procedure Make_Image_Link (Renderer : in Wiki_Links_Bean;
Link : in Wiki.Strings.WString;
URI : out Unbounded_Wide_Wide_String;
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 Wiki_Links_Bean;
Link : in Wiki.Strings.WString;
URI : out Unbounded_Wide_Wide_String;
Exists : out Boolean);
-- The Wiki template plugin that retrieves the template content from the Wiki space.
type Wiki_Template_Bean is new Wiki.Plugins.Templates.Template_Plugin
and Wiki.Plugins.Plugin_Factory
and Util.Beans.Basic.Readonly_Bean with record
-- The wiki space identifier.
Wiki_Space_Id : ADO.Identifier;
end record;
-- Get the value identified by the name.
overriding
function Get_Value (From : in Wiki_Template_Bean;
Name : in String) return Util.Beans.Objects.Object;
-- Get the template content for the plugin evaluation.
overriding
procedure Get_Template (Plugin : in out Wiki_Template_Bean;
Params : in out Wiki.Attributes.Attribute_List;
Template : out Wiki.Strings.UString);
-- Find a plugin knowing its name.
overriding
function Find (Factory : in Wiki_Template_Bean;
Name : in String) return Wiki.Plugins.Wiki_Plugin_Access;
type Wiki_View_Bean is new AWA.Wikis.Models.Wiki_View_Info with record
-- The wiki module instance.
Module : Modules.Wiki_Module_Access := null;
-- The wiki space identifier.
Wiki_Space_Id : ADO.Identifier;
-- List of tags associated with the wiki page.
Tags : aliased AWA.Tags.Beans.Tag_List_Bean;
Tags_Bean : Util.Beans.Basic.Readonly_Bean_Access;
-- The read page counter associated with the wiki page.
Counter : aliased AWA.Counters.Beans.Counter_Bean (Of_Type => ADO.Objects.KEY_INTEGER,
Of_Class => Models.WIKI_PAGE_TABLE);
Counter_Bean : Util.Beans.Basic.Readonly_Bean_Access;
-- The wiki page links.
Links : aliased Wiki_Links_Bean;
Links_Bean : Util.Beans.Basic.Readonly_Bean_Access;
-- The wiki plugins.
Plugins : aliased Wiki_Template_Bean;
Plugins_Bean : Util.Beans.Basic.Readonly_Bean_Access;
end record;
type Wiki_View_Bean_Access is access all Wiki_View_Bean'Class;
-- Get the value identified by the name.
overriding
function Get_Value (From : in Wiki_View_Bean;
Name : in String) return Util.Beans.Objects.Object;
-- Set the value identified by the name.
overriding
procedure Set_Value (From : in out Wiki_View_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object);
-- Load the information about the wiki page to display it.
overriding
procedure Load (Bean : in out Wiki_View_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String);
-- Create the Wiki_View_Bean bean instance.
function Create_Wiki_View_Bean (Module : in AWA.Wikis.Modules.Wiki_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access;
function Get_Wiki_View_Bean is
new ASF.Helpers.Beans.Get_Bean (Element_Type => Wiki_View_Bean,
Element_Access => Wiki_View_Bean_Access);
-- Get a select item list which contains a list of wiki formats.
function Create_Format_List_Bean (Module : in AWA.Wikis.Modules.Wiki_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access;
type Wiki_Space_Bean is new AWA.Wikis.Models.Wiki_Space_Bean with record
Module : Modules.Wiki_Module_Access := null;
-- List of tags associated with the question.
Tags : aliased AWA.Tags.Beans.Tag_List_Bean;
Tags_Bean : Util.Beans.Basic.Readonly_Bean_Access;
end record;
type Wiki_Space_Bean_Access is access all Wiki_Space_Bean'Class;
-- Get the value identified by the name.
overriding
function Get_Value (From : in Wiki_Space_Bean;
Name : in String) return Util.Beans.Objects.Object;
-- Set the value identified by the name.
overriding
procedure Set_Value (From : in out Wiki_Space_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object);
-- Create or save the wiki space.
overriding
procedure Save (Bean : in out Wiki_Space_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String);
-- Load the wiki space information.
overriding
procedure Load (Bean : in out Wiki_Space_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String);
-- Delete the wiki space.
procedure Delete (Bean : in out Wiki_Space_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String);
-- Create the Wiki_Space_Bean bean instance.
function Create_Wiki_Space_Bean (Module : in AWA.Wikis.Modules.Wiki_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access;
-- ------------------------------
-- Wiki Page Bean
-- ------------------------------
-- The <tt>Wiki_Page_Bean</tt> is used to edit a wiki page. The model type inherit from
-- the <tt>Wiki_Page</tt> and the wiki page text is hold in the <tt>Content</tt> member.
-- When a new content is updated, the <tt>Set_Value</tt> procedure sets it in the
-- <tt>New_Content</tt> member. It is compared to the current wiki text to decide whether
-- we have to create a new version or not.
type Wiki_Page_Bean is new AWA.Wikis.Models.Wiki_Page_Bean with record
Module : Modules.Wiki_Module_Access := null;
-- The page content.
Content : Models.Wiki_Content_Ref;
Has_Content : Boolean := False;
Format : AWA.Wikis.Models.Format_Type := AWA.Wikis.Models.FORMAT_CREOLE;
New_Content : Ada.Strings.Unbounded.Unbounded_String;
New_Comment : Ada.Strings.Unbounded.Unbounded_String;
Wiki_Space : Wiki_Space_Bean;
-- List of tags associated with the wiki page.
Tags : aliased AWA.Tags.Beans.Tag_List_Bean;
Tags_Bean : Util.Beans.Basic.Readonly_Bean_Access;
end record;
type Wiki_Page_Bean_Access is access all Wiki_Page_Bean'Class;
-- Returns True if the wiki page has a new text content and requires
-- a new version to be created.
function Has_New_Content (Bean : in Wiki_Page_Bean) return Boolean;
-- Get the value identified by the name.
overriding
function Get_Value (From : in Wiki_Page_Bean;
Name : in String) return Util.Beans.Objects.Object;
-- Set the value identified by the name.
overriding
procedure Set_Value (From : in out Wiki_Page_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object);
-- Create or save the wiki page.
overriding
procedure Save (Bean : in out Wiki_Page_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String);
-- Load the wiki page.
overriding
procedure Load (Bean : in out Wiki_Page_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String);
-- Setup the wiki page for the creation.
overriding
procedure Setup (Bean : in out Wiki_Page_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String);
-- Delete the wiki page.
overriding
procedure Delete (Bean : in out Wiki_Page_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String);
-- Create the Wiki_Page_Bean bean instance.
function Create_Wiki_Page_Bean (Module : in AWA.Wikis.Modules.Wiki_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access;
-- ------------------------------
-- Wiki List Bean
-- ------------------------------
-- The <b>Wiki_List_Bean</b> gives a list of visible wikis to be displayed to users.
-- The list can be filtered by a given tag. The list pagination is supported.
type Wiki_List_Bean is new AWA.Wikis.Models.Wiki_Page_List_Bean with record
Module : Modules.Wiki_Module_Access := null;
Pages : aliased AWA.Wikis.Models.Wiki_Page_Info_List_Bean;
Tags : AWA.Tags.Beans.Entity_Tag_Map;
Pages_Bean : AWA.Wikis.Models.Wiki_Page_Info_List_Bean_Access;
end record;
type Wiki_List_Bean_Access is access all Wiki_List_Bean'Class;
-- Get the value identified by the name.
overriding
function Get_Value (From : in Wiki_List_Bean;
Name : in String) return Util.Beans.Objects.Object;
-- Set the value identified by the name.
overriding
procedure Set_Value (From : in out Wiki_List_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object);
overriding
procedure Load (From : in out Wiki_List_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String);
-- Load the list of pages. If a tag was set, filter the list of pages with the tag.
procedure Load_List (Into : in out Wiki_List_Bean);
-- Create the Post_List_Bean bean instance.
function Create_Wiki_List_Bean (Module : in AWA.Wikis.Modules.Wiki_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access;
-- ------------------------------
-- Wiki Version List Bean
-- ------------------------------
type Wiki_Version_List_Bean is new AWA.Wikis.Models.Wiki_Version_List_Bean with record
Module : Modules.Wiki_Module_Access := null;
Versions : aliased AWA.Wikis.Models.Wiki_Version_Info_List_Bean;
Versions_Bean : AWA.Wikis.Models.Wiki_Version_Info_List_Bean_Access;
end record;
type Wiki_Version_List_Bean_Access is access all Wiki_Version_List_Bean'Class;
-- Get the value identified by the name.
overriding
function Get_Value (From : in Wiki_Version_List_Bean;
Name : in String) return Util.Beans.Objects.Object;
-- Set the value identified by the name.
overriding
procedure Set_Value (From : in out Wiki_Version_List_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object);
overriding
procedure Load (Into : in out Wiki_Version_List_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String);
-- Create the Post_List_Bean bean instance.
function Create_Wiki_Version_List_Bean (Module : in AWA.Wikis.Modules.Wiki_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access;
type Init_Flag is (INIT_WIKI_LIST);
type Init_Map is array (Init_Flag) of Boolean;
-- ------------------------------
-- Admin List Bean
-- ------------------------------
-- The <b>Wiki_Admin_Bean</b> is used for the administration of a wiki. It gives the
-- list of wikis and pages that are created, published or not.
type Wiki_Admin_Bean is new Util.Beans.Basic.Bean with record
Module : AWA.Wikis.Modules.Wiki_Module_Access := null;
-- The wiki space identifier.
Wiki_Id : ADO.Identifier := ADO.NO_IDENTIFIER;
-- List of blogs.
Wiki_List : aliased AWA.Wikis.Models.Wiki_Info_List_Bean;
Wiki_List_Bean : AWA.Wikis.Models.Wiki_Info_List_Bean_Access;
-- Initialization flags.
Init_Flags : aliased Init_Map := (others => False);
Flags : access Init_Map;
end record;
type Wiki_Admin_Bean_Access is access all Wiki_Admin_Bean;
-- Get the wiki space identifier.
function Get_Wiki_Id (List : in Wiki_Admin_Bean) return ADO.Identifier;
overriding
function Get_Value (List : in Wiki_Admin_Bean;
Name : in String) return Util.Beans.Objects.Object;
-- Set the value identified by the name.
overriding
procedure Set_Value (From : in out Wiki_Admin_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object);
-- Load the list of wikis.
procedure Load_Wikis (List : in Wiki_Admin_Bean);
-- Create the Wiki_Admin_Bean bean instance.
function Create_Wiki_Admin_Bean (Module : in AWA.Wikis.Modules.Wiki_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access;
end AWA.Wikis.Beans;
|
Update the Wiki_Template_Bean type to implement the Plugin factory interface Declare the Find procedure
|
Update the Wiki_Template_Bean type to implement the Plugin factory interface
Declare the Find procedure
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
b94d6e0c8bc728a3a9f86a4c479eee3d3bd5e806
|
src/security-policies-roles.adb
|
src/security-policies-roles.adb
|
-----------------------------------------------------------------------
-- security-policies-roles -- Role based policies
-- Copyright (C) 2010, 2011, 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Log.Loggers;
with Util.Serialize.Mappers.Record_Mapper;
with Security.Controllers;
with Security.Controllers.Roles;
package body Security.Policies.Roles is
use Util.Log;
-- The logger
Log : constant Loggers.Logger := Loggers.Create ("Security.Policies.Roles");
-- ------------------------------
-- Set the roles which are assigned to the user in the security context.
-- The role policy will use these roles to verify a permission.
-- ------------------------------
procedure Set_Role_Context (Context : in out Security.Contexts.Security_Context'Class;
Roles : in Role_Map) is
Policy : constant Security.Policies.Policy_Access := Context.Get_Policy (NAME);
Data : Role_Policy_Context_Access;
begin
if Policy = null then
Log.Error ("There is no security policy: " & NAME);
end if;
Data := new Role_Policy_Context;
Data.Roles := Roles;
Context.Set_Policy_Context (Policy, Data.all'Access);
end Set_Role_Context;
-- ------------------------------
-- Get the policy name.
-- ------------------------------
overriding
function Get_Name (From : in Role_Policy) return String is
pragma Unreferenced (From);
begin
return NAME;
end Get_Name;
-- ------------------------------
-- Get the role name.
-- ------------------------------
function Get_Role_Name (Manager : in Role_Policy;
Role : in Role_Type) return String is
use type Ada.Strings.Unbounded.String_Access;
begin
if Manager.Names (Role) = null then
return "";
else
return Manager.Names (Role).all;
end if;
end Get_Role_Name;
-- ------------------------------
-- Find the role type associated with the role name identified by <b>Name</b>.
-- Raises <b>Invalid_Name</b> if there is no role type.
-- ------------------------------
function Find_Role (Manager : in Role_Policy;
Name : in String) return Role_Type is
use type Ada.Strings.Unbounded.String_Access;
begin
Log.Debug ("Searching role {0}", Name);
for I in Role_Type'First .. Manager.Next_Role loop
exit when Manager.Names (I) = null;
if Name = Manager.Names (I).all then
return I;
end if;
end loop;
Log.Debug ("Role {0} not found", Name);
raise Invalid_Name;
end Find_Role;
-- ------------------------------
-- Create a role
-- ------------------------------
procedure Create_Role (Manager : in out Role_Policy;
Name : in String;
Role : out Role_Type) is
begin
Role := Manager.Next_Role;
Log.Info ("Role {0} is {1}", Name, Role_Type'Image (Role));
if Manager.Next_Role = Role_Type'Last then
Log.Error ("Too many roles allocated. Number of roles is {0}",
Role_Type'Image (Role_Type'Last));
else
Manager.Next_Role := Manager.Next_Role + 1;
end if;
Manager.Names (Role) := new String '(Name);
end Create_Role;
-- ------------------------------
-- Get or build a permission type for the given name.
-- ------------------------------
procedure Add_Role_Type (Manager : in out Role_Policy;
Name : in String;
Result : out Role_Type) is
begin
Result := Manager.Find_Role (Name);
exception
when Invalid_Name =>
Manager.Create_Role (Name, Result);
end Add_Role_Type;
type Config_Fields is (FIELD_NAME, FIELD_ROLE, FIELD_ROLE_PERMISSION, FIELD_ROLE_NAME);
type Controller_Config_Access is access all Controller_Config;
procedure Set_Member (Into : in out Controller_Config;
Field : in Config_Fields;
Value : in Util.Beans.Objects.Object);
-- ------------------------------
-- Called while parsing the XML policy file when the <name>, <role> and <role-permission>
-- XML entities are found. Create the new permission when the complete permission definition
-- has been parsed and save the permission in the security manager.
-- ------------------------------
procedure Set_Member (Into : in out Controller_Config;
Field : in Config_Fields;
Value : in Util.Beans.Objects.Object) is
use Security.Controllers.Roles;
begin
case Field is
when FIELD_NAME =>
Into.Name := Value;
when FIELD_ROLE =>
declare
Role : constant String := Util.Beans.Objects.To_String (Value);
begin
Into.Roles (Into.Count + 1) := Into.Manager.Find_Role (Role);
Into.Count := Into.Count + 1;
exception
when Permissions.Invalid_Name =>
raise Util.Serialize.Mappers.Field_Error with "Invalid role: " & Role;
end;
when FIELD_ROLE_PERMISSION =>
if Into.Count = 0 then
raise Util.Serialize.Mappers.Field_Error with "Missing at least one role";
end if;
declare
Name : constant String := Util.Beans.Objects.To_String (Into.Name);
Perm : constant Role_Controller_Access
:= new Role_Controller '(Count => Into.Count,
Roles => Into.Roles (1 .. Into.Count));
begin
Into.Manager.Add_Permission (Name, Perm.all'Access);
Into.Count := 0;
end;
when FIELD_ROLE_NAME =>
declare
Name : constant String := Util.Beans.Objects.To_String (Value);
Role : Role_Type;
begin
Into.Manager.Add_Role_Type (Name, Role);
end;
end case;
end Set_Member;
package Config_Mapper is
new Util.Serialize.Mappers.Record_Mapper (Element_Type => Controller_Config,
Element_Type_Access => Controller_Config_Access,
Fields => Config_Fields,
Set_Member => Set_Member);
Mapper : aliased Config_Mapper.Mapper;
-- ------------------------------
-- Setup the XML parser to read the <b>role-permission</b> description.
-- ------------------------------
procedure Prepare_Config (Policy : in out Role_Policy;
Reader : in out Util.Serialize.IO.XML.Parser) is
Config : Controller_Config_Access := new Controller_Config;
begin
Reader.Add_Mapping ("policy-rules", Mapper'Access);
Reader.Add_Mapping ("module", Mapper'Access);
Config.Manager := Policy'Unchecked_Access;
Config_Mapper.Set_Context (Reader, Config);
end Prepare_Config;
-- ------------------------------
-- Finalize the policy manager.
-- ------------------------------
overriding
procedure Finalize (Policy : in out Role_Policy) is
use type Ada.Strings.Unbounded.String_Access;
begin
for I in Policy.Names'Range loop
exit when Policy.Names (I) = null;
Ada.Strings.Unbounded.Free (Policy.Names (I));
end loop;
end Finalize;
begin
Mapper.Add_Mapping ("role-permission", FIELD_ROLE_PERMISSION);
Mapper.Add_Mapping ("role-permission/name", FIELD_NAME);
Mapper.Add_Mapping ("role-permission/role", FIELD_ROLE);
Mapper.Add_Mapping ("security-role/role-name", FIELD_ROLE_NAME);
end Security.Policies.Roles;
|
-----------------------------------------------------------------------
-- security-policies-roles -- Role based policies
-- Copyright (C) 2010, 2011, 2012 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Log.Loggers;
with Util.Serialize.Mappers.Record_Mapper;
with Util.Strings.Tokenizers;
with Security.Controllers;
with Security.Controllers.Roles;
package body Security.Policies.Roles is
use Util.Log;
-- The logger
Log : constant Loggers.Logger := Loggers.Create ("Security.Policies.Roles");
-- ------------------------------
-- Set the roles which are assigned to the user in the security context.
-- The role policy will use these roles to verify a permission.
-- ------------------------------
procedure Set_Role_Context (Context : in out Security.Contexts.Security_Context'Class;
Roles : in Role_Map) is
Policy : constant Security.Policies.Policy_Access := Context.Get_Policy (NAME);
Data : Role_Policy_Context_Access;
begin
if Policy = null then
Log.Error ("There is no security policy: " & NAME);
end if;
Data := new Role_Policy_Context;
Data.Roles := Roles;
Context.Set_Policy_Context (Policy, Data.all'Access);
end Set_Role_Context;
-- ------------------------------
-- Get the policy name.
-- ------------------------------
overriding
function Get_Name (From : in Role_Policy) return String is
pragma Unreferenced (From);
begin
return NAME;
end Get_Name;
-- ------------------------------
-- Get the role name.
-- ------------------------------
function Get_Role_Name (Manager : in Role_Policy;
Role : in Role_Type) return String is
use type Ada.Strings.Unbounded.String_Access;
begin
if Manager.Names (Role) = null then
return "";
else
return Manager.Names (Role).all;
end if;
end Get_Role_Name;
-- ------------------------------
-- Find the role type associated with the role name identified by <b>Name</b>.
-- Raises <b>Invalid_Name</b> if there is no role type.
-- ------------------------------
function Find_Role (Manager : in Role_Policy;
Name : in String) return Role_Type is
use type Ada.Strings.Unbounded.String_Access;
begin
Log.Debug ("Searching role {0}", Name);
for I in Role_Type'First .. Manager.Next_Role loop
exit when Manager.Names (I) = null;
if Name = Manager.Names (I).all then
return I;
end if;
end loop;
Log.Debug ("Role {0} not found", Name);
raise Invalid_Name;
end Find_Role;
-- ------------------------------
-- Create a role
-- ------------------------------
procedure Create_Role (Manager : in out Role_Policy;
Name : in String;
Role : out Role_Type) is
begin
Role := Manager.Next_Role;
Log.Info ("Role {0} is {1}", Name, Role_Type'Image (Role));
if Manager.Next_Role = Role_Type'Last then
Log.Error ("Too many roles allocated. Number of roles is {0}",
Role_Type'Image (Role_Type'Last));
else
Manager.Next_Role := Manager.Next_Role + 1;
end if;
Manager.Names (Role) := new String '(Name);
end Create_Role;
-- ------------------------------
-- Get or build a permission type for the given name.
-- ------------------------------
procedure Add_Role_Type (Manager : in out Role_Policy;
Name : in String;
Result : out Role_Type) is
begin
Result := Manager.Find_Role (Name);
exception
when Invalid_Name =>
Manager.Create_Role (Name, Result);
end Add_Role_Type;
-- ------------------------------
-- Set the roles specified in the <tt>Roles</tt> parameter. Each role is represented by
-- its name and multiple roles are separated by ','.
-- Raises Invalid_Name if a role was not found.
-- ------------------------------
procedure Set_Roles (Manager : in Role_Policy;
Roles : in String;
Into : out Role_Map) is
procedure Process (Role : in String;
Done : out Boolean);
procedure Process (Role : in String;
Done : out Boolean) is
begin
Into (Manager.Find_Role (Role)) := True;
Done := False;
end Process;
begin
Into := (others => False);
Util.Strings.Tokenizers.Iterate_Tokens (Content => Roles,
Pattern => ",",
Process => Process'Access,
Going => Ada.Strings.Forward);
end Set_Roles;
type Config_Fields is (FIELD_NAME, FIELD_ROLE, FIELD_ROLE_PERMISSION, FIELD_ROLE_NAME);
type Controller_Config_Access is access all Controller_Config;
procedure Set_Member (Into : in out Controller_Config;
Field : in Config_Fields;
Value : in Util.Beans.Objects.Object);
-- ------------------------------
-- Called while parsing the XML policy file when the <name>, <role> and <role-permission>
-- XML entities are found. Create the new permission when the complete permission definition
-- has been parsed and save the permission in the security manager.
-- ------------------------------
procedure Set_Member (Into : in out Controller_Config;
Field : in Config_Fields;
Value : in Util.Beans.Objects.Object) is
use Security.Controllers.Roles;
begin
case Field is
when FIELD_NAME =>
Into.Name := Value;
when FIELD_ROLE =>
declare
Role : constant String := Util.Beans.Objects.To_String (Value);
begin
Into.Roles (Into.Count + 1) := Into.Manager.Find_Role (Role);
Into.Count := Into.Count + 1;
exception
when Permissions.Invalid_Name =>
raise Util.Serialize.Mappers.Field_Error with "Invalid role: " & Role;
end;
when FIELD_ROLE_PERMISSION =>
if Into.Count = 0 then
raise Util.Serialize.Mappers.Field_Error with "Missing at least one role";
end if;
declare
Name : constant String := Util.Beans.Objects.To_String (Into.Name);
Perm : constant Role_Controller_Access
:= new Role_Controller '(Count => Into.Count,
Roles => Into.Roles (1 .. Into.Count));
begin
Into.Manager.Add_Permission (Name, Perm.all'Access);
Into.Count := 0;
end;
when FIELD_ROLE_NAME =>
declare
Name : constant String := Util.Beans.Objects.To_String (Value);
Role : Role_Type;
begin
Into.Manager.Add_Role_Type (Name, Role);
end;
end case;
end Set_Member;
package Config_Mapper is
new Util.Serialize.Mappers.Record_Mapper (Element_Type => Controller_Config,
Element_Type_Access => Controller_Config_Access,
Fields => Config_Fields,
Set_Member => Set_Member);
Mapper : aliased Config_Mapper.Mapper;
-- ------------------------------
-- Setup the XML parser to read the <b>role-permission</b> description.
-- ------------------------------
procedure Prepare_Config (Policy : in out Role_Policy;
Reader : in out Util.Serialize.IO.XML.Parser) is
Config : Controller_Config_Access := new Controller_Config;
begin
Reader.Add_Mapping ("policy-rules", Mapper'Access);
Reader.Add_Mapping ("module", Mapper'Access);
Config.Manager := Policy'Unchecked_Access;
Config_Mapper.Set_Context (Reader, Config);
end Prepare_Config;
-- ------------------------------
-- Finalize the policy manager.
-- ------------------------------
overriding
procedure Finalize (Policy : in out Role_Policy) is
use type Ada.Strings.Unbounded.String_Access;
begin
for I in Policy.Names'Range loop
exit when Policy.Names (I) = null;
Ada.Strings.Unbounded.Free (Policy.Names (I));
end loop;
end Finalize;
begin
Mapper.Add_Mapping ("role-permission", FIELD_ROLE_PERMISSION);
Mapper.Add_Mapping ("role-permission/name", FIELD_NAME);
Mapper.Add_Mapping ("role-permission/role", FIELD_ROLE);
Mapper.Add_Mapping ("security-role/role-name", FIELD_ROLE_NAME);
end Security.Policies.Roles;
|
Implement Set_Roles
|
Implement Set_Roles
|
Ada
|
apache-2.0
|
stcarrez/ada-security
|
7644788f7c9af47067296b2c8ae09572e5e9fb38
|
src/gen-model-mappings.ads
|
src/gen-model-mappings.ads
|
-----------------------------------------------------------------------
-- gen-model-mappings -- Type mappings for Code Generator
-- Copyright (C) 2011, 2012, 2015, 2018 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with 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";
Postgresql_MAPPING : constant String := "Postgresql";
type Basic_Type is (T_BOOLEAN, T_INTEGER, T_DATE, T_ENUM, T_IDENTIFIER, T_STRING, T_BLOB,
T_ENTITY_TYPE, 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;
-- Get the type name.
function Get_Type_Name (From : Mapping_Definition) return String;
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, 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.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";
Postgresql_MAPPING : constant String := "Postgresql";
type Basic_Type is (T_BOOLEAN, T_INTEGER, T_DATE, T_ENUM, T_IDENTIFIER, T_STRING, T_BLOB,
T_ENTITY_TYPE, 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;
-- Get the type name according to the mapping definition.
function Get_Type_Name (Name : in Ada.Strings.Unbounded.Unbounded_String) return String;
-- Get the type name.
function Get_Type_Name (From : Mapping_Definition) return String;
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;
|
Declare a Get_Type_Name function to get a type using the mapping table
|
Declare a Get_Type_Name function to get a type using the mapping table
|
Ada
|
apache-2.0
|
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
|
fdcc18b2b5245aed9653210b2c41ce20f5048cee
|
src/core/texts/util-texts-builders.adb
|
src/core/texts/util-texts-builders.adb
|
-----------------------------------------------------------------------
-- util-texts-builders -- Text builder
-- Copyright (C) 2013, 2016, 2017, 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;
package body Util.Texts.Builders is
-- ------------------------------
-- Get the length of the item builder.
-- ------------------------------
function Length (Source : in Builder) return Natural is
begin
return Source.Length;
end Length;
-- ------------------------------
-- Get the capacity of the builder.
-- ------------------------------
function Capacity (Source : in Builder) return Natural is
B : constant Block_Access := Source.Current;
begin
return Source.Length + B.Len - B.Last;
end Capacity;
-- ------------------------------
-- Get the builder block size.
-- ------------------------------
function Block_Size (Source : in Builder) return Positive is
begin
return Source.Block_Size;
end Block_Size;
-- ------------------------------
-- Set the block size for the allocation of next chunks.
-- ------------------------------
procedure Set_Block_Size (Source : in out Builder;
Size : in Positive) is
begin
Source.Block_Size := Size;
end Set_Block_Size;
-- ------------------------------
-- Append the <tt>New_Item</tt> at the end of the source growing the buffer if necessary.
-- ------------------------------
procedure Append (Source : in out Builder;
New_Item : in Input) is
B : Block_Access := Source.Current;
Start : Natural := New_Item'First;
Last : constant Natural := New_Item'Last;
begin
while Start <= Last loop
declare
Space : Natural := B.Len - B.Last;
Size : constant Natural := Last - Start + 1;
begin
if Space > Size then
Space := Size;
elsif Space = 0 then
if Size > Source.Block_Size then
B.Next_Block := new Block (Size);
else
B.Next_Block := new Block (Source.Block_Size);
end if;
B := B.Next_Block;
Source.Current := B;
if B.Len > Size then
Space := Size;
else
Space := B.Len;
end if;
end if;
B.Content (B.Last + 1 .. B.Last + Space) := New_Item (Start .. Start + Space - 1);
Source.Length := Source.Length + Space;
B.Last := B.Last + Space;
Start := Start + Space;
end;
end loop;
end Append;
-- ------------------------------
-- Append the <tt>New_Item</tt> at the end of the source growing the buffer if necessary.
-- ------------------------------
procedure Append (Source : in out Builder;
New_Item : in Element_Type) is
B : Block_Access := Source.Current;
begin
if B.Len = B.Last then
B.Next_Block := new Block (Source.Block_Size);
B := B.Next_Block;
Source.Current := B;
end if;
Source.Length := Source.Length + 1;
B.Last := B.Last + 1;
B.Content (B.Last) := New_Item;
end Append;
procedure Inline_Append (Source : in out Builder) is
B : Block_Access := Source.Current;
Last : Natural;
begin
loop
if B.Len = B.Last then
B.Next_Block := new Block (Source.Block_Size);
B := B.Next_Block;
Source.Current := B;
end if;
Process (B.Content (B.Last + 1 .. B.Len), Last);
exit when Last > B.Len or Last <= B.Last;
Source.Length := Source.Length + Last - B.Last;
B.Last := Last;
exit when Last < B.Len;
end loop;
end Inline_Append;
-- ------------------------------
-- Clear the source freeing any storage allocated for the buffer.
-- ------------------------------
procedure Clear (Source : in out Builder) is
procedure Free is
new Ada.Unchecked_Deallocation (Object => Block, Name => Block_Access);
Current, Next : Block_Access;
begin
Next := Source.First.Next_Block;
while Next /= null loop
Current := Next;
Next := Current.Next_Block;
Free (Current);
end loop;
Source.First.Next_Block := null;
Source.First.Last := 0;
Source.Current := Source.First'Unchecked_Access;
Source.Length := 0;
end Clear;
-- ------------------------------
-- Iterate over the buffer content calling the <tt>Process</tt> procedure with each
-- chunk.
-- ------------------------------
procedure Iterate (Source : in Builder;
Process : not null access procedure (Chunk : in Input)) is
begin
if Source.First.Last > 0 then
Process (Source.First.Content (1 .. Source.First.Last));
declare
B : Block_Access := Source.First.Next_Block;
begin
while B /= null loop
Process (B.Content (1 .. B.Last));
B := B.Next_Block;
end loop;
end;
end if;
end Iterate;
procedure Inline_Iterate (Source : in Builder) is
begin
if Source.First.Last > 0 then
Process (Source.First.Content (1 .. Source.First.Last));
declare
B : Block_Access := Source.First.Next_Block;
begin
while B /= null loop
Process (B.Content (1 .. B.Last));
B := B.Next_Block;
end loop;
end;
end if;
end Inline_Iterate;
-- ------------------------------
-- Return the content starting from the tail and up to <tt>Length</tt> items.
-- ------------------------------
function Tail (Source : in Builder;
Length : in Natural) return Input is
Last : constant Natural := Source.Current.Last;
begin
if Last >= Length then
return Source.Current.Content (Last - Length + 1 .. Last);
elsif Length >= Source.Length then
return To_Array (Source);
else
declare
Result : Input (1 .. Length);
Offset : Natural := Source.Length - Length;
B : access constant Block := Source.First'Access;
Src_Pos : Positive := 1;
Dst_Pos : Positive := 1;
Len : Natural;
begin
-- Skip the data moving to next blocks as needed.
while Offset /= 0 loop
if Offset < B.Last then
Src_Pos := Offset + 1;
Offset := 0;
else
Offset := Offset - B.Last + 1;
B := B.Next_Block;
end if;
end loop;
-- Copy what remains until we reach the length.
while Dst_Pos <= Length loop
Len := B.Last - Src_Pos + 1;
Result (Dst_Pos .. Dst_Pos + Len - 1) := B.Content (Src_Pos .. B.Last);
Src_Pos := 1;
Dst_Pos := Dst_Pos + Len;
B := B.Next_Block;
end loop;
return Result;
end;
end if;
end Tail;
-- ------------------------------
-- Get the buffer content as an array.
-- ------------------------------
function To_Array (Source : in Builder) return Input is
Result : Input (1 .. Source.Length);
begin
if Source.First.Last > 0 then
declare
Pos : Positive := Source.First.Last;
B : Block_Access := Source.First.Next_Block;
begin
Result (1 .. Pos) := Source.First.Content (1 .. Pos);
while B /= null loop
Result (Pos + 1 .. Pos + B.Last) := B.Content (1 .. B.Last);
Pos := Pos + B.Last;
B := B.Next_Block;
end loop;
end;
end if;
return Result;
end To_Array;
-- ------------------------------
-- Get the element at the given position.
-- ------------------------------
function Element (Source : in Builder;
Position : in Positive) return Element_Type is
begin
if Position <= Source.First.Last then
return Source.First.Content (Position);
else
declare
Pos : Positive := Position - Source.First.Last;
B : Block_Access := Source.First.Next_Block;
begin
loop
if Pos <= B.Last then
return B.Content (Pos);
end if;
Pos := Pos - B.Last;
B := B.Next_Block;
end loop;
end;
end if;
end Element;
-- ------------------------------
-- Find the position of some content by running the `Index` function.
-- The `Index` function is called with chunks starting at the given position and
-- until it returns a positive value or we reach the last chunk. It must return
-- the found position in the chunk.
-- ------------------------------
function Find (Source : in Builder;
Position : in Positive) return Natural is
Result : Natural;
begin
if Position <= Source.First.Last then
Result := Index (Source.First.Content (Position .. Source.First.Last));
if Result > 0 then
return Result;
end if;
end if;
declare
Pos : Integer := Position - Source.First.Last;
Offset : Positive := Source.First.Last;
B : Block_Access := Source.First.Next_Block;
begin
loop
if B = null then
return 0;
end if;
if Pos <= B.Last then
Result := Index (B.Content (1 .. B.Last));
if Result > 0 then
return Offset + Result;
end if;
end if;
Pos := Pos - B.Last;
Offset := Offset + B.Last;
B := B.Next_Block;
end loop;
end;
end Find;
-- ------------------------------
-- Call the <tt>Process</tt> procedure with the full buffer content, trying to avoid
-- secondary stack copies as much as possible.
-- ------------------------------
procedure Get (Source : in Builder) is
begin
if Source.Length < Source.First.Len then
Process (Source.First.Content (1 .. Source.Length));
else
declare
Content : constant Input := To_Array (Source);
begin
Process (Content);
end;
end if;
end Get;
-- ------------------------------
-- Format the message and replace occurrences of argument patterns by
-- their associated value.
-- Returns the formatted message in the stream
-- ------------------------------
procedure Format (Into : in out Builder;
Message : in Input;
Arguments : in Value_List) is
C : Element_Type;
Old_Pos : Natural;
N : Natural := 0;
Pos : Natural := Message'First;
First : Natural := Pos;
begin
-- Replace {N} with arg1, arg2, arg3 or ?
while Pos <= Message'Last loop
C := Message (Pos);
if Element_Type'Pos (C) = Character'Pos ('{') and then Pos + 1 <= Message'Last then
if First /= Pos then
Append (Into, Message (First .. Pos - 1));
end if;
N := 0;
Pos := Pos + 1;
C := Message (Pos);
-- Handle {} replacement to emit the current argument and advance argument position.
if Element_Type'Pos (C) = Character'Pos ('}') then
Pos := Pos + 1;
if N >= Arguments'Length then
First := Pos - 2;
else
Append (Into, Arguments (N + Arguments'First));
First := Pos;
end if;
N := N + 1;
else
N := 0;
Old_Pos := Pos - 1;
loop
if Element_Type'Pos (C) >= Character'Pos ('0')
and Element_Type'Pos (C) <= Character'Pos ('9')
then
N := N * 10 + Natural (Element_Type'Pos (C) - Character'Pos ('0'));
Pos := Pos + 1;
if Pos > Message'Last then
First := Old_Pos;
exit;
end if;
elsif Element_Type'Pos (C) = Character'Pos ('}') then
Pos := Pos + 1;
if N >= Arguments'Length then
First := Old_Pos;
else
Append (Into, Arguments (N + Arguments'First));
First := Pos;
end if;
exit;
else
First := Old_Pos;
exit;
end if;
C := Message (Pos);
end loop;
end if;
else
Pos := Pos + 1;
end if;
end loop;
if First /= Pos then
Append (Into, Message (First .. Pos - 1));
end if;
end Format;
-- ------------------------------
-- Setup the builder.
-- ------------------------------
overriding
procedure Initialize (Source : in out Builder) is
begin
Source.Current := Source.First'Unchecked_Access;
end Initialize;
-- ------------------------------
-- Finalize the builder releasing the storage.
-- ------------------------------
overriding
procedure Finalize (Source : in out Builder) is
begin
Clear (Source);
end Finalize;
end Util.Texts.Builders;
|
-----------------------------------------------------------------------
-- util-texts-builders -- Text builder
-- Copyright (C) 2013, 2016, 2017, 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;
package body Util.Texts.Builders is
-- ------------------------------
-- Get the length of the item builder.
-- ------------------------------
function Length (Source : in Builder) return Natural is
begin
return Source.Length;
end Length;
-- ------------------------------
-- Get the capacity of the builder.
-- ------------------------------
function Capacity (Source : in Builder) return Natural is
B : constant Block_Access := Source.Current;
begin
return Source.Length + B.Len - B.Last;
end Capacity;
-- ------------------------------
-- Get the builder block size.
-- ------------------------------
function Block_Size (Source : in Builder) return Positive is
begin
return Source.Block_Size;
end Block_Size;
-- ------------------------------
-- Set the block size for the allocation of next chunks.
-- ------------------------------
procedure Set_Block_Size (Source : in out Builder;
Size : in Positive) is
begin
Source.Block_Size := Size;
end Set_Block_Size;
-- ------------------------------
-- Append the <tt>New_Item</tt> at the end of the source growing the buffer if necessary.
-- ------------------------------
procedure Append (Source : in out Builder;
New_Item : in Input) is
B : Block_Access := Source.Current;
Start : Natural := New_Item'First;
Last : constant Natural := New_Item'Last;
begin
while Start <= Last loop
declare
Space : Natural := B.Len - B.Last;
Size : constant Natural := Last - Start + 1;
begin
if Space > Size then
Space := Size;
elsif Space = 0 then
if Size > Source.Block_Size then
B.Next_Block := new Block (Size);
else
B.Next_Block := new Block (Source.Block_Size);
end if;
B := B.Next_Block;
Source.Current := B;
if B.Len > Size then
Space := Size;
else
Space := B.Len;
end if;
end if;
B.Content (B.Last + 1 .. B.Last + Space) := New_Item (Start .. Start + Space - 1);
Source.Length := Source.Length + Space;
B.Last := B.Last + Space;
Start := Start + Space;
end;
end loop;
end Append;
-- ------------------------------
-- Append the <tt>New_Item</tt> at the end of the source growing the buffer if necessary.
-- ------------------------------
procedure Append (Source : in out Builder;
New_Item : in Element_Type) is
B : Block_Access := Source.Current;
begin
if B.Len = B.Last then
B.Next_Block := new Block (Source.Block_Size);
B := B.Next_Block;
Source.Current := B;
end if;
Source.Length := Source.Length + 1;
B.Last := B.Last + 1;
B.Content (B.Last) := New_Item;
end Append;
procedure Inline_Append (Source : in out Builder) is
B : Block_Access := Source.Current;
Last : Natural;
begin
loop
if B.Len = B.Last then
B.Next_Block := new Block (Source.Block_Size);
B := B.Next_Block;
Source.Current := B;
end if;
Process (B.Content (B.Last + 1 .. B.Len), Last);
exit when Last > B.Len or Last <= B.Last;
Source.Length := Source.Length + Last - B.Last;
B.Last := Last;
exit when Last < B.Len;
end loop;
end Inline_Append;
-- ------------------------------
-- Append in `Into` builder the `Content` builder starting at `From` position
-- and the up to and including the `To` position.
-- ------------------------------
procedure Append (Into : in out Builder;
Content : in Builder;
From : in Positive;
To : in Positive) is
begin
if From <= Content.First.Last then
if To <= Content.First.Last then
Append (Into, Content.First.Content (From .. To));
return;
end if;
Append (Into, Content.First.Content (From .. Content.First.Last));
end if;
declare
Pos : Integer := From - Into.First.Last;
Last : Integer := To - Into.First.Last;
B : Block_Access := Into.First.Next_Block;
begin
loop
if B = null then
return;
end if;
if Pos <= B.Last then
if Last <= B.Last then
Append (Into, B.Content (1 .. Last));
return;
end if;
Append (Into, B.Content (1 .. B.Last));
end if;
Pos := Pos - B.Last;
Last := Last - B.Last;
B := B.Next_Block;
end loop;
end;
end Append;
-- ------------------------------
-- Clear the source freeing any storage allocated for the buffer.
-- ------------------------------
procedure Clear (Source : in out Builder) is
procedure Free is
new Ada.Unchecked_Deallocation (Object => Block, Name => Block_Access);
Current, Next : Block_Access;
begin
Next := Source.First.Next_Block;
while Next /= null loop
Current := Next;
Next := Current.Next_Block;
Free (Current);
end loop;
Source.First.Next_Block := null;
Source.First.Last := 0;
Source.Current := Source.First'Unchecked_Access;
Source.Length := 0;
end Clear;
-- ------------------------------
-- Iterate over the buffer content calling the <tt>Process</tt> procedure with each
-- chunk.
-- ------------------------------
procedure Iterate (Source : in Builder;
Process : not null access procedure (Chunk : in Input)) is
begin
if Source.First.Last > 0 then
Process (Source.First.Content (1 .. Source.First.Last));
declare
B : Block_Access := Source.First.Next_Block;
begin
while B /= null loop
Process (B.Content (1 .. B.Last));
B := B.Next_Block;
end loop;
end;
end if;
end Iterate;
procedure Inline_Iterate (Source : in Builder) is
begin
if Source.First.Last > 0 then
Process (Source.First.Content (1 .. Source.First.Last));
declare
B : Block_Access := Source.First.Next_Block;
begin
while B /= null loop
Process (B.Content (1 .. B.Last));
B := B.Next_Block;
end loop;
end;
end if;
end Inline_Iterate;
-- ------------------------------
-- Return the content starting from the tail and up to <tt>Length</tt> items.
-- ------------------------------
function Tail (Source : in Builder;
Length : in Natural) return Input is
Last : constant Natural := Source.Current.Last;
begin
if Last >= Length then
return Source.Current.Content (Last - Length + 1 .. Last);
elsif Length >= Source.Length then
return To_Array (Source);
else
declare
Result : Input (1 .. Length);
Offset : Natural := Source.Length - Length;
B : access constant Block := Source.First'Access;
Src_Pos : Positive := 1;
Dst_Pos : Positive := 1;
Len : Natural;
begin
-- Skip the data moving to next blocks as needed.
while Offset /= 0 loop
if Offset < B.Last then
Src_Pos := Offset + 1;
Offset := 0;
else
Offset := Offset - B.Last + 1;
B := B.Next_Block;
end if;
end loop;
-- Copy what remains until we reach the length.
while Dst_Pos <= Length loop
Len := B.Last - Src_Pos + 1;
Result (Dst_Pos .. Dst_Pos + Len - 1) := B.Content (Src_Pos .. B.Last);
Src_Pos := 1;
Dst_Pos := Dst_Pos + Len;
B := B.Next_Block;
end loop;
return Result;
end;
end if;
end Tail;
-- ------------------------------
-- Get the buffer content as an array.
-- ------------------------------
function To_Array (Source : in Builder) return Input is
Result : Input (1 .. Source.Length);
begin
if Source.First.Last > 0 then
declare
Pos : Positive := Source.First.Last;
B : Block_Access := Source.First.Next_Block;
begin
Result (1 .. Pos) := Source.First.Content (1 .. Pos);
while B /= null loop
Result (Pos + 1 .. Pos + B.Last) := B.Content (1 .. B.Last);
Pos := Pos + B.Last;
B := B.Next_Block;
end loop;
end;
end if;
return Result;
end To_Array;
-- ------------------------------
-- Get the element at the given position.
-- ------------------------------
function Element (Source : in Builder;
Position : in Positive) return Element_Type is
begin
if Position <= Source.First.Last then
return Source.First.Content (Position);
else
declare
Pos : Positive := Position - Source.First.Last;
B : Block_Access := Source.First.Next_Block;
begin
loop
if Pos <= B.Last then
return B.Content (Pos);
end if;
Pos := Pos - B.Last;
B := B.Next_Block;
end loop;
end;
end if;
end Element;
-- ------------------------------
-- Find the position of some content by running the `Index` function.
-- The `Index` function is called with chunks starting at the given position and
-- until it returns a positive value or we reach the last chunk. It must return
-- the found position in the chunk.
-- ------------------------------
function Find (Source : in Builder;
Position : in Positive) return Natural is
Result : Natural;
begin
if Position <= Source.First.Last then
Result := Index (Source.First.Content (Position .. Source.First.Last));
if Result > 0 then
return Result;
end if;
end if;
declare
Pos : Integer := Position - Source.First.Last;
Offset : Positive := Source.First.Last;
B : Block_Access := Source.First.Next_Block;
begin
loop
if B = null then
return 0;
end if;
if Pos <= B.Last then
if Pos > 0 then
Result := Index (B.Content (Pos .. B.Last));
else
Result := Index (B.Content (1 .. B.Last));
end if;
if Result > 0 then
return Offset + Result;
end if;
end if;
Pos := Pos - B.Last;
Offset := Offset + B.Last;
B := B.Next_Block;
end loop;
end;
end Find;
-- ------------------------------
-- Call the <tt>Process</tt> procedure with the full buffer content, trying to avoid
-- secondary stack copies as much as possible.
-- ------------------------------
procedure Get (Source : in Builder) is
begin
if Source.Length < Source.First.Len then
Process (Source.First.Content (1 .. Source.Length));
else
declare
Content : constant Input := To_Array (Source);
begin
Process (Content);
end;
end if;
end Get;
-- ------------------------------
-- Format the message and replace occurrences of argument patterns by
-- their associated value.
-- Returns the formatted message in the stream
-- ------------------------------
procedure Format (Into : in out Builder;
Message : in Input;
Arguments : in Value_List) is
C : Element_Type;
Old_Pos : Natural;
N : Natural := 0;
Pos : Natural := Message'First;
First : Natural := Pos;
begin
-- Replace {N} with arg1, arg2, arg3 or ?
while Pos <= Message'Last loop
C := Message (Pos);
if Element_Type'Pos (C) = Character'Pos ('{') and then Pos + 1 <= Message'Last then
if First /= Pos then
Append (Into, Message (First .. Pos - 1));
end if;
N := 0;
Pos := Pos + 1;
C := Message (Pos);
-- Handle {} replacement to emit the current argument and advance argument position.
if Element_Type'Pos (C) = Character'Pos ('}') then
Pos := Pos + 1;
if N >= Arguments'Length then
First := Pos - 2;
else
Append (Into, Arguments (N + Arguments'First));
First := Pos;
end if;
N := N + 1;
else
N := 0;
Old_Pos := Pos - 1;
loop
if Element_Type'Pos (C) >= Character'Pos ('0')
and Element_Type'Pos (C) <= Character'Pos ('9')
then
N := N * 10 + Natural (Element_Type'Pos (C) - Character'Pos ('0'));
Pos := Pos + 1;
if Pos > Message'Last then
First := Old_Pos;
exit;
end if;
elsif Element_Type'Pos (C) = Character'Pos ('}') then
Pos := Pos + 1;
if N >= Arguments'Length then
First := Old_Pos;
else
Append (Into, Arguments (N + Arguments'First));
First := Pos;
end if;
exit;
else
First := Old_Pos;
exit;
end if;
C := Message (Pos);
end loop;
end if;
else
Pos := Pos + 1;
end if;
end loop;
if First /= Pos then
Append (Into, Message (First .. Pos - 1));
end if;
end Format;
-- ------------------------------
-- Setup the builder.
-- ------------------------------
overriding
procedure Initialize (Source : in out Builder) is
begin
Source.Current := Source.First'Unchecked_Access;
end Initialize;
-- ------------------------------
-- Finalize the builder releasing the storage.
-- ------------------------------
overriding
procedure Finalize (Source : in out Builder) is
begin
Clear (Source);
end Finalize;
end Util.Texts.Builders;
|
Implement the new Append procedure
|
Implement the new Append procedure
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
922bd81e0f5a3dd14c48ee43397f257fc84a5f09
|
src/util-streams-pipes.adb
|
src/util-streams-pipes.adb
|
-----------------------------------------------------------------------
-- util-streams-raw -- Raw streams for Unix based systems
-- Copyright (C) 2011, 2013, 2016 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.IO_Exceptions;
package body Util.Streams.Pipes is
-- -----------------------
-- 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) is
begin
Util.Processes.Set_Shell (Stream.Proc, Shell);
end Set_Shell;
-- -----------------------
-- 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) is
begin
Util.Processes.Spawn (Stream.Proc, Command, Mode);
end Open;
-- -----------------------
-- Close the pipe and wait for the external process to terminate.
-- -----------------------
overriding
procedure Close (Stream : in out Pipe_Stream) is
begin
Util.Processes.Wait (Stream.Proc);
end Close;
-- -----------------------
-- Get the process exit status.
-- -----------------------
function Get_Exit_Status (Stream : in Pipe_Stream) return Integer is
begin
return Util.Processes.Get_Exit_Status (Stream.Proc);
end Get_Exit_Status;
-- -----------------------
-- Returns True if the process is running.
-- -----------------------
function Is_Running (Stream : in Pipe_Stream) return Boolean is
begin
return Util.Processes.Is_Running (Stream.Proc);
end Is_Running;
-- -----------------------
-- Write the buffer array to the output stream.
-- -----------------------
overriding
procedure Write (Stream : in out Pipe_Stream;
Buffer : in Ada.Streams.Stream_Element_Array) is
Output : constant Streams.Output_Stream_Access := Processes.Get_Input_Stream (Stream.Proc);
begin
if Output = null then
raise Ada.IO_Exceptions.Status_Error with "Process is not launched";
end if;
Output.Write (Buffer);
end Write;
-- -----------------------
-- Read into the buffer as many bytes as possible and return in
-- <b>last</b> the position of the last byte read.
-- -----------------------
overriding
procedure Read (Stream : in out Pipe_Stream;
Into : out Ada.Streams.Stream_Element_Array;
Last : out Ada.Streams.Stream_Element_Offset) is
Input : constant Streams.Input_Stream_Access := Processes.Get_Output_Stream (Stream.Proc);
begin
if Input = null then
raise Ada.IO_Exceptions.Status_Error with "Process is not launched";
end if;
Input.Read (Into, Last);
end Read;
-- -----------------------
-- Flush the stream and release the buffer.
-- -----------------------
overriding
procedure Finalize (Object : in out Pipe_Stream) is
begin
null;
end Finalize;
end Util.Streams.Pipes;
|
-----------------------------------------------------------------------
-- util-streams-raw -- Raw streams for Unix based systems
-- Copyright (C) 2011, 2013, 2016, 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.IO_Exceptions;
package body Util.Streams.Pipes is
-- -----------------------
-- 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) is
begin
Util.Processes.Set_Shell (Stream.Proc, Shell);
end Set_Shell;
-- -----------------------
-- 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) is
begin
Util.Processes.Set_Input_Stream (Stream.Proc, File);
end Set_Input_Stream;
-- -----------------------
-- 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) is
begin
Util.Processes.Set_Output_Stream (Stream.Proc, File, Append);
end Set_Output_Stream;
-- -----------------------
-- 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) is
begin
Util.Processes.Set_Error_Stream (Stream.Proc, File, Append);
end Set_Error_Stream;
-- -----------------------
-- 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) is
begin
Util.Processes.Set_Working_Directory (Stream.Proc, Path);
end Set_Working_Directory;
-- -----------------------
-- 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) is
begin
Util.Processes.Spawn (Stream.Proc, Command, Mode);
end Open;
-- -----------------------
-- Close the pipe and wait for the external process to terminate.
-- -----------------------
overriding
procedure Close (Stream : in out Pipe_Stream) is
begin
Util.Processes.Wait (Stream.Proc);
end Close;
-- -----------------------
-- Get the process exit status.
-- -----------------------
function Get_Exit_Status (Stream : in Pipe_Stream) return Integer is
begin
return Util.Processes.Get_Exit_Status (Stream.Proc);
end Get_Exit_Status;
-- -----------------------
-- Returns True if the process is running.
-- -----------------------
function Is_Running (Stream : in Pipe_Stream) return Boolean is
begin
return Util.Processes.Is_Running (Stream.Proc);
end Is_Running;
-- -----------------------
-- Write the buffer array to the output stream.
-- -----------------------
overriding
procedure Write (Stream : in out Pipe_Stream;
Buffer : in Ada.Streams.Stream_Element_Array) is
Output : constant Streams.Output_Stream_Access := Processes.Get_Input_Stream (Stream.Proc);
begin
if Output = null then
raise Ada.IO_Exceptions.Status_Error with "Process is not launched";
end if;
Output.Write (Buffer);
end Write;
-- -----------------------
-- Read into the buffer as many bytes as possible and return in
-- <b>last</b> the position of the last byte read.
-- -----------------------
overriding
procedure Read (Stream : in out Pipe_Stream;
Into : out Ada.Streams.Stream_Element_Array;
Last : out Ada.Streams.Stream_Element_Offset) is
Input : constant Streams.Input_Stream_Access := Processes.Get_Output_Stream (Stream.Proc);
begin
if Input = null then
raise Ada.IO_Exceptions.Status_Error with "Process is not launched";
end if;
Input.Read (Into, Last);
end Read;
-- -----------------------
-- Flush the stream and release the buffer.
-- -----------------------
overriding
procedure Finalize (Object : in out Pipe_Stream) is
begin
null;
end Finalize;
end Util.Streams.Pipes;
|
Implement Set_Input_Stream, Set_Output_Stream, Set_Error_Stream, Set_Working_Directory procedures
|
Implement Set_Input_Stream, Set_Output_Stream, Set_Error_Stream, Set_Working_Directory procedures
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
becdd5927a7cac7e10c479de21487c922a5c5a81
|
hal/src/hal-filesystem.ads
|
hal/src/hal-filesystem.ads
|
package HAL.Filesystem is
subtype Pathname is String;
type File_Kind is (Regular_File, Directory);
type File_Mode is (Read_Only, Write_Only, Read_Write);
type Permission_Kind is (Others_Execute, Others_Write, Others_Read,
Group_Execute, Group_Write, Group_Read,
Owner_Execute, Owner_Write, Owner_Read);
type Permission_Set is array (Permission_Kind) of Boolean;
type Status_Kind is (Status_Ok,
Symbolic_Links_Loop,
Permission_Denied,
Input_Output_Error,
No_Such_File_Or_Directory,
Filename_Is_Too_Long,
Not_A_Directory,
Representation_Overflow,
Invalid_Argument,
Not_Enough_Space,
Not_Enough_Memory,
Bad_Address,
File_Exists,
Read_Only_File_System,
Operation_Not_Permitted,
No_Space_Left_On_Device,
Too_Many_Links,
Resource_Busy,
Buffer_Is_Too_Small,
Read_Would_Block,
Call_Was_Interrupted);
type FS_Driver is limited interface;
type FS_Driver_Ref is access all FS_Driver'Class;
function Create_Node (This : in out FS_Driver;
Path : Pathname;
Kind : File_Kind)
return Status_Kind is abstract;
end HAL.Filesystem;
|
with Interfaces; use Interfaces;
package HAL.Filesystem is
subtype Pathname is String;
type File_Kind is (Regular_File, Directory);
type File_Mode is (Read_Only, Write_Only, Read_Write);
type Permission_Kind is (Others_Execute, Others_Write, Others_Read,
Group_Execute, Group_Write, Group_Read,
Owner_Execute, Owner_Write, Owner_Read);
type Permission_Set is array (Permission_Kind) of Boolean;
type Status_Kind is (Status_Ok,
Symbolic_Links_Loop,
Permission_Denied,
Input_Output_Error,
No_Such_File_Or_Directory,
Filename_Is_Too_Long,
Not_A_Directory,
Representation_Overflow,
Invalid_Argument,
Not_Enough_Space,
Not_Enough_Memory,
Bad_Address,
File_Exists,
Read_Only_File_System,
Operation_Not_Permitted,
No_Space_Left_On_Device,
Too_Many_Links,
Resource_Busy,
Buffer_Is_Too_Small,
Read_Would_Block,
Call_Was_Interrupted);
type User_ID is new Natural;
type Group_ID is new Natural;
type IO_Count is new Unsigned_64;
type FS_Driver is limited interface;
type FS_Driver_Ref is access all FS_Driver'Class;
function Create_Node (This : in out FS_Driver;
Path : Pathname;
Kind : File_Kind)
return Status_Kind is abstract;
function Create_Directory (This : in out FS_Driver;
Path : Pathname)
return Status_Kind is abstract;
function Unlink (This : in out FS_Driver;
Path : Pathname)
return Status_Kind is abstract;
function Remove_Directory (This : in out FS_Driver;
Path : Pathname)
return Status_Kind is abstract;
function Rename (This : in out FS_Driver;
Old_Path : Pathname;
New_Path : Pathname)
return Status_Kind is abstract;
function Change_Permissions (This : in out FS_Driver;
Path : Pathname;
Permissions : Permission_Set)
return Status_Kind is abstract;
function Change_Owner_And_Group (This : in out FS_Driver;
Path : Pathname;
Owner : User_ID;
Group : Group_ID)
return Status_Kind is abstract;
function Change_Permissions (This : in out FS_Driver;
Path : Pathname;
Lenght : IO_Count)
return Status_Kind is abstract;
end HAL.Filesystem;
|
Add a few function in the file system interface
|
Add a few function in the file system interface
|
Ada
|
bsd-3-clause
|
Fabien-Chouteau/Ada_Drivers_Library,lambourg/Ada_Drivers_Library,simonjwright/Ada_Drivers_Library,simonjwright/Ada_Drivers_Library,Fabien-Chouteau/Ada_Drivers_Library,AdaCore/Ada_Drivers_Library,ellamosi/Ada_BMP_Library,AdaCore/Ada_Drivers_Library
|
e25ffdbb4451fd3c682ec63ffe997a8d8d280e61
|
ARM/STM32/drivers/stm32-gpio.adb
|
ARM/STM32/drivers/stm32-gpio.adb
|
------------------------------------------------------------------------------
-- --
-- Copyright (C) 2015, AdaCore --
-- --
-- Redistribution and use in source and binary forms, with or without --
-- modification, are permitted provided that the following conditions are --
-- met: --
-- 1. Redistributions of source code must retain the above copyright --
-- notice, this list of conditions and the following disclaimer. --
-- 2. Redistributions in binary form must reproduce the above copyright --
-- notice, this list of conditions and the following disclaimer in --
-- the documentation and/or other materials provided with the --
-- distribution. --
-- 3. Neither the name of STMicroelectronics nor the names of its --
-- contributors may be used to endorse or promote products derived --
-- from this software without specific prior written permission. --
-- --
-- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS --
-- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT --
-- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR --
-- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT --
-- HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, --
-- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT --
-- LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, --
-- DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY --
-- THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT --
-- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE --
-- OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. --
-- --
-- --
-- This file is based on: --
-- --
-- @file stm32f4xx_hal_gpio.c --
-- @author MCD Application Team --
-- @version V1.1.0 --
-- @date 19-June-2014 --
-- @brief GPIO HAL module driver. --
-- --
-- COPYRIGHT(c) 2014 STMicroelectronics --
------------------------------------------------------------------------------
with System; use System;
with STM32_SVD.GPIO; use STM32_SVD.GPIO;
with STM32.RCC;
with STM32.SYSCFG;
with System.Machine_Code;
package body STM32.GPIO is
procedure Lock_The_Pin (Port : in out Internal_GPIO_Port; Pin : Short);
-- This is the routine that actually locks the pin for the port. It is an
-- internal routine and has no preconditions. We use it to avoid redundant
-- calls to the precondition that checks that the pin is not already
-- locked. The redundancy would otherwise occur because the routine that
-- locks an array of pins is implemented by calling the routine that locks
-- a single pin: both those Lock routines have a precondition that checks
-- that the pin(s) is not already being locked.
-------------
-- Any_Set --
-------------
function Any_Set (Pins : GPIO_Points) return Boolean is
begin
for Pin of Pins loop
if Pin.Set then
return True;
end if;
end loop;
return False;
end Any_Set;
---------
-- Set --
---------
overriding
function Set (This : GPIO_Point) return Boolean is
(This.Periph.IDR.IDR.Arr (This.Pin));
-------------
-- All_Set --
-------------
function All_Set (Pins : GPIO_Points) return Boolean is
begin
for Pin of Pins loop
if not Pin.Set then
return False;
end if;
end loop;
return True;
end All_Set;
---------
-- Set --
---------
overriding
procedure Set (This : in out GPIO_Point) is
begin
This.Periph.BSRR.BS.Arr (This.Pin) := True;
end Set;
---------
-- Set --
---------
procedure Set (Pins : in out GPIO_Points) is
begin
for Pin of Pins loop
Pin.Set;
end loop;
end Set;
-----------
-- Clear --
-----------
overriding
procedure Clear (This : in out GPIO_Point) is
begin
This.Periph.BSRR.BR.Arr (This.Pin) := True;
end Clear;
-----------
-- Clear --
-----------
procedure Clear (Pins : in out GPIO_Points) is
begin
for Pin of Pins loop
Pin.Clear;
end loop;
end Clear;
------------
-- Toggle --
------------
overriding
procedure Toggle (This : in out GPIO_Point) is
begin
This.Periph.ODR.ODR.Arr (This.Pin) :=
not This.Periph.ODR.ODR.Arr (This.Pin);
end Toggle;
------------
-- Toggle --
------------
procedure Toggle (Points : in out GPIO_Points) is
begin
for Point of Points loop
Point.Toggle;
end loop;
end Toggle;
------------
-- Locked --
------------
function Locked (Pin : GPIO_Point) return Boolean is
(Pin.Periph.LCKR.LCK.Arr (Pin.Pin));
------------------
-- Lock_The_Pin --
------------------
procedure Lock_The_Pin (Port : in out Internal_GPIO_Port; Pin : Short) is
Temp : Word;
pragma Volatile (Temp);
use System.Machine_Code;
use ASCII;
begin
-- As per the Reference Manual (RM0090; Doc ID 018909 Rev 6) pg 282,
-- a specific sequence is required to set the Lock bit. Throughout the
-- sequence the same value for the lower 15 bits of the word must be
-- used (ie the pin number). The lock bit is referred to as LCKK in
-- the doc.
-- Temp := LCCK or Pin'Enum_Rep;
--
-- -- set the lock bit
-- Port.LCKR := Temp;
--
-- -- clear the lock bit
-- Port.LCKR := Pin'Enum_Rep;
--
-- -- set the lock bit again
-- Port.LCKR := Temp;
--
-- -- read the lock bit
-- Temp := Port.LCKR;
--
-- -- read the lock bit again
-- Temp := Port.LCKR;
-- We use the following assembly language sequence because the above
-- high-level version in Ada works only if the optimizer is enabled.
-- This is not an issue specific to Ada. If you need a specific sequence
-- of instructions you should really specify those instructions.
-- We don't want the functionality to depend on the switches, and we
-- don't want to preclude debugging, hence the following:
Asm ("orr r3, %2, #65536" & LF & HT &
"str r3, %0" & LF & HT &
"ldr r3, %0" & LF & HT & -- temp <- pin or LCCK
"str r3, [%1, #28]" & LF & HT & -- temp -> lckr
"str %2, [%1, #28]" & LF & HT & -- pin -> lckr
"ldr r3, %0" & LF & HT &
"str r3, [%1, #28]" & LF & HT & -- temp -> lckr
"ldr r3, [%1, #28]" & LF & HT &
"str r3, %0" & LF & HT & -- temp <- lckr
"ldr r3, [%1, #28]" & LF & HT &
"str r3, %0" & LF & HT, -- temp <- lckr
Inputs => (Address'Asm_Input ("r", Port'Address), -- %1
(Short'Asm_Input ("r", Pin))), -- %2
Outputs => (Word'Asm_Output ("=m", Temp)), -- %0
Volatile => True,
Clobber => ("r2, r3"));
end Lock_The_Pin;
----------
-- Lock --
----------
procedure Lock (Point : GPIO_Point) is
begin
Lock_The_Pin (Point.Periph.all, Shift_Left (1, Point.Pin));
end Lock;
----------
-- Lock --
----------
procedure Lock (Points : GPIO_Points) is
begin
for Point of Points loop
Point.Lock;
end loop;
end Lock;
------------------
-- Configure_IO --
------------------
procedure Configure_IO
(Point : GPIO_Point;
Config : GPIO_Port_Configuration)
is
MODER : MODER_Register := Point.Periph.MODER;
OTYPER : OTYPER_Register := Point.Periph.OTYPER;
OSPEEDR : OSPEEDR_Register := Point.Periph.OSPEEDR;
PUPDR : PUPDR_Register := Point.Periph.PUPDR;
begin
MODER.Arr (Point.Pin) :=
Pin_IO_Modes'Enum_Rep (Config.Mode);
OTYPER.OT.Arr (Point.Pin) := Config.Output_Type = Open_Drain;
OSPEEDR.Arr (Point.Pin) :=
Pin_Output_Speeds'Enum_Rep (Config.Speed);
PUPDR.Arr (Point.Pin) :=
Internal_Pin_Resistors'Enum_Rep (Config.Resistors);
Point.Periph.MODER := MODER;
Point.Periph.OTYPER := OTYPER;
Point.Periph.OSPEEDR := OSPEEDR;
Point.Periph.PUPDR := PUPDR;
end Configure_IO;
------------------
-- Configure_IO --
------------------
procedure Configure_IO
(Points : GPIO_Points;
Config : GPIO_Port_Configuration)
is
begin
for Point of Points loop
Point.Configure_IO (Config);
end loop;
end Configure_IO;
----------------------------------
-- Configure_Alternate_Function --
----------------------------------
procedure Configure_Alternate_Function
(Point : GPIO_Point;
AF : GPIO_Alternate_Function)
is
begin
if Point.Pin < 8 then
Point.Periph.AFRL.Arr (Point.Pin) := UInt4 (AF);
else
Point.Periph.AFRH.Arr (Point.Pin) := UInt4 (AF);
end if;
end Configure_Alternate_Function;
----------------------------------
-- Configure_Alternate_Function --
----------------------------------
procedure Configure_Alternate_Function
(Points : GPIO_Points;
AF : GPIO_Alternate_Function)
is
begin
for Point of Points loop
Point.Configure_Alternate_Function (AF);
end loop;
end Configure_Alternate_Function;
-------------------------------
-- Get_Interrupt_Line_Number --
-------------------------------
function Get_Interrupt_Line_Number
(Point : GPIO_Point) return EXTI.External_Line_Number
is
begin
return EXTI.External_Line_Number'Val (Point.Pin);
end Get_Interrupt_Line_Number;
-----------------------
-- Configure_Trigger --
-----------------------
procedure Configure_Trigger
(Point : GPIO_Point;
Trigger : EXTI.External_Triggers)
is
use STM32.EXTI;
Line : constant External_Line_Number :=
External_Line_Number'Val (Point.Pin);
use STM32.SYSCFG, STM32.RCC;
begin
SYSCFG_Clock_Enable;
Connect_External_Interrupt (Point);
if Trigger in Interrupt_Triggers then
Enable_External_Interrupt (Line, Trigger);
else
Enable_External_Event (Line, Trigger);
end if;
end Configure_Trigger;
-----------------------
-- Configure_Trigger --
-----------------------
procedure Configure_Trigger
(Points : GPIO_Points;
Trigger : EXTI.External_Triggers)
is
begin
for Point of Points loop
Point.Configure_Trigger (Trigger);
end loop;
end Configure_Trigger;
end STM32.GPIO;
|
------------------------------------------------------------------------------
-- --
-- Copyright (C) 2015, AdaCore --
-- --
-- Redistribution and use in source and binary forms, with or without --
-- modification, are permitted provided that the following conditions are --
-- met: --
-- 1. Redistributions of source code must retain the above copyright --
-- notice, this list of conditions and the following disclaimer. --
-- 2. Redistributions in binary form must reproduce the above copyright --
-- notice, this list of conditions and the following disclaimer in --
-- the documentation and/or other materials provided with the --
-- distribution. --
-- 3. Neither the name of STMicroelectronics nor the names of its --
-- contributors may be used to endorse or promote products derived --
-- from this software without specific prior written permission. --
-- --
-- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS --
-- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT --
-- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR --
-- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT --
-- HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, --
-- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT --
-- LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, --
-- DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY --
-- THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT --
-- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE --
-- OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. --
-- --
-- --
-- This file is based on: --
-- --
-- @file stm32f4xx_hal_gpio.c --
-- @author MCD Application Team --
-- @version V1.1.0 --
-- @date 19-June-2014 --
-- @brief GPIO HAL module driver. --
-- --
-- COPYRIGHT(c) 2014 STMicroelectronics --
------------------------------------------------------------------------------
with System; use System;
with STM32_SVD.GPIO; use STM32_SVD.GPIO;
with STM32.RCC;
with STM32.SYSCFG;
with System.Machine_Code;
package body STM32.GPIO is
procedure Lock_The_Pin (Port : in out Internal_GPIO_Port; Pin : Short);
-- This is the routine that actually locks the pin for the port. It is an
-- internal routine and has no preconditions. We use it to avoid redundant
-- calls to the precondition that checks that the pin is not already
-- locked. The redundancy would otherwise occur because the routine that
-- locks an array of pins is implemented by calling the routine that locks
-- a single pin: both those Lock routines have a precondition that checks
-- that the pin(s) is not already being locked.
-------------
-- Any_Set --
-------------
function Any_Set (Pins : GPIO_Points) return Boolean is
begin
for Pin of Pins loop
if Pin.Set then
return True;
end if;
end loop;
return False;
end Any_Set;
---------
-- Set --
---------
overriding
function Set (This : GPIO_Point) return Boolean is
(This.Periph.IDR.IDR.Arr (This.Pin));
-------------
-- All_Set --
-------------
function All_Set (Pins : GPIO_Points) return Boolean is
begin
for Pin of Pins loop
if not Pin.Set then
return False;
end if;
end loop;
return True;
end All_Set;
---------
-- Set --
---------
overriding
procedure Set (This : in out GPIO_Point) is
begin
This.Periph.BSRR.BS.Arr (This.Pin) := True;
end Set;
---------
-- Set --
---------
procedure Set (Pins : in out GPIO_Points) is
begin
for Pin of Pins loop
Pin.Set;
end loop;
end Set;
-----------
-- Clear --
-----------
overriding
procedure Clear (This : in out GPIO_Point) is
begin
This.Periph.BSRR.BR.Arr (This.Pin) := True;
end Clear;
-----------
-- Clear --
-----------
procedure Clear (Pins : in out GPIO_Points) is
begin
for Pin of Pins loop
Pin.Clear;
end loop;
end Clear;
------------
-- Toggle --
------------
overriding
procedure Toggle (This : in out GPIO_Point) is
begin
This.Periph.ODR.ODR.Arr (This.Pin) :=
not This.Periph.ODR.ODR.Arr (This.Pin);
end Toggle;
------------
-- Toggle --
------------
procedure Toggle (Points : in out GPIO_Points) is
begin
for Point of Points loop
Point.Toggle;
end loop;
end Toggle;
------------
-- Locked --
------------
function Locked (Pin : GPIO_Point) return Boolean is
(Pin.Periph.LCKR.LCK.Arr (Pin.Pin));
------------------
-- Lock_The_Pin --
------------------
procedure Lock_The_Pin (Port : in out Internal_GPIO_Port; Pin : Short) is
Temp : Word;
pragma Volatile (Temp);
use System.Machine_Code;
use ASCII;
begin
-- As per the Reference Manual (RM0090; Doc ID 018909 Rev 6) pg 282,
-- a specific sequence is required to set the Lock bit. Throughout the
-- sequence the same value for the lower 15 bits of the word must be
-- used (ie the pin number). The lock bit is referred to as LCKK in
-- the doc.
-- Temp := LCCK or Pin'Enum_Rep;
--
-- -- set the lock bit
-- Port.LCKR := Temp;
--
-- -- clear the lock bit
-- Port.LCKR := Pin'Enum_Rep;
--
-- -- set the lock bit again
-- Port.LCKR := Temp;
--
-- -- read the lock bit
-- Temp := Port.LCKR;
--
-- -- read the lock bit again
-- Temp := Port.LCKR;
-- We use the following assembly language sequence because the above
-- high-level version in Ada works only if the optimizer is enabled.
-- This is not an issue specific to Ada. If you need a specific sequence
-- of instructions you should really specify those instructions.
-- We don't want the functionality to depend on the switches, and we
-- don't want to preclude debugging, hence the following:
Asm ("orr r3, %2, #65536" & LF & HT &
"str r3, %0" & LF & HT &
"ldr r3, %0" & LF & HT & -- temp <- pin or LCCK
"str r3, [%1, #28]" & LF & HT & -- temp -> lckr
"str %2, [%1, #28]" & LF & HT & -- pin -> lckr
"ldr r3, %0" & LF & HT &
"str r3, [%1, #28]" & LF & HT & -- temp -> lckr
"ldr r3, [%1, #28]" & LF & HT &
"str r3, %0" & LF & HT & -- temp <- lckr
"ldr r3, [%1, #28]" & LF & HT &
"str r3, %0" & LF & HT, -- temp <- lckr
Inputs => (Address'Asm_Input ("r", Port'Address), -- %1
(Short'Asm_Input ("r", Pin))), -- %2
Outputs => (Word'Asm_Output ("=m", Temp)), -- %0
Volatile => True,
Clobber => ("r2, r3"));
end Lock_The_Pin;
----------
-- Lock --
----------
procedure Lock (Point : GPIO_Point) is
begin
Lock_The_Pin (Point.Periph.all, Shift_Left (1, Point.Pin));
end Lock;
----------
-- Lock --
----------
procedure Lock (Points : GPIO_Points) is
begin
for Point of Points loop
if not Locked (Point) then
Point.Lock;
end if;
end loop;
end Lock;
------------------
-- Configure_IO --
------------------
procedure Configure_IO
(Point : GPIO_Point;
Config : GPIO_Port_Configuration)
is
MODER : MODER_Register := Point.Periph.MODER;
OTYPER : OTYPER_Register := Point.Periph.OTYPER;
OSPEEDR : OSPEEDR_Register := Point.Periph.OSPEEDR;
PUPDR : PUPDR_Register := Point.Periph.PUPDR;
begin
MODER.Arr (Point.Pin) :=
Pin_IO_Modes'Enum_Rep (Config.Mode);
OTYPER.OT.Arr (Point.Pin) := Config.Output_Type = Open_Drain;
OSPEEDR.Arr (Point.Pin) :=
Pin_Output_Speeds'Enum_Rep (Config.Speed);
PUPDR.Arr (Point.Pin) :=
Internal_Pin_Resistors'Enum_Rep (Config.Resistors);
Point.Periph.MODER := MODER;
Point.Periph.OTYPER := OTYPER;
Point.Periph.OSPEEDR := OSPEEDR;
Point.Periph.PUPDR := PUPDR;
end Configure_IO;
------------------
-- Configure_IO --
------------------
procedure Configure_IO
(Points : GPIO_Points;
Config : GPIO_Port_Configuration)
is
begin
for Point of Points loop
Point.Configure_IO (Config);
end loop;
end Configure_IO;
----------------------------------
-- Configure_Alternate_Function --
----------------------------------
procedure Configure_Alternate_Function
(Point : GPIO_Point;
AF : GPIO_Alternate_Function)
is
begin
if Point.Pin < 8 then
Point.Periph.AFRL.Arr (Point.Pin) := UInt4 (AF);
else
Point.Periph.AFRH.Arr (Point.Pin) := UInt4 (AF);
end if;
end Configure_Alternate_Function;
----------------------------------
-- Configure_Alternate_Function --
----------------------------------
procedure Configure_Alternate_Function
(Points : GPIO_Points;
AF : GPIO_Alternate_Function)
is
begin
for Point of Points loop
Point.Configure_Alternate_Function (AF);
end loop;
end Configure_Alternate_Function;
-------------------------------
-- Get_Interrupt_Line_Number --
-------------------------------
function Get_Interrupt_Line_Number
(Point : GPIO_Point) return EXTI.External_Line_Number
is
begin
return EXTI.External_Line_Number'Val (Point.Pin);
end Get_Interrupt_Line_Number;
-----------------------
-- Configure_Trigger --
-----------------------
procedure Configure_Trigger
(Point : GPIO_Point;
Trigger : EXTI.External_Triggers)
is
use STM32.EXTI;
Line : constant External_Line_Number :=
External_Line_Number'Val (Point.Pin);
use STM32.SYSCFG, STM32.RCC;
begin
SYSCFG_Clock_Enable;
Connect_External_Interrupt (Point);
if Trigger in Interrupt_Triggers then
Enable_External_Interrupt (Line, Trigger);
else
Enable_External_Event (Line, Trigger);
end if;
end Configure_Trigger;
-----------------------
-- Configure_Trigger --
-----------------------
procedure Configure_Trigger
(Points : GPIO_Points;
Trigger : EXTI.External_Triggers)
is
begin
for Point of Points loop
Point.Configure_Trigger (Trigger);
end loop;
end Configure_Trigger;
end STM32.GPIO;
|
Fix pre-condition issue when soft resetting boards.
|
Fix pre-condition issue when soft resetting boards.
|
Ada
|
bsd-3-clause
|
AdaCore/Ada_Drivers_Library,ellamosi/Ada_BMP_Library,simonjwright/Ada_Drivers_Library,simonjwright/Ada_Drivers_Library,Fabien-Chouteau/Ada_Drivers_Library,AdaCore/Ada_Drivers_Library,lambourg/Ada_Drivers_Library,Fabien-Chouteau/Ada_Drivers_Library
|
7f237ef2057724da67ee41276723c6975500ac82
|
ARM/STMicro/STM32/drivers/dma2d/stm32-dma2d.ads
|
ARM/STMicro/STM32/drivers/dma2d/stm32-dma2d.ads
|
------------------------------------------------------------------------------
-- --
-- Copyright (C) 2015, AdaCore --
-- --
-- Redistribution and use in source and binary forms, with or without --
-- modification, are permitted provided that the following conditions are --
-- met: --
-- 1. Redistributions of source code must retain the above copyright --
-- notice, this list of conditions and the following disclaimer. --
-- 2. Redistributions in binary form must reproduce the above copyright --
-- notice, this list of conditions and the following disclaimer in --
-- the documentation and/or other materials provided with the --
-- distribution. --
-- 3. Neither the name of STMicroelectronics nor the names of its --
-- contributors may be used to endorse or promote products derived --
-- from this software without specific prior written permission. --
-- --
-- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS --
-- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT --
-- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR --
-- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT --
-- HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, --
-- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT --
-- LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, --
-- DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY --
-- THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT --
-- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE --
-- OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. --
-- --
------------------------------------------------------------------------------
with Ada.Unchecked_Conversion;
with STM32.LCD;
private with STM32_SVD;
package STM32.DMA2D is
type DMA2D_Color is record
Alpha : Byte;
Red : Byte;
Green : Byte;
Blue : Byte;
end record;
for DMA2D_Color use record
Alpha at 3 range 0 .. 7;
Red at 2 range 0 .. 7;
Green at 1 range 0 .. 7;
Blue at 0 range 0 .. 7;
end record;
-- This bit is set and cleared by software. It cannot be modified
-- while a transfer is ongoing.
type DMA2D_MODE is
(
-- Memory-to-memory (FG fetch only)
M2M,
-- Memory-to-memory with PFC (FG fetch only with FG PFC active)
M2M_PFC,
-- Memory-to-memory with blending (FG and BG fetch with PFC and
-- blending)
M2M_BLEND,
-- Register-to-memory (no FG nor BG, only output stage active)
R2M
);
for DMA2D_MODE'Size use 2;
-- Configuration Error Interrupt Enable
type DMA2D_FLAG is
(Disable,
Enable);
-- Abort
-- This bit can be used to abort the current transfer. This bit is
-- set by software and is automatically reset by hardware when the
-- START bit is reset.
type DMA2D_ABORT is
(
-- 0: No transfer abort requested
Not_Requested,
-- 1: Transfer abort requested
Requested);
-- Suspend
-- This bit can be used to suspend the current transfer. This bit
-- is set and reset by software. It is automatically reset by
-- hardware when the START bit is reset.
type DMA2D_SUSPEND is
(
-- Transfer not suspended
Not_Suspended,
-- Transfer suspended
Supended);
-- Start
-- This bit can be used to launch the DMA2D according to the
-- parameters loaded in the various configuration registers. This
-- bit is automatically reset by the following events:
-- - At the end of the transfer
-- - When the data transfer is aborted by the user application by
-- setting the ABORT bit in DMA2D_CR
-- - When a data transfer error occurs
-- - When the data transfer has not started due to a configuration
-- error or another transfer operation already ongoing (automatic
-- CLUT loading)
type DMA2D_START is
(Not_Started,
Start);
-- These bits defines the color format
subtype DMA2D_Color_Mode is STM32.LCD.Pixel_Format;
-- (ARGB8888,
-- RGB888,
-- RGB565,
-- ARGB1555,
-- ARGB4444);
-- for DMA2D_Color_Mode'Size use 3;
-- Alpha mode
-- 00: No modification of the foreground image alpha channel value
-- 01: Replace original foreground image alpha channel value by ALPHA[7:0]
-- 10: Replace original foreground image alpha channel value by ALPHA[7:0]
-- multiplied with original alpha channel value
-- other configurations are meaningless
type DMA2D_AM is
(NO_MODIF,
REPLACE,
MULTIPLY);
for DMA2D_AM'Size use 2;
procedure DMA2D_DeInit;
type DMA2D_Sync_Procedure is access procedure;
procedure DMA2D_Init
(Init : DMA2D_Sync_Procedure;
Wait : DMA2D_Sync_Procedure);
type DMA2D_Buffer is record
Addr : System.Address;
Width : Natural;
Height : Natural;
Color_Mode : DMA2D_Color_Mode;
Swap_X_Y : Boolean;
end record;
Null_Buffer : constant DMA2D_Buffer :=
(Addr => System'To_Address (0),
Width => 0,
Height => 0,
Color_Mode => DMA2D_Color_Mode'First,
Swap_X_Y => False);
procedure DMA2D_Fill
(Buffer : DMA2D_Buffer;
Color : DMA2D_Color;
Synchronous : Boolean := False);
-- Fill the specified buffer with 'Color'
procedure DMA2D_Fill
(Buffer : DMA2D_Buffer;
Color : Word;
Synchronous : Boolean := False);
-- Same as above, using the destination buffer native color representation
procedure DMA2D_Set_Pixel
(Buffer : DMA2D_Buffer;
X, Y : Integer;
Color : DMA2D_Color;
Synchronous : Boolean := False);
procedure DMA2D_Set_Pixel
(Buffer : DMA2D_Buffer;
X, Y : Integer;
Color : Word;
Synchronous : Boolean := False);
-- Same as above, using the destination buffer native color representation
procedure DMA2D_Set_Pixel_Blend
(Buffer : DMA2D_Buffer;
X, Y : Integer;
Color : DMA2D_Color;
Synchronous : Boolean := False);
procedure DMA2D_Fill_Rect
(Buffer : DMA2D_Buffer;
Color : DMA2D_Color;
X : Integer;
Y : Integer;
Width : Integer;
Height : Integer;
Synchronous : Boolean := False);
-- Fill the specified area of the buffer with 'Color'
procedure DMA2D_Fill_Rect
(Buffer : DMA2D_Buffer;
Color : Word;
X : Integer;
Y : Integer;
Width : Integer;
Height : Integer;
Synchronous : Boolean := False);
-- Same as above, using the destination buffer native color representation
procedure DMA2D_Draw_Rect
(Buffer : DMA2D_Buffer;
Color : DMA2D_Color;
X : Integer;
Y : Integer;
Width : Integer;
Height : Integer);
-- Fill the specified area of the buffer with 'Color'
procedure DMA2D_Copy_Rect
(Src_Buffer : DMA2D_Buffer;
X_Src : Natural;
Y_Src : Natural;
Dst_Buffer : DMA2D_Buffer;
X_Dst : Natural;
Y_Dst : Natural;
Bg_Buffer : DMA2D_Buffer;
X_Bg : Natural;
Y_Bg : Natural;
Width : Natural;
Height : Natural;
Synchronous : Boolean := False);
-- Copy a rectangular area from Src to Dst
-- If Blend is set, then the rectangle will be merged with the destination
-- area, taking into account the opacity of the source. Else, it is simply
-- copied.
--
-- if Bg_Buffer is not Null_Buffer, then the copy will be performed in
-- blend mode: Bg_Buffer and Src_Buffer are combined first and then copied
-- to Dst_Buffer.
procedure DMA2D_Draw_Vertical_Line
(Buffer : DMA2D_Buffer;
Color : DMA2D_Color;
X : Integer;
Y : Integer;
Height : Integer;
Synchronous : Boolean := False);
-- Draws a vertical line
procedure DMA2D_Draw_Horizontal_Line
(Buffer : DMA2D_Buffer;
Color : DMA2D_Color;
X : Integer;
Y : Integer;
Width : Integer;
Synchronous : Boolean := False);
-- Draws a vertical line
private
function As_UInt3 is new Ada.Unchecked_Conversion
(DMA2D_Color_Mode, STM32_SVD.UInt3);
end STM32.DMA2D;
|
------------------------------------------------------------------------------
-- --
-- Copyright (C) 2015, AdaCore --
-- --
-- Redistribution and use in source and binary forms, with or without --
-- modification, are permitted provided that the following conditions are --
-- met: --
-- 1. Redistributions of source code must retain the above copyright --
-- notice, this list of conditions and the following disclaimer. --
-- 2. Redistributions in binary form must reproduce the above copyright --
-- notice, this list of conditions and the following disclaimer in --
-- the documentation and/or other materials provided with the --
-- distribution. --
-- 3. Neither the name of STMicroelectronics nor the names of its --
-- contributors may be used to endorse or promote products derived --
-- from this software without specific prior written permission. --
-- --
-- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS --
-- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT --
-- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR --
-- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT --
-- HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, --
-- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT --
-- LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, --
-- DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY --
-- THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT --
-- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE --
-- OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. --
-- --
------------------------------------------------------------------------------
with Ada.Unchecked_Conversion;
with STM32.LCD;
private with STM32_SVD;
package STM32.DMA2D is
type DMA2D_Color is record
Alpha : Byte;
Red : Byte;
Green : Byte;
Blue : Byte;
end record;
for DMA2D_Color use record
Alpha at 3 range 0 .. 7;
Red at 2 range 0 .. 7;
Green at 1 range 0 .. 7;
Blue at 0 range 0 .. 7;
end record;
Black : constant DMA2D_Color := (255, 0, 0, 0);
White : constant DMA2D_Color := (255, 255, 255, 255);
-- This bit is set and cleared by software. It cannot be modified
-- while a transfer is ongoing.
type DMA2D_MODE is
(
-- Memory-to-memory (FG fetch only)
M2M,
-- Memory-to-memory with PFC (FG fetch only with FG PFC active)
M2M_PFC,
-- Memory-to-memory with blending (FG and BG fetch with PFC and
-- blending)
M2M_BLEND,
-- Register-to-memory (no FG nor BG, only output stage active)
R2M
);
for DMA2D_MODE'Size use 2;
-- Configuration Error Interrupt Enable
type DMA2D_FLAG is
(Disable,
Enable);
-- Abort
-- This bit can be used to abort the current transfer. This bit is
-- set by software and is automatically reset by hardware when the
-- START bit is reset.
type DMA2D_ABORT is
(
-- 0: No transfer abort requested
Not_Requested,
-- 1: Transfer abort requested
Requested);
-- Suspend
-- This bit can be used to suspend the current transfer. This bit
-- is set and reset by software. It is automatically reset by
-- hardware when the START bit is reset.
type DMA2D_SUSPEND is
(
-- Transfer not suspended
Not_Suspended,
-- Transfer suspended
Supended);
-- Start
-- This bit can be used to launch the DMA2D according to the
-- parameters loaded in the various configuration registers. This
-- bit is automatically reset by the following events:
-- - At the end of the transfer
-- - When the data transfer is aborted by the user application by
-- setting the ABORT bit in DMA2D_CR
-- - When a data transfer error occurs
-- - When the data transfer has not started due to a configuration
-- error or another transfer operation already ongoing (automatic
-- CLUT loading)
type DMA2D_START is
(Not_Started,
Start);
-- These bits defines the color format
subtype DMA2D_Color_Mode is STM32.LCD.Pixel_Format;
-- (ARGB8888,
-- RGB888,
-- RGB565,
-- ARGB1555,
-- ARGB4444);
-- for DMA2D_Color_Mode'Size use 3;
-- Alpha mode
-- 00: No modification of the foreground image alpha channel value
-- 01: Replace original foreground image alpha channel value by ALPHA[7:0]
-- 10: Replace original foreground image alpha channel value by ALPHA[7:0]
-- multiplied with original alpha channel value
-- other configurations are meaningless
type DMA2D_AM is
(NO_MODIF,
REPLACE,
MULTIPLY);
for DMA2D_AM'Size use 2;
procedure DMA2D_DeInit;
type DMA2D_Sync_Procedure is access procedure;
procedure DMA2D_Init
(Init : DMA2D_Sync_Procedure;
Wait : DMA2D_Sync_Procedure);
type DMA2D_Buffer is record
Addr : System.Address;
Width : Natural;
Height : Natural;
Color_Mode : DMA2D_Color_Mode;
Swap_X_Y : Boolean;
end record;
Null_Buffer : constant DMA2D_Buffer :=
(Addr => System'To_Address (0),
Width => 0,
Height => 0,
Color_Mode => DMA2D_Color_Mode'First,
Swap_X_Y => False);
procedure DMA2D_Fill
(Buffer : DMA2D_Buffer;
Color : DMA2D_Color;
Synchronous : Boolean := False);
-- Fill the specified buffer with 'Color'
procedure DMA2D_Fill
(Buffer : DMA2D_Buffer;
Color : Word;
Synchronous : Boolean := False);
-- Same as above, using the destination buffer native color representation
procedure DMA2D_Set_Pixel
(Buffer : DMA2D_Buffer;
X, Y : Integer;
Color : DMA2D_Color;
Synchronous : Boolean := False);
procedure DMA2D_Set_Pixel
(Buffer : DMA2D_Buffer;
X, Y : Integer;
Color : Word;
Synchronous : Boolean := False);
-- Same as above, using the destination buffer native color representation
procedure DMA2D_Set_Pixel_Blend
(Buffer : DMA2D_Buffer;
X, Y : Integer;
Color : DMA2D_Color;
Synchronous : Boolean := False);
procedure DMA2D_Fill_Rect
(Buffer : DMA2D_Buffer;
Color : DMA2D_Color;
X : Integer;
Y : Integer;
Width : Integer;
Height : Integer;
Synchronous : Boolean := False);
-- Fill the specified area of the buffer with 'Color'
procedure DMA2D_Fill_Rect
(Buffer : DMA2D_Buffer;
Color : Word;
X : Integer;
Y : Integer;
Width : Integer;
Height : Integer;
Synchronous : Boolean := False);
-- Same as above, using the destination buffer native color representation
procedure DMA2D_Draw_Rect
(Buffer : DMA2D_Buffer;
Color : DMA2D_Color;
X : Integer;
Y : Integer;
Width : Integer;
Height : Integer);
-- Fill the specified area of the buffer with 'Color'
procedure DMA2D_Copy_Rect
(Src_Buffer : DMA2D_Buffer;
X_Src : Natural;
Y_Src : Natural;
Dst_Buffer : DMA2D_Buffer;
X_Dst : Natural;
Y_Dst : Natural;
Bg_Buffer : DMA2D_Buffer;
X_Bg : Natural;
Y_Bg : Natural;
Width : Natural;
Height : Natural;
Synchronous : Boolean := False);
-- Copy a rectangular area from Src to Dst
-- If Blend is set, then the rectangle will be merged with the destination
-- area, taking into account the opacity of the source. Else, it is simply
-- copied.
--
-- if Bg_Buffer is not Null_Buffer, then the copy will be performed in
-- blend mode: Bg_Buffer and Src_Buffer are combined first and then copied
-- to Dst_Buffer.
procedure DMA2D_Draw_Vertical_Line
(Buffer : DMA2D_Buffer;
Color : DMA2D_Color;
X : Integer;
Y : Integer;
Height : Integer;
Synchronous : Boolean := False);
-- Draws a vertical line
procedure DMA2D_Draw_Horizontal_Line
(Buffer : DMA2D_Buffer;
Color : DMA2D_Color;
X : Integer;
Y : Integer;
Width : Integer;
Synchronous : Boolean := False);
-- Draws a vertical line
private
function As_UInt3 is new Ada.Unchecked_Conversion
(DMA2D_Color_Mode, STM32_SVD.UInt3);
end STM32.DMA2D;
|
Add Black & White constants to the DMA2D spec.
|
Add Black & White constants to the DMA2D spec.
|
Ada
|
bsd-3-clause
|
AdaCore/Ada_Drivers_Library,AdaCore/Ada_Drivers_Library,Fabien-Chouteau/Ada_Drivers_Library,simonjwright/Ada_Drivers_Library,lambourg/Ada_Drivers_Library,simonjwright/Ada_Drivers_Library,Fabien-Chouteau/Ada_Drivers_Library,ellamosi/Ada_BMP_Library
|
c10ea2209a84170fb64a3cf0ca473f520f596c82
|
mat/src/mat-expressions.adb
|
mat/src/mat-expressions.adb
|
-----------------------------------------------------------------------
-- 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.Unchecked_Deallocation;
with MAT.Types;
with MAT.Memory;
with MAT.Expressions.Parser;
package body MAT.Expressions is
procedure Free is
new Ada.Unchecked_Deallocation (Object => Node_Type,
Name => Node_Type_Access);
-- Destroy recursively the node, releasing the storage.
procedure Destroy (Node : in out Node_Type_Access);
-- ------------------------------
-- Create a NOT expression node.
-- ------------------------------
function Create_Not (Expr : in Expression_Type) return Expression_Type is
Result : Expression_Type;
begin
Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE,
Kind => N_NOT,
Expr => Expr.Node);
Util.Concurrent.Counters.Increment (Expr.Node.Ref_Counter);
return Result;
end Create_Not;
-- ------------------------------
-- Create a AND expression node.
-- ------------------------------
function Create_And (Left : in Expression_Type;
Right : in Expression_Type) return Expression_Type is
Result : Expression_Type;
begin
Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE,
Kind => N_AND,
Left => Left.Node,
Right => Right.Node);
Util.Concurrent.Counters.Increment (Left.Node.Ref_Counter);
Util.Concurrent.Counters.Increment (Right.Node.Ref_Counter);
return Result;
end Create_And;
-- ------------------------------
-- Create a OR expression node.
-- ------------------------------
function Create_Or (Left : in Expression_Type;
Right : in Expression_Type) return Expression_Type is
Result : Expression_Type;
begin
Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE,
Kind => N_OR,
Left => Left.Node,
Right => Right.Node);
Util.Concurrent.Counters.Increment (Left.Node.Ref_Counter);
Util.Concurrent.Counters.Increment (Right.Node.Ref_Counter);
return Result;
end Create_Or;
-- ------------------------------
-- Create an INSIDE expression node.
-- ------------------------------
function Create_Inside (Name : in Ada.Strings.Unbounded.Unbounded_String;
Kind : in Inside_Type) return Expression_Type is
Result : Expression_Type;
begin
Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE,
Kind => N_INSIDE,
Name => Name,
Inside => Kind);
return Result;
end Create_Inside;
-- ------------------------------
-- Create an size range expression node.
-- ------------------------------
function Create_Size (Min : in MAT.Types.Target_Size;
Max : in MAT.Types.Target_Size) return Expression_Type is
Result : Expression_Type;
begin
Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE,
Kind => N_RANGE_SIZE,
Min_Size => Min,
Max_Size => Max);
return Result;
end Create_Size;
-- ------------------------------
-- Create an addr range expression node.
-- ------------------------------
function Create_Addr (Min : in MAT.Types.Target_Addr;
Max : in MAT.Types.Target_Addr) return Expression_Type is
Result : Expression_Type;
begin
Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE,
Kind => N_RANGE_ADDR,
Min_Addr => Min,
Max_Addr => Max);
return Result;
end Create_Addr;
-- ------------------------------
-- 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 is
Result : Expression_Type;
begin
Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE,
Kind => N_RANGE_TIME,
Min_Time => Min,
Max_Time => Max);
return Result;
end Create_Time;
-- ------------------------------
-- 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 is
begin
if Node.Node = null then
return True;
else
return Is_Selected (Node.Node.all, Addr, Allocation);
end if;
end Is_Selected;
-- ------------------------------
-- Evaluate the expression to check if the event described by the
-- context is selected. Returns True if the event is selected.
-- ------------------------------
function Is_Selected (Node : in Expression_Type;
Event : in MAT.Events.Targets.Probe_Event_Type) return Boolean is
begin
return Is_Selected (Node.Node.all, Event);
end Is_Selected;
-- ------------------------------
-- 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 is
use type MAT.Types.Target_Size;
use type MAT.Types.Target_Tick_Ref;
begin
case Node.Kind is
when N_NOT =>
return not Is_Selected (Node.Expr.all, Addr, Allocation);
when N_AND =>
return Is_Selected (Node.Left.all, Addr, Allocation)
and then Is_Selected (Node.Right.all, Addr, Allocation);
when N_OR =>
return Is_Selected (Node.Left.all, Addr, Allocation)
or else Is_Selected (Node.Right.all, Addr, Allocation);
when N_RANGE_SIZE =>
return Allocation.Size >= Node.Min_Size
and Allocation.Size <= Node.Max_Size;
when N_RANGE_ADDR =>
return Addr >= Node.Min_Addr
and Addr <= Node.Max_Addr;
when N_RANGE_TIME =>
return Allocation.Time >= Node.Min_Time
and Allocation.Time <= Node.Max_Time;
when others =>
return False;
end case;
end Is_Selected;
-- ------------------------------
-- Evaluate the expression to check if the event described by the
-- context is selected. Returns True if the event is selected.
-- ------------------------------
function Is_Selected (Node : in Node_Type;
Event : in MAT.Events.Targets.Probe_Event_Type) return Boolean is
use type MAT.Types.Target_Size;
use type MAT.Types.Target_Tick_Ref;
begin
case Node.Kind is
when N_NOT =>
return not Is_Selected (Node.Expr.all, Event);
when N_AND =>
return Is_Selected (Node.Left.all, Event)
and then Is_Selected (Node.Right.all, Event);
when N_OR =>
return Is_Selected (Node.Left.all, Event)
or else Is_Selected (Node.Right.all, Event);
when N_RANGE_SIZE =>
return Event.Size >= Node.Min_Size
and Event.Size <= Node.Max_Size;
when N_RANGE_ADDR =>
return Event.Addr >= Node.Min_Addr
and Event.Addr <= Node.Max_Addr;
when N_RANGE_TIME =>
return Event.Time >= Node.Min_Time
and Event.Time <= Node.Max_Time;
when others =>
return False;
end case;
end Is_Selected;
-- ------------------------------
-- Parse the string and return the expression tree.
-- ------------------------------
function Parse (Expr : in String) return Expression_Type is
begin
return MAT.Expressions.Parser.Parse (Expr);
end Parse;
-- ------------------------------
-- Destroy recursively the node, releasing the storage.
-- ------------------------------
procedure Destroy (Node : in out Node_Type_Access) is
Release : Boolean;
begin
if Node /= null then
Util.Concurrent.Counters.Decrement (Node.Ref_Counter, Release);
case Node.Kind is
when N_NOT =>
Destroy (Node.Expr);
when N_AND | N_OR =>
Destroy (Node.Left);
Destroy (Node.Right);
when others =>
null;
end case;
if Release then
Free (Node);
else
Node := null;
end if;
end if;
end Destroy;
-- ------------------------------
-- Release the reference and destroy the expression tree if it was the last reference.
-- ------------------------------
overriding
procedure Finalize (Obj : in out Expression_Type) is
begin
if Obj.Node /= null then
Destroy (Obj.Node);
end if;
end Finalize;
-- ------------------------------
-- Update the reference after an assignment.
-- ------------------------------
overriding
procedure Adjust (Obj : in out Expression_Type) is
begin
if Obj.Node /= null then
Util.Concurrent.Counters.Increment (Obj.Node.Ref_Counter);
end if;
end Adjust;
end MAT.Expressions;
|
-----------------------------------------------------------------------
-- mat-expressions -- Expressions for memory slot selection
-- Copyright (C) 2014, 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Unchecked_Deallocation;
with MAT.Types;
with MAT.Memory;
with MAT.Expressions.Parser;
package body MAT.Expressions is
procedure Free is
new Ada.Unchecked_Deallocation (Object => Node_Type,
Name => Node_Type_Access);
-- Destroy recursively the node, releasing the storage.
procedure Destroy (Node : in out Node_Type_Access);
-- ------------------------------
-- Create a NOT expression node.
-- ------------------------------
function Create_Not (Expr : in Expression_Type) return Expression_Type is
Result : Expression_Type;
begin
Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE,
Kind => N_NOT,
Expr => Expr.Node);
Util.Concurrent.Counters.Increment (Expr.Node.Ref_Counter);
return Result;
end Create_Not;
-- ------------------------------
-- Create a AND expression node.
-- ------------------------------
function Create_And (Left : in Expression_Type;
Right : in Expression_Type) return Expression_Type is
Result : Expression_Type;
begin
Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE,
Kind => N_AND,
Left => Left.Node,
Right => Right.Node);
Util.Concurrent.Counters.Increment (Left.Node.Ref_Counter);
Util.Concurrent.Counters.Increment (Right.Node.Ref_Counter);
return Result;
end Create_And;
-- ------------------------------
-- Create a OR expression node.
-- ------------------------------
function Create_Or (Left : in Expression_Type;
Right : in Expression_Type) return Expression_Type is
Result : Expression_Type;
begin
Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE,
Kind => N_OR,
Left => Left.Node,
Right => Right.Node);
Util.Concurrent.Counters.Increment (Left.Node.Ref_Counter);
Util.Concurrent.Counters.Increment (Right.Node.Ref_Counter);
return Result;
end Create_Or;
-- ------------------------------
-- Create an INSIDE expression node.
-- ------------------------------
function Create_Inside (Name : in Ada.Strings.Unbounded.Unbounded_String;
Kind : in Inside_Type) return Expression_Type is
Result : Expression_Type;
begin
Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE,
Kind => N_INSIDE,
Name => Name,
Inside => Kind);
return Result;
end Create_Inside;
-- ------------------------------
-- Create an size range expression node.
-- ------------------------------
function Create_Size (Min : in MAT.Types.Target_Size;
Max : in MAT.Types.Target_Size) return Expression_Type is
Result : Expression_Type;
begin
Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE,
Kind => N_RANGE_SIZE,
Min_Size => Min,
Max_Size => Max);
return Result;
end Create_Size;
-- ------------------------------
-- Create an addr range expression node.
-- ------------------------------
function Create_Addr (Min : in MAT.Types.Target_Addr;
Max : in MAT.Types.Target_Addr) return Expression_Type is
Result : Expression_Type;
begin
Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE,
Kind => N_RANGE_ADDR,
Min_Addr => Min,
Max_Addr => Max);
return Result;
end Create_Addr;
-- ------------------------------
-- 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 is
Result : Expression_Type;
begin
Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE,
Kind => N_RANGE_TIME,
Min_Time => Min,
Max_Time => Max);
return Result;
end Create_Time;
-- ------------------------------
-- Create an event ID range expression node.
-- ------------------------------
function Create_Event (Min : in MAT.Events.Targets.Event_Id_Type;
Max : in MAT.Events.Targets.Event_Id_Type) return Expression_Type is
Result : Expression_Type;
begin
Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE,
Kind => N_EVENT,
Min_Event => Min,
Max_Event => Max);
return Result;
end Create_Event;
-- ------------------------------
-- 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 is
begin
if Node.Node = null then
return True;
else
return Is_Selected (Node.Node.all, Addr, Allocation);
end if;
end Is_Selected;
-- ------------------------------
-- Evaluate the expression to check if the event described by the
-- context is selected. Returns True if the event is selected.
-- ------------------------------
function Is_Selected (Node : in Expression_Type;
Event : in MAT.Events.Targets.Probe_Event_Type) return Boolean is
begin
return Is_Selected (Node.Node.all, Event);
end Is_Selected;
-- ------------------------------
-- 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 is
use type MAT.Types.Target_Size;
use type MAT.Types.Target_Tick_Ref;
begin
case Node.Kind is
when N_NOT =>
return not Is_Selected (Node.Expr.all, Addr, Allocation);
when N_AND =>
return Is_Selected (Node.Left.all, Addr, Allocation)
and then Is_Selected (Node.Right.all, Addr, Allocation);
when N_OR =>
return Is_Selected (Node.Left.all, Addr, Allocation)
or else Is_Selected (Node.Right.all, Addr, Allocation);
when N_RANGE_SIZE =>
return Allocation.Size >= Node.Min_Size
and Allocation.Size <= Node.Max_Size;
when N_RANGE_ADDR =>
return Addr >= Node.Min_Addr
and Addr <= Node.Max_Addr;
when N_RANGE_TIME =>
return Allocation.Time >= Node.Min_Time
and Allocation.Time <= Node.Max_Time;
when others =>
return False;
end case;
end Is_Selected;
-- ------------------------------
-- Evaluate the expression to check if the event described by the
-- context is selected. Returns True if the event is selected.
-- ------------------------------
function Is_Selected (Node : in Node_Type;
Event : in MAT.Events.Targets.Probe_Event_Type) return Boolean is
use type MAT.Types.Target_Size;
use type MAT.Types.Target_Tick_Ref;
begin
case Node.Kind is
when N_NOT =>
return not Is_Selected (Node.Expr.all, Event);
when N_AND =>
return Is_Selected (Node.Left.all, Event)
and then Is_Selected (Node.Right.all, Event);
when N_OR =>
return Is_Selected (Node.Left.all, Event)
or else Is_Selected (Node.Right.all, Event);
when N_RANGE_SIZE =>
return Event.Size >= Node.Min_Size
and Event.Size <= Node.Max_Size;
when N_RANGE_ADDR =>
return Event.Addr >= Node.Min_Addr
and Event.Addr <= Node.Max_Addr;
when N_RANGE_TIME =>
return Event.Time >= Node.Min_Time
and Event.Time <= Node.Max_Time;
when others =>
return False;
end case;
end Is_Selected;
-- ------------------------------
-- Parse the string and return the expression tree.
-- ------------------------------
function Parse (Expr : in String) return Expression_Type is
begin
return MAT.Expressions.Parser.Parse (Expr);
end Parse;
-- ------------------------------
-- Destroy recursively the node, releasing the storage.
-- ------------------------------
procedure Destroy (Node : in out Node_Type_Access) is
Release : Boolean;
begin
if Node /= null then
Util.Concurrent.Counters.Decrement (Node.Ref_Counter, Release);
case Node.Kind is
when N_NOT =>
Destroy (Node.Expr);
when N_AND | N_OR =>
Destroy (Node.Left);
Destroy (Node.Right);
when others =>
null;
end case;
if Release then
Free (Node);
else
Node := null;
end if;
end if;
end Destroy;
-- ------------------------------
-- Release the reference and destroy the expression tree if it was the last reference.
-- ------------------------------
overriding
procedure Finalize (Obj : in out Expression_Type) is
begin
if Obj.Node /= null then
Destroy (Obj.Node);
end if;
end Finalize;
-- ------------------------------
-- Update the reference after an assignment.
-- ------------------------------
overriding
procedure Adjust (Obj : in out Expression_Type) is
begin
if Obj.Node /= null then
Util.Concurrent.Counters.Increment (Obj.Node.Ref_Counter);
end if;
end Adjust;
end MAT.Expressions;
|
Implement the Create_Event function to build an expression node that checks the event ID range
|
Implement the Create_Event function to build an expression node that checks the event ID range
|
Ada
|
apache-2.0
|
stcarrez/mat,stcarrez/mat,stcarrez/mat
|
62f6a892ff8d30e92978b2c48e0220688cbff0ef
|
synth.adb
|
synth.adb
|
-- This file is covered by the Internet Software Consortium (ISC) License
-- Reference: License.txt
with Ada.Command_Line;
with Ada.Text_IO;
with Actions;
with PortScan;
with Parameters;
procedure synth
is
type mandate_type is (unset, status, help, configure, version, up_system,
up_repo, purge, everything, build, install,
just_build, test);
mandate : mandate_type := unset;
package CLI renames Ada.Command_Line;
package TIO renames Ada.Text_IO;
package ACT renames Actions;
begin
if CLI.Argument_Count = 0 then
ACT.print_version;
return;
end if;
declare
first : constant String := CLI.Argument (1);
comerr : constant String := "Synth command error: ";
begin
if first = "help" then
mandate := help;
elsif first = "status" then
mandate := status;
elsif first = "version" then
mandate := version;
elsif first = "configure" then
mandate := configure;
elsif first = "install" then
mandate := install;
elsif first = "build" then
mandate := build;
elsif first = "just-build" then
mandate := just_build;
elsif first = "upgrade-system" then
mandate := up_system;
elsif first = "update-repository" then
mandate := up_repo;
elsif first = "purge-distfiles" then
mandate := purge;
elsif first = "everything" then
mandate := everything;
elsif first = "test" then
mandate := test;
end if;
if CLI.Argument_Count > 1 then
case mandate is
when unset =>
ACT.print_version;
TIO.Put_Line (comerr & "'" & first &
"' is not a valid keyword.");
return;
when help | configure | version | up_repo | up_system | purge |
everything =>
ACT.print_version;
TIO.Put_Line (comerr & "'" & first &
"' keyword uses no arguments.");
return;
when others => null;
end case;
-- TO DO: check validity of Arguments 2+
PortScan.set_cores;
if not Parameters.load_configuration (PortScan.cores_available)
then
TIO.Put_Line (comerr & "configuration failed to load.");
return;
end if;
case mandate is
when help | configure | version | up_repo | up_system | purge |
everything | unset =>
-- Handled above. Don't use "others" here;
-- we don't want to disable full coverage
null;
when status =>
TIO.Put_Line ("multi-arg STATUS to be implemented ...");
return;
when just_build =>
TIO.Put_Line ("JUST-BUILD to be implemented ...");
return;
when build =>
TIO.Put_Line ("BUILD to be implemented ...");
return;
when install =>
TIO.Put_Line ("INSTALL to be implemented ...");
return;
when test =>
TIO.Put_Line ("TEST to be implemented ...");
return;
end case;
else
-- We have exactly one argument
case mandate is
when build | just_build | install | test =>
ACT.print_version;
TIO.Put_Line (comerr & "'" & first &
"' requires at least one argument.");
return;
when version =>
ACT.print_version;
return;
when help =>
ACT.print_help;
return;
when unset =>
ACT.print_version;
TIO.Put_Line (comerr & "'" & first &
"' is not a valid keyword.");
return;
when others => null;
end case;
PortScan.set_cores;
if not Parameters.load_configuration (PortScan.cores_available)
then
TIO.Put_Line ("Synth error: configuration failed to load.");
return;
end if;
case mandate is
when build | just_build | install | test | version | help |
unset =>
-- Handled above. Don't use "others" here;
-- we don't want to disable full coverage
null;
when configure =>
ACT.launch_configure_menu (PortScan.cores_available);
return;
when status =>
TIO.Put_Line ("single STATUS to be implemented ...");
return;
when up_system =>
TIO.Put_Line ("UPGRADE-SYSTEM to be implemented ...");
return;
when up_repo =>
TIO.Put_Line ("UPDATE_REPO to be implemented ...");
return;
when purge =>
TIO.Put_Line ("PURGE to be implemented ...");
return;
when everything =>
TIO.Put_Line ("EVERYTHING to be implemented ...");
return;
end case;
end if;
end;
-- pid : PortScan.port_id;
-- good_scan : Boolean;
-- pkg_good : Boolean;
-- package T renames Ada.Text_IO;
-- package OPS renames PortScan.Ops;
-- use type PortScan.port_id;
--
-- begin
--
--
-- Replicant.initialize;
-- -- Replicant.launch_slave (3);
-- -- Replicant.launch_slave (12);
-- -- delay 35.0;
-- -- Replicant.destroy_slave (3);
-- -- Replicant.destroy_slave (12);
-- -- return;
--
-- -- needs to read environment or make -C <anyport> -V PORTSDIR
-- -- good_scan := PortScan.scan_entire_ports_tree (portsdir => "/usr/xports");
--
-- good_scan := PortScan.scan_single_port
-- (portsdir => USS (Parameters.configuration.dir_portsdir),
-- catport => "ports-mgmt/pkg",
-- repository => USS (Parameters.configuration.dir_repository));
--
-- if good_scan then
-- PortScan.set_build_priority;
-- else
-- T.Put_Line ("pkg(8) scan failure, exiting");
-- Replicant.finalize;
-- return;
-- end if;
--
-- PortScan.Packages.limited_sanity_check
-- (repository => USS (Parameters.configuration.dir_repository));
--
-- if not PortScan.Packages.queue_is_empty then
-- PortScan.Buildcycle.initialize (False);
-- pid := PortScan.Ops.top_buildable_port;
-- T.Put_Line ("Rebuilding pkg(8) First ...");
--
-- Replicant.launch_slave (id => 1);
-- pkg_good := PortScan.Buildcycle.build_package
-- (id => 1, sequence_id => pid);
-- Replicant.destroy_slave (id => 1);
-- if not pkg_good then
-- T.Put_Line ("Failed to build pkg(8), exiting");
-- Replicant.finalize;
-- return;
-- end if;
-- end if;
--
-- PortScan.reset_ports_tree;
--
-- good_scan := PortScan.scan_single_port
-- (portsdir => USS (Parameters.configuration.dir_portsdir),
-- catport => "editors/joe",
-- repository => USS (Parameters.configuration.dir_repository));
--
--
--
-- -- good_scan := PortScan.scan_single_port
-- -- (portsdir => USS (Parameters.configuration.dir_portsdir),
-- -- catport => "mail/thunderbird",
-- -- repository => USS (Parameters.configuration.dir_repository));
--
-- if good_scan then
-- PortScan.set_build_priority;
-- else
-- Replicant.finalize;
-- return;
-- end if;
--
--
-- PortScan.Packages.limited_sanity_check
-- (repository => USS (Parameters.configuration.dir_repository));
--
-- -- return;
--
-- T.Put_Line ("");
-- T.Put_Line ("Initial Queue length is" & OPS.queue_length'Img);
-- loop
-- pid := OPS.next_ignored_port;
-- if pid = PortScan.port_match_failed then
-- exit;
-- end if;
-- T.Put_Line (OPS.port_name (pid) & " has been ignored: " &
-- (OPS.ignore_reason (pid)));
-- OPS.cascade_failed_build (pid);
-- end loop;
-- T.Put_Line ("Final Queue length is" & OPS.queue_length'Img);
-- if PortScan.Packages.queue_is_empty then
-- T.Put_Line ("Everything is Ok, there's nothing to do.");
-- else
-- if OPS.integrity_intact then
-- T.Put_Line ("Integrity intact");
-- else
-- T.Put_Line ("Integrity lost !!!!");
-- end if;
--
-- T.Put_Line ("Starting build simulation");
-- PortScan.Buildcycle.initialize (True);
-- OPS.parallel_bulk_run
-- (num_builders => Parameters.configuration.num_builders);
-- end if;
-- Replicant.finalize;
--
--
-- -- PortScan.release_ports_tree;
end synth;
|
-- This file is covered by the Internet Software Consortium (ISC) License
-- Reference: License.txt
with Ada.Command_Line;
with Ada.Text_IO;
with Actions;
with PortScan;
with Parameters;
procedure synth
is
type mandate_type is (unset, status, help, configure, version, up_system,
up_repo, purge, everything, build, install, force,
just_build, test);
mandate : mandate_type := unset;
package CLI renames Ada.Command_Line;
package TIO renames Ada.Text_IO;
package ACT renames Actions;
begin
if CLI.Argument_Count = 0 then
ACT.print_version;
return;
end if;
declare
first : constant String := CLI.Argument (1);
comerr : constant String := "Synth command error: ";
begin
if first = "help" then
mandate := help;
elsif first = "status" then
mandate := status;
elsif first = "version" then
mandate := version;
elsif first = "configure" then
mandate := configure;
elsif first = "install" then
mandate := install;
elsif first = "build" then
mandate := build;
elsif first = "force" then
mandate := force;
elsif first = "just-build" then
mandate := just_build;
elsif first = "upgrade-system" then
mandate := up_system;
elsif first = "update-repository" then
mandate := up_repo;
elsif first = "purge-distfiles" then
mandate := purge;
elsif first = "everything" then
mandate := everything;
elsif first = "test" then
mandate := test;
end if;
if CLI.Argument_Count > 1 then
case mandate is
when unset =>
ACT.print_version;
TIO.Put_Line (comerr & "'" & first &
"' is not a valid keyword.");
return;
when help | configure | version | up_repo | up_system | purge |
everything =>
ACT.print_version;
TIO.Put_Line (comerr & "'" & first &
"' keyword uses no arguments.");
return;
when others => null;
end case;
-- TO DO: check validity of Arguments 2+
PortScan.set_cores;
if not Parameters.load_configuration (PortScan.cores_available)
then
TIO.Put_Line (comerr & "configuration failed to load.");
return;
end if;
case mandate is
when help | configure | version | up_repo | up_system | purge |
everything | unset =>
-- Handled above. Don't use "others" here;
-- we don't want to disable full coverage
null;
when status =>
TIO.Put_Line ("multi-arg STATUS to be implemented ...");
return;
when just_build =>
TIO.Put_Line ("JUST-BUILD to be implemented ...");
return;
when build =>
TIO.Put_Line ("BUILD to be implemented ...");
return;
when force =>
TIO.Put_Line ("FORCE to be implemented ...");
return;
when install =>
TIO.Put_Line ("INSTALL to be implemented ...");
return;
when test =>
TIO.Put_Line ("TEST to be implemented ...");
return;
end case;
else
-- We have exactly one argument
case mandate is
when build | force | just_build | install | test =>
ACT.print_version;
TIO.Put_Line (comerr & "'" & first &
"' requires at least one argument.");
return;
when version =>
ACT.print_version;
return;
when help =>
ACT.print_help;
return;
when unset =>
ACT.print_version;
TIO.Put_Line (comerr & "'" & first &
"' is not a valid keyword.");
return;
when others => null;
end case;
PortScan.set_cores;
if not Parameters.load_configuration (PortScan.cores_available)
then
TIO.Put_Line ("Synth error: configuration failed to load.");
return;
end if;
case mandate is
when build | just_build | install | test | version | help |
force | unset =>
-- Handled above. Don't use "others" here;
-- we don't want to disable full coverage
null;
when configure =>
ACT.launch_configure_menu (PortScan.cores_available);
return;
when status =>
TIO.Put_Line ("single STATUS to be implemented ...");
return;
when up_system =>
TIO.Put_Line ("UPGRADE-SYSTEM to be implemented ...");
return;
when up_repo =>
TIO.Put_Line ("UPDATE_REPO to be implemented ...");
return;
when purge =>
TIO.Put_Line ("PURGE to be implemented ...");
return;
when everything =>
TIO.Put_Line ("EVERYTHING to be implemented ...");
return;
end case;
end if;
end;
-- pid : PortScan.port_id;
-- good_scan : Boolean;
-- pkg_good : Boolean;
-- package T renames Ada.Text_IO;
-- package OPS renames PortScan.Ops;
-- use type PortScan.port_id;
--
-- begin
--
--
-- Replicant.initialize;
-- -- Replicant.launch_slave (3);
-- -- Replicant.launch_slave (12);
-- -- delay 35.0;
-- -- Replicant.destroy_slave (3);
-- -- Replicant.destroy_slave (12);
-- -- return;
--
-- -- needs to read environment or make -C <anyport> -V PORTSDIR
-- -- good_scan := PortScan.scan_entire_ports_tree (portsdir => "/usr/xports");
--
-- good_scan := PortScan.scan_single_port
-- (portsdir => USS (Parameters.configuration.dir_portsdir),
-- catport => "ports-mgmt/pkg",
-- repository => USS (Parameters.configuration.dir_repository));
--
-- if good_scan then
-- PortScan.set_build_priority;
-- else
-- T.Put_Line ("pkg(8) scan failure, exiting");
-- Replicant.finalize;
-- return;
-- end if;
--
-- PortScan.Packages.limited_sanity_check
-- (repository => USS (Parameters.configuration.dir_repository));
--
-- if not PortScan.Packages.queue_is_empty then
-- PortScan.Buildcycle.initialize (False);
-- pid := PortScan.Ops.top_buildable_port;
-- T.Put_Line ("Rebuilding pkg(8) First ...");
--
-- Replicant.launch_slave (id => 1);
-- pkg_good := PortScan.Buildcycle.build_package
-- (id => 1, sequence_id => pid);
-- Replicant.destroy_slave (id => 1);
-- if not pkg_good then
-- T.Put_Line ("Failed to build pkg(8), exiting");
-- Replicant.finalize;
-- return;
-- end if;
-- end if;
--
-- PortScan.reset_ports_tree;
--
-- good_scan := PortScan.scan_single_port
-- (portsdir => USS (Parameters.configuration.dir_portsdir),
-- catport => "editors/joe",
-- repository => USS (Parameters.configuration.dir_repository));
--
--
--
-- -- good_scan := PortScan.scan_single_port
-- -- (portsdir => USS (Parameters.configuration.dir_portsdir),
-- -- catport => "mail/thunderbird",
-- -- repository => USS (Parameters.configuration.dir_repository));
--
-- if good_scan then
-- PortScan.set_build_priority;
-- else
-- Replicant.finalize;
-- return;
-- end if;
--
--
-- PortScan.Packages.limited_sanity_check
-- (repository => USS (Parameters.configuration.dir_repository));
--
-- -- return;
--
-- T.Put_Line ("");
-- T.Put_Line ("Initial Queue length is" & OPS.queue_length'Img);
-- loop
-- pid := OPS.next_ignored_port;
-- if pid = PortScan.port_match_failed then
-- exit;
-- end if;
-- T.Put_Line (OPS.port_name (pid) & " has been ignored: " &
-- (OPS.ignore_reason (pid)));
-- OPS.cascade_failed_build (pid);
-- end loop;
-- T.Put_Line ("Final Queue length is" & OPS.queue_length'Img);
-- if PortScan.Packages.queue_is_empty then
-- T.Put_Line ("Everything is Ok, there's nothing to do.");
-- else
-- if OPS.integrity_intact then
-- T.Put_Line ("Integrity intact");
-- else
-- T.Put_Line ("Integrity lost !!!!");
-- end if;
--
-- T.Put_Line ("Starting build simulation");
-- PortScan.Buildcycle.initialize (True);
-- OPS.parallel_bulk_run
-- (num_builders => Parameters.configuration.num_builders);
-- end if;
-- Replicant.finalize;
--
--
-- -- PortScan.release_ports_tree;
end synth;
|
Add forgotten "force" command (still to be implemented)
|
Add forgotten "force" command (still to be implemented)
|
Ada
|
isc
|
jrmarino/synth,jrmarino/synth,jrmarino/synth,jrmarino/synth
|
68440d0a0c9a90b3148c3c1b2a4deb5c3f26ba27
|
src/security-oauth-jwt.ads
|
src/security-oauth-jwt.ads
|
-----------------------------------------------------------------------
-- security-oauth-jwt -- OAuth Java Web Token
-- Copyright (C) 2013 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Calendar;
with Util.Properties;
-- === JSON Web Token ===
-- JSON Web Token (JWT) is a compact URL-safe means of representing claims to be transferred
-- between two parties. A JWT token is returned by an authorization server. It contains
-- useful information that allows to verify the authentication and identify the user.
--
-- The <tt>Security.OAuth.JWT</tt> package implements the decoding part of JWT defined in:
-- JSON Web Token (JWT), http://tools.ietf.org/html/draft-ietf-oauth-json-web-token-07
--
-- A list of pre-defined ID tokens are returned in the JWT token claims and used for
-- the OpenID Connect. This is specified in
-- OpenID Connect Basic Client Profile 1.0 - draft 26,
-- http://openid.net/specs/openid-connect-basic-1_0.html
--
package Security.OAuth.JWT is
-- Exception raised if the encoded token is invalid or cannot be decoded.
Invalid_Token : exception;
type Token is private;
-- Get the issuer claim from the token (the "iss" claim).
function Get_Issuer (From : in Token) return String;
-- Get the subject claim from the token (the "sub" claim).
function Get_Subject (From : in Token) return String;
-- Get the audience claim from the token (the "aud" claim).
function Get_Audience (From : in Token) return String;
-- Get the expiration claim from the token (the "exp" claim).
function Get_Expiration (From : in Token) return Ada.Calendar.Time;
-- Get the not before claim from the token (the "nbf" claim).
function Get_Not_Before (From : in Token) return Ada.Calendar.Time;
-- Get the issued at claim from the token (the "iat" claim).
-- This is the time when the JWT was issued.
function Get_Issued_At (From : in Token) return Ada.Calendar.Time;
-- Get the authentication time claim from the token (the "auth_time" claim).
function Get_Authentication_Time (From : in Token) return Ada.Calendar.Time;
-- Get the JWT ID claim from the token (the "jti" claim).
function Get_JWT_ID (From : in Token) return String;
-- Get the authorized clients claim from the token (the "azp" claim).
function Get_Authorized_Presenters (From : in Token) return String;
-- Get the claim with the given name from the token.
function Get_Claim (From : in Token;
Name : in String) return String;
-- Decode a string representing an encoded JWT token according to the JWT specification:
--
-- Section 7. Rules for Creating and Validating a JWT
--
-- The JWT token is composed of 3 parts encoded in Base64url and separated by '.' .
-- The first part represents the header, the second part the claims and the last part
-- the signature. The <tt>Decode</tt> operation splits the parts, decodes them,
-- parses the JSON content represented by the header and the claims.
-- The <tt>Decode</tt> operation does not verify the signature (yet!).
--
-- Return the decoded token or raise an exception.
function Decode (Content : in String) return Token;
private
type Claims is new Util.Properties.Manager with null record;
type Token is record
Header : Util.Properties.Manager;
Claims : Util.Properties.Manager;
end record;
end Security.OAuth.JWT;
|
-----------------------------------------------------------------------
-- security-oauth-jwt -- OAuth Java Web Token
-- Copyright (C) 2013 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Calendar;
with Util.Properties;
-- === JSON Web Token ===
-- JSON Web Token (JWT) is a compact URL-safe means of representing claims to be transferred
-- between two parties. A JWT token is returned by an authorization server. It contains
-- useful information that allows to verify the authentication and identify the user.
--
-- The <tt>Security.OAuth.JWT</tt> package implements the decoding part of JWT defined in:
-- JSON Web Token (JWT), http://tools.ietf.org/html/draft-ietf-oauth-json-web-token-07
--
-- A list of pre-defined ID tokens are returned in the JWT token claims and used for
-- the OpenID Connect. This is specified in
-- OpenID Connect Basic Client Profile 1.0 - draft 26,
-- http://openid.net/specs/openid-connect-basic-1_0.html
--
package Security.OAuth.JWT is
-- Exception raised if the encoded token is invalid or cannot be decoded.
Invalid_Token : exception;
type Token is private;
-- Get the issuer claim from the token (the "iss" claim).
function Get_Issuer (From : in Token) return String;
-- Get the subject claim from the token (the "sub" claim).
function Get_Subject (From : in Token) return String;
-- Get the audience claim from the token (the "aud" claim).
function Get_Audience (From : in Token) return String;
-- Get the expiration claim from the token (the "exp" claim).
function Get_Expiration (From : in Token) return Ada.Calendar.Time;
-- Get the not before claim from the token (the "nbf" claim).
function Get_Not_Before (From : in Token) return Ada.Calendar.Time;
-- Get the issued at claim from the token (the "iat" claim).
-- This is the time when the JWT was issued.
function Get_Issued_At (From : in Token) return Ada.Calendar.Time;
-- Get the authentication time claim from the token (the "auth_time" claim).
function Get_Authentication_Time (From : in Token) return Ada.Calendar.Time;
-- Get the JWT ID claim from the token (the "jti" claim).
function Get_JWT_ID (From : in Token) return String;
-- Get the authorized clients claim from the token (the "azp" claim).
function Get_Authorized_Presenters (From : in Token) return String;
-- Get the claim with the given name from the token.
function Get_Claim (From : in Token;
Name : in String;
Default : in String := "") return String;
-- Decode a string representing an encoded JWT token according to the JWT specification:
--
-- Section 7. Rules for Creating and Validating a JWT
--
-- The JWT token is composed of 3 parts encoded in Base64url and separated by '.' .
-- The first part represents the header, the second part the claims and the last part
-- the signature. The <tt>Decode</tt> operation splits the parts, decodes them,
-- parses the JSON content represented by the header and the claims.
-- The <tt>Decode</tt> operation does not verify the signature (yet!).
--
-- Return the decoded token or raise an exception.
function Decode (Content : in String) return Token;
private
type Claims is new Util.Properties.Manager with null record;
type Token is record
Header : Util.Properties.Manager;
Claims : Util.Properties.Manager;
end record;
end Security.OAuth.JWT;
|
Update Get_Claim to add a default value returned if the claim does not exist
|
Update Get_Claim to add a default value returned if the claim does not exist
|
Ada
|
apache-2.0
|
Letractively/ada-security
|
eeccd0044ccc6d63e765cad663b4f39eb12c5d84
|
regtests/util-properties-tests.adb
|
regtests/util-properties-tests.adb
|
-----------------------------------------------------------------------
-- Util -- Unit tests for properties
-- Copyright (C) 2009, 2010, 2011, 2014, 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Test_Caller;
with Ada.Text_IO;
with Util.Properties;
with Util.Properties.Basic;
package body Util.Properties.Tests is
use Ada.Text_IO;
use type Ada.Containers.Count_Type;
use Util.Properties.Basic;
use Util;
-- Test
-- Properties.Set
-- Properties.Exists
-- Properties.Get
procedure Test_Property (T : in out Test) is
Props : Properties.Manager;
begin
T.Assert (Exists (Props, "test") = False,
"Invalid properties");
Props.Set ("test", "toto");
T.Assert (Exists (Props, "test"),
"Property was not inserted");
declare
V : constant String := Props.Get ("test");
begin
T.Assert (V = "toto",
"Property was not set correctly");
end;
end Test_Property;
-- Test basic properties
-- Get
-- Set
procedure Test_Integer_Property (T : in out Test) is
Props : Properties.Manager;
V : Integer := 23;
begin
Integer_Property.Set (Props, "test-integer", V);
T.Assert (Props.Exists ("test-integer"), "Invalid properties");
V := Integer_Property.Get (Props, "test-integer");
T.Assert (V = 23, "Property was not inserted");
Integer_Property.Set (Props, "test-integer", 24);
V := Integer_Property.Get (Props, "test-integer");
T.Assert (V = 24, "Property was not inserted");
V := Integer_Property.Get (Props, "unknown", 25);
T.Assert (V = 25, "Default value must be returned for a Get");
end Test_Integer_Property;
-- Test loading of property files
procedure Test_Load_Property (T : in out Test) is
Props : Properties.Manager;
F : File_Type;
begin
Open (F, In_File, "regtests/test.properties");
Load_Properties (Props, F);
Close (F);
declare
Names : Util.Strings.Vectors.Vector;
begin
Props.Get_Names (Names);
T.Assert (Names.Length > 30,
"Loading the test properties returned too few properties");
T.Assert (To_String (Props.Get ("root.dir")) = ".",
"Invalid property 'root.dir'");
T.Assert (To_String (Props.Get ("console.lib")) = "${dist.lib.dir}/console.jar",
"Invalid property 'console.lib'");
end;
exception
when Ada.Text_IO.Name_Error =>
Ada.Text_IO.Put_Line ("Cannot find test file: regtests/test.properties");
raise;
end Test_Load_Property;
-- ------------------------------
-- Test loading of property files
-- ------------------------------
procedure Test_Load_Strip_Property (T : in out Test) is
Props : Properties.Manager;
F : File_Type;
begin
-- Load, filter and strip properties
Open (F, In_File, "regtests/test.properties");
Load_Properties (Props, F, "tomcat.", True);
Close (F);
declare
Names : Util.Strings.Vectors.Vector;
begin
Props.Get_Names (Names);
T.Assert (Names.Length > 3,
"Loading the test properties returned too few properties");
T.Assert (To_String (Props.Get ("version")) = "0.6",
"Invalid property 'root.dir'");
end;
exception
when Ada.Text_IO.Name_Error =>
Ada.Text_IO.Put_Line ("Cannot find test file: regtests/test.properties");
raise;
end Test_Load_Strip_Property;
-- ------------------------------
-- Test copy of properties
-- ------------------------------
procedure Test_Copy_Property (T : in out Test) is
Props : Properties.Manager;
begin
Props.Set ("prefix.one", "1");
Props.Set ("prefix.two", "2");
Props.Set ("prefix", "Not copied");
Props.Set ("prefix.", "Copied");
declare
Copy : Properties.Manager;
begin
Copy.Copy (From => Props,
Prefix => "prefix.",
Strip => True);
T.Assert (Copy.Exists ("one"), "Property one not found");
T.Assert (Copy.Exists ("two"), "Property two not found");
T.Assert (Copy.Exists (""), "Property '' does not exist.");
end;
end Test_Copy_Property;
procedure Test_Set_Preserve_Original (T : in out Test) is
Props1 : Properties.Manager;
begin
Props1.Set ("a", "b");
Props1.Set ("c", "d");
declare
Props2 : Properties.Manager;
begin
Props2 := Props1;
T.Assert (Props2.Exists ("a"), "Property a not found in props2 after assignment");
T.Assert (Props2.Exists ("c"), "Property b not found in props2 after assignment");
Util.Tests.Assert_Equals (T, "b", String '(Props2.Get ("a")), "Invalid property a");
Props1.Set ("a", "d");
Util.Tests.Assert_Equals (T, "d", String '(Props1.Get ("a")),
"Wrong property a in props1");
Util.Tests.Assert_Equals (T, "b", String '(Props2.Get ("a")),
"Wrong property a in props2");
Props2 := Props1;
Util.Tests.Assert_Equals (T, "d", String '(Props2.Get ("a")),
"Wrong property a in props2");
Props2.Set ("e", "f");
Props2.Set ("c", "g");
Props1 := Props2;
-- Release Props2 but the property manager is internally shared so the Props1 is
-- not changed.
end;
T.Assert (Props1.Exists ("e"), "Property e not found in props1 after assignment");
T.Assert (Props1.Exists ("c"), "Property c not found in props1 after assignment");
Util.Tests.Assert_Equals (T, "g", String '(Props1.Get ("c")),
"Wrong property c in props1");
end Test_Set_Preserve_Original;
procedure Test_Remove_Preserve_Original (T : in out Test) is
Props1 : Properties.Manager;
begin
Props1.Set ("a", "b");
Props1.Set ("c", "d");
declare
Props2 : Properties.Manager;
begin
Props2 := Props1;
T.Assert (Props2.Exists ("a"), "Property a not found in props2 after assignment");
T.Assert (Props2.Exists ("c"), "Property b not found in props2 after assignment");
Props1.Remove ("a");
T.Assert (not Props1.Exists ("a"), "Property a was not removed from props1");
T.Assert (Props2.Exists ("a"), "Property a was removed from props2");
Props1 := Props2;
-- Release Props2 but the property manager is internally shared so the Props1 is
-- not changed.
end;
Util.Tests.Assert_Equals (T, "b", String '(Props1.Get ("a")),
"Wrong property a in props1");
end Test_Remove_Preserve_Original;
procedure Test_Missing_Property (T : in out Test) is
Props : Properties.Manager;
V : Unbounded_String;
begin
T.Assert (Util.Beans.Objects.Is_Null (Props.Get_Value ("missing")),
"The Get_Value operation must return a null object");
begin
V := Props.Get ("missing");
T.Fail ("Exception NO_PROPERTY was not raised");
exception
when NO_PROPERTY =>
null;
end;
Props.Set ("a", "b");
T.Assert (Util.Beans.Objects.Is_Null (Props.Get_Value ("missing")),
"The Get_Value operation must return a null object");
begin
V := Props.Get ("missing");
T.Fail ("Exception NO_PROPERTY was not raised");
exception
when NO_PROPERTY =>
null;
end;
end Test_Missing_Property;
procedure Test_Load_Ini_Property (T : in out Test) is
Props : Properties.Manager;
F : File_Type;
begin
Open (F, In_File, "regtests/files/my.cnf");
Load_Properties (Props, F);
Close (F);
declare
V : Util.Properties.Value;
P : Properties.Manager;
begin
V := Props.Get_Value ("mysqld");
T.Assert (Util.Properties.Is_Manager (V),
"Value 'mysqld' must be a property manager");
P := Util.Properties.To_Manager (V);
T.Assert (P.Exists ("user"),
"The [mysqld] property manager should contain a 'user' property");
V := Props.Get_Value ("mysqld_safe");
T.Assert (Util.Properties.Is_Manager (V),
"Value 'mysqld_safe' must be a property manager");
P := Util.Properties.To_Manager (V);
T.Assert (P.Exists ("socket"),
"The [mysqld] property manager should contain a 'socket' property");
end;
exception
when Ada.Text_IO.Name_Error =>
Ada.Text_IO.Put_Line ("Cannot find test file: regtests/files/my.cnf");
raise;
end Test_Load_Ini_Property;
package Caller is new Util.Test_Caller (Test, "Properties");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test Util.Properties.Set",
Test_Property'Access);
Caller.Add_Test (Suite, "Test Util.Properties.Get",
Test_Property'Access);
Caller.Add_Test (Suite, "Test Util.Properties.Exists",
Test_Property'Access);
Caller.Add_Test (Suite, "Test Util.Properties.Get (NO_PROPERTY)",
Test_Missing_Property'Access);
Caller.Add_Test (Suite, "Test Util.Properties.Discrete.Get",
Test_Integer_Property'Access);
Caller.Add_Test (Suite, "Test Util.Properties.Discrete.Set",
Test_Integer_Property'Access);
Caller.Add_Test (Suite, "Test Util.Properties.Load_Properties",
Test_Load_Property'Access);
Caller.Add_Test (Suite, "Test Util.Properties.Load_Properties (INI)",
Test_Load_Ini_Property'Access);
Caller.Add_Test (Suite, "Test Util.Properties.Load_Strip_Properties",
Test_Load_Strip_Property'Access);
Caller.Add_Test (Suite, "Test Util.Properties.Copy",
Test_Copy_Property'Access);
Caller.Add_Test (Suite, "Test Util.Properties.Set+Assign",
Test_Set_Preserve_Original'Access);
Caller.Add_Test (Suite, "Test Util.Properties.Set+Assign+Remove",
Test_Remove_Preserve_Original'Access);
end Add_Tests;
end Util.Properties.Tests;
|
-----------------------------------------------------------------------
-- Util -- Unit tests for properties
-- Copyright (C) 2009, 2010, 2011, 2014, 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Test_Caller;
with Ada.Text_IO;
with Util.Properties;
with Util.Properties.Basic;
package body Util.Properties.Tests is
use Ada.Text_IO;
use type Ada.Containers.Count_Type;
use Util.Properties.Basic;
use Util;
-- Test
-- Properties.Set
-- Properties.Exists
-- Properties.Get
procedure Test_Property (T : in out Test) is
Props : Properties.Manager;
begin
T.Assert (Exists (Props, "test") = False,
"Invalid properties");
Props.Set ("test", "toto");
T.Assert (Exists (Props, "test"),
"Property was not inserted");
declare
V : constant String := Props.Get ("test");
begin
T.Assert (V = "toto",
"Property was not set correctly");
end;
end Test_Property;
-- Test basic properties
-- Get
-- Set
procedure Test_Integer_Property (T : in out Test) is
Props : Properties.Manager;
V : Integer := 23;
begin
Integer_Property.Set (Props, "test-integer", V);
T.Assert (Props.Exists ("test-integer"), "Invalid properties");
V := Integer_Property.Get (Props, "test-integer");
T.Assert (V = 23, "Property was not inserted");
Integer_Property.Set (Props, "test-integer", 24);
V := Integer_Property.Get (Props, "test-integer");
T.Assert (V = 24, "Property was not inserted");
V := Integer_Property.Get (Props, "unknown", 25);
T.Assert (V = 25, "Default value must be returned for a Get");
end Test_Integer_Property;
-- Test loading of property files
procedure Test_Load_Property (T : in out Test) is
Props : Properties.Manager;
F : File_Type;
begin
Open (F, In_File, "regtests/test.properties");
Load_Properties (Props, F);
Close (F);
declare
Names : Util.Strings.Vectors.Vector;
begin
Props.Get_Names (Names);
T.Assert (Names.Length > 30,
"Loading the test properties returned too few properties");
T.Assert (To_String (Props.Get ("root.dir")) = ".",
"Invalid property 'root.dir'");
T.Assert (To_String (Props.Get ("console.lib")) = "${dist.lib.dir}/console.jar",
"Invalid property 'console.lib'");
end;
exception
when Ada.Text_IO.Name_Error =>
Ada.Text_IO.Put_Line ("Cannot find test file: regtests/test.properties");
raise;
end Test_Load_Property;
-- ------------------------------
-- Test loading of property files
-- ------------------------------
procedure Test_Load_Strip_Property (T : in out Test) is
Props : Properties.Manager;
F : File_Type;
begin
-- Load, filter and strip properties
Open (F, In_File, "regtests/test.properties");
Load_Properties (Props, F, "tomcat.", True);
Close (F);
declare
Names : Util.Strings.Vectors.Vector;
begin
Props.Get_Names (Names);
T.Assert (Names.Length > 3,
"Loading the test properties returned too few properties");
T.Assert (To_String (Props.Get ("version")) = "0.6",
"Invalid property 'root.dir'");
end;
exception
when Ada.Text_IO.Name_Error =>
Ada.Text_IO.Put_Line ("Cannot find test file: regtests/test.properties");
raise;
end Test_Load_Strip_Property;
-- ------------------------------
-- Test copy of properties
-- ------------------------------
procedure Test_Copy_Property (T : in out Test) is
Props : Properties.Manager;
begin
Props.Set ("prefix.one", "1");
Props.Set ("prefix.two", "2");
Props.Set ("prefix", "Not copied");
Props.Set ("prefix.", "Copied");
declare
Copy : Properties.Manager;
begin
Copy.Copy (From => Props,
Prefix => "prefix.",
Strip => True);
T.Assert (Copy.Exists ("one"), "Property one not found");
T.Assert (Copy.Exists ("two"), "Property two not found");
T.Assert (Copy.Exists (""), "Property '' does not exist.");
end;
end Test_Copy_Property;
procedure Test_Set_Preserve_Original (T : in out Test) is
Props1 : Properties.Manager;
begin
Props1.Set ("a", "b");
Props1.Set ("c", "d");
declare
Props2 : Properties.Manager;
begin
Props2 := Props1;
T.Assert (Props2.Exists ("a"), "Property a not found in props2 after assignment");
T.Assert (Props2.Exists ("c"), "Property b not found in props2 after assignment");
Util.Tests.Assert_Equals (T, "b", String '(Props2.Get ("a")), "Invalid property a");
Props1.Set ("a", "d");
Util.Tests.Assert_Equals (T, "d", String '(Props1.Get ("a")),
"Wrong property a in props1");
Util.Tests.Assert_Equals (T, "b", String '(Props2.Get ("a")),
"Wrong property a in props2");
Props2 := Props1;
Util.Tests.Assert_Equals (T, "d", String '(Props2.Get ("a")),
"Wrong property a in props2");
Props2.Set ("e", "f");
Props2.Set ("c", "g");
Props1 := Props2;
-- Release Props2 but the property manager is internally shared so the Props1 is
-- not changed.
end;
T.Assert (Props1.Exists ("e"), "Property e not found in props1 after assignment");
T.Assert (Props1.Exists ("c"), "Property c not found in props1 after assignment");
Util.Tests.Assert_Equals (T, "g", String '(Props1.Get ("c")),
"Wrong property c in props1");
end Test_Set_Preserve_Original;
procedure Test_Remove_Preserve_Original (T : in out Test) is
Props1 : Properties.Manager;
begin
Props1.Set ("a", "b");
Props1.Set ("c", "d");
declare
Props2 : Properties.Manager;
begin
Props2 := Props1;
T.Assert (Props2.Exists ("a"), "Property a not found in props2 after assignment");
T.Assert (Props2.Exists ("c"), "Property b not found in props2 after assignment");
Props1.Remove ("a");
T.Assert (not Props1.Exists ("a"), "Property a was not removed from props1");
T.Assert (Props2.Exists ("a"), "Property a was removed from props2");
Props1 := Props2;
-- Release Props2 but the property manager is internally shared so the Props1 is
-- not changed.
end;
Util.Tests.Assert_Equals (T, "b", String '(Props1.Get ("a")),
"Wrong property a in props1");
end Test_Remove_Preserve_Original;
procedure Test_Missing_Property (T : in out Test) is
Props : Properties.Manager;
V : Unbounded_String;
begin
T.Assert (Util.Beans.Objects.Is_Null (Props.Get_Value ("missing")),
"The Get_Value operation must return a null object");
begin
V := Props.Get ("missing");
T.Fail ("Exception NO_PROPERTY was not raised");
exception
when NO_PROPERTY =>
null;
end;
T.Assert (Ada.Strings.Unbounded.Length (V) = 0, "Variable get's corrupted");
Props.Set ("a", "b");
T.Assert (Util.Beans.Objects.Is_Null (Props.Get_Value ("missing")),
"The Get_Value operation must return a null object");
begin
V := Props.Get ("missing");
T.Fail ("Exception NO_PROPERTY was not raised");
exception
when NO_PROPERTY =>
null;
end;
end Test_Missing_Property;
procedure Test_Load_Ini_Property (T : in out Test) is
Props : Properties.Manager;
F : File_Type;
begin
Open (F, In_File, "regtests/files/my.cnf");
Load_Properties (Props, F);
Close (F);
declare
V : Util.Properties.Value;
P : Properties.Manager;
begin
V := Props.Get_Value ("mysqld");
T.Assert (Util.Properties.Is_Manager (V),
"Value 'mysqld' must be a property manager");
P := Util.Properties.To_Manager (V);
T.Assert (P.Exists ("user"),
"The [mysqld] property manager should contain a 'user' property");
V := Props.Get_Value ("mysqld_safe");
T.Assert (Util.Properties.Is_Manager (V),
"Value 'mysqld_safe' must be a property manager");
P := Util.Properties.To_Manager (V);
T.Assert (P.Exists ("socket"),
"The [mysqld] property manager should contain a 'socket' property");
end;
exception
when Ada.Text_IO.Name_Error =>
Ada.Text_IO.Put_Line ("Cannot find test file: regtests/files/my.cnf");
raise;
end Test_Load_Ini_Property;
package Caller is new Util.Test_Caller (Test, "Properties");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test Util.Properties.Set",
Test_Property'Access);
Caller.Add_Test (Suite, "Test Util.Properties.Get",
Test_Property'Access);
Caller.Add_Test (Suite, "Test Util.Properties.Exists",
Test_Property'Access);
Caller.Add_Test (Suite, "Test Util.Properties.Get (NO_PROPERTY)",
Test_Missing_Property'Access);
Caller.Add_Test (Suite, "Test Util.Properties.Discrete.Get",
Test_Integer_Property'Access);
Caller.Add_Test (Suite, "Test Util.Properties.Discrete.Set",
Test_Integer_Property'Access);
Caller.Add_Test (Suite, "Test Util.Properties.Load_Properties",
Test_Load_Property'Access);
Caller.Add_Test (Suite, "Test Util.Properties.Load_Properties (INI)",
Test_Load_Ini_Property'Access);
Caller.Add_Test (Suite, "Test Util.Properties.Load_Strip_Properties",
Test_Load_Strip_Property'Access);
Caller.Add_Test (Suite, "Test Util.Properties.Copy",
Test_Copy_Property'Access);
Caller.Add_Test (Suite, "Test Util.Properties.Set+Assign",
Test_Set_Preserve_Original'Access);
Caller.Add_Test (Suite, "Test Util.Properties.Set+Assign+Remove",
Test_Remove_Preserve_Original'Access);
end Add_Tests;
end Util.Properties.Tests;
|
Fix compilation warning
|
Fix compilation warning
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
2429782f49a8f27638b2971270a01d1d15b18219
|
regtests/asf-testsuite.adb
|
regtests/asf-testsuite.adb
|
-----------------------------------------------------------------------
-- ASF testsuite - Ada Server Faces Test suite
-- 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 AUnit.Assertions;
with ASF.Contexts.Writer.Tests;
with ASF.Views.Facelets.Tests;
with ASF.Applications.Views.Tests;
with ASF.Sessions.Tests;
with AUnit.Reporter.Text;
with AUnit.Run;
package body ASF.Testsuite is
use AUnit.Assertions;
procedure Run is
Ret : aliased Test_Suite;
function Get_Suite return Access_Test_Suite;
function Get_Suite return Access_Test_Suite is
begin
return Ret'Unchecked_Access;
end Get_Suite;
procedure Runner is new AUnit.Run.Test_Runner (Get_Suite);
Reporter : AUnit.Reporter.Text.Text_Reporter;
begin
ASF.Contexts.Writer.Tests.Add_Tests (Ret'Unchecked_Access);
ASF.Views.Facelets.Tests.Add_Tests (Ret'Unchecked_Access);
ASF.Applications.Views.Tests.Add_Tests (Ret'Unchecked_Access);
Runner (Reporter);
end Run;
Tests : aliased Test_Suite;
function Suite return Access_Test_Suite is
Ret : constant Access_Test_Suite := Tests'Access;
begin
ASF.Contexts.Writer.Tests.Add_Tests (Ret);
ASF.Views.Facelets.Tests.Add_Tests (Ret);
ASF.Applications.Views.Tests.Add_Tests (Ret);
ASF.Sessions.Tests.Add_Tests (Ret);
return Ret;
end Suite;
end ASF.Testsuite;
|
-----------------------------------------------------------------------
-- ASF testsuite - Ada Server Faces Test suite
-- 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 AUnit.Assertions;
with ASF.Contexts.Writer.Tests;
with ASF.Views.Facelets.Tests;
with ASF.Applications.Views.Tests;
with ASF.Sessions.Tests;
with ASF.Servlets.Tests;
with AUnit.Reporter.Text;
with AUnit.Run;
package body ASF.Testsuite is
use AUnit.Assertions;
procedure Run is
Ret : aliased Test_Suite;
function Get_Suite return Access_Test_Suite;
function Get_Suite return Access_Test_Suite is
begin
return Ret'Unchecked_Access;
end Get_Suite;
procedure Runner is new AUnit.Run.Test_Runner (Get_Suite);
Reporter : AUnit.Reporter.Text.Text_Reporter;
begin
ASF.Contexts.Writer.Tests.Add_Tests (Ret'Unchecked_Access);
ASF.Views.Facelets.Tests.Add_Tests (Ret'Unchecked_Access);
ASF.Applications.Views.Tests.Add_Tests (Ret'Unchecked_Access);
Runner (Reporter);
end Run;
Tests : aliased Test_Suite;
function Suite return Access_Test_Suite is
Ret : constant Access_Test_Suite := Tests'Access;
begin
ASF.Contexts.Writer.Tests.Add_Tests (Ret);
ASF.Views.Facelets.Tests.Add_Tests (Ret);
ASF.Applications.Views.Tests.Add_Tests (Ret);
ASF.Sessions.Tests.Add_Tests (Ret);
ASF.Servlets.Tests.Add_Tests (Ret);
return Ret;
end Suite;
end ASF.Testsuite;
|
Add servlet tests
|
Add servlet tests
|
Ada
|
apache-2.0
|
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
|
0be320dd994a8d948b2e65ac778169bd5957b00f
|
awa/plugins/awa-blogs/src/awa-blogs-beans.ads
|
awa/plugins/awa-blogs/src/awa-blogs-beans.ads
|
-----------------------------------------------------------------------
-- awa-blogs-beans -- Beans for blog module
-- Copyright (C) 2011, 2012, 2013, 2014 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Util.Beans.Basic;
with Util.Beans.Objects;
with ADO;
with AWA.Blogs.Modules;
with AWA.Blogs.Models;
with AWA.Tags.Beans;
package AWA.Blogs.Beans is
-- Attributes exposed by <b>Post_Bean</b>
BLOG_ID_ATTR : constant String := "blogId";
POST_ID_ATTR : constant String := "id";
POST_UID_ATTR : constant String := "uid";
POST_TITLE_ATTR : constant String := "title";
POST_TEXT_ATTR : constant String := "text";
POST_URI_ATTR : constant String := "uri";
POST_STATUS_ATTR : constant String := "status";
POST_USERNAME_ATTR : constant String := "username";
POST_TAG_ATTR : constant String := "tags";
POST_ALLOW_COMMENTS_ATTR : constant String := "allow_comments";
-- ------------------------------
-- Blog Bean
-- ------------------------------
-- The <b>Blog_Bean</b> holds the information about the current blog.
-- It allows to create the blog as well as update its primary title.
type Blog_Bean is new AWA.Blogs.Models.Blog_Bean with record
Module : AWA.Blogs.Modules.Blog_Module_Access := null;
end record;
type Blog_Bean_Access is access all Blog_Bean'Class;
-- Get the value identified by the name.
overriding
function Get_Value (From : in Blog_Bean;
Name : in String) return Util.Beans.Objects.Object;
-- Set the value identified by the name.
overriding
procedure Set_Value (From : in out Blog_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object);
-- Create a new blog.
overriding
procedure Create (Bean : in out Blog_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String);
type Post_Bean is new AWA.Blogs.Models.Post_Bean with record
Module : AWA.Blogs.Modules.Blog_Module_Access := null;
Blog_Id : ADO.Identifier;
-- List of tags associated with the post.
Tags : aliased AWA.Tags.Beans.Tag_List_Bean;
Tags_Bean : Util.Beans.Basic.Readonly_Bean_Access;
end record;
type Post_Bean_Access is access all Post_Bean'Class;
-- Get the value identified by the name.
overriding
function Get_Value (From : in Post_Bean;
Name : in String) return Util.Beans.Objects.Object;
-- Set the value identified by the name.
overriding
procedure Set_Value (From : in out Post_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object);
-- Load the post.
procedure Load_Post (Post : in out Post_Bean;
Id : in ADO.Identifier);
-- Create or save the post.
overriding
procedure Save (Bean : in out Post_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String);
-- Delete a post.
overriding
procedure Delete (Bean : in out Post_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String);
-- Load the post.
overriding
procedure Load (Bean : in out Post_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String);
-- Create the Blog_Bean bean instance.
function Create_Blog_Bean (Module : in AWA.Blogs.Modules.Blog_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access;
-- Create the Post_Bean bean instance.
function Create_Post_Bean (Module : in AWA.Blogs.Modules.Blog_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access;
-- List of posts visible to anybody.
type Post_List_Bean is limited new Util.Beans.Basic.Bean with record
Posts : aliased AWA.Blogs.Models.Post_Info_List_Bean;
Service : Modules.Blog_Module_Access := null;
Tag : Ada.Strings.Unbounded.Unbounded_String;
Tags : AWA.Tags.Beans.Entity_Tag_Map;
Posts_Bean : AWA.Blogs.Models.Post_Info_List_Bean_Access;
end record;
type Post_List_Bean_Access is access all Post_List_Bean'Class;
-- Get the value identified by the name.
overriding
function Get_Value (From : in Post_List_Bean;
Name : in String) return Util.Beans.Objects.Object;
-- Set the value identified by the name.
overriding
procedure Set_Value (From : in out Post_List_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object);
-- Load the list of posts. If a tag was set, filter the list of posts with the tag.
procedure Load_List (Into : in out Post_List_Bean);
-- Create the Post_List_Bean bean instance.
function Create_Post_List_Bean (Module : in AWA.Blogs.Modules.Blog_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access;
-- Create the Blog_Admin_Bean bean instance.
function Create_Blog_Admin_Bean (Module : in AWA.Blogs.Modules.Blog_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access;
-- Get a select item list which contains a list of post status.
function Create_Status_List (Module : in AWA.Blogs.Modules.Blog_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access;
type Init_Flag is (INIT_BLOG_LIST, INIT_POST_LIST, INIT_COMMENT_LIST);
type Init_Map is array (Init_Flag) of Boolean;
type Blog_Admin_Bean is new Util.Beans.Basic.Bean with record
Module : AWA.Blogs.Modules.Blog_Module_Access := null;
-- The blog identifier.
Blog_Id : ADO.Identifier := ADO.NO_IDENTIFIER;
-- List of blogs.
Blog_List : aliased AWA.Blogs.Models.Blog_Info_List_Bean;
Blog_List_Bean : AWA.Blogs.Models.Blog_Info_List_Bean_Access;
-- List of posts.
Post_List : aliased AWA.Blogs.Models.Admin_Post_Info_List_Bean;
Post_List_Bean : AWA.Blogs.Models.Admin_Post_Info_List_Bean_Access;
-- List of comments.
Comment_List : aliased AWA.Blogs.Models.Comment_Info_List_Bean;
Comment_List_Bean : AWA.Blogs.Models.Comment_Info_List_Bean_Access;
-- Initialization flags.
Init_Flags : aliased Init_Map := (others => False);
Flags : access Init_Map;
end record;
type Blog_Admin_Bean_Access is access all Blog_Admin_Bean;
-- Get the blog identifier.
function Get_Blog_Id (List : in Blog_Admin_Bean) return ADO.Identifier;
-- Load the posts associated with the current blog.
procedure Load_Posts (List : in Blog_Admin_Bean);
-- Load the comments associated with the current blog.
procedure Load_Comments (List : in Blog_Admin_Bean);
overriding
function Get_Value (List : in Blog_Admin_Bean;
Name : in String) return Util.Beans.Objects.Object;
-- Set the value identified by the name.
overriding
procedure Set_Value (From : in out Blog_Admin_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object);
-- Load the list of blogs.
procedure Load_Blogs (List : in Blog_Admin_Bean);
end AWA.Blogs.Beans;
|
-----------------------------------------------------------------------
-- awa-blogs-beans -- Beans for blog module
-- Copyright (C) 2011, 2012, 2013, 2014 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Util.Beans.Basic;
with Util.Beans.Objects;
with ADO;
with AWA.Blogs.Modules;
with AWA.Blogs.Models;
with AWA.Tags.Beans;
package AWA.Blogs.Beans is
-- Attributes exposed by <b>Post_Bean</b>
BLOG_ID_ATTR : constant String := "blogId";
POST_ID_ATTR : constant String := "id";
POST_UID_ATTR : constant String := "uid";
POST_TITLE_ATTR : constant String := "title";
POST_TEXT_ATTR : constant String := "text";
POST_URI_ATTR : constant String := "uri";
POST_STATUS_ATTR : constant String := "status";
POST_USERNAME_ATTR : constant String := "username";
POST_TAG_ATTR : constant String := "tags";
POST_ALLOW_COMMENTS_ATTR : constant String := "allow_comments";
-- ------------------------------
-- Blog Bean
-- ------------------------------
-- The <b>Blog_Bean</b> holds the information about the current blog.
-- It allows to create the blog as well as update its primary title.
type Blog_Bean is new AWA.Blogs.Models.Blog_Bean with record
Module : AWA.Blogs.Modules.Blog_Module_Access := null;
end record;
type Blog_Bean_Access is access all Blog_Bean'Class;
-- Get the value identified by the name.
overriding
function Get_Value (From : in Blog_Bean;
Name : in String) return Util.Beans.Objects.Object;
-- Set the value identified by the name.
overriding
procedure Set_Value (From : in out Blog_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object);
-- Create a new blog.
overriding
procedure Create (Bean : in out Blog_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String);
type Post_Bean is new AWA.Blogs.Models.Post_Bean with record
Module : AWA.Blogs.Modules.Blog_Module_Access := null;
Blog_Id : ADO.Identifier;
-- List of tags associated with the post.
Tags : aliased AWA.Tags.Beans.Tag_List_Bean;
Tags_Bean : Util.Beans.Basic.Readonly_Bean_Access;
end record;
type Post_Bean_Access is access all Post_Bean'Class;
-- Get the value identified by the name.
overriding
function Get_Value (From : in Post_Bean;
Name : in String) return Util.Beans.Objects.Object;
-- Set the value identified by the name.
overriding
procedure Set_Value (From : in out Post_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object);
-- Load the post.
procedure Load_Post (Post : in out Post_Bean;
Id : in ADO.Identifier);
-- Create or save the post.
overriding
procedure Save (Bean : in out Post_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String);
-- Delete a post.
overriding
procedure Delete (Bean : in out Post_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String);
-- Load the post.
overriding
procedure Load (Bean : in out Post_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String);
-- Create the Blog_Bean bean instance.
function Create_Blog_Bean (Module : in AWA.Blogs.Modules.Blog_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access;
-- Create the Post_Bean bean instance.
function Create_Post_Bean (Module : in AWA.Blogs.Modules.Blog_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access;
-- List of posts visible to anybody.
type Post_List_Bean is new AWA.Blogs.Models.Post_List_Bean with record
Posts : aliased AWA.Blogs.Models.Post_Info_List_Bean;
Service : Modules.Blog_Module_Access := null;
Tags : AWA.Tags.Beans.Entity_Tag_Map;
Posts_Bean : AWA.Blogs.Models.Post_Info_List_Bean_Access;
end record;
type Post_List_Bean_Access is access all Post_List_Bean'Class;
-- Get the value identified by the name.
overriding
function Get_Value (From : in Post_List_Bean;
Name : in String) return Util.Beans.Objects.Object;
-- Set the value identified by the name.
overriding
procedure Set_Value (From : in out Post_List_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object);
overriding
procedure Load (From : in out Post_List_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String);
-- Load the list of posts. If a tag was set, filter the list of posts with the tag.
procedure Load_List (Into : in out Post_List_Bean);
-- Create the Post_List_Bean bean instance.
function Create_Post_List_Bean (Module : in AWA.Blogs.Modules.Blog_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access;
-- Create the Blog_Admin_Bean bean instance.
function Create_Blog_Admin_Bean (Module : in AWA.Blogs.Modules.Blog_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access;
-- Get a select item list which contains a list of post status.
function Create_Status_List (Module : in AWA.Blogs.Modules.Blog_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access;
type Init_Flag is (INIT_BLOG_LIST, INIT_POST_LIST, INIT_COMMENT_LIST);
type Init_Map is array (Init_Flag) of Boolean;
type Blog_Admin_Bean is new Util.Beans.Basic.Bean with record
Module : AWA.Blogs.Modules.Blog_Module_Access := null;
-- The blog identifier.
Blog_Id : ADO.Identifier := ADO.NO_IDENTIFIER;
-- List of blogs.
Blog_List : aliased AWA.Blogs.Models.Blog_Info_List_Bean;
Blog_List_Bean : AWA.Blogs.Models.Blog_Info_List_Bean_Access;
-- List of posts.
Post_List : aliased AWA.Blogs.Models.Admin_Post_Info_List_Bean;
Post_List_Bean : AWA.Blogs.Models.Admin_Post_Info_List_Bean_Access;
-- List of comments.
Comment_List : aliased AWA.Blogs.Models.Comment_Info_List_Bean;
Comment_List_Bean : AWA.Blogs.Models.Comment_Info_List_Bean_Access;
-- Initialization flags.
Init_Flags : aliased Init_Map := (others => False);
Flags : access Init_Map;
end record;
type Blog_Admin_Bean_Access is access all Blog_Admin_Bean;
-- Get the blog identifier.
function Get_Blog_Id (List : in Blog_Admin_Bean) return ADO.Identifier;
-- Load the posts associated with the current blog.
procedure Load_Posts (List : in Blog_Admin_Bean);
-- Load the comments associated with the current blog.
procedure Load_Comments (List : in Blog_Admin_Bean);
overriding
function Get_Value (List : in Blog_Admin_Bean;
Name : in String) return Util.Beans.Objects.Object;
-- Set the value identified by the name.
overriding
procedure Set_Value (From : in out Blog_Admin_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object);
-- Load the list of blogs.
procedure Load_Blogs (List : in Blog_Admin_Bean);
end AWA.Blogs.Beans;
|
Use the UML Post_List_Bean type and override the Load operation
|
Use the UML Post_List_Bean type and override the Load operation
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
ba38c6d574a7da94b3729a7e223fd13c99519032
|
src/util-encoders-aes.ads
|
src/util-encoders-aes.ads
|
-----------------------------------------------------------------------
-- util-encoders-aes -- AES encryption and decryption
-- Copyright (C) 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Streams;
with Interfaces;
-- The <b>Util.Encodes.SHA1</b> package generates SHA-1 hash according to
-- RFC3174 or [FIPS-180-1].
package Util.Encoders.AES is
type Key_Type is private;
-- ------------------------------
-- ------------------------------
subtype Block_Type is Ada.Streams.Stream_Element_Array (1 .. 16);
procedure Set_Encrypt_Key (Key : out Key_Type;
Data : in Ada.Streams.Stream_Element_Array);
procedure Set_Decrypt_Key (Key : out Key_Type;
Data : in Ada.Streams.Stream_Element_Array);
procedure Encrypt (Input : in Block_Type;
Output : out Block_Type;
Key : in Key_Type);
procedure Encrypt (Input : in Ada.Streams.Stream_Element_Array;
Output : out Ada.Streams.Stream_Element_Array;
Last : out Ada.Streams.Stream_Element_Offset;
Key : in Key_Type);
procedure Decrypt (Input : in Block_Type;
Output : out Block_Type;
Key : in Key_Type);
-- ------------------------------
-- AES encoder
-- ------------------------------
-- This <b>Encoder</b> translates the (binary) input stream into
-- an SHA1 hexadecimal stream. The encoding alphabet is: 0123456789ABCDEF.
type Encoder is new Util.Encoders.Transformer with private;
-- Encodes the binary input stream represented by <b>Data</b> into
-- an SHA-1 hash output stream <b>Into</b>.
--
-- If the transformer does not have enough room to write the result,
-- it must return in <b>Encoded</b> the index of the last encoded
-- position in the <b>Data</b> stream.
--
-- The transformer returns in <b>Last</b> the last valid position
-- in the output stream <b>Into</b>.
--
-- The <b>Encoding_Error</b> exception is raised if the input
-- stream cannot be transformed.
overriding
procedure Transform (E : in Encoder;
Data : in Ada.Streams.Stream_Element_Array;
Into : out Ada.Streams.Stream_Element_Array;
Last : out Ada.Streams.Stream_Element_Offset;
Encoded : out Ada.Streams.Stream_Element_Offset);
private
type Encoder is new Util.Encoders.Transformer with null record;
use Interfaces;
type Block_Key is array (0 .. 59) of Unsigned_32;
type Key_Type is record
Key : Block_Key;
Rounds : Natural := 0;
end record;
end Util.Encoders.AES;
|
-----------------------------------------------------------------------
-- util-encoders-aes -- AES encryption and decryption
-- Copyright (C) 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Streams;
with Interfaces;
-- The <b>Util.Encodes.SHA1</b> package generates SHA-1 hash according to
-- RFC3174 or [FIPS-180-1].
package Util.Encoders.AES is
type Key_Type is private;
-- ------------------------------
-- ------------------------------
subtype Block_Type is Ada.Streams.Stream_Element_Array (1 .. 16);
procedure Set_Encrypt_Key (Key : out Key_Type;
Data : in Ada.Streams.Stream_Element_Array);
procedure Set_Decrypt_Key (Key : out Key_Type;
Data : in Ada.Streams.Stream_Element_Array);
procedure Encrypt (Input : in Block_Type;
Output : out Block_Type;
Key : in Key_Type);
procedure Encrypt (Input : in Ada.Streams.Stream_Element_Array;
Output : out Ada.Streams.Stream_Element_Array;
Last : out Ada.Streams.Stream_Element_Offset;
Key : in Key_Type);
procedure Decrypt (Input : in Block_Type;
Output : out Block_Type;
Key : in Key_Type);
-- ------------------------------
-- AES encoder
-- ------------------------------
-- This <b>Encoder</b> translates the (binary) input stream into
-- an SHA1 hexadecimal stream. The encoding alphabet is: 0123456789ABCDEF.
type Encoder is new Util.Encoders.Transformer with private;
-- Encodes the binary input stream represented by <b>Data</b> into
-- an SHA-1 hash output stream <b>Into</b>.
--
-- If the transformer does not have enough room to write the result,
-- it must return in <b>Encoded</b> the index of the last encoded
-- position in the <b>Data</b> stream.
--
-- The transformer returns in <b>Last</b> the last valid position
-- in the output stream <b>Into</b>.
--
-- The <b>Encoding_Error</b> exception is raised if the input
-- stream cannot be transformed.
overriding
procedure Transform (E : in out Encoder;
Data : in Ada.Streams.Stream_Element_Array;
Into : out Ada.Streams.Stream_Element_Array;
Last : out Ada.Streams.Stream_Element_Offset;
Encoded : out Ada.Streams.Stream_Element_Offset);
private
type Encoder is new Util.Encoders.Transformer with null record;
use Interfaces;
type Block_Key is array (0 .. 59) of Unsigned_32;
type Key_Type is record
Key : Block_Key;
Rounds : Natural := 0;
end record;
end Util.Encoders.AES;
|
Change the Transformer interface to accept in out parameter for the Transformer
|
Change the Transformer interface to accept in out parameter for the Transformer
|
Ada
|
apache-2.0
|
stcarrez/ada-util,stcarrez/ada-util
|
64575a9df8e9c7a440adade335dc35b9b3aabebe
|
src/wiki-filters-html.adb
|
src/wiki-filters-html.adb
|
-----------------------------------------------------------------------
-- wiki-filters-html -- Wiki HTML filters
-- Copyright (C) 2015, 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.Helpers;
package body Wiki.Filters.Html is
-- ------------------------------
-- Add a simple node such as N_LINE_BREAK, N_HORIZONTAL_RULE or N_PARAGRAPH to the document.
-- ------------------------------
overriding
procedure Add_Node (Filter : in out Html_Filter_Type;
Document : in out Wiki.Documents.Document;
Kind : in Wiki.Nodes.Simple_Node_Kind) is
Tag : Html_Tag;
begin
case Kind is
when N_LINE_BREAK =>
Tag := BR_TAG;
when N_PARAGRAPH =>
Tag := P_TAG;
when N_HORIZONTAL_RULE =>
Tag := HR_TAG;
when N_TOC_DISPLAY | N_NONE =>
return;
when N_NEWLINE | N_LIST_END | N_LIST_ITEM_END | N_NUM_LIST_END
| N_LIST_ITEM =>
Filter_Type (Filter).Add_Node (Document, Kind);
return;
end case;
if Filter.Allowed (Tag) then
Filter_Type (Filter).Add_Node (Document, Kind);
end if;
end Add_Node;
-- ------------------------------
-- Add a text content with the given format to the document.
-- ------------------------------
overriding
procedure Add_Text (Filter : in out Html_Filter_Type;
Document : in out Wiki.Documents.Document;
Text : in Wiki.Strings.WString;
Format : in Wiki.Format_Map) is
begin
if Filter.Hide_Level > 0 then
return;
end if;
Filter_Type (Filter).Add_Text (Document, Text, Format);
end Add_Text;
-- ------------------------------
-- Add a section header with the given level in the document.
-- ------------------------------
overriding
procedure Add_Header (Filter : in out Html_Filter_Type;
Document : in out Wiki.Documents.Document;
Header : in Wiki.Strings.WString;
Level : in Natural) is
begin
Filter.Flush_Stack (Document);
Filter_Type (Filter).Add_Header (Document, Header, Level);
end Add_Header;
-- ------------------------------
-- Push a HTML node with the given tag to the document.
-- ------------------------------
overriding
procedure Push_Node (Filter : in out Html_Filter_Type;
Document : in out Wiki.Documents.Document;
Tag : in Wiki.Html_Tag;
Attributes : in out Wiki.Attributes.Attribute_List) is
Current_Tag : Html_Tag;
begin
while not Filter.Stack.Is_Empty loop
Current_Tag := Filter.Stack.Last_Element;
if Wiki.Helpers.Need_Close (Tag, Current_Tag) then
if Filter.Hide_Level = 0 then
Filter_Type (Filter).Pop_Node (Document, Current_Tag);
end if;
Filter.Stack.Delete_Last;
end if;
exit;
end loop;
if Filter.Hidden (Tag) then
Filter.Hide_Level := Filter.Hide_Level + 1;
elsif not Filter.Allowed (Tag) then
return;
end if;
Filter.Stack.Append (Tag);
if Filter.Hide_Level = 0 then
Filter_Type (Filter).Push_Node (Document, Tag, Attributes);
end if;
end Push_Node;
-- ------------------------------
-- Pop a HTML node with the given tag.
-- ------------------------------
overriding
procedure Pop_Node (Filter : in out Html_Filter_Type;
Document : in out Wiki.Documents.Document;
Tag : in Wiki.Html_Tag) is
Current_Tag : Html_Tag;
begin
if Filter.Stack.Is_Empty then
return;
elsif not Filter.Allowed (Tag) and not Filter.Hidden (Tag) then
return;
end if;
-- Emit a end tag element until we find our matching tag and the top most tag
-- allows the end tag to be omitted (ex: a td, tr, td, dd, ...).
while not Filter.Stack.Is_Empty loop
Current_Tag := Filter.Stack.Last_Element;
exit when Current_Tag = Tag or not Tag_Omission (Current_Tag);
if Filter.Hide_Level = 0 then
Filter_Type (Filter).Pop_Node (Document, Current_Tag);
end if;
Filter.Stack.Delete_Last;
end loop;
if Filter.Hide_Level = 0 then
Filter_Type (Filter).Pop_Node (Document, Tag);
end if;
if Filter.Hidden (Current_Tag) then
Filter.Hide_Level := Filter.Hide_Level - 1;
end if;
Filter.Stack.Delete_Last;
end Pop_Node;
-- ------------------------------
-- Add a link.
-- ------------------------------
overriding
procedure Add_Link (Filter : in out Html_Filter_Type;
Document : in out Wiki.Documents.Document;
Name : in Wiki.Strings.WString;
Attributes : in out Wiki.Attributes.Attribute_List) is
begin
if Filter.Allowed (A_TAG) then
Filter_Type (Filter).Add_Link (Document, Name, Attributes);
end if;
end Add_Link;
-- ------------------------------
-- Add an image.
-- ------------------------------
overriding
procedure Add_Image (Filter : in out Html_Filter_Type;
Document : in out Wiki.Documents.Document;
Name : in Wiki.Strings.WString;
Attributes : in out Wiki.Attributes.Attribute_List) is
begin
if Filter.Allowed (IMG_TAG) then
Filter_Type (Filter).Add_Image (Document, Name, Attributes);
end if;
end Add_Image;
-- ------------------------------
-- Flush the HTML element that have not yet been closed.
-- ------------------------------
procedure Flush_Stack (Filter : in out Html_Filter_Type;
Document : in out Wiki.Documents.Document) is
begin
while not Filter.Stack.Is_Empty loop
declare
Tag : constant Html_Tag := Filter.Stack.Last_Element;
begin
if Filter.Hide_Level = 0 then
Filter_Type (Filter).Pop_Node (Document, Tag);
end if;
if Filter.Hidden (Tag) then
Filter.Hide_Level := Filter.Hide_Level - 1;
end if;
end;
Filter.Stack.Delete_Last;
end loop;
end Flush_Stack;
-- ------------------------------
-- Finish the document after complete wiki text has been parsed.
-- ------------------------------
overriding
procedure Finish (Filter : in out Html_Filter_Type;
Document : in out Wiki.Documents.Document) is
begin
Filter.Flush_Stack (Document);
Filter_Type (Filter).Finish (Document);
end Finish;
-- ------------------------------
-- Mark the HTML tag as being forbidden.
-- ------------------------------
procedure Forbidden (Filter : in out Html_Filter_Type;
Tag : in Html_Tag) is
begin
Filter.Allowed (Tag) := False;
end Forbidden;
-- ------------------------------
-- Mark the HTML tag as being allowed.
-- ------------------------------
procedure Allowed (Filter : in out Html_Filter_Type;
Tag : in Html_Tag) is
begin
Filter.Allowed (Tag) := True;
end Allowed;
-- ------------------------------
-- Mark the HTML tag as being hidden. The tag and its inner content including the text
-- will be removed and not passed to the final document.
-- ------------------------------
procedure Hide (Filter : in out Html_Filter_Type;
Tag : in Html_Tag) is
begin
Filter.Hidden (Tag) := True;
end Hide;
-- ------------------------------
-- Mark the HTML tag as being visible.
-- ------------------------------
procedure Visible (Filter : in out Html_Filter_Type;
Tag : in Html_Tag) is
begin
Filter.Hidden (Tag) := False;
end Visible;
end Wiki.Filters.Html;
|
-----------------------------------------------------------------------
-- wiki-filters-html -- Wiki HTML filters
-- Copyright (C) 2015, 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.Helpers;
package body Wiki.Filters.Html is
-- ------------------------------
-- Add a simple node such as N_LINE_BREAK, N_HORIZONTAL_RULE or N_PARAGRAPH to the document.
-- ------------------------------
overriding
procedure Add_Node (Filter : in out Html_Filter_Type;
Document : in out Wiki.Documents.Document;
Kind : in Wiki.Nodes.Simple_Node_Kind) is
Tag : Html_Tag;
begin
case Kind is
when N_LINE_BREAK =>
Tag := BR_TAG;
when N_PARAGRAPH =>
Tag := P_TAG;
when N_HORIZONTAL_RULE =>
Tag := HR_TAG;
when N_TOC_DISPLAY | N_NONE =>
return;
when N_NEWLINE | N_LIST_END | N_LIST_ITEM_END | N_NUM_LIST_END
| N_LIST_ITEM | N_END_DEFINITION =>
Filter_Type (Filter).Add_Node (Document, Kind);
return;
end case;
if Filter.Allowed (Tag) then
Filter_Type (Filter).Add_Node (Document, Kind);
end if;
end Add_Node;
-- ------------------------------
-- Add a text content with the given format to the document.
-- ------------------------------
overriding
procedure Add_Text (Filter : in out Html_Filter_Type;
Document : in out Wiki.Documents.Document;
Text : in Wiki.Strings.WString;
Format : in Wiki.Format_Map) is
begin
if Filter.Hide_Level > 0 then
return;
end if;
Filter_Type (Filter).Add_Text (Document, Text, Format);
end Add_Text;
-- ------------------------------
-- Add a section header with the given level in the document.
-- ------------------------------
overriding
procedure Add_Header (Filter : in out Html_Filter_Type;
Document : in out Wiki.Documents.Document;
Header : in Wiki.Strings.WString;
Level : in Natural) is
begin
Filter.Flush_Stack (Document);
Filter_Type (Filter).Add_Header (Document, Header, Level);
end Add_Header;
-- ------------------------------
-- Push a HTML node with the given tag to the document.
-- ------------------------------
overriding
procedure Push_Node (Filter : in out Html_Filter_Type;
Document : in out Wiki.Documents.Document;
Tag : in Wiki.Html_Tag;
Attributes : in out Wiki.Attributes.Attribute_List) is
Current_Tag : Html_Tag;
begin
while not Filter.Stack.Is_Empty loop
Current_Tag := Filter.Stack.Last_Element;
if Wiki.Helpers.Need_Close (Tag, Current_Tag) then
if Filter.Hide_Level = 0 then
Filter_Type (Filter).Pop_Node (Document, Current_Tag);
end if;
Filter.Stack.Delete_Last;
end if;
exit;
end loop;
if Filter.Hidden (Tag) then
Filter.Hide_Level := Filter.Hide_Level + 1;
elsif not Filter.Allowed (Tag) then
return;
end if;
Filter.Stack.Append (Tag);
if Filter.Hide_Level = 0 then
Filter_Type (Filter).Push_Node (Document, Tag, Attributes);
end if;
end Push_Node;
-- ------------------------------
-- Pop a HTML node with the given tag.
-- ------------------------------
overriding
procedure Pop_Node (Filter : in out Html_Filter_Type;
Document : in out Wiki.Documents.Document;
Tag : in Wiki.Html_Tag) is
Current_Tag : Html_Tag;
begin
if Filter.Stack.Is_Empty then
return;
elsif not Filter.Allowed (Tag) and not Filter.Hidden (Tag) then
return;
end if;
-- Emit a end tag element until we find our matching tag and the top most tag
-- allows the end tag to be omitted (ex: a td, tr, td, dd, ...).
while not Filter.Stack.Is_Empty loop
Current_Tag := Filter.Stack.Last_Element;
exit when Current_Tag = Tag or not Tag_Omission (Current_Tag);
if Filter.Hide_Level = 0 then
Filter_Type (Filter).Pop_Node (Document, Current_Tag);
end if;
Filter.Stack.Delete_Last;
end loop;
if Filter.Hide_Level = 0 then
Filter_Type (Filter).Pop_Node (Document, Tag);
end if;
if Filter.Hidden (Current_Tag) then
Filter.Hide_Level := Filter.Hide_Level - 1;
end if;
Filter.Stack.Delete_Last;
end Pop_Node;
-- ------------------------------
-- Add a link.
-- ------------------------------
overriding
procedure Add_Link (Filter : in out Html_Filter_Type;
Document : in out Wiki.Documents.Document;
Name : in Wiki.Strings.WString;
Attributes : in out Wiki.Attributes.Attribute_List) is
begin
if Filter.Allowed (A_TAG) then
Filter_Type (Filter).Add_Link (Document, Name, Attributes);
end if;
end Add_Link;
-- ------------------------------
-- Add an image.
-- ------------------------------
overriding
procedure Add_Image (Filter : in out Html_Filter_Type;
Document : in out Wiki.Documents.Document;
Name : in Wiki.Strings.WString;
Attributes : in out Wiki.Attributes.Attribute_List) is
begin
if Filter.Allowed (IMG_TAG) then
Filter_Type (Filter).Add_Image (Document, Name, Attributes);
end if;
end Add_Image;
-- ------------------------------
-- Flush the HTML element that have not yet been closed.
-- ------------------------------
procedure Flush_Stack (Filter : in out Html_Filter_Type;
Document : in out Wiki.Documents.Document) is
begin
while not Filter.Stack.Is_Empty loop
declare
Tag : constant Html_Tag := Filter.Stack.Last_Element;
begin
if Filter.Hide_Level = 0 then
Filter_Type (Filter).Pop_Node (Document, Tag);
end if;
if Filter.Hidden (Tag) then
Filter.Hide_Level := Filter.Hide_Level - 1;
end if;
end;
Filter.Stack.Delete_Last;
end loop;
end Flush_Stack;
-- ------------------------------
-- Finish the document after complete wiki text has been parsed.
-- ------------------------------
overriding
procedure Finish (Filter : in out Html_Filter_Type;
Document : in out Wiki.Documents.Document) is
begin
Filter.Flush_Stack (Document);
Filter_Type (Filter).Finish (Document);
end Finish;
-- ------------------------------
-- Mark the HTML tag as being forbidden.
-- ------------------------------
procedure Forbidden (Filter : in out Html_Filter_Type;
Tag : in Html_Tag) is
begin
Filter.Allowed (Tag) := False;
end Forbidden;
-- ------------------------------
-- Mark the HTML tag as being allowed.
-- ------------------------------
procedure Allowed (Filter : in out Html_Filter_Type;
Tag : in Html_Tag) is
begin
Filter.Allowed (Tag) := True;
end Allowed;
-- ------------------------------
-- Mark the HTML tag as being hidden. The tag and its inner content including the text
-- will be removed and not passed to the final document.
-- ------------------------------
procedure Hide (Filter : in out Html_Filter_Type;
Tag : in Html_Tag) is
begin
Filter.Hidden (Tag) := True;
end Hide;
-- ------------------------------
-- Mark the HTML tag as being visible.
-- ------------------------------
procedure Visible (Filter : in out Html_Filter_Type;
Tag : in Html_Tag) is
begin
Filter.Hidden (Tag) := False;
end Visible;
end Wiki.Filters.Html;
|
Add support for N_END_DEFINITION node
|
Add support for N_END_DEFINITION node
|
Ada
|
apache-2.0
|
stcarrez/ada-wiki,stcarrez/ada-wiki
|
f7c54a5dde5412d25d95ac990ec1f9254c5edb8b
|
src/mysql/ado-mysql.ads
|
src/mysql/ado-mysql.ads
|
-----------------------------------------------------------------------
-- ado-mysql -- MySQL Database Drivers
-- Copyright (C) 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.Properties;
-- === MySQL Database Driver ===
-- The MySQL database driver can be initialize explicitly by using the `ado_mysql`
-- GNAT project and calling the initialization procedure.
--
-- ADO.Mysql.Initialize ("db.properties");
--
-- The set of configuration properties can be set programatically and passed to the
-- `Initialize` operation.
--
-- Config : Util.Properties.Manager;
-- ...
-- Config.Set ("ado.database", "mysql://localhost:3306/ado_test");
-- Config.Set ("ado.queries.path", ".;db");
-- ADO.Mysql.Initialize (Config);
--
-- The MySQL database driver supports the following properties:
--
-- | Name | Description |
-- | ----------- | --------- |
-- | user | The user name to connect to the server |
-- | password | The user password to connect to the server |
-- | socket | The optional Unix socket path for a Unix socket base connection |
-- | encoding | The encoding to be used for the connection (ex: UTF-8) |
--
package ADO.Mysql is
-- 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);
end ADO.Mysql;
|
-----------------------------------------------------------------------
-- ado-mysql -- MySQL Database Drivers
-- Copyright (C) 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.Properties;
-- === MySQL Database Driver ===
-- The MySQL database driver can be initialize explicitly by using the `ado_mysql`
-- GNAT project and calling the initialization procedure.
--
-- ADO.Mysql.Initialize ("db.properties");
--
-- The set of configuration properties can be set programatically and passed to the
-- `Initialize` operation.
--
-- Config : Util.Properties.Manager;
-- ...
-- Config.Set ("ado.database", "mysql://localhost:3306/ado_test");
-- Config.Set ("ado.queries.path", ".;db");
-- ADO.Mysql.Initialize (Config);
--
-- The MySQL database driver supports the following properties:
--
-- | Name | Description |
-- | ----------- | --------- |
-- | user | The user name to connect to the server |
-- | password | The user password to connect to the server |
-- | socket | The optional Unix socket path for a Unix socket base connection |
-- | encoding | The encoding to be used for the connection (ex: UTF-8) |
--
package ADO.Mysql is
-- Initialize the Mysql driver.
procedure Initialize;
-- 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);
end ADO.Mysql;
|
Declare the Initialize procedure
|
Declare the Initialize procedure
|
Ada
|
apache-2.0
|
stcarrez/ada-ado
|
07d8801d2a5dceed5bbec726b3290ae68584bb7b
|
matp/src/mat-formats.adb
|
matp/src/mat-formats.adb
|
-----------------------------------------------------------------------
-- mat-formats - Format various types for the console or GUI interface
-- Copyright (C) 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Strings;
package body MAT.Formats is
use type MAT.Types.Target_Tick_Ref;
Hex_Prefix : Boolean := True;
Conversion : constant String (1 .. 10) := "0123456789";
function Location (File : in Ada.Strings.Unbounded.Unbounded_String) return String;
function Event_Malloc (Item : in MAT.Events.Target_Event_Type;
Related : in MAT.Events.Tools.Target_Event_Vector;
Start_Time : in MAT.Types.Target_Tick_Ref) return String;
function Event_Free (Item : in MAT.Events.Target_Event_Type;
Related : in MAT.Events.Tools.Target_Event_Vector;
Start_Time : in MAT.Types.Target_Tick_Ref) return String;
-- ------------------------------
-- Format the PID into a string.
-- ------------------------------
function Pid (Value : in MAT.Types.Target_Process_Ref) return String is
begin
return Util.Strings.Image (Natural (Value));
end Pid;
-- ------------------------------
-- Format the address into a string.
-- ------------------------------
function Addr (Value : in MAT.Types.Target_Addr) return String is
Hex : constant String := MAT.Types.Hex_Image (Value);
begin
if Hex_Prefix then
return "0x" & Hex;
else
return Hex;
end if;
end Addr;
-- ------------------------------
-- Format the size into a string.
-- ------------------------------
function Size (Value : in MAT.Types.Target_Size) return String is
Result : constant String := MAT.Types.Target_Size'Image (Value);
begin
if Result (Result'First) = ' ' then
return Result (Result'First + 1 .. Result'Last);
else
return Result;
end if;
end Size;
-- ------------------------------
-- Format the memory growth size into a string.
-- ------------------------------
function Size (Alloced : in MAT.Types.Target_Size;
Freed : in MAT.Types.Target_Size) return String is
use type MAT.Types.Target_Size;
begin
if Alloced > Freed then
return Size (Alloced - Freed);
elsif Alloced < Freed then
return "-" & Size (Freed - Alloced);
else
return "=" & Size (Alloced);
end if;
end Size;
-- ------------------------------
-- Format the time relative to the start time.
-- ------------------------------
function Time (Value : in MAT.Types.Target_Tick_Ref;
Start : in MAT.Types.Target_Tick_Ref) return String is
T : constant MAT.Types.Target_Tick_Ref := Value - Start;
Sec : constant MAT.Types.Target_Tick_Ref := T / 1_000_000;
Usec : constant MAT.Types.Target_Tick_Ref := T mod 1_000_000;
Msec : Natural := Natural (Usec / 1_000);
Frac : String (1 .. 5);
begin
Frac (5) := 's';
Frac (4) := Conversion (Msec mod 10 + 1);
Msec := Msec / 10;
Frac (3) := Conversion (Msec mod 10 + 1);
Msec := Msec / 10;
Frac (2) := Conversion (Msec mod 10 + 1);
Frac (1) := '.';
return MAT.Types.Target_Tick_Ref'Image (Sec) & Frac;
end Time;
-- ------------------------------
-- Format the duration in seconds, milliseconds or microseconds.
-- ------------------------------
function Duration (Value : in MAT.Types.Target_Tick_Ref) return String is
Sec : constant MAT.Types.Target_Tick_Ref := Value / 1_000_000;
Usec : constant MAT.Types.Target_Tick_Ref := Value mod 1_000_000;
Msec : constant Natural := Natural (Usec / 1_000);
Val : Natural;
Frac : String (1 .. 5);
begin
if Sec = 0 and Msec = 0 then
return Util.Strings.Image (Integer (Usec)) & "us";
elsif Sec = 0 then
Val := Natural (Usec mod 1_000);
Frac (5) := 's';
Frac (4) := 'm';
Frac (3) := Conversion (Val mod 10 + 1);
Val := Val / 10;
Frac (3) := Conversion (Val mod 10 + 1);
Val := Val / 10;
Frac (2) := Conversion (Val mod 10 + 1);
Frac (1) := '.';
return Util.Strings.Image (Integer (Msec)) & Frac;
else
Val := Msec;
Frac (4) := 's';
Frac (3) := Conversion (Val mod 10 + 1);
Val := Val / 10;
Frac (3) := Conversion (Val mod 10 + 1);
Val := Val / 10;
Frac (2) := Conversion (Val mod 10 + 1);
Frac (1) := '.';
return Util.Strings.Image (Integer (Sec)) & Frac (1 .. 4);
end if;
end Duration;
function Location (File : in Ada.Strings.Unbounded.Unbounded_String) return String is
Pos : constant Natural := Ada.Strings.Unbounded.Index (File, "/", Ada.Strings.Backward);
Len : constant Natural := Ada.Strings.Unbounded.Length (File);
begin
if Pos /= 0 then
return Ada.Strings.Unbounded.Slice (File, Pos + 1, Len);
else
return Ada.Strings.Unbounded.To_String (File);
end if;
end Location;
-- ------------------------------
-- Format a file, line, function information into a string.
-- ------------------------------
function Location (File : in Ada.Strings.Unbounded.Unbounded_String;
Line : in Natural;
Func : in Ada.Strings.Unbounded.Unbounded_String) return String is
begin
if Ada.Strings.Unbounded.Length (File) = 0 then
return Ada.Strings.Unbounded.To_String (Func);
elsif Line > 0 then
declare
Num : constant String := Natural'Image (Line);
begin
return Ada.Strings.Unbounded.To_String (Func) & " ("
& Location (File) & ":" & Num (Num'First + 1 .. Num'Last) & ")";
end;
else
return Ada.Strings.Unbounded.To_String (Func) & " (" & Location (File) & ")";
end if;
end Location;
-- ------------------------------
-- Format an event range description.
-- ------------------------------
function Event (First : in MAT.Events.Target_Event_Type;
Last : in MAT.Events.Target_Event_Type) return String is
use type MAT.Events.Event_Id_Type;
Id1 : constant String := MAT.Events.Event_Id_Type'Image (First.Id);
Id2 : constant String := MAT.Events.Event_Id_Type'Image (Last.Id);
begin
if First.Id = Last.Id then
return Id1 (Id1'First + 1 .. Id1'Last);
else
return Id1 (Id1'First + 1 .. Id1'Last) & ".." & Id2 (Id2'First + 1 .. Id2'Last);
end if;
end Event;
-- ------------------------------
-- Format a short description of the event.
-- ------------------------------
function Event (Item : in MAT.Events.Target_Event_Type;
Mode : in Format_Type := NORMAL) return String is
use type MAT.Types.Target_Addr;
begin
case Item.Index is
when MAT.Events.MSG_MALLOC =>
if Mode = BRIEF then
return "malloc";
else
return "malloc(" & Size (Item.Size) & ") = " & Addr (Item.Addr);
end if;
when MAT.Events.MSG_REALLOC =>
if Mode = BRIEF then
if Item.Old_Addr = 0 then
return "realloc";
else
return "realloc";
end if;
else
if Item.Old_Addr = 0 then
return "realloc(0," & Size (Item.Size) & ") = "
& Addr (Item.Addr);
else
return "realloc(" & Addr (Item.Old_Addr) & "," & Size (Item.Size) & ") = "
& Addr (Item.Addr);
end if;
end if;
when MAT.Events.MSG_FREE =>
if Mode = BRIEF then
return "free";
else
return "free(" & Addr (Item.Addr) & "), " & Size (Item.Size);
end if;
when MAT.Events.MSG_BEGIN =>
return "begin";
when MAT.Events.MSG_END =>
return "end";
when MAT.Events.MSG_LIBRARY =>
return "library";
end case;
end Event;
function Event_Malloc (Item : in MAT.Events.Target_Event_Type;
Related : in MAT.Events.Tools.Target_Event_Vector;
Start_Time : in MAT.Types.Target_Tick_Ref) return String is
Free_Event : MAT.Events.Target_Event_Type;
begin
Free_Event := MAT.Events.Tools.Find (Related, MAT.Events.MSG_FREE);
return Size (Item.Size) & " bytes allocated after " & Duration (Item.Time - Start_Time)
& ", freed " & Duration (Free_Event.Time - Item.Time)
& " after by event" & MAT.Events.Event_Id_Type'Image (Free_Event.Id)
;
exception
when MAT.Events.Tools.Not_Found =>
return Size (Item.Size) & " bytes allocated (never freed)";
end Event_Malloc;
function Event_Free (Item : in MAT.Events.Target_Event_Type;
Related : in MAT.Events.Tools.Target_Event_Vector;
Start_Time : in MAT.Types.Target_Tick_Ref) return String is
Alloc_Event : MAT.Events.Target_Event_Type;
begin
Alloc_Event := MAT.Events.Tools.Find (Related, MAT.Events.MSG_MALLOC);
return Size (Alloc_Event.Size) & " bytes freed after " & Duration (Item.Time - Start_Time)
& ", alloc'ed for " & Duration (Item.Time - Alloc_Event.Time)
& " by event" & MAT.Events.Event_Id_Type'Image (Alloc_Event.Id);
exception
when MAT.Events.Tools.Not_Found =>
return Size (Item.Size) & " bytes freed";
end Event_Free;
-- ------------------------------
-- Format a short description of the event.
-- ------------------------------
function Event (Item : in MAT.Events.Target_Event_Type;
Related : in MAT.Events.Tools.Target_Event_Vector;
Start_Time : in MAT.Types.Target_Tick_Ref) return String is
begin
case Item.Index is
when MAT.Events.MSG_MALLOC =>
return Event_Malloc (Item, Related, Start_Time);
when MAT.Events.MSG_REALLOC =>
return Size (Item.Size) & " bytes reallocated";
when MAT.Events.MSG_FREE =>
return Event_Free (Item, Related, Start_Time);
when MAT.Events.MSG_BEGIN =>
return "Begin event";
when MAT.Events.MSG_END =>
return "End event";
when MAT.Events.MSG_LIBRARY =>
return "Library information event";
end case;
end Event;
end MAT.Formats;
|
-----------------------------------------------------------------------
-- mat-formats - Format various types for the console or GUI interface
-- Copyright (C) 2015 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Strings;
package body MAT.Formats is
use type MAT.Types.Target_Tick_Ref;
Hex_Prefix : Boolean := True;
Conversion : constant String (1 .. 10) := "0123456789";
function Location (File : in Ada.Strings.Unbounded.Unbounded_String) return String;
function Event_Malloc (Item : in MAT.Events.Target_Event_Type;
Related : in MAT.Events.Tools.Target_Event_Vector;
Start_Time : in MAT.Types.Target_Tick_Ref) return String;
function Event_Free (Item : in MAT.Events.Target_Event_Type;
Related : in MAT.Events.Tools.Target_Event_Vector;
Start_Time : in MAT.Types.Target_Tick_Ref) return String;
-- ------------------------------
-- Format the PID into a string.
-- ------------------------------
function Pid (Value : in MAT.Types.Target_Process_Ref) return String is
begin
return Util.Strings.Image (Natural (Value));
end Pid;
-- ------------------------------
-- Format the address into a string.
-- ------------------------------
function Addr (Value : in MAT.Types.Target_Addr) return String is
Hex : constant String := MAT.Types.Hex_Image (Value);
begin
if Hex_Prefix then
return "0x" & Hex;
else
return Hex;
end if;
end Addr;
-- ------------------------------
-- Format the size into a string.
-- ------------------------------
function Size (Value : in MAT.Types.Target_Size) return String is
Result : constant String := MAT.Types.Target_Size'Image (Value);
begin
if Result (Result'First) = ' ' then
return Result (Result'First + 1 .. Result'Last);
else
return Result;
end if;
end Size;
-- ------------------------------
-- Format the memory growth size into a string.
-- ------------------------------
function Size (Alloced : in MAT.Types.Target_Size;
Freed : in MAT.Types.Target_Size) return String is
use type MAT.Types.Target_Size;
begin
if Alloced > Freed then
return Size (Alloced - Freed);
elsif Alloced < Freed then
return "-" & Size (Freed - Alloced);
else
return "=" & Size (Alloced);
end if;
end Size;
-- ------------------------------
-- Format the time relative to the start time.
-- ------------------------------
function Time (Value : in MAT.Types.Target_Tick_Ref;
Start : in MAT.Types.Target_Tick_Ref) return String is
T : constant MAT.Types.Target_Tick_Ref := Value - Start;
Sec : constant MAT.Types.Target_Tick_Ref := T / 1_000_000;
Usec : constant MAT.Types.Target_Tick_Ref := T mod 1_000_000;
Msec : Natural := Natural (Usec / 1_000);
Frac : String (1 .. 5);
begin
Frac (5) := 's';
Frac (4) := Conversion (Msec mod 10 + 1);
Msec := Msec / 10;
Frac (3) := Conversion (Msec mod 10 + 1);
Msec := Msec / 10;
Frac (2) := Conversion (Msec mod 10 + 1);
Frac (1) := '.';
return MAT.Types.Target_Tick_Ref'Image (Sec) & Frac;
end Time;
-- ------------------------------
-- Format the duration in seconds, milliseconds or microseconds.
-- ------------------------------
function Duration (Value : in MAT.Types.Target_Tick_Ref) return String is
Sec : constant MAT.Types.Target_Tick_Ref := Value / 1_000_000;
Usec : constant MAT.Types.Target_Tick_Ref := Value mod 1_000_000;
Msec : constant Natural := Natural (Usec / 1_000);
Val : Natural;
Frac : String (1 .. 5);
begin
if Sec = 0 and Msec = 0 then
return Util.Strings.Image (Integer (Usec)) & "us";
elsif Sec = 0 then
Val := Natural (Usec mod 1_000);
Frac (5) := 's';
Frac (4) := 'm';
Frac (3) := Conversion (Val mod 10 + 1);
Val := Val / 10;
Frac (3) := Conversion (Val mod 10 + 1);
Val := Val / 10;
Frac (2) := Conversion (Val mod 10 + 1);
Frac (1) := '.';
return Util.Strings.Image (Integer (Msec)) & Frac;
else
Val := Msec;
Frac (4) := 's';
Frac (3) := Conversion (Val mod 10 + 1);
Val := Val / 10;
Frac (3) := Conversion (Val mod 10 + 1);
Val := Val / 10;
Frac (2) := Conversion (Val mod 10 + 1);
Frac (1) := '.';
return Util.Strings.Image (Integer (Sec)) & Frac (1 .. 4);
end if;
end Duration;
function Location (File : in Ada.Strings.Unbounded.Unbounded_String) return String is
Pos : constant Natural := Ada.Strings.Unbounded.Index (File, "/", Ada.Strings.Backward);
Len : constant Natural := Ada.Strings.Unbounded.Length (File);
begin
if Pos /= 0 then
return Ada.Strings.Unbounded.Slice (File, Pos + 1, Len);
else
return Ada.Strings.Unbounded.To_String (File);
end if;
end Location;
-- ------------------------------
-- Format a file, line, function information into a string.
-- ------------------------------
function Location (File : in Ada.Strings.Unbounded.Unbounded_String;
Line : in Natural;
Func : in Ada.Strings.Unbounded.Unbounded_String) return String is
begin
if Ada.Strings.Unbounded.Length (File) = 0 then
return Ada.Strings.Unbounded.To_String (Func);
elsif Line > 0 then
declare
Num : constant String := Natural'Image (Line);
begin
return Ada.Strings.Unbounded.To_String (Func) & " ("
& Location (File) & ":" & Num (Num'First + 1 .. Num'Last) & ")";
end;
else
return Ada.Strings.Unbounded.To_String (Func) & " (" & Location (File) & ")";
end if;
end Location;
-- ------------------------------
-- Format an event range description.
-- ------------------------------
function Event (First : in MAT.Events.Target_Event_Type;
Last : in MAT.Events.Target_Event_Type) return String is
use type MAT.Events.Event_Id_Type;
Id1 : constant String := MAT.Events.Event_Id_Type'Image (First.Id);
Id2 : constant String := MAT.Events.Event_Id_Type'Image (Last.Id);
begin
if First.Id = Last.Id then
return Id1 (Id1'First + 1 .. Id1'Last);
else
return Id1 (Id1'First + 1 .. Id1'Last) & ".." & Id2 (Id2'First + 1 .. Id2'Last);
end if;
end Event;
-- ------------------------------
-- Format a short description of the event.
-- ------------------------------
function Event (Item : in MAT.Events.Target_Event_Type;
Mode : in Format_Type := NORMAL) return String is
use type MAT.Types.Target_Addr;
begin
case Item.Index is
when MAT.Events.MSG_MALLOC =>
if Mode = BRIEF then
return "malloc";
else
return "malloc(" & Size (Item.Size) & ") = " & Addr (Item.Addr);
end if;
when MAT.Events.MSG_REALLOC =>
if Mode = BRIEF then
if Item.Old_Addr = 0 then
return "realloc";
else
return "realloc";
end if;
else
if Item.Old_Addr = 0 then
return "realloc(0," & Size (Item.Size) & ") = "
& Addr (Item.Addr);
else
return "realloc(" & Addr (Item.Old_Addr) & "," & Size (Item.Size) & ") = "
& Addr (Item.Addr);
end if;
end if;
when MAT.Events.MSG_FREE =>
if Mode = BRIEF then
return "free";
else
return "free(" & Addr (Item.Addr) & "), " & Size (Item.Size);
end if;
when MAT.Events.MSG_BEGIN =>
return "begin";
when MAT.Events.MSG_END =>
return "end";
when MAT.Events.MSG_LIBRARY =>
return "library";
end case;
end Event;
function Event_Malloc (Item : in MAT.Events.Target_Event_Type;
Related : in MAT.Events.Tools.Target_Event_Vector;
Start_Time : in MAT.Types.Target_Tick_Ref) return String is
Free_Event : MAT.Events.Target_Event_Type;
begin
Free_Event := MAT.Events.Tools.Find (Related, MAT.Events.MSG_FREE);
return Size (Item.Size) & " bytes allocated after " & Duration (Item.Time - Start_Time)
& ", freed " & Duration (Free_Event.Time - Item.Time)
& " after by event" & MAT.Events.Event_Id_Type'Image (Free_Event.Id)
;
exception
when MAT.Events.Tools.Not_Found =>
return Size (Item.Size) & " bytes allocated (never freed)";
end Event_Malloc;
function Event_Free (Item : in MAT.Events.Target_Event_Type;
Related : in MAT.Events.Tools.Target_Event_Vector;
Start_Time : in MAT.Types.Target_Tick_Ref) return String is
Alloc_Event : MAT.Events.Target_Event_Type;
begin
Alloc_Event := MAT.Events.Tools.Find (Related, MAT.Events.MSG_MALLOC);
return Size (Alloc_Event.Size) & " bytes freed after " & Duration (Item.Time - Start_Time)
& ", alloc'ed for " & Duration (Item.Time - Alloc_Event.Time)
& " by event" & MAT.Events.Event_Id_Type'Image (Alloc_Event.Id);
exception
when MAT.Events.Tools.Not_Found =>
return Size (Item.Size) & " bytes freed";
end Event_Free;
-- ------------------------------
-- Format a short description of the event.
-- ------------------------------
function Event (Item : in MAT.Events.Target_Event_Type;
Related : in MAT.Events.Tools.Target_Event_Vector;
Start_Time : in MAT.Types.Target_Tick_Ref) return String is
begin
case Item.Index is
when MAT.Events.MSG_MALLOC =>
return Event_Malloc (Item, Related, Start_Time);
when MAT.Events.MSG_REALLOC =>
return Size (Item.Size) & " bytes reallocated";
when MAT.Events.MSG_FREE =>
return Event_Free (Item, Related, Start_Time);
when MAT.Events.MSG_BEGIN =>
return "Begin event";
when MAT.Events.MSG_END =>
return "End event";
when MAT.Events.MSG_LIBRARY =>
return "Library information event";
end case;
end Event;
-- ------------------------------
-- Format a short description of the memory allocation slot.
-- ------------------------------
function Slot (Value : in MAT.Types.Target_Addr;
Item : in MAT.Memory.Allocation;
Start_Time : in MAT.Types.Target_Tick_Ref) return String is
begin
return Addr (Value) & " is " & Size (Item.Size)
& " bytes allocated after " & Duration (Item.Time - Start_Time)
& " by event" & MAT.Events.Event_Id_Type'Image (Item.Event);
end Slot;
end MAT.Formats;
|
Implement the Slot procedure to format a short memory slot description
|
Implement the Slot procedure to format a short memory slot description
|
Ada
|
apache-2.0
|
stcarrez/mat,stcarrez/mat,stcarrez/mat
|
2f55684da59bd80ed9371ee08bb9b051e7d1539f
|
src/wiki-plugins.ads
|
src/wiki-plugins.ads
|
-----------------------------------------------------------------------
-- wiki-plugins -- Wiki plugins
-- Copyright (C) 2016 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Wiki.Attributes;
with Wiki.Documents;
with Wiki.Filters;
-- == Plugins ==
-- The <b>Wiki.Plugins</b> package defines the plugin interface that is used by the wiki
-- engine to provide pluggable extensions in the Wiki.
--
package Wiki.Plugins is
pragma Preelaborate;
type Plugin_Context;
type Wiki_Plugin is limited interface;
type Wiki_Plugin_Access is access all Wiki_Plugin'Class;
type Plugin_Factory is limited interface;
type Plugin_Factory_Access is access all Plugin_Factory'Class;
-- Find a plugin knowing its name.
function Find (Factory : in Plugin_Factory;
Name : in String) return Wiki_Plugin_Access is abstract;
type Plugin_Context is limited record
Filters : Wiki.Filters.Filter_Chain;
Factory : Plugin_Factory_Access;
Variables : Wiki.Attributes.Attribute_List;
Syntax : Wiki.Wiki_Syntax;
end record;
-- Expand the plugin configured with the parameters for the document.
procedure Expand (Plugin : in out Wiki_Plugin;
Document : in out Wiki.Documents.Document;
Params : in out Wiki.Attributes.Attribute_List;
Context : in Plugin_Context) is abstract;
end Wiki.Plugins;
|
-----------------------------------------------------------------------
-- wiki-plugins -- Wiki plugins
-- Copyright (C) 2016 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Wiki.Attributes;
with Wiki.Documents;
with Wiki.Filters;
-- == Plugins ==
-- The <b>Wiki.Plugins</b> package defines the plugin interface that is used by the wiki
-- engine to provide pluggable extensions in the Wiki.
--
package Wiki.Plugins is
pragma Preelaborate;
type Plugin_Context;
type Wiki_Plugin is limited interface;
type Wiki_Plugin_Access is access all Wiki_Plugin'Class;
type Plugin_Factory is limited interface;
type Plugin_Factory_Access is access all Plugin_Factory'Class;
-- Find a plugin knowing its name.
function Find (Factory : in Plugin_Factory;
Name : in String) return Wiki_Plugin_Access is abstract;
type Plugin_Context is limited record
Previous : access Plugin_Context;
Filters : Wiki.Filters.Filter_Chain;
Factory : Plugin_Factory_Access;
Variables : Wiki.Attributes.Attribute_List;
Syntax : Wiki.Wiki_Syntax;
Is_Hidden : Boolean := False;
end record;
-- Expand the plugin configured with the parameters for the document.
procedure Expand (Plugin : in out Wiki_Plugin;
Document : in out Wiki.Documents.Document;
Params : in out Wiki.Attributes.Attribute_List;
Context : in Plugin_Context) is abstract;
end Wiki.Plugins;
|
Add Is_Hidden boolean property and link to the previous wiki context
|
Add Is_Hidden boolean property and link to the previous wiki context
|
Ada
|
apache-2.0
|
stcarrez/ada-wiki,stcarrez/ada-wiki
|
1d06e41976952b4e724130e8cb1b4ce4078cd54c
|
awa/plugins/awa-jobs/src/awa-jobs-modules.adb
|
awa/plugins/awa-jobs/src/awa-jobs-modules.adb
|
-----------------------------------------------------------------------
-- awa-jobs-modules -- Job module
-- Copyright (C) 2012, 2013, 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.Tags;
with Util.Log.Loggers;
with AWA.Applications;
with AWA.Modules.Get;
with AWA.Modules.Beans;
with AWA.Jobs.Beans;
package body AWA.Jobs.Modules is
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("AWA.Jobs.Modules");
package Register_Beans is new AWA.Modules.Beans (Module => Job_Module,
Module_Access => Job_Module_Access);
-- ------------------------------
-- Initialize the job module.
-- ------------------------------
overriding
procedure Initialize (Plugin : in out Job_Module;
App : in AWA.Modules.Application_Access;
Props : in ASF.Applications.Config) is
begin
Log.Info ("Initializing the jobs module");
Register_Beans.Register (Plugin => Plugin,
Name => "AWA.Jobs.Beans.Process_Bean",
Handler => AWA.Jobs.Beans.Create_Process_Bean'Access);
AWA.Modules.Module (Plugin).Initialize (App, Props);
end Initialize;
-- ------------------------------
-- Get the job module instance associated with the current application.
-- ------------------------------
function Get_Job_Module return Job_Module_Access is
function Get is new AWA.Modules.Get (Job_Module, Job_Module_Access, NAME);
begin
return Get;
end Get_Job_Module;
-- ------------------------------
-- Registers the job work procedure represented by `Work` under the name `Name`.
-- ------------------------------
procedure Register (Plugin : in out Job_Module;
Definition : in AWA.Jobs.Services.Job_Factory_Access) is
Name : constant String := Ada.Tags.Expanded_Name (Definition.all'Tag);
Ename : constant String := Ada.Tags.External_Tag (Definition.all'Tag);
begin
Log.Info ("Register job {0} - {1}", Name, Ename);
Plugin.Factory.Include (Name, Definition);
end Register;
-- ------------------------------
-- Find the job work factory registered under the name `Name`.
-- Returns null if there is no such factory.
-- ------------------------------
function Find_Factory (Plugin : in Job_Module;
Name : in String) return AWA.Jobs.Services.Job_Factory_Access is
Pos : constant Job_Factory_Map.Cursor := Plugin.Factory.Find (Name);
begin
if Job_Factory_Map.Has_Element (Pos) then
return Job_Factory_Map.Element (Pos);
else
return null;
end if;
end Find_Factory;
end AWA.Jobs.Modules;
|
-----------------------------------------------------------------------
-- awa-jobs-modules -- Job module
-- Copyright (C) 2012, 2013, 2020, 2021 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Tags;
with Util.Log.Loggers;
with AWA.Modules.Get;
with AWA.Modules.Beans;
with AWA.Jobs.Beans;
package body AWA.Jobs.Modules is
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("AWA.Jobs.Modules");
package Register_Beans is new AWA.Modules.Beans (Module => Job_Module,
Module_Access => Job_Module_Access);
-- ------------------------------
-- Initialize the job module.
-- ------------------------------
overriding
procedure Initialize (Plugin : in out Job_Module;
App : in AWA.Modules.Application_Access;
Props : in ASF.Applications.Config) is
begin
Log.Info ("Initializing the jobs module");
Register_Beans.Register (Plugin => Plugin,
Name => "AWA.Jobs.Beans.Process_Bean",
Handler => AWA.Jobs.Beans.Create_Process_Bean'Access);
AWA.Modules.Module (Plugin).Initialize (App, Props);
end Initialize;
-- ------------------------------
-- Get the job module instance associated with the current application.
-- ------------------------------
function Get_Job_Module return Job_Module_Access is
function Get is new AWA.Modules.Get (Job_Module, Job_Module_Access, NAME);
begin
return Get;
end Get_Job_Module;
-- ------------------------------
-- Registers the job work procedure represented by `Work` under the name `Name`.
-- ------------------------------
procedure Register (Plugin : in out Job_Module;
Definition : in AWA.Jobs.Services.Job_Factory_Access) is
Name : constant String := Ada.Tags.Expanded_Name (Definition.all'Tag);
Ename : constant String := Ada.Tags.External_Tag (Definition.all'Tag);
begin
Log.Info ("Register job {0} - {1}", Name, Ename);
Plugin.Factory.Include (Name, Definition);
end Register;
-- ------------------------------
-- Find the job work factory registered under the name `Name`.
-- Returns null if there is no such factory.
-- ------------------------------
function Find_Factory (Plugin : in Job_Module;
Name : in String) return AWA.Jobs.Services.Job_Factory_Access is
Pos : constant Job_Factory_Map.Cursor := Plugin.Factory.Find (Name);
begin
if Job_Factory_Map.Has_Element (Pos) then
return Job_Factory_Map.Element (Pos);
else
return null;
end if;
end Find_Factory;
end AWA.Jobs.Modules;
|
Fix compilation warning
|
Fix compilation warning
|
Ada
|
apache-2.0
|
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
|
1c583d65cb0a555f08a7e97508e428c44304a854
|
src/gen-commands.ads
|
src/gen-commands.ads
|
-----------------------------------------------------------------------
-- gen-commands -- Commands for dynamo
-- Copyright (C) 2011, 2012, 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Commands.Drivers;
with Gen.Generator;
package Gen.Commands is
package Drivers is
new Util.Commands.Drivers (Context_Type => Gen.Generator.Handler,
Driver_Name => "gen-commands");
subtype Command is Drivers.Command_Type;
subtype Command_Access is Drivers.Command_Access;
subtype Argument_List is Util.Commands.Argument_List;
Driver : Drivers.Driver_Type;
-- Print dynamo usage
procedure Usage;
-- Print dynamo short usage.
procedure Short_Help_Usage;
end Gen.Commands;
|
-----------------------------------------------------------------------
-- gen-commands -- Commands for dynamo
-- Copyright (C) 2011, 2012, 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Commands.Drivers;
with Gen.Generator;
package Gen.Commands is
package Drivers is
new Util.Commands.Drivers (Context_Type => Gen.Generator.Handler,
Driver_Name => "gen-commands");
subtype Command is Drivers.Command_Type;
subtype Command_Access is Drivers.Command_Access;
subtype Argument_List is Util.Commands.Argument_List;
Driver : Drivers.Driver_Type;
-- Print dynamo short usage.
procedure Short_Help_Usage;
end Gen.Commands;
|
Remove the declaration of Usage procedure
|
Remove the declaration of Usage procedure
|
Ada
|
apache-2.0
|
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.