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
25e835187a9904f6451e24cb91ef83018c21606a
asfunit/asf-tests.adb
asfunit/asf-tests.adb
----------------------------------------------------------------------- -- ASF tests - ASF Tests Framework -- Copyright (C) 2011, 2012, 2013 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with GNAT.Regpat; with Ada.Strings.Unbounded; with Util.Files; with ASF.Streams; with ASF.Servlets.Faces; with ASF.Servlets.Files; with ASF.Servlets.Ajax; with ASF.Servlets.Measures; with ASF.Responses; with ASF.Responses.Tools; with ASF.Filters.Dump; package body ASF.Tests is use Ada.Strings.Unbounded; use Util.Tests; CONTEXT_PATH : constant String := "/asfunit"; Server : access ASF.Server.Container; App : ASF.Applications.Main.Application_Access := null; Faces : aliased ASF.Servlets.Faces.Faces_Servlet; Files : aliased ASF.Servlets.Files.File_Servlet; Ajax : aliased ASF.Servlets.Ajax.Ajax_Servlet; Dump : aliased ASF.Filters.Dump.Dump_Filter; Measures : aliased ASF.Servlets.Measures.Measure_Servlet; -- Save the response headers and content in a file procedure Save_Response (Name : in String; Response : in out ASF.Responses.Mockup.Response); -- ------------------------------ -- Initialize the awa test framework mockup. -- ------------------------------ procedure Initialize (Props : in Util.Properties.Manager; Application : in ASF.Applications.Main.Application_Access := null; Factory : in out ASF.Applications.Main.Application_Factory'Class) is use type ASF.Applications.Main.Application_Access; C : ASF.Applications.Config; begin if Application /= null then App := Application; else App := new ASF.Applications.Main.Application; end if; Server := new ASF.Server.Container; Server.Register_Application (CONTEXT_PATH, App.all'Access); C.Copy (Props); App.Initialize (C, Factory); App.Register ("layoutMsg", "layout"); App.Set_Global ("contextPath", CONTEXT_PATH); -- Register the servlets and filters App.Add_Servlet (Name => "faces", Server => Faces'Access); App.Add_Servlet (Name => "files", Server => Files'Access); App.Add_Servlet (Name => "ajax", Server => Ajax'Access); App.Add_Servlet (Name => "measures", Server => Measures'Access); App.Add_Filter (Name => "dump", Filter => Dump'Access); App.Add_Filter (Name => "measures", Filter => Measures'Access); -- Define servlet mappings App.Add_Mapping (Name => "faces", Pattern => "*.html"); App.Add_Mapping (Name => "files", Pattern => "*.css"); App.Add_Mapping (Name => "files", Pattern => "*.js"); App.Add_Mapping (Name => "files", Pattern => "*.properties"); App.Add_Mapping (Name => "files", Pattern => "*.xhtml"); App.Add_Mapping (Name => "ajax", Pattern => "/ajax/*"); App.Add_Mapping (Name => "measures", Pattern => "stats.xml"); App.Add_Filter_Mapping (Name => "measures", Pattern => "*"); App.Add_Filter_Mapping (Name => "measures", Pattern => "/ajax/*"); App.Add_Filter_Mapping (Name => "measures", Pattern => "*.html"); App.Add_Filter_Mapping (Name => "measures", Pattern => "*.xhtml"); App.Add_Filter_Mapping (Name => "dump", Pattern => "*.html"); App.Add_Filter_Mapping (Name => "dump", Pattern => "*.css"); App.Add_Filter_Mapping (Name => "dump", Pattern => "/ajax/*"); end Initialize; -- ------------------------------ -- Get the server -- ------------------------------ function Get_Server return access ASF.Server.Container is begin return Server; end Get_Server; -- ------------------------------ -- Get the test application. -- ------------------------------ function Get_Application return ASF.Applications.Main.Application_Access is begin return App; end Get_Application; -- ------------------------------ -- Save the response headers and content in a file -- ------------------------------ procedure Save_Response (Name : in String; Response : in out ASF.Responses.Mockup.Response) is use ASF.Responses; Info : constant String := Tools.To_String (Reply => Response, Html => False, Print_Headers => True); Result_Path : constant String := Util.Tests.Get_Test_Path ("regtests/result"); Content : Unbounded_String; Stream : ASF.Streams.Print_Stream := Response.Get_Output_Stream; begin Response.Read_Content (Content); Stream.Write (Content); Insert (Content, 1, Info); Util.Files.Write_File (Result_Path & "/" & Name, Content); end Save_Response; -- ------------------------------ -- Simulate a raw request. The URI and method must have been set on the Request object. -- ------------------------------ procedure Do_Req (Request : in out ASF.Requests.Mockup.Request; Response : in out ASF.Responses.Mockup.Response) is begin -- For the purpose of writing tests, clear the buffer before invoking the service. Response.Clear; Server.Service (Request => Request, Response => Response); end Do_Req; -- ------------------------------ -- Simulate a GET request on the given URI with the request parameters. -- Get the result in the response object. -- ------------------------------ procedure Do_Get (Request : in out ASF.Requests.Mockup.Request; Response : in out ASF.Responses.Mockup.Response; URI : in String; Save : in String := "") is begin Request.Set_Method (Method => "GET"); Request.Set_Request_URI (URI => CONTEXT_PATH & URI); Request.Set_Protocol (Protocol => "HTTP/1.1"); Do_Req (Request, Response); if Save'Length > 0 then Save_Response (Save, Response); end if; end Do_Get; -- ------------------------------ -- Simulate a POST request on the given URI with the request parameters. -- Get the result in the response object. -- ------------------------------ procedure Do_Post (Request : in out ASF.Requests.Mockup.Request; Response : in out ASF.Responses.Mockup.Response; URI : in String; Save : in String := "") is begin Request.Set_Method (Method => "POST"); Request.Set_Request_URI (URI => CONTEXT_PATH & URI); Request.Set_Protocol (Protocol => "HTTP/1.1"); Do_Req (Request, Response); if Save'Length > 0 then Save_Response (Save, Response); end if; end Do_Post; -- ------------------------------ -- Check that the response body contains the string -- ------------------------------ procedure Assert_Contains (T : in Util.Tests.Test'Class; Value : in String; Reply : in out ASF.Responses.Mockup.Response; Message : in String := "Test failed"; Source : String := GNAT.Source_Info.File; Line : Natural := GNAT.Source_Info.Line) is Stream : ASF.Streams.Print_Stream := Reply.Get_Output_Stream; Content : Unbounded_String; begin Reply.Read_Content (Content); Stream.Write (Content); Assert_Equals (T, ASF.Responses.SC_OK, Reply.Get_Status, "Invalid response", Source, Line); T.Assert (Condition => Index (Content, Value) > 0, Message => Message & ": value '" & Value & "' not found", Source => Source, Line => Line); end Assert_Contains; -- ------------------------------ -- Check that the response body matches the regular expression -- ------------------------------ procedure Assert_Matches (T : in Util.Tests.Test'Class; Pattern : in String; Reply : in out ASF.Responses.Mockup.Response; Message : in String := "Test failed"; Status : in Natural := ASF.Responses.SC_OK; Source : String := GNAT.Source_Info.File; Line : Natural := GNAT.Source_Info.Line) is use GNAT.Regpat; Stream : ASF.Streams.Print_Stream := Reply.Get_Output_Stream; Content : Unbounded_String; Regexp : constant Pattern_Matcher := Compile (Expression => Pattern, Flags => Multiple_Lines); begin Reply.Read_Content (Content); Stream.Write (Content); Assert_Equals (T, Status, Reply.Get_Status, "Invalid response", Source, Line); T.Assert (Condition => Match (Regexp, To_String (Content)), Message => Message & ": does not match '" & Pattern & "'", Source => Source, Line => Line); end Assert_Matches; -- ------------------------------ -- Check that the response body is a redirect to the given URI. -- ------------------------------ procedure Assert_Redirect (T : in Util.Tests.Test'Class; Value : in String; Reply : in out ASF.Responses.Mockup.Response; Message : in String := "Test failed"; Source : String := GNAT.Source_Info.File; Line : Natural := GNAT.Source_Info.Line) is begin Assert_Equals (T, ASF.Responses.SC_MOVED_TEMPORARILY, Reply.Get_Status, "Invalid response", Source, Line); Util.Tests.Assert_Equals (T, Value, Reply.Get_Header ("Location"), Message & ": missing Location", Source, Line); end Assert_Redirect; end ASF.Tests;
----------------------------------------------------------------------- -- ASF tests - ASF Tests Framework -- Copyright (C) 2011, 2012, 2013, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with GNAT.Regpat; with Ada.Strings.Unbounded; with Ada.Unchecked_Deallocation; with Util.Files; with ASF.Streams; with ASF.Servlets.Faces; with ASF.Servlets.Files; with ASF.Servlets.Ajax; with ASF.Servlets.Measures; with ASF.Responses; with ASF.Responses.Tools; with ASF.Filters.Dump; with ASF.Contexts.Faces; with EL.Variables.Default; package body ASF.Tests is use Ada.Strings.Unbounded; use Util.Tests; CONTEXT_PATH : constant String := "/asfunit"; Server : access ASF.Server.Container; App : ASF.Applications.Main.Application_Access := null; Faces : aliased ASF.Servlets.Faces.Faces_Servlet; Files : aliased ASF.Servlets.Files.File_Servlet; Ajax : aliased ASF.Servlets.Ajax.Ajax_Servlet; Dump : aliased ASF.Filters.Dump.Dump_Filter; Measures : aliased ASF.Servlets.Measures.Measure_Servlet; -- Save the response headers and content in a file procedure Save_Response (Name : in String; Response : in out ASF.Responses.Mockup.Response); -- ------------------------------ -- Initialize the awa test framework mockup. -- ------------------------------ procedure Initialize (Props : in Util.Properties.Manager; Application : in ASF.Applications.Main.Application_Access := null; Factory : in out ASF.Applications.Main.Application_Factory'Class) is use type ASF.Applications.Main.Application_Access; C : ASF.Applications.Config; begin if Application /= null then App := Application; else App := new ASF.Applications.Main.Application; end if; Server := new ASF.Server.Container; Server.Register_Application (CONTEXT_PATH, App.all'Access); C.Copy (Props); App.Initialize (C, Factory); App.Register ("layoutMsg", "layout"); App.Set_Global ("contextPath", CONTEXT_PATH); -- Register the servlets and filters App.Add_Servlet (Name => "faces", Server => Faces'Access); App.Add_Servlet (Name => "files", Server => Files'Access); App.Add_Servlet (Name => "ajax", Server => Ajax'Access); App.Add_Servlet (Name => "measures", Server => Measures'Access); App.Add_Filter (Name => "dump", Filter => Dump'Access); App.Add_Filter (Name => "measures", Filter => ASF.Filters.Filter'Class (Measures)'Access); -- Define servlet mappings App.Add_Mapping (Name => "faces", Pattern => "*.html"); App.Add_Mapping (Name => "files", Pattern => "*.css"); App.Add_Mapping (Name => "files", Pattern => "*.js"); App.Add_Mapping (Name => "files", Pattern => "*.properties"); App.Add_Mapping (Name => "files", Pattern => "*.xhtml"); App.Add_Mapping (Name => "ajax", Pattern => "/ajax/*"); App.Add_Mapping (Name => "measures", Pattern => "stats.xml"); App.Add_Filter_Mapping (Name => "measures", Pattern => "*"); App.Add_Filter_Mapping (Name => "measures", Pattern => "/ajax/*"); App.Add_Filter_Mapping (Name => "measures", Pattern => "*.html"); App.Add_Filter_Mapping (Name => "measures", Pattern => "*.xhtml"); App.Add_Filter_Mapping (Name => "dump", Pattern => "*.html"); App.Add_Filter_Mapping (Name => "dump", Pattern => "*.css"); App.Add_Filter_Mapping (Name => "dump", Pattern => "/ajax/*"); end Initialize; -- ------------------------------ -- Get the server -- ------------------------------ function Get_Server return access ASF.Server.Container is begin return Server; end Get_Server; -- ------------------------------ -- Get the test application. -- ------------------------------ function Get_Application return ASF.Applications.Main.Application_Access is begin return App; end Get_Application; -- ------------------------------ -- Save the response headers and content in a file -- ------------------------------ procedure Save_Response (Name : in String; Response : in out ASF.Responses.Mockup.Response) is use ASF.Responses; Info : constant String := Tools.To_String (Reply => Response, Html => False, Print_Headers => True); Result_Path : constant String := Util.Tests.Get_Test_Path ("regtests/result"); Content : Unbounded_String; Stream : ASF.Streams.Print_Stream := Response.Get_Output_Stream; begin Response.Read_Content (Content); Stream.Write (Content); Insert (Content, 1, Info); Util.Files.Write_File (Result_Path & "/" & Name, Content); end Save_Response; -- ------------------------------ -- Simulate a raw request. The URI and method must have been set on the Request object. -- ------------------------------ procedure Do_Req (Request : in out ASF.Requests.Mockup.Request; Response : in out ASF.Responses.Mockup.Response) is begin -- For the purpose of writing tests, clear the buffer before invoking the service. Response.Clear; Server.Service (Request => Request, Response => Response); end Do_Req; -- ------------------------------ -- Simulate a GET request on the given URI with the request parameters. -- Get the result in the response object. -- ------------------------------ procedure Do_Get (Request : in out ASF.Requests.Mockup.Request; Response : in out ASF.Responses.Mockup.Response; URI : in String; Save : in String := "") is begin Request.Set_Method (Method => "GET"); Request.Set_Request_URI (URI => CONTEXT_PATH & URI); Request.Set_Protocol (Protocol => "HTTP/1.1"); Do_Req (Request, Response); if Save'Length > 0 then Save_Response (Save, Response); end if; end Do_Get; -- ------------------------------ -- Simulate a POST request on the given URI with the request parameters. -- Get the result in the response object. -- ------------------------------ procedure Do_Post (Request : in out ASF.Requests.Mockup.Request; Response : in out ASF.Responses.Mockup.Response; URI : in String; Save : in String := "") is begin Request.Set_Method (Method => "POST"); Request.Set_Request_URI (URI => CONTEXT_PATH & URI); Request.Set_Protocol (Protocol => "HTTP/1.1"); Do_Req (Request, Response); if Save'Length > 0 then Save_Response (Save, Response); end if; end Do_Post; -- ------------------------------ -- Check that the response body contains the string -- ------------------------------ procedure Assert_Contains (T : in Util.Tests.Test'Class; Value : in String; Reply : in out ASF.Responses.Mockup.Response; Message : in String := "Test failed"; Source : String := GNAT.Source_Info.File; Line : Natural := GNAT.Source_Info.Line) is Stream : ASF.Streams.Print_Stream := Reply.Get_Output_Stream; Content : Unbounded_String; begin Reply.Read_Content (Content); Stream.Write (Content); Assert_Equals (T, ASF.Responses.SC_OK, Reply.Get_Status, "Invalid response", Source, Line); T.Assert (Condition => Index (Content, Value) > 0, Message => Message & ": value '" & Value & "' not found", Source => Source, Line => Line); end Assert_Contains; -- ------------------------------ -- Check that the response body matches the regular expression -- ------------------------------ procedure Assert_Matches (T : in Util.Tests.Test'Class; Pattern : in String; Reply : in out ASF.Responses.Mockup.Response; Message : in String := "Test failed"; Status : in Natural := ASF.Responses.SC_OK; Source : String := GNAT.Source_Info.File; Line : Natural := GNAT.Source_Info.Line) is use GNAT.Regpat; Stream : ASF.Streams.Print_Stream := Reply.Get_Output_Stream; Content : Unbounded_String; Regexp : constant Pattern_Matcher := Compile (Expression => Pattern, Flags => Multiple_Lines); begin Reply.Read_Content (Content); Stream.Write (Content); Assert_Equals (T, Status, Reply.Get_Status, "Invalid response", Source, Line); T.Assert (Condition => Match (Regexp, To_String (Content)), Message => Message & ": does not match '" & Pattern & "'", Source => Source, Line => Line); end Assert_Matches; -- ------------------------------ -- Check that the response body is a redirect to the given URI. -- ------------------------------ procedure Assert_Redirect (T : in Util.Tests.Test'Class; Value : in String; Reply : in out ASF.Responses.Mockup.Response; Message : in String := "Test failed"; Source : String := GNAT.Source_Info.File; Line : Natural := GNAT.Source_Info.Line) is begin Assert_Equals (T, ASF.Responses.SC_MOVED_TEMPORARILY, Reply.Get_Status, "Invalid response", Source, Line); Util.Tests.Assert_Equals (T, Value, Reply.Get_Header ("Location"), Message & ": missing Location", Source, Line); end Assert_Redirect; -- ------------------------------ -- Cleanup the test instance. -- ------------------------------ overriding procedure Tear_Down (T : in out EL_Test) is procedure Free is new Ada.Unchecked_Deallocation (EL.Contexts.Default.Default_Context'Class, EL.Contexts.Default.Default_Context_Access); procedure Free is new Ada.Unchecked_Deallocation (EL.Variables.Variable_Mapper'Class, EL.Variables.Variable_Mapper_Access); procedure Free is new Ada.Unchecked_Deallocation (EL.Contexts.Default.Default_ELResolver'Class, EL.Contexts.Default.Default_ELResolver_Access); begin ASF.Contexts.Faces.Restore (null); Free (T.ELContext); Free (T.Variables); Free (T.Root_Resolver); end Tear_Down; -- ------------------------------ -- Setup the test instance. -- ------------------------------ overriding procedure Set_Up (T : in out EL_Test) is begin T.ELContext := new EL.Contexts.Default.Default_Context; T.Root_Resolver := new EL.Contexts.Default.Default_ELResolver; T.Variables := new EL.Variables.Default.Default_Variable_Mapper; T.ELContext.Set_Resolver (T.Root_Resolver.all'Access); T.ELContext.Set_Variable_Mapper (T.Variables.all'Access); end Set_Up; end ASF.Tests;
Implement the Set_Up and Tear_Down procedure for the EL_Test
Implement the Set_Up and Tear_Down procedure for the EL_Test
Ada
apache-2.0
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
85b75d2ced6ff8bb4eee639d26f5377472d5b595
src/wiki-nodes.adb
src/wiki-nodes.adb
----------------------------------------------------------------------- -- wiki-nodes -- Wiki Document Internal representation -- Copyright (C) 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Unchecked_Deallocation; package body Wiki.Nodes is -- ------------------------------ -- Append a node to the tag node. -- ------------------------------ procedure Append (Into : in Node_Type_Access; Node : in Node_Type_Access) is begin if Into.Children = null then Into.Children := new Node_List; Into.Children.Current := Into.Children.First'Access; end if; Append (Into.Children.all, Node); end Append; -- ------------------------------ -- Append a node to the node list. -- ------------------------------ procedure Append (Into : in out Node_List; Node : in Node_Type_Access) is Block : Node_List_Block_Access := Into.Current; begin if Block.Last = Block.Max then Block.Next := new Node_List_Block (Into.Length); Block := Block.Next; Into.Current := Block; end if; Block.Last := Block.Last + 1; Block.List (Block.Last) := Node; Into.Length := Into.Length + 1; end Append; -- ------------------------------ -- Finalize the node list to release the allocated memory. -- ------------------------------ overriding procedure Finalize (List : in out Node_List) is procedure Free is new Ada.Unchecked_Deallocation (Node_List_Block, Node_List_Block_Access); procedure Free is new Ada.Unchecked_Deallocation (Node_Type, Node_Type_Access); procedure Free is new Ada.Unchecked_Deallocation (Node_List, Node_List_Access); procedure Release (List : in Node_List_Block_Access); procedure Free_Block (Block : in out Node_List_Block) is begin for I in 1 .. Block.Last loop if Block.List (I).Kind = N_TAG_START then Free (Block.List (I).Children); end if; Free (Block.List (I)); end loop; end Free_Block; procedure Release (List : in Node_List_Block_Access) is Next : Node_List_Block_Access := List; Block : Node_List_Block_Access; begin while Next /= null loop Block := Next; Free_Block (Block.all); Next := Next.Next; Free (Block); end loop; end Release; begin Release (List.First.Next); Free_Block (List.First); end Finalize; -- ------------------------------ -- Iterate over the nodes of the list and call the <tt>Process</tt> procedure with -- each node instance. -- ------------------------------ procedure Iterate (List : in Node_List_Access; Process : not null access procedure (Node : in Node_Type)) is Block : Node_List_Block_Access := List.First'Access; begin loop for I in 1 .. Block.Last loop Process (Block.List (I).all); end loop; Block := Block.Next; exit when Block = null; end loop; end Iterate; -- ------------------------------ -- Append a node to the node list. -- ------------------------------ procedure Append (Into : in out Node_List_Ref; Node : in Node_Type_Access) is begin if Into.Is_Null then Node_List_Refs.Ref (Into) := Node_List_Refs.Create; Into.Value.Current := Into.Value.First'Access; end if; Append (Into.Value.all, Node); end Append; -- ------------------------------ -- Iterate over the nodes of the list and call the <tt>Process</tt> procedure with -- each node instance. -- ------------------------------ procedure Iterate (List : in Node_List_Ref; Process : not null access procedure (Node : in Node_Type)) is begin if not List.Is_Null then Iterate (List.Value, Process); end if; end Iterate; -- ------------------------------ -- Returns True if the list reference is empty. -- ------------------------------ function Is_Empty (List : in Node_List_Ref) return Boolean is begin return List.Is_Null; end Is_Empty; end Wiki.Nodes;
----------------------------------------------------------------------- -- wiki-nodes -- Wiki Document Internal representation -- Copyright (C) 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Unchecked_Deallocation; package body Wiki.Nodes is -- ------------------------------ -- Append a node to the tag node. -- ------------------------------ procedure Append (Into : in Node_Type_Access; Node : in Node_Type_Access) is begin if Into.Children = null then Into.Children := new Node_List; Into.Children.Current := Into.Children.First'Access; end if; Append (Into.Children.all, Node); end Append; -- ------------------------------ -- Append a node to the node list. -- ------------------------------ procedure Append (Into : in out Node_List; Node : in Node_Type_Access) is Block : Node_List_Block_Access := Into.Current; begin if Block.Last = Block.Max then Block.Next := new Node_List_Block (Into.Length); Block := Block.Next; Into.Current := Block; end if; Block.Last := Block.Last + 1; Block.List (Block.Last) := Node; Into.Length := Into.Length + 1; end Append; -- ------------------------------ -- Finalize the node list to release the allocated memory. -- ------------------------------ overriding procedure Finalize (List : in out Node_List) is procedure Free is new Ada.Unchecked_Deallocation (Node_List_Block, Node_List_Block_Access); procedure Free is new Ada.Unchecked_Deallocation (Node_Type, Node_Type_Access); procedure Free is new Ada.Unchecked_Deallocation (Node_List, Node_List_Access); procedure Release (List : in Node_List_Block_Access); procedure Free_Block (Block : in out Node_List_Block) is begin for I in 1 .. Block.Last loop if Block.List (I).Kind = N_TAG_START then Free (Block.List (I).Children); end if; Free (Block.List (I)); end loop; end Free_Block; procedure Release (List : in Node_List_Block_Access) is Next : Node_List_Block_Access := List; Block : Node_List_Block_Access; begin while Next /= null loop Block := Next; Free_Block (Block.all); Next := Next.Next; Free (Block); end loop; end Release; begin Release (List.First.Next); Free_Block (List.First); end Finalize; -- ------------------------------ -- Iterate over the nodes of the list and call the <tt>Process</tt> procedure with -- each node instance. -- ------------------------------ procedure Iterate (List : in Node_List_Access; Process : not null access procedure (Node : in Node_Type)) is Block : Node_List_Block_Access := List.First'Access; begin loop for I in 1 .. Block.Last loop Process (Block.List (I).all); end loop; Block := Block.Next; exit when Block = null; end loop; end Iterate; -- ------------------------------ -- Append a node to the node list. -- ------------------------------ procedure Append (Into : in out Node_List_Ref; Node : in Node_Type_Access) is begin if Into.Is_Null then Node_List_Refs.Ref (Into) := Node_List_Refs.Create; Into.Value.Current := Into.Value.First'Access; end if; Append (Into.Value.all, Node); end Append; -- ------------------------------ -- Iterate over the nodes of the list and call the <tt>Process</tt> procedure with -- each node instance. -- ------------------------------ procedure Iterate (List : in Node_List_Ref; Process : not null access procedure (Node : in Node_Type)) is begin if not List.Is_Null then Iterate (List.Value, Process); end if; end Iterate; -- ------------------------------ -- Returns True if the list reference is empty. -- ------------------------------ function Is_Empty (List : in Node_List_Ref) return Boolean is begin return List.Is_Null; end Is_Empty; -- ------------------------------ -- Get the number of nodes in the list. -- ------------------------------ function Length (List : in Node_List_Ref) return Natural is begin if List.Is_Null then return 0; else return List.Value.Length; end if; end Length; end Wiki.Nodes;
Implement the Length procedure
Implement the Length procedure
Ada
apache-2.0
stcarrez/ada-wiki,stcarrez/ada-wiki
0765b64b4878f8de55665f73943fea87255565b6
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); 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 ("url-policy", FIELD_POLICY); Policy_Mapping.Add_Mapping ("url-policy/@id", FIELD_ID); Policy_Mapping.Add_Mapping ("url-policy/permission", FIELD_PERMISSION); Policy_Mapping.Add_Mapping ("url-policy/url-pattern", FIELD_URL_PATTERN); end Security.Policies.Urls;
----------------------------------------------------------------------- -- security-policies-urls -- URL security policy -- Copyright (C) 2010, 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR 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 ("url-policy", FIELD_POLICY); Policy_Mapping.Add_Mapping ("url-policy/@id", FIELD_ID); Policy_Mapping.Add_Mapping ("url-policy/permission", FIELD_PERMISSION); Policy_Mapping.Add_Mapping ("url-policy/url-pattern", FIELD_URL_PATTERN); end Security.Policies.Urls;
Check the permission using the context operation Has_Permission
Check the permission using the context operation Has_Permission
Ada
apache-2.0
Letractively/ada-security
d603fd0bb2519543a4f128dde437863325ef1c66
awa/plugins/awa-counters/src/awa-counters-definition.ads
awa/plugins/awa-counters/src/awa-counters-definition.ads
----------------------------------------------------------------------- -- awa-counters-definition -- Counter definition -- 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. ----------------------------------------------------------------------- -- The <tt>AWA.Counters.Definition</tt> package is instantiated for each counter definition. generic Table : ADO.Schemas.Class_Mapping_Access; Field : String; package AWA.Counters.Definition is Def_Name : aliased constant String := Field; package Def is new Counter_Arrays.Definition (Counter_Def '(Table, Def_Name'Access)); -- Get the counter definition index. function Index return Counter_Index_Type renames Def.Kind; end AWA.Counters.Definition;
----------------------------------------------------------------------- -- awa-counters-definition -- Counter definition -- 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. ----------------------------------------------------------------------- -- The <tt>AWA.Counters.Definition</tt> package is instantiated for each counter definition. generic Table : ADO.Schemas.Class_Mapping_Access; Field : String; package AWA.Counters.Definition is Def_Name : aliased constant String := Field; -- Get the counter definition index. function Index return Counter_Index_Type; private package Def is new Counter_Arrays.Definition (Counter_Def '(Table, Def_Name'Access)); -- Get the counter definition index. function Index return Counter_Index_Type renames Def.Kind; end AWA.Counters.Definition;
Move the Counter_Arrays.Definition package instantiation in the private part
Move the Counter_Arrays.Definition package instantiation in the private part
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
6c32be93977c1b08dd64284a76a2679b9b5aad76
tools/druss-commands-bboxes.adb
tools/druss-commands-bboxes.adb
----------------------------------------------------------------------- -- druss-commands-bboxes -- Commands to manage the bboxes -- Copyright (C) 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Text_IO; with Ada.Streams; with Ada.Strings.Unbounded; with Util.Log.Loggers; with Util.Properties; with Util.Strings; with Util.Strings.Sets; with Bbox.API; with Druss.Gateways; with Druss.Config; with UPnP.SSDP; package body Druss.Commands.Bboxes is use Ada.Strings.Unbounded; use Ada.Text_IO; use type Ada.Streams.Stream_Element_Offset; use type Ada.Streams.Stream_Element; -- The logger Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Druss.Commands.Bboxes"); procedure Discover (IP : in String) is Box : Bbox.API.Client_Type; Info : Util.Properties.Manager; begin Box.Set_Server (IP); Box.Get ("device", Info); if Info.Get ("device.modelname", "") /= "" then Log.Info ("Found a bbox at {0}", IP); end if; exception when E : others => null; end Discover; -- Add the bbox with the given IP address. procedure Add_Bbox (Command : in Command_Type; IP : in String; Context : in out Context_Type) is Box : Bbox.API.Client_Type; Info : Util.Properties.Manager; Gw : Druss.Gateways.Gateway_Ref := Druss.Gateways.Find_IP (Context.Gateways, IP); begin if not Gw.Is_Null then Log.Debug ("Bbox {0} is already registered", IP); return; end if; Box.Set_Server (IP); Box.Get ("device", Info); if Info.Get ("device.modelname", "") /= "" then Log.Info ("Found a new bbox at {0}", IP); Gw := Druss.Gateways.Gateway_Refs.Create; Gw.Value.IP := Ada.Strings.Unbounded.To_Unbounded_String (IP); Context.Gateways.Append (Gw); end if; exception when E : others => null; end Add_Bbox; procedure Discover (Command : in Command_Type; Context : in out Context_Type) is Retry : Natural := 0; Scanner : UPnP.SSDP.Scanner_Type; Itf_IPs : Util.Strings.Sets.Set; procedure Check_Bbox (IP : in String) is Box : Bbox.API.Client_Type; Info : Util.Properties.Manager; begin Box.Set_Server (IP); Box.Get ("device", Info); if Info.Get ("device.modelname", "") /= "" then Log.Info ("Found a bbox at {0}", IP); end if; exception when E : others => null; end Check_Bbox; procedure Process (URI : in String) is Pos : Natural; begin if URI'Length <= 7 or else URI (URI'First .. URI'First + 6) /= "http://" then return; end if; Pos := Util.Strings.Index (URI, ':', 6); if Pos > 0 then Command.Add_Bbox (URI (URI'First + 7 .. Pos - 1), Context); -- Check_Bbox (); end if; end Process; begin Log.Info ("Discovering gateways on the network"); Scanner.Initialize; Scanner.Find_IPv4_Addresses (Itf_IPs); while Retry < 5 loop Scanner.Send_Discovery ("urn:schemas-upnp-org:device:InternetGatewayDevice:1", Itf_IPs); Scanner.Discover ("urn:schemas-upnp-org:device:InternetGatewayDevice:1", Process'Access, 1.0); Retry := Retry + 1; end loop; Druss.Config.Save_Gateways (Context.Gateways); end Discover; -- ------------------------------ -- Set the password to be used by the Bbox API to connect to the box. -- ------------------------------ procedure Password (Command : in Command_Type; Args : in Util.Commands.Argument_List'Class; Context : in out Context_Type) is procedure Change_Password (Gateway : in out Druss.Gateways.Gateway_Type; Passwd : in String) is begin Gateway.Passwd := Ada.Strings.Unbounded.To_Unbounded_String (Passwd); end Change_Password; begin Druss.Commands.Gateway_Command (Command, Args, 2, Change_Password'Access, Context); Druss.Config.Save_Gateways (Context.Gateways); end Password; -- ------------------------------ -- Enable or disable the bbox management by Druss. -- ------------------------------ procedure Do_Enable (Command : in Command_Type; Args : in Util.Commands.Argument_List'Class; State : in Boolean; Context : in out Context_Type) is procedure Change_Enable (Gateway : in out Druss.Gateways.Gateway_Type; Command : in String) is begin Gateway.Enable := State; end Change_Enable; begin Druss.Commands.Gateway_Command (Command, Args, 1, Change_Enable'Access, Context); Druss.Config.Save_Gateways (Context.Gateways); end Do_Enable; -- ------------------------------ -- Execute the command with the arguments. The command name is passed with the command -- arguments. -- ------------------------------ overriding procedure Execute (Command : in Command_Type; Name : in String; Args : in Util.Commands.Argument_List'Class; Context : in out Context_Type) is begin if Args.Get_Count = 0 then Druss.Commands.Driver.Usage (Args); elsif Args.Get_Argument (1) = "discover" then Command.Discover (Context); elsif Args.Get_Argument (1) = "password" then Command.Password (Args, Context); elsif Args.Get_Argument (1) = "enable" then Command.Do_Enable (Args, True, Context); elsif Args.Get_Argument (1) = "disable" then Command.Do_Enable (Args, False, Context); else Put_Line ("Invalid sub-command: " & Args.Get_Argument (1)); Druss.Commands.Driver.Usage (Args); end if; end Execute; -- ------------------------------ -- Write the help associated with the command. -- ------------------------------ overriding procedure Help (Command : in Command_Type; Context : in out Context_Type) is begin Put_Line ("bbox: Manage and define the configuration to connect to the Bbox"); Put_Line ("Usage: bbox <operation>..."); New_Line; Put_Line (" Druss needs to know the list of Bboxes which are available on the network."); Put_Line (" It also need some credentials to connect to the Bbox using the Bbox API."); Put_Line (" The 'bbox' command allows to manage that list and configuration."); Put_Line (" Examples:"); Put_Line (" bbox discover Discover the bbox(es) connected to the LAN"); Put_Line (" bbox add IP Add a bbox knowing its IP address"); Put_Line (" bbox del IP Delete a bbox from the list"); Put_Line (" bbox enable IP Enable the bbox (it will be managed by Druss)"); Put_Line (" bbox disable IP Disable the bbox (it will not be managed)"); Put_Line (" bbox password <pass> [IP] Set the bbox API connection password"); end Help; end Druss.Commands.Bboxes;
----------------------------------------------------------------------- -- druss-commands-bboxes -- Commands to manage the bboxes -- Copyright (C) 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Streams; with Ada.Strings.Unbounded; with Util.Log.Loggers; with Util.Properties; with Util.Strings; with Util.Strings.Sets; with Bbox.API; with Druss.Gateways; with Druss.Config; with UPnP.SSDP; package body Druss.Commands.Bboxes is use Ada.Strings.Unbounded; use type Ada.Streams.Stream_Element_Offset; use type Ada.Streams.Stream_Element; -- The logger Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Druss.Commands.Bboxes"); -- ------------------------------ -- Add the bbox with the given IP address. -- ------------------------------ procedure Add_Bbox (Command : in Command_Type; IP : in String; Context : in out Context_Type) is pragma Unreferenced (Command); Box : Bbox.API.Client_Type; Info : Util.Properties.Manager; Gw : Druss.Gateways.Gateway_Ref := Druss.Gateways.Find_IP (Context.Gateways, IP); begin if not Gw.Is_Null then Log.Debug ("Bbox {0} is already registered", IP); return; end if; Box.Set_Server (IP); Box.Get ("device", Info); if Info.Get ("device.modelname", "") /= "" then Context.Console.Notice (N_INFO, "Found a new bbox at " & IP); Gw := Druss.Gateways.Gateway_Refs.Create; Gw.Value.Ip := Ada.Strings.Unbounded.To_Unbounded_String (IP); Context.Gateways.Append (Gw); end if; exception when others => Log.Debug ("Ignoring IP {0} because some exception happened", IP); end Add_Bbox; procedure Discover (Command : in Command_Type; Context : in out Context_Type) is procedure Process (URI : in String); Retry : Natural := 0; Scanner : UPnP.SSDP.Scanner_Type; Itf_IPs : Util.Strings.Sets.Set; procedure Process (URI : in String) is Pos : Natural; begin if URI'Length <= 7 or else URI (URI'First .. URI'First + 6) /= "http://" then return; end if; Pos := Util.Strings.Index (URI, ':', 6); if Pos > 0 then Command.Add_Bbox (URI (URI'First + 7 .. Pos - 1), Context); end if; end Process; begin Log.Info ("Discovering gateways on the network"); Scanner.Initialize; Scanner.Find_IPv4_Addresses (Itf_IPs); while Retry < 5 loop Scanner.Send_Discovery ("urn:schemas-upnp-org:device:InternetGatewayDevice:1", Itf_IPs); Scanner.Discover ("urn:schemas-upnp-org:device:InternetGatewayDevice:1", Process'Access, 1.0); Retry := Retry + 1; end loop; Druss.Config.Save_Gateways (Context.Gateways); end Discover; -- ------------------------------ -- Set the password to be used by the Bbox API to connect to the box. -- ------------------------------ procedure Do_Password (Command : in Command_Type; Args : in Util.Commands.Argument_List'Class; Context : in out Context_Type) is procedure Change_Password (Gateway : in out Druss.Gateways.Gateway_Type; Passwd : in String); procedure Change_Password (Gateway : in out Druss.Gateways.Gateway_Type; Passwd : in String) is begin Gateway.Passwd := Ada.Strings.Unbounded.To_Unbounded_String (Passwd); end Change_Password; begin Druss.Commands.Gateway_Command (Command, Args, 2, Change_Password'Access, Context); Druss.Config.Save_Gateways (Context.Gateways); end Do_Password; -- ------------------------------ -- Enable or disable the bbox management by Druss. -- ------------------------------ procedure Do_Enable (Command : in Command_Type; Args : in Util.Commands.Argument_List'Class; Context : in out Context_Type) is procedure Change_Enable (Gateway : in out Druss.Gateways.Gateway_Type; Command : in String); procedure Change_Enable (Gateway : in out Druss.Gateways.Gateway_Type; Command : in String) is begin Gateway.Enable := Command = "enable"; end Change_Enable; begin Druss.Commands.Gateway_Command (Command, Args, 1, Change_Enable'Access, Context); Druss.Config.Save_Gateways (Context.Gateways); end Do_Enable; -- ------------------------------ -- Execute the command with the arguments. The command name is passed with the command -- arguments. -- ------------------------------ overriding procedure Execute (Command : in Command_Type; Name : in String; Args : in Util.Commands.Argument_List'Class; Context : in out Context_Type) is pragma Unreferenced (Name); begin if Args.Get_Count = 0 then Druss.Commands.Driver.Usage (Args); elsif Args.Get_Argument (1) = "discover" then Command.Discover (Context); elsif Args.Get_Argument (1) = "password" then Command.Do_Password (Args, Context); elsif Args.Get_Argument (1) in "enable" | "disable" then Command.Do_Enable (Args, Context); else Context.Console.Notice (N_USAGE, "Invalid sub-command: " & Args.Get_Argument (1)); Druss.Commands.Driver.Usage (Args); end if; end Execute; -- ------------------------------ -- Write the help associated with the command. -- ------------------------------ overriding procedure Help (Command : in Command_Type; Context : in out Context_Type) is pragma Unreferenced (Command); Console : constant Druss.Commands.Consoles.Console_Access := Context.Console; begin Console.Notice (N_HELP, "bbox: Manage and define the configuration to connect to the Bbox"); Console.Notice (N_HELP, "Usage: bbox <operation>..."); Console.Notice (N_HELP, ""); Console.Notice (N_HELP, " Druss needs to know the list of Bboxes which are available" & " on the network."); Console.Notice (N_HELP, " It also need some credentials to connect to the Bbox using" & " the Bbox API."); Console.Notice (N_HELP, " The 'bbox' command allows to manage that list and configuration."); Console.Notice (N_HELP, " Examples:"); Console.Notice (N_HELP, " bbox discover Discover the bbox(es) connected to the LAN"); Console.Notice (N_HELP, " bbox add IP Add a bbox knowing its IP address"); Console.Notice (N_HELP, " bbox del IP Delete a bbox from the list"); Console.Notice (N_HELP, " bbox enable IP Enable the bbox (it will be used by Druss)"); Console.Notice (N_HELP, " bbox disable IP Disable the bbox (it will not be managed)"); Console.Notice (N_HELP, " bbox password <pass> [IP] Set the bbox API connection password"); end Help; end Druss.Commands.Bboxes;
Rename Password into Do_Password Fix compilation warnings Remove unused functions
Rename Password into Do_Password Fix compilation warnings Remove unused functions
Ada
apache-2.0
stcarrez/bbox-ada-api
fc471d755ce5dc02a888561a9f137680a166fb8c
src/sqlite/ado-drivers-connections-sqlite.adb
src/sqlite/ado-drivers-connections-sqlite.adb
----------------------------------------------------------------------- -- ADO Sqlite Database -- SQLite Database connections -- Copyright (C) 2009, 2010, 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Sqlite3_H; with Interfaces.C.Strings; with Util.Log; with Util.Log.Loggers; with ADO.Statements.Sqlite; package body ADO.Drivers.Connections.Sqlite is use Util.Log; use ADO.Statements.Sqlite; use Interfaces.C; pragma Linker_Options ("-lsqlite3"); Log : constant Loggers.Logger := Loggers.Create ("ADO.Databases.Sqlite"); Driver_Name : aliased constant String := "sqlite"; Driver : aliased Sqlite_Driver; No_Callback : constant Sqlite3_H.sqlite3_callback := null; -- ------------------------------ -- Get the database driver which manages this connection. -- ------------------------------ overriding function Get_Driver (Database : in Database_Connection) return Driver_Access is pragma Unreferenced (Database); begin return Driver'Access; end Get_Driver; -- ------------------------------ -- Check for an error after executing a sqlite statement. -- ------------------------------ procedure Check_Error (Connection : in Sqlite_Access; Result : in int) is begin if Result /= Sqlite3_H.SQLITE_OK and Result /= Sqlite3_H.SQLITE_DONE then declare Error : constant Strings.chars_ptr := Sqlite3_H.sqlite3_errmsg (Connection); Msg : constant String := Strings.Value (Error); begin Log.Error ("Error {0}: {1}", int'Image (Result), Msg); end; end if; end Check_Error; overriding function Create_Statement (Database : in Database_Connection; Table : in ADO.Schemas.Class_Mapping_Access) return Query_Statement_Access is begin return Create_Statement (Database => Database.Server, Table => Table); end Create_Statement; overriding function Create_Statement (Database : in Database_Connection; Query : in String) return Query_Statement_Access is begin return Create_Statement (Database => Database.Server, Query => Query); end Create_Statement; -- ------------------------------ -- Create a delete statement. -- ------------------------------ overriding function Create_Statement (Database : in Database_Connection; Table : in ADO.Schemas.Class_Mapping_Access) return Delete_Statement_Access is begin return Create_Statement (Database => Database.Server, Table => Table); end Create_Statement; -- ------------------------------ -- Create an insert statement. -- ------------------------------ overriding function Create_Statement (Database : in Database_Connection; Table : in ADO.Schemas.Class_Mapping_Access) return Insert_Statement_Access is begin return Create_Statement (Database => Database.Server, Table => Table); end Create_Statement; -- ------------------------------ -- Create an update statement. -- ------------------------------ overriding function Create_Statement (Database : in Database_Connection; Table : in ADO.Schemas.Class_Mapping_Access) return Update_Statement_Access is begin return Create_Statement (Database => Database.Server, Table => Table); end Create_Statement; -- ------------------------------ -- Start a transaction. -- ------------------------------ procedure Begin_Transaction (Database : in out Database_Connection) is begin -- Database.Execute ("begin transaction;"); null; end Begin_Transaction; -- ------------------------------ -- Commit the current transaction. -- ------------------------------ procedure Commit (Database : in out Database_Connection) is begin -- Database.Execute ("commit transaction;"); null; end Commit; -- ------------------------------ -- Rollback the current transaction. -- ------------------------------ procedure Rollback (Database : in out Database_Connection) is begin -- Database.Execute ("rollback transaction;"); null; end Rollback; procedure Sqlite3_Free (Arg1 : Strings.chars_ptr); pragma Import (C, sqlite3_free, "sqlite3_free"); procedure Execute (Database : in out Database_Connection; SQL : in Query_String) is use type Strings.chars_ptr; SQL_Stat : Strings.chars_ptr := Strings.New_String (SQL); Result : int; Error_Msg : Strings.chars_ptr; begin Log.Debug ("Execute: {0}", SQL); for Retry in 1 .. 100 loop Result := Sqlite3_H.sqlite3_exec (Database.Server, SQL_Stat, No_Callback, System.Null_Address, Error_Msg'Address); exit when Result /= Sqlite3_H.SQLITE_BUSY; delay 0.01 * Retry; end loop; Check_Error (Database.Server, Result); if Error_Msg /= Strings.Null_Ptr then Log.Error ("Error: {0}", Strings.Value (Error_Msg)); Sqlite3_Free (Error_Msg); end if; -- Free Strings.Free (SQL_Stat); end Execute; -- ------------------------------ -- Closes the database connection -- ------------------------------ overriding procedure Close (Database : in out Database_Connection) is pragma Unreferenced (Database); Result : int; begin Log.Info ("Close connection"); -- if Database.Count = 1 then -- Result := Sqlite3_H.sqlite3_close (Database.Server); -- Database.Server := System.Null_Address; -- end if; pragma Unreferenced (Result); end Close; -- ------------------------------ -- Releases the sqlite connection if it is open -- ------------------------------ overriding procedure Finalize (Database : in out Database_Connection) is Result : int; begin Log.Debug ("Release connection"); Database.Count := Database.Count - 1; -- if Database.Count <= 1 then -- Result := Sqlite3_H.Sqlite3_Close (Database.Server); -- end if; -- Database.Server := System.Null_Address; pragma Unreferenced (Result); end Finalize; -- ------------------------------ -- Load the database schema definition for the current database. -- ------------------------------ overriding procedure Load_Schema (Database : in Database_Connection; Schema : out ADO.Schemas.Schema_Definition) is begin null; end Load_Schema; DB : ADO.Drivers.Connections.Database_Connection_Access := null; -- ------------------------------ -- Initialize the database connection manager. -- ------------------------------ procedure Create_Connection (D : in out Sqlite_Driver; Config : in Configuration'Class; Result : out ADO.Drivers.Connections.Database_Connection_Access) is pragma Unreferenced (D); use Strings; use type System.Address; Name : constant String := To_String (Config.Database); Filename : Strings.chars_ptr; Status : int; Handle : aliased System.Address; Flags : constant int := Sqlite3_H.SQLITE_OPEN_FULLMUTEX + Sqlite3_H.SQLITE_OPEN_READWRITE; begin Log.Info ("Opening database {0}", Name); if DB /= null then Result := DB; DB.Count := DB.Count + 1; return; end if; Filename := Strings.New_String (Name); Status := Sqlite3_H.sqlite3_open_v2 (Filename, Handle'Access, Flags, Strings.Null_Ptr); Strings.Free (Filename); if Status /= Sqlite3_H.SQLITE_OK then raise DB_Error; end if; declare Database : constant Database_Connection_Access := new Database_Connection; procedure Configure (Name, Item : in Util.Properties.Value); procedure Configure (Name, Item : in Util.Properties.Value) is SQL : constant String := "PRAGMA " & To_String (Name) & "=" & To_String (Item); begin Database.Execute (SQL); end Configure; begin Database.Server := Handle; Database.Count := 2; Database.Name := Config.Database; -- Configure the connection by setting up the SQLite 'pragma X=Y' SQL commands. -- Typical configuration includes: -- synchronous=OFF -- temp_store=MEMORY -- encoding='UTF-8' Config.Properties.Iterate (Process => Configure'Access); Result := Database.all'Access; DB := Result; end; end Create_Connection; -- ------------------------------ -- Initialize the SQLite driver. -- ------------------------------ procedure Initialize is use type Util.Strings.Name_Access; begin Log.Debug ("Initializing sqlite driver"); if Driver.Name = null then Driver.Name := Driver_Name'Access; Register (Driver'Access); end if; end Initialize; end ADO.Drivers.Connections.Sqlite;
----------------------------------------------------------------------- -- ADO Sqlite Database -- SQLite Database connections -- Copyright (C) 2009, 2010, 2011, 2012, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Sqlite3_H; with Interfaces.C.Strings; with Util.Log; with Util.Log.Loggers; with ADO.Statements.Sqlite; with ADO.Schemas.Sqlite; package body ADO.Drivers.Connections.Sqlite is use ADO.Statements.Sqlite; use Interfaces.C; pragma Linker_Options ("-lsqlite3"); Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("ADO.Databases.Sqlite"); Driver_Name : aliased constant String := "sqlite"; Driver : aliased Sqlite_Driver; No_Callback : constant Sqlite3_H.sqlite3_callback := null; -- ------------------------------ -- Get the database driver which manages this connection. -- ------------------------------ overriding function Get_Driver (Database : in Database_Connection) return Driver_Access is pragma Unreferenced (Database); begin return Driver'Access; end Get_Driver; -- ------------------------------ -- Check for an error after executing a sqlite statement. -- ------------------------------ procedure Check_Error (Connection : in Sqlite_Access; Result : in int) is begin if Result /= Sqlite3_H.SQLITE_OK and Result /= Sqlite3_H.SQLITE_DONE then declare Error : constant Strings.chars_ptr := Sqlite3_H.sqlite3_errmsg (Connection); Msg : constant String := Strings.Value (Error); begin Log.Error ("Error {0}: {1}", int'Image (Result), Msg); end; end if; end Check_Error; overriding function Create_Statement (Database : in Database_Connection; Table : in ADO.Schemas.Class_Mapping_Access) return Query_Statement_Access is begin return Create_Statement (Database => Database.Server, Table => Table); end Create_Statement; overriding function Create_Statement (Database : in Database_Connection; Query : in String) return Query_Statement_Access is begin return Create_Statement (Database => Database.Server, Query => Query); end Create_Statement; -- ------------------------------ -- Create a delete statement. -- ------------------------------ overriding function Create_Statement (Database : in Database_Connection; Table : in ADO.Schemas.Class_Mapping_Access) return Delete_Statement_Access is begin return Create_Statement (Database => Database.Server, Table => Table); end Create_Statement; -- ------------------------------ -- Create an insert statement. -- ------------------------------ overriding function Create_Statement (Database : in Database_Connection; Table : in ADO.Schemas.Class_Mapping_Access) return Insert_Statement_Access is begin return Create_Statement (Database => Database.Server, Table => Table); end Create_Statement; -- ------------------------------ -- Create an update statement. -- ------------------------------ overriding function Create_Statement (Database : in Database_Connection; Table : in ADO.Schemas.Class_Mapping_Access) return Update_Statement_Access is begin return Create_Statement (Database => Database.Server, Table => Table); end Create_Statement; -- ------------------------------ -- Start a transaction. -- ------------------------------ procedure Begin_Transaction (Database : in out Database_Connection) is begin -- Database.Execute ("begin transaction;"); null; end Begin_Transaction; -- ------------------------------ -- Commit the current transaction. -- ------------------------------ procedure Commit (Database : in out Database_Connection) is begin -- Database.Execute ("commit transaction;"); null; end Commit; -- ------------------------------ -- Rollback the current transaction. -- ------------------------------ procedure Rollback (Database : in out Database_Connection) is begin -- Database.Execute ("rollback transaction;"); null; end Rollback; procedure Sqlite3_Free (Arg1 : Strings.chars_ptr); pragma Import (C, sqlite3_free, "sqlite3_free"); procedure Execute (Database : in out Database_Connection; SQL : in Query_String) is use type Strings.chars_ptr; SQL_Stat : Strings.chars_ptr := Strings.New_String (SQL); Result : int; Error_Msg : Strings.chars_ptr; begin Log.Debug ("Execute: {0}", SQL); for Retry in 1 .. 100 loop Result := Sqlite3_H.sqlite3_exec (Database.Server, SQL_Stat, No_Callback, System.Null_Address, Error_Msg'Address); exit when Result /= Sqlite3_H.SQLITE_BUSY; delay 0.01 * Retry; end loop; Check_Error (Database.Server, Result); if Error_Msg /= Strings.Null_Ptr then Log.Error ("Error: {0}", Strings.Value (Error_Msg)); Sqlite3_Free (Error_Msg); end if; -- Free Strings.Free (SQL_Stat); end Execute; -- ------------------------------ -- Closes the database connection -- ------------------------------ overriding procedure Close (Database : in out Database_Connection) is pragma Unreferenced (Database); Result : int; begin Log.Info ("Close connection"); -- if Database.Count = 1 then -- Result := Sqlite3_H.sqlite3_close (Database.Server); -- Database.Server := System.Null_Address; -- end if; pragma Unreferenced (Result); end Close; -- ------------------------------ -- Releases the sqlite connection if it is open -- ------------------------------ overriding procedure Finalize (Database : in out Database_Connection) is Result : int; begin Log.Debug ("Release connection"); Database.Count := Database.Count - 1; -- if Database.Count <= 1 then -- Result := Sqlite3_H.Sqlite3_Close (Database.Server); -- end if; -- Database.Server := System.Null_Address; pragma Unreferenced (Result); end Finalize; -- ------------------------------ -- Load the database schema definition for the current database. -- ------------------------------ overriding procedure Load_Schema (Database : in Database_Connection; Schema : out ADO.Schemas.Schema_Definition) is begin ADO.Schemas.Sqlite.Load_Schema (Database, Schema); end Load_Schema; DB : ADO.Drivers.Connections.Database_Connection_Access := null; -- ------------------------------ -- Initialize the database connection manager. -- ------------------------------ procedure Create_Connection (D : in out Sqlite_Driver; Config : in Configuration'Class; Result : out ADO.Drivers.Connections.Database_Connection_Access) is pragma Unreferenced (D); use Strings; use type System.Address; Name : constant String := To_String (Config.Database); Filename : Strings.chars_ptr; Status : int; Handle : aliased System.Address; Flags : constant int := Sqlite3_H.SQLITE_OPEN_FULLMUTEX + Sqlite3_H.SQLITE_OPEN_READWRITE; begin Log.Info ("Opening database {0}", Name); if DB /= null then Result := DB; DB.Count := DB.Count + 1; return; end if; Filename := Strings.New_String (Name); Status := Sqlite3_H.sqlite3_open_v2 (Filename, Handle'Access, Flags, Strings.Null_Ptr); Strings.Free (Filename); if Status /= Sqlite3_H.SQLITE_OK then raise DB_Error; end if; declare Database : constant Database_Connection_Access := new Database_Connection; procedure Configure (Name, Item : in Util.Properties.Value); procedure Configure (Name, Item : in Util.Properties.Value) is SQL : constant String := "PRAGMA " & To_String (Name) & "=" & To_String (Item); begin Database.Execute (SQL); end Configure; begin Database.Server := Handle; Database.Count := 2; Database.Name := Config.Database; -- Configure the connection by setting up the SQLite 'pragma X=Y' SQL commands. -- Typical configuration includes: -- synchronous=OFF -- temp_store=MEMORY -- encoding='UTF-8' Config.Properties.Iterate (Process => Configure'Access); Result := Database.all'Access; DB := Result; end; end Create_Connection; -- ------------------------------ -- Initialize the SQLite driver. -- ------------------------------ procedure Initialize is use type Util.Strings.Name_Access; begin Log.Debug ("Initializing sqlite driver"); if Driver.Name = null then Driver.Name := Driver_Name'Access; Register (Driver'Access); end if; end Initialize; end ADO.Drivers.Connections.Sqlite;
Implement the Load_Schema procedure for SQLite database connection
Implement the Load_Schema procedure for SQLite database connection
Ada
apache-2.0
stcarrez/ada-ado
383d00d9a08b5e7bf44d54fd35f64f356c7c5872
src/asf-routes.ads
src/asf-routes.ads
----------------------------------------------------------------------- -- asf-routes -- Request routing -- Copyright (C) 2015, 2016, 2017, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Servlet.Routes.Servlets; package ASF.Routes is type Faces_Route_Type is new Servlet.Routes.Servlets.Servlet_Route_Type with record View : Ada.Strings.Unbounded.Unbounded_String; end record; type Faces_Route_Type_Access is access all Faces_Route_Type'Class; subtype Route_Type is Servlet.Routes.Route_Type; subtype Route_Type_Access is Servlet.Routes.Route_Type_Access; subtype Route_Type_Ref is Servlet.Routes.Route_Type_Ref; subtype Route_Context_Type is Servlet.Routes.Route_Context_Type; package Route_Type_Refs renames Servlet.Routes.Route_Type_Refs; end ASF.Routes;
----------------------------------------------------------------------- -- asf-routes -- Request routing -- Copyright (C) 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 Servlet.Routes.Servlets; package ASF.Routes is type Faces_Route_Type is new Servlet.Routes.Servlets.Servlet_Route_Type with record View : Ada.Strings.Unbounded.Unbounded_String; end record; type Faces_Route_Type_Access is access all Faces_Route_Type'Class; subtype Route_Type is Servlet.Routes.Route_Type; subtype Route_Type_Access is Servlet.Routes.Route_Type_Access; subtype Route_Type_Accessor is Servlet.Routes.Route_Type_Accessor; subtype Route_Type_Ref is Servlet.Routes.Route_Type_Ref; subtype Route_Context_Type is Servlet.Routes.Route_Context_Type; package Route_Type_Refs renames Servlet.Routes.Route_Type_Refs; end ASF.Routes;
Declare Route_Type_Accessor subtype
Declare Route_Type_Accessor subtype
Ada
apache-2.0
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
6f4d5b1608e2919d716a86cad71e6a12c5825616
awa/plugins/awa-comments/src/model/awa-comments-models.ads
awa/plugins/awa-comments/src/model/awa-comments-models.ads
----------------------------------------------------------------------- -- AWA.Comments.Models -- AWA.Comments.Models ----------------------------------------------------------------------- -- File generated by ada-gen DO NOT MODIFY -- Template used: templates/model/package-spec.xhtml -- Ada Generator: https://ada-gen.googlecode.com/svn/trunk Revision 1095 ----------------------------------------------------------------------- -- Copyright (C) 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. ----------------------------------------------------------------------- pragma Warnings (Off); with ADO.Sessions; with ADO.Objects; with ADO.Statements; with ADO.SQL; with ADO.Schemas; with ADO.Queries; with ADO.Queries.Loaders; with Ada.Calendar; with Ada.Containers.Vectors; with Ada.Strings.Unbounded; with Util.Beans.Objects; with Util.Beans.Objects.Enums; with Util.Beans.Basic.Lists; with ADO.Audits; with AWA.Users.Models; with Util.Beans.Methods; pragma Warnings (On); package AWA.Comments.Models is pragma Style_Checks ("-mr"); -- -------------------- -- The format type defines the message format type. -- -------------------- type Format_Type is (FORMAT_TEXT, FORMAT_WIKI, FORMAT_HTML); for Format_Type use (FORMAT_TEXT => 0, FORMAT_WIKI => 1, FORMAT_HTML => 2); package Format_Type_Objects is new Util.Beans.Objects.Enums (Format_Type); -- -------------------- -- The status type defines whether the comment is visible or not. -- The comment can be put in the COMMENT_WAITING state so that -- it is not immediately visible. It must be put in the COMMENT_PUBLISHED -- state to be visible. -- -------------------- type Status_Type is (COMMENT_PUBLISHED, COMMENT_WAITING, COMMENT_SPAM, COMMENT_BLOCKED, COMMENT_ARCHIVED); for Status_Type use (COMMENT_PUBLISHED => 0, COMMENT_WAITING => 1, COMMENT_SPAM => 2, COMMENT_BLOCKED => 3, COMMENT_ARCHIVED => 4); package Status_Type_Objects is new Util.Beans.Objects.Enums (Status_Type); type Comment_Ref is new ADO.Objects.Object_Ref with null record; -- -------------------- -- The Comment table records a user comment associated with a database entity. -- The comment can be associated with any other database record. -- -------------------- -- Create an object key for Comment. function Comment_Key (Id : in ADO.Identifier) return ADO.Objects.Object_Key; -- Create an object key for Comment from a string. -- Raises Constraint_Error if the string cannot be converted into the object key. function Comment_Key (Id : in String) return ADO.Objects.Object_Key; Null_Comment : constant Comment_Ref; function "=" (Left, Right : Comment_Ref'Class) return Boolean; -- Set the comment publication date procedure Set_Create_Date (Object : in out Comment_Ref; Value : in Ada.Calendar.Time); -- Get the comment publication date function Get_Create_Date (Object : in Comment_Ref) return Ada.Calendar.Time; -- Set the comment message. procedure Set_Message (Object : in out Comment_Ref; Value : in Ada.Strings.Unbounded.Unbounded_String); procedure Set_Message (Object : in out Comment_Ref; Value : in String); -- Get the comment message. function Get_Message (Object : in Comment_Ref) return Ada.Strings.Unbounded.Unbounded_String; function Get_Message (Object : in Comment_Ref) return String; -- Set the entity identifier to which this comment is associated procedure Set_Entity_Id (Object : in out Comment_Ref; Value : in ADO.Identifier); -- Get the entity identifier to which this comment is associated function Get_Entity_Id (Object : in Comment_Ref) return ADO.Identifier; -- Set the comment identifier procedure Set_Id (Object : in out Comment_Ref; Value : in ADO.Identifier); -- Get the comment identifier function Get_Id (Object : in Comment_Ref) return ADO.Identifier; -- Get the optimistic lock version. function Get_Version (Object : in Comment_Ref) return Integer; -- Set the entity type that identifies the table to which the comment is associated. procedure Set_Entity_Type (Object : in out Comment_Ref; Value : in ADO.Entity_Type); -- Get the entity type that identifies the table to which the comment is associated. function Get_Entity_Type (Object : in Comment_Ref) return ADO.Entity_Type; -- Set the comment status to decide whether the comment is visible (published) or not. procedure Set_Status (Object : in out Comment_Ref; Value : in AWA.Comments.Models.Status_Type); -- Get the comment status to decide whether the comment is visible (published) or not. function Get_Status (Object : in Comment_Ref) return AWA.Comments.Models.Status_Type; -- Set the comment format type. procedure Set_Format (Object : in out Comment_Ref; Value : in AWA.Comments.Models.Format_Type); -- Get the comment format type. function Get_Format (Object : in Comment_Ref) return AWA.Comments.Models.Format_Type; -- procedure Set_Author (Object : in out Comment_Ref; Value : in AWA.Users.Models.User_Ref'Class); -- function Get_Author (Object : in Comment_Ref) return AWA.Users.Models.User_Ref'Class; -- Load the entity identified by 'Id'. -- Raises the NOT_FOUND exception if it does not exist. procedure Load (Object : in out Comment_Ref; Session : in out ADO.Sessions.Session'Class; Id : in ADO.Identifier); -- Load the entity identified by 'Id'. -- Returns True in <b>Found</b> if the object was found and False if it does not exist. procedure Load (Object : in out Comment_Ref; Session : in out ADO.Sessions.Session'Class; Id : in ADO.Identifier; Found : out Boolean); -- Find and load the entity. overriding procedure Find (Object : in out Comment_Ref; Session : in out ADO.Sessions.Session'Class; Query : in ADO.SQL.Query'Class; Found : out Boolean); -- Save the entity. If the entity does not have an identifier, an identifier is allocated -- and it is inserted in the table. Otherwise, only data fields which have been changed -- are updated. overriding procedure Save (Object : in out Comment_Ref; Session : in out ADO.Sessions.Master_Session'Class); -- Delete the entity. overriding procedure Delete (Object : in out Comment_Ref; Session : in out ADO.Sessions.Master_Session'Class); overriding function Get_Value (From : in Comment_Ref; Name : in String) return Util.Beans.Objects.Object; -- Table definition COMMENT_TABLE : constant ADO.Schemas.Class_Mapping_Access; -- Internal method to allocate the Object_Record instance overriding procedure Allocate (Object : in out Comment_Ref); -- Copy of the object. procedure Copy (Object : in Comment_Ref; Into : in out Comment_Ref); -- -------------------- -- The comment information. -- -------------------- type Comment_Info is new Util.Beans.Basic.Bean with record -- the comment identifier. Id : ADO.Identifier; -- the comment author's name. Author : Ada.Strings.Unbounded.Unbounded_String; -- the comment author's email. Email : Ada.Strings.Unbounded.Unbounded_String; -- the comment date. Date : Ada.Calendar.Time; -- the comment format type. Format : AWA.Comments.Models.Format_Type; -- the comment text. Comment : Ada.Strings.Unbounded.Unbounded_String; -- the comment status. Status : AWA.Comments.Models.Status_Type; end record; -- Get the bean attribute identified by the name. overriding function Get_Value (From : in Comment_Info; Name : in String) return Util.Beans.Objects.Object; -- Set the bean attribute identified by the name. overriding procedure Set_Value (Item : in out Comment_Info; Name : in String; Value : in Util.Beans.Objects.Object); package Comment_Info_Beans is new Util.Beans.Basic.Lists (Element_Type => Comment_Info); package Comment_Info_Vectors renames Comment_Info_Beans.Vectors; subtype Comment_Info_List_Bean is Comment_Info_Beans.List_Bean; type Comment_Info_List_Bean_Access is access all Comment_Info_List_Bean; -- Run the query controlled by <b>Context</b> and append the list in <b>Object</b>. procedure List (Object : in out Comment_Info_List_Bean'Class; Session : in out ADO.Sessions.Session'Class; Context : in out ADO.Queries.Context'Class); subtype Comment_Info_Vector is Comment_Info_Vectors.Vector; -- Run the query controlled by <b>Context</b> and append the list in <b>Object</b>. procedure List (Object : in out Comment_Info_Vector; Session : in out ADO.Sessions.Session'Class; Context : in out ADO.Queries.Context'Class); Query_Comment_List : constant ADO.Queries.Query_Definition_Access; Query_All_Comment_List : constant ADO.Queries.Query_Definition_Access; type Comment_Bean is abstract new AWA.Comments.Models.Comment_Ref and Util.Beans.Basic.Bean and Util.Beans.Methods.Method_Bean with null record; -- This bean provides some methods that can be used in a Method_Expression. overriding function Get_Method_Bindings (From : in Comment_Bean) return Util.Beans.Methods.Method_Binding_Array_Access; -- Set the bean attribute identified by the name. overriding procedure Set_Value (Item : in out Comment_Bean; Name : in String; Value : in Util.Beans.Objects.Object); procedure Create (Bean : in out Comment_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is abstract; procedure Delete (Bean : in out Comment_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is abstract; procedure Save (Bean : in out Comment_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is abstract; procedure Publish (Bean : in out Comment_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is abstract; private COMMENT_NAME : aliased constant String := "awa_comment"; COL_0_1_NAME : aliased constant String := "create_date"; COL_1_1_NAME : aliased constant String := "message"; COL_2_1_NAME : aliased constant String := "entity_id"; COL_3_1_NAME : aliased constant String := "id"; COL_4_1_NAME : aliased constant String := "version"; COL_5_1_NAME : aliased constant String := "entity_type"; COL_6_1_NAME : aliased constant String := "status"; COL_7_1_NAME : aliased constant String := "format"; COL_8_1_NAME : aliased constant String := "author_id"; COMMENT_DEF : aliased constant ADO.Schemas.Class_Mapping := (Count => 9, Table => COMMENT_NAME'Access, Members => ( 1 => COL_0_1_NAME'Access, 2 => COL_1_1_NAME'Access, 3 => COL_2_1_NAME'Access, 4 => COL_3_1_NAME'Access, 5 => COL_4_1_NAME'Access, 6 => COL_5_1_NAME'Access, 7 => COL_6_1_NAME'Access, 8 => COL_7_1_NAME'Access, 9 => COL_8_1_NAME'Access) ); COMMENT_TABLE : constant ADO.Schemas.Class_Mapping_Access := COMMENT_DEF'Access; COMMENT_AUDIT_DEF : aliased constant ADO.Audits.Auditable_Mapping := (Count => 3, Of_Class => COMMENT_DEF'Access, Members => ( 1 => 1, 2 => 6, 3 => 7) ); COMMENT_AUDIT_TABLE : constant ADO.Audits.Auditable_Mapping_Access := COMMENT_AUDIT_DEF'Access; Null_Comment : constant Comment_Ref := Comment_Ref'(ADO.Objects.Object_Ref with null record); type Comment_Impl is new ADO.Audits.Auditable_Object_Record (Key_Type => ADO.Objects.KEY_INTEGER, Of_Class => COMMENT_DEF'Access, With_Audit => COMMENT_AUDIT_DEF'Access) with record Create_Date : Ada.Calendar.Time; Message : Ada.Strings.Unbounded.Unbounded_String; Entity_Id : ADO.Identifier; Version : Integer; Entity_Type : ADO.Entity_Type; Status : AWA.Comments.Models.Status_Type; Format : AWA.Comments.Models.Format_Type; Author : AWA.Users.Models.User_Ref; end record; type Comment_Access is access all Comment_Impl; overriding procedure Destroy (Object : access Comment_Impl); overriding procedure Find (Object : in out Comment_Impl; Session : in out ADO.Sessions.Session'Class; Query : in ADO.SQL.Query'Class; Found : out Boolean); overriding procedure Load (Object : in out Comment_Impl; Session : in out ADO.Sessions.Session'Class); procedure Load (Object : in out Comment_Impl; Stmt : in out ADO.Statements.Query_Statement'Class; Session : in out ADO.Sessions.Session'Class); overriding procedure Save (Object : in out Comment_Impl; Session : in out ADO.Sessions.Master_Session'Class); procedure Create (Object : in out Comment_Impl; Session : in out ADO.Sessions.Master_Session'Class); overriding procedure Delete (Object : in out Comment_Impl; Session : in out ADO.Sessions.Master_Session'Class); procedure Set_Field (Object : in out Comment_Ref'Class; Impl : out Comment_Access); package File_1 is new ADO.Queries.Loaders.File (Path => "comment-queries.xml", Sha1 => "80302F51E2EC9855EFAFB43954D724A697C1F8E6"); package Def_Commentinfo_Comment_List is new ADO.Queries.Loaders.Query (Name => "comment-list", File => File_1.File'Access); Query_Comment_List : constant ADO.Queries.Query_Definition_Access := Def_Commentinfo_Comment_List.Query'Access; package Def_Commentinfo_All_Comment_List is new ADO.Queries.Loaders.Query (Name => "all-comment-list", File => File_1.File'Access); Query_All_Comment_List : constant ADO.Queries.Query_Definition_Access := Def_Commentinfo_All_Comment_List.Query'Access; end AWA.Comments.Models;
----------------------------------------------------------------------- -- AWA.Comments.Models -- AWA.Comments.Models ----------------------------------------------------------------------- -- File generated by ada-gen DO NOT MODIFY -- Template used: templates/model/package-spec.xhtml -- Ada Generator: https://ada-gen.googlecode.com/svn/trunk Revision 1095 ----------------------------------------------------------------------- -- Copyright (C) 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. ----------------------------------------------------------------------- pragma Warnings (Off); with ADO.Sessions; with ADO.Objects; with ADO.Statements; with ADO.SQL; with ADO.Schemas; with ADO.Queries; with ADO.Queries.Loaders; with Ada.Calendar; with Ada.Containers.Vectors; with Ada.Strings.Unbounded; with Util.Beans.Objects; with Util.Beans.Objects.Enums; with Util.Beans.Basic.Lists; with ADO.Audits; with AWA.Users.Models; with Util.Beans.Methods; pragma Warnings (On); package AWA.Comments.Models is pragma Style_Checks ("-mr"); -- -------------------- -- The format type defines the message format type. -- -------------------- type Format_Type is (FORMAT_TEXT, FORMAT_WIKI, FORMAT_HTML); for Format_Type use (FORMAT_TEXT => 0, FORMAT_WIKI => 1, FORMAT_HTML => 2); package Format_Type_Objects is new Util.Beans.Objects.Enums (Format_Type); type Nullable_Format_Type is record Is_Null : Boolean := True; Value : Format_Type; end record; -- -------------------- -- The status type defines whether the comment is visible or not. -- The comment can be put in the COMMENT_WAITING state so that -- it is not immediately visible. It must be put in the COMMENT_PUBLISHED -- state to be visible. -- -------------------- type Status_Type is (COMMENT_PUBLISHED, COMMENT_WAITING, COMMENT_SPAM, COMMENT_BLOCKED, COMMENT_ARCHIVED); for Status_Type use (COMMENT_PUBLISHED => 0, COMMENT_WAITING => 1, COMMENT_SPAM => 2, COMMENT_BLOCKED => 3, COMMENT_ARCHIVED => 4); package Status_Type_Objects is new Util.Beans.Objects.Enums (Status_Type); type Nullable_Status_Type is record Is_Null : Boolean := True; Value : Status_Type; end record; type Comment_Ref is new ADO.Objects.Object_Ref with null record; -- -------------------- -- The Comment table records a user comment associated with a database entity. -- The comment can be associated with any other database record. -- -------------------- -- Create an object key for Comment. function Comment_Key (Id : in ADO.Identifier) return ADO.Objects.Object_Key; -- Create an object key for Comment from a string. -- Raises Constraint_Error if the string cannot be converted into the object key. function Comment_Key (Id : in String) return ADO.Objects.Object_Key; Null_Comment : constant Comment_Ref; function "=" (Left, Right : Comment_Ref'Class) return Boolean; -- Set the comment publication date procedure Set_Create_Date (Object : in out Comment_Ref; Value : in Ada.Calendar.Time); -- Get the comment publication date function Get_Create_Date (Object : in Comment_Ref) return Ada.Calendar.Time; -- Set the comment message. procedure Set_Message (Object : in out Comment_Ref; Value : in Ada.Strings.Unbounded.Unbounded_String); procedure Set_Message (Object : in out Comment_Ref; Value : in String); -- Get the comment message. function Get_Message (Object : in Comment_Ref) return Ada.Strings.Unbounded.Unbounded_String; function Get_Message (Object : in Comment_Ref) return String; -- Set the entity identifier to which this comment is associated procedure Set_Entity_Id (Object : in out Comment_Ref; Value : in ADO.Identifier); -- Get the entity identifier to which this comment is associated function Get_Entity_Id (Object : in Comment_Ref) return ADO.Identifier; -- Set the comment identifier procedure Set_Id (Object : in out Comment_Ref; Value : in ADO.Identifier); -- Get the comment identifier function Get_Id (Object : in Comment_Ref) return ADO.Identifier; -- Get the optimistic lock version. function Get_Version (Object : in Comment_Ref) return Integer; -- Set the entity type that identifies the table to which the comment is associated. procedure Set_Entity_Type (Object : in out Comment_Ref; Value : in ADO.Entity_Type); -- Get the entity type that identifies the table to which the comment is associated. function Get_Entity_Type (Object : in Comment_Ref) return ADO.Entity_Type; -- Set the comment status to decide whether the comment is visible (published) or not. procedure Set_Status (Object : in out Comment_Ref; Value : in AWA.Comments.Models.Status_Type); -- Get the comment status to decide whether the comment is visible (published) or not. function Get_Status (Object : in Comment_Ref) return AWA.Comments.Models.Status_Type; -- Set the comment format type. procedure Set_Format (Object : in out Comment_Ref; Value : in AWA.Comments.Models.Format_Type); -- Get the comment format type. function Get_Format (Object : in Comment_Ref) return AWA.Comments.Models.Format_Type; -- procedure Set_Author (Object : in out Comment_Ref; Value : in AWA.Users.Models.User_Ref'Class); -- function Get_Author (Object : in Comment_Ref) return AWA.Users.Models.User_Ref'Class; -- Load the entity identified by 'Id'. -- Raises the NOT_FOUND exception if it does not exist. procedure Load (Object : in out Comment_Ref; Session : in out ADO.Sessions.Session'Class; Id : in ADO.Identifier); -- Load the entity identified by 'Id'. -- Returns True in <b>Found</b> if the object was found and False if it does not exist. procedure Load (Object : in out Comment_Ref; Session : in out ADO.Sessions.Session'Class; Id : in ADO.Identifier; Found : out Boolean); -- Find and load the entity. overriding procedure Find (Object : in out Comment_Ref; Session : in out ADO.Sessions.Session'Class; Query : in ADO.SQL.Query'Class; Found : out Boolean); -- Save the entity. If the entity does not have an identifier, an identifier is allocated -- and it is inserted in the table. Otherwise, only data fields which have been changed -- are updated. overriding procedure Save (Object : in out Comment_Ref; Session : in out ADO.Sessions.Master_Session'Class); -- Delete the entity. overriding procedure Delete (Object : in out Comment_Ref; Session : in out ADO.Sessions.Master_Session'Class); overriding function Get_Value (From : in Comment_Ref; Name : in String) return Util.Beans.Objects.Object; -- Table definition COMMENT_TABLE : constant ADO.Schemas.Class_Mapping_Access; -- Internal method to allocate the Object_Record instance overriding procedure Allocate (Object : in out Comment_Ref); -- Copy of the object. procedure Copy (Object : in Comment_Ref; Into : in out Comment_Ref); -- -------------------- -- The comment information. -- -------------------- type Comment_Info is new Util.Beans.Basic.Bean with record -- the comment identifier. Id : ADO.Identifier; -- the comment author's name. Author : Ada.Strings.Unbounded.Unbounded_String; -- the comment author's email. Email : Ada.Strings.Unbounded.Unbounded_String; -- the comment date. Date : Ada.Calendar.Time; -- the comment format type. Format : AWA.Comments.Models.Format_Type; -- the comment text. Comment : Ada.Strings.Unbounded.Unbounded_String; -- the comment status. Status : AWA.Comments.Models.Status_Type; end record; -- Get the bean attribute identified by the name. overriding function Get_Value (From : in Comment_Info; Name : in String) return Util.Beans.Objects.Object; -- Set the bean attribute identified by the name. overriding procedure Set_Value (Item : in out Comment_Info; Name : in String; Value : in Util.Beans.Objects.Object); package Comment_Info_Beans is new Util.Beans.Basic.Lists (Element_Type => Comment_Info); package Comment_Info_Vectors renames Comment_Info_Beans.Vectors; subtype Comment_Info_List_Bean is Comment_Info_Beans.List_Bean; type Comment_Info_List_Bean_Access is access all Comment_Info_List_Bean; -- Run the query controlled by <b>Context</b> and append the list in <b>Object</b>. procedure List (Object : in out Comment_Info_List_Bean'Class; Session : in out ADO.Sessions.Session'Class; Context : in out ADO.Queries.Context'Class); subtype Comment_Info_Vector is Comment_Info_Vectors.Vector; -- Run the query controlled by <b>Context</b> and append the list in <b>Object</b>. procedure List (Object : in out Comment_Info_Vector; Session : in out ADO.Sessions.Session'Class; Context : in out ADO.Queries.Context'Class); Query_Comment_List : constant ADO.Queries.Query_Definition_Access; Query_All_Comment_List : constant ADO.Queries.Query_Definition_Access; type Comment_Bean is abstract new AWA.Comments.Models.Comment_Ref and Util.Beans.Basic.Bean and Util.Beans.Methods.Method_Bean with null record; -- This bean provides some methods that can be used in a Method_Expression. overriding function Get_Method_Bindings (From : in Comment_Bean) return Util.Beans.Methods.Method_Binding_Array_Access; -- Set the bean attribute identified by the name. overriding procedure Set_Value (Item : in out Comment_Bean; Name : in String; Value : in Util.Beans.Objects.Object); procedure Create (Bean : in out Comment_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is abstract; procedure Delete (Bean : in out Comment_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is abstract; procedure Save (Bean : in out Comment_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is abstract; procedure Publish (Bean : in out Comment_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is abstract; private COMMENT_NAME : aliased constant String := "awa_comment"; COL_0_1_NAME : aliased constant String := "create_date"; COL_1_1_NAME : aliased constant String := "message"; COL_2_1_NAME : aliased constant String := "entity_id"; COL_3_1_NAME : aliased constant String := "id"; COL_4_1_NAME : aliased constant String := "version"; COL_5_1_NAME : aliased constant String := "entity_type"; COL_6_1_NAME : aliased constant String := "status"; COL_7_1_NAME : aliased constant String := "format"; COL_8_1_NAME : aliased constant String := "author_id"; COMMENT_DEF : aliased constant ADO.Schemas.Class_Mapping := (Count => 9, Table => COMMENT_NAME'Access, Members => ( 1 => COL_0_1_NAME'Access, 2 => COL_1_1_NAME'Access, 3 => COL_2_1_NAME'Access, 4 => COL_3_1_NAME'Access, 5 => COL_4_1_NAME'Access, 6 => COL_5_1_NAME'Access, 7 => COL_6_1_NAME'Access, 8 => COL_7_1_NAME'Access, 9 => COL_8_1_NAME'Access) ); COMMENT_TABLE : constant ADO.Schemas.Class_Mapping_Access := COMMENT_DEF'Access; COMMENT_AUDIT_DEF : aliased constant ADO.Audits.Auditable_Mapping := (Count => 3, Of_Class => COMMENT_DEF'Access, Members => ( 1 => 1, 2 => 6, 3 => 7) ); COMMENT_AUDIT_TABLE : constant ADO.Audits.Auditable_Mapping_Access := COMMENT_AUDIT_DEF'Access; Null_Comment : constant Comment_Ref := Comment_Ref'(ADO.Objects.Object_Ref with null record); type Comment_Impl is new ADO.Audits.Auditable_Object_Record (Key_Type => ADO.Objects.KEY_INTEGER, Of_Class => COMMENT_DEF'Access, With_Audit => COMMENT_AUDIT_DEF'Access) with record Create_Date : Ada.Calendar.Time; Message : Ada.Strings.Unbounded.Unbounded_String; Entity_Id : ADO.Identifier; Version : Integer; Entity_Type : ADO.Entity_Type; Status : AWA.Comments.Models.Status_Type; Format : AWA.Comments.Models.Format_Type; Author : AWA.Users.Models.User_Ref; end record; type Comment_Access is access all Comment_Impl; overriding procedure Destroy (Object : access Comment_Impl); overriding procedure Find (Object : in out Comment_Impl; Session : in out ADO.Sessions.Session'Class; Query : in ADO.SQL.Query'Class; Found : out Boolean); overriding procedure Load (Object : in out Comment_Impl; Session : in out ADO.Sessions.Session'Class); procedure Load (Object : in out Comment_Impl; Stmt : in out ADO.Statements.Query_Statement'Class; Session : in out ADO.Sessions.Session'Class); overriding procedure Save (Object : in out Comment_Impl; Session : in out ADO.Sessions.Master_Session'Class); procedure Create (Object : in out Comment_Impl; Session : in out ADO.Sessions.Master_Session'Class); overriding procedure Delete (Object : in out Comment_Impl; Session : in out ADO.Sessions.Master_Session'Class); procedure Set_Field (Object : in out Comment_Ref'Class; Impl : out Comment_Access); package File_1 is new ADO.Queries.Loaders.File (Path => "comment-queries.xml", Sha1 => "80302F51E2EC9855EFAFB43954D724A697C1F8E6"); package Def_Commentinfo_Comment_List is new ADO.Queries.Loaders.Query (Name => "comment-list", File => File_1.File'Access); Query_Comment_List : constant ADO.Queries.Query_Definition_Access := Def_Commentinfo_Comment_List.Query'Access; package Def_Commentinfo_All_Comment_List is new ADO.Queries.Loaders.Query (Name => "all-comment-list", File => File_1.File'Access); Query_All_Comment_List : constant ADO.Queries.Query_Definition_Access := Def_Commentinfo_All_Comment_List.Query'Access; end AWA.Comments.Models;
Rebuild the model files
Rebuild the model files
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
a5c54f9df003406ff140afcec40be6d7c1f0918a
Ada/src/Problem_70.adb
Ada/src/Problem_70.adb
with Ada.Text_IO; with PrimeUtilities; package body Problem_70 is package IO renames Ada.Text_IO; subtype Ten_Million is Integer range 1 .. 9_999_999; package Ten_Million_Primes is new PrimeUtilities(Ten_Million); type Long_Sieve is Array (Positive range <>) of Long_Float; type Digit_Count is Array(Character range '0' .. '9') of Natural; Max_Double : constant := Long_Float(Ten_Million'Last); function Make_Long_Float_Sieve return Long_Sieve is old_sieve : constant Ten_Million_Primes.Sieve := Ten_Million_Primes.Generate_Sieve(Ten_Million'Last / 2); new_sieve : Long_Sieve(1 .. old_sieve'Last); begin for i in new_sieve'Range loop new_sieve(i) := Long_Float(old_sieve(i)); end loop; return new_sieve; end Make_Long_Float_Sieve; procedure Solve is sieve : constant Long_Sieve := Make_Long_Float_Sieve; best : Ten_Million := 1; best_ratio : Long_Float := 0.0; function Convert(num : Long_Float) return Digit_Count is num_cnv : constant Ten_Million := Ten_Million(Long_Float'Rounding(num)); str : constant String := Ten_Million'Image(num_cnv); counts : Digit_Count := (others => 0); begin for i in 2 .. str'Last loop counts(str(i)) := counts(str(i)) + 1; end loop; return counts; end Convert; procedure Check(num, ratio : Long_Float) is euler : constant Long_Float := num * ratio; num_c : constant Digit_Count := Convert(num); euler_c : constant Digit_Count := Convert(euler); begin for c in num_c'Range loop if num_c(c) /= euler_c(c) then return; end if; end loop; best := Ten_Million(Long_Float'Rounding(num)); best_ratio := ratio; end Check; procedure Solve_Recursive(min_index : Positive; start_ratio : Long_Float; So_Far : Long_Float) is prime : Long_Float; total : Long_Float; ratio : Long_Float; begin for prime_index in min_index .. sieve'Last loop prime := sieve(prime_index); total := So_Far * prime; ratio := start_ratio * ((prime - 1.0) / prime); exit when total > Max_Double or ratio < 0.1; loop if ratio > best_ratio then Check(total, ratio); end if; Solve_Recursive(prime_index + 1, ratio, total); total := total * prime; exit when total > Max_Double; end loop; end loop; end Solve_Recursive; begin Solve_Recursive(sieve'First, 1.0, 1.0); IO.Put_Line(Integer'Image(best)); end Solve; end Problem_70;
with Ada.Text_IO; with PrimeUtilities; package body Problem_70 is package IO renames Ada.Text_IO; subtype Ten_Million is Integer range 1 .. 9_999_999; package Ten_Million_Primes is new PrimeUtilities(Ten_Million); type Digit_Count is Array(Character range '0' .. '9') of Natural; procedure Solve is sieve : constant Ten_Million_Primes.Sieve := Ten_Million_Primes.Generate_Sieve(Ten_Million'Last / 2); best : Ten_Million := 1; best_ratio : Long_Float := 0.0; function Convert(num : Ten_Million) return Digit_Count is str : constant String := Ten_Million'Image(num); counts : Digit_Count := (others => 0); begin for i in 2 .. str'Last loop counts(str(i)) := counts(str(i)) + 1; end loop; return counts; end Convert; procedure Check(num, euler : Ten_Million; ratio : Long_Float) is num_c : constant Digit_Count := Convert(num); euler_c : constant Digit_Count := Convert(euler); begin for c in num_c'Range loop if num_c(c) /= euler_c(c) then return; end if; end loop; best := num; best_ratio := ratio; end Check; procedure Solve_Recursive(min_index : Positive; start_ratio : Long_Float; start_euler, so_far : Ten_Million) is prime : Ten_Million; total : Ten_Million; euler : Ten_Million; ratio : Long_Float; begin for prime_index in min_index .. sieve'Last loop prime := sieve(prime_index); exit when Ten_Million'Last / prime < so_far; total := so_far * prime; euler := start_euler * (prime - 1); ratio := start_ratio * (1.0 - 1.0 / Long_Float(prime)); exit when ratio < 0.1; loop if ratio > best_ratio then Check(total, euler, ratio); end if; Solve_Recursive(prime_index + 1, ratio, euler, total); exit when Ten_Million'Last / prime < total; total := total * prime; euler := euler * prime; end loop; end loop; end Solve_Recursive; begin Solve_Recursive(sieve'First, 1.0, 1, 1); IO.Put_Line(Integer'Image(best)); end Solve; end Problem_70;
Convert problem 70 to be all integer math.
Convert problem 70 to be all integer math. I lose a fair chunk of time because I still stay within domains at all times so I do a divide before I multiply instead of getting the overflow if my numbers are large enough, but it still ends up ~50 ms faster than the previous attempt and doesn't look as odd from using doubles everywhere for integer math.
Ada
unlicense
Tim-Tom/project-euler,Tim-Tom/project-euler,Tim-Tom/project-euler
b7974b9ce885bc137a75946f3f7c27c58d668220
awa/plugins/awa-mail/src/awa-mail-components.ads
awa/plugins/awa-mail/src/awa-mail-components.ads
----------------------------------------------------------------------- -- awa-mail-components -- Mail UI Components -- Copyright (C) 2012, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with ASF.Components.Core; with AWA.Mail.Clients; -- == Components == -- The <b>AWA.Mail.Components</b> package defines several UI components that represent -- a mail message in an ASF view. The components allow the creation, formatting and -- sending of a mail message using the same mechanism as the application presentation layer. -- Example: -- -- <f:view xmlns="mail:http://code.google.com/p/ada-awa/mail"> -- <mail:message> -- <mail:subject>Welcome</mail:subject> -- <mail:to name="Iorek Byrnison">[email protected]</mail:to> -- <mail:body> -- ... -- </mail:body> -- </mail:message> -- </f:view> -- -- When the view which contains these components is rendered, a mail message is built -- and initialized by rendering the inner components. The body and other components can use -- other application UI components to render useful content. The email is send after -- the <b>mail:message</b> has finished to render its inner children. -- -- The <b>mail:subject</b> component describes the mail subject. -- -- The <b>mail:to</b> component define the mail recipient. There can be several recepients. -- -- The <b>mail:body</b> component contains the mail body. package AWA.Mail.Components is type UIMailComponent is new ASF.Components.Core.UIComponentBase with private; -- Get the mail message instance. function Get_Message (UI : in UIMailComponent) return AWA.Mail.Clients.Mail_Message_Access; private type UIMailComponent is new ASF.Components.Core.UIComponentBase with null record; end AWA.Mail.Components;
----------------------------------------------------------------------- -- awa-mail-components -- Mail UI Components -- Copyright (C) 2012, 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 ASF.Components.Core; with AWA.Mail.Clients; -- == Components == -- The `AWA.Mail.Components` package defines several UI components that represent -- a mail message in an ASF view. The components allow the creation, formatting -- and sending of a mail message using the same mechanism as the application -- presentation layer. Example: -- -- <f:view xmlns="mail:http://code.google.com/p/ada-awa/mail"> -- <mail:message> -- <mail:subject>Welcome</mail:subject> -- <mail:to name="Iorek Byrnison">[email protected]</mail:to> -- <mail:body> -- ... -- </mail:body> -- <mail:attachment value="/images/mail-image.jpg" -- fileName="image.jpg" -- contentType="image/jpg"/> -- </mail:message> -- </f:view> -- -- When the view which contains these components is rendered, a mail message -- is built and initialized by rendering the inner components. The body and -- other components can use other application UI components to render useful -- content. The email is send after the `mail:message` has finished to render -- its inner children. -- -- The `mail:subject` component describes the mail subject. -- -- The `mail:to` component define the mail recipient. -- There can be several recepients. -- -- The `mail:body` component contains the mail body. -- -- The `mail:attachment` component allows to include some attachment. package AWA.Mail.Components is type UIMailComponent is new ASF.Components.Core.UIComponentBase with private; -- Get the mail message instance. function Get_Message (UI : in UIMailComponent) return AWA.Mail.Clients.Mail_Message_Access; private type UIMailComponent is new ASF.Components.Core.UIComponentBase with null record; end AWA.Mail.Components;
Clarify the documentation to format a mail message
Clarify the documentation to format a mail message
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
ff6ce94fb811fb8ce7f7b2fcc36653f378790706
src/wiki-render-wiki.ads
src/wiki-render-wiki.ads
----------------------------------------------------------------------- -- wiki-render-wiki -- Wiki to Wiki renderer -- Copyright (C) 2015, 2016, 2020 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Wide_Wide_Maps; with Ada.Strings.Wide_Wide_Unbounded; with Wiki.Documents; with Wiki.Attributes; with Wiki.Streams; 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 Wiki_Syntax); -- Render the node instance from the document. overriding procedure Render (Engine : in out Wiki_Renderer; Doc : in Documents.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); -- Render an image. procedure Render_Image (Engine : in out Wiki_Renderer; Link : in Strings.WString; Attrs : in Attributes.Attribute_List); -- Render a quote. procedure Render_Quote (Engine : in out Wiki_Renderer; Title : in Strings.WString; Attrs : in Attributes.Attribute_List); -- 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); -- Render a text block that is pre-formatted. procedure Render_Preformatted (Engine : in out Wiki_Renderer; Text : in Strings.WString; Format : in Strings.WString); procedure Render_Tag (Engine : in out Wiki_Renderer; Doc : in Documents.Document; Node : in Nodes.Node_Type); -- Finish the document after complete wiki text has been parsed. procedure Finish (Engine : in out Wiki_Renderer; Doc : in Documents.Document); -- Set the text style format. procedure Set_Format (Engine : in out Wiki_Renderer; Format : in Format_Map); private use Ada.Strings.Wide_Wide_Unbounded; 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, Quote_Start, Quote_End, Quote_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 : Wiki_Syntax := 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, 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.Wide_Wide_Maps; with Ada.Strings.Wide_Wide_Unbounded; with Wiki.Documents; with Wiki.Attributes; with Wiki.Streams; 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 Wiki_Syntax); -- Render the node instance from the document. overriding procedure Render (Engine : in out Wiki_Renderer; Doc : in Documents.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); -- Render an image. procedure Render_Image (Engine : in out Wiki_Renderer; Link : in Strings.WString; Attrs : in Attributes.Attribute_List); -- Render a quote. procedure Render_Quote (Engine : in out Wiki_Renderer; Title : in Strings.WString; Attrs : in Attributes.Attribute_List); -- 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); -- Render a text block that is pre-formatted. procedure Render_Preformatted (Engine : in out Wiki_Renderer; Text : in Strings.WString; Format : in Strings.WString); procedure Render_Tag (Engine : in out Wiki_Renderer; Doc : in Documents.Document; Node : in Nodes.Node_Type); -- Finish the document after complete wiki text has been parsed. procedure Finish (Engine : in out Wiki_Renderer; Doc : in Documents.Document); -- Set the text style format. procedure Set_Format (Engine : in out Wiki_Renderer; Format : in Format_Map); private use Ada.Strings.Wide_Wide_Unbounded; 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, Quote_Start, Quote_End, Quote_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 : Wiki_Syntax := 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; Link_First : Boolean := False; Html_Blockquote : 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;
Add Link_First and Html_Blockquote attributes in the renderer
Add Link_First and Html_Blockquote attributes in the renderer
Ada
apache-2.0
stcarrez/ada-wiki,stcarrez/ada-wiki
5ed979e25d3a036eed66841bae874a2b4beffacf
tools/druss-commands.adb
tools/druss-commands.adb
----------------------------------------------------------------------- -- 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.Strings; with Druss.Commands.Bboxes; with Druss.Commands.Get; with Druss.Commands.Status; with Druss.Commands.Wifi; with Druss.Commands.Devices; with Druss.Commands.Ping; package body Druss.Commands is function Uptime_Image (Value : in Natural) return String; Help_Command : aliased Druss.Commands.Drivers.Help_Command_Type; Bbox_Commands : aliased Druss.Commands.Bboxes.Command_Type; Get_Commands : aliased Druss.Commands.Get.Command_Type; Wifi_Commands : aliased Druss.Commands.Wifi.Command_Type; Status_Commands : aliased Druss.Commands.Status.Command_Type; Device_Commands : aliased Druss.Commands.Devices.Command_Type; Ping_Commands : aliased Druss.Commands.Ping.Command_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) is pragma Unreferenced (Command); begin if Args.Get_Count < Arg_Pos then Context.Console.Notice (N_USAGE, "Missing argument for command"); Druss.Commands.Driver.Usage (Args); end if; declare procedure Operation (Gateway : in out Druss.Gateways.Gateway_Type); Param : constant String := Args.Get_Argument (Arg_Pos); Gw : Druss.Gateways.Gateway_Ref; procedure Operation (Gateway : in out Druss.Gateways.Gateway_Type) is begin Process (Gateway, Param); end Operation; begin if Args.Get_Count = Arg_Pos then Druss.Gateways.Iterate (Context.Gateways, Gateways.ITER_ENABLE, Operation'Access); else for I in Arg_Pos + 1 .. Args.Get_Count loop Gw := Druss.Gateways.Find_IP (Context.Gateways, Args.Get_Argument (I)); if not Gw.Is_Null then Operation (Gw.Value.all); end if; end loop; end if; end; end Gateway_Command; procedure Initialize is begin Driver.Set_Description ("Druss - The Bbox master controller"); Driver.Set_Usage ("[-v] [-o file] [-c config] <command> [<args>]" & ASCII.LF & "where:" & ASCII.LF & " -v Verbose execution mode" & ASCII.LF & " -c config Use the configuration file" & " (instead of $HOME/.config/druss/druss.properties)" & ASCII.LF & " -o file The output file to use"); Driver.Add_Command ("help", Help_Command'Access); Driver.Add_Command ("bbox", Bbox_Commands'Access); Driver.Add_Command ("get", Get_Commands'Access); Driver.Add_Command ("wifi", Wifi_Commands'Access); Driver.Add_Command ("status", Status_Commands'Access); Driver.Add_Command ("devices", Device_Commands'Access); Driver.Add_Command ("ping", Ping_Commands'Access); end Initialize; -- ------------------------------ -- Print the bbox API status. -- ------------------------------ procedure Print_Status (Console : in Consoles.Console_Access; Field : in Field_Type; Value : in String) is begin if Value = "2" then Console.Print_Field (Field, "OK"); elsif Value = "-1" then Console.Print_Field (Field, "KO"); elsif Value = "1" then Console.Print_Field (Field, "Starting"); elsif Value = "0" then Console.Print_Field (Field, "Stopped"); else Console.Print_Field (Field, "?"); end if; end Print_Status; -- ------------------------------ -- Print a ON/OFF status. -- ------------------------------ procedure Print_On_Off (Console : in Consoles.Console_Access; Field : in Field_Type; Value : in String) is begin if Value = "1" then Console.Print_Field (Field, "ON"); elsif Value = "0" then Console.Print_Field (Field, "OFF"); else Console.Print_Field (Field, ""); end if; end Print_On_Off; function Uptime_Image (Value : in Natural) return String is D : constant Natural := Value / 86400; R : constant Natural := Value mod 86400; H : constant Natural := R / 3600; M : constant Natural := (R mod 3600) / 60; S : constant Natural := (R mod 3600) mod 60; begin if D > 0 then return Util.Strings.Image (D) & "d" & (if H > 0 then Natural'Image (H) & "h" else "") & (if M > 0 then Natural'Image (M) & "m" else ""); elsif H > 0 then return Util.Strings.Image (H) & "h" & (if M > 0 then Natural'Image (M) & "m" else ""); else return Util.Strings.Image (M) & "m" & Natural'Image (S) & "s"; end if; end Uptime_Image; -- Print a uptime. procedure Print_Uptime (Console : in Consoles.Console_Access; Field : in Field_Type; Value : in String) is begin if Value = "" then Console.Print_Field (Field, Value); else Console.Print_Field (Field, Uptime_Image (Natural'Value (Value))); end if; exception when others => Console.Print_Field (Field, Value); end Print_Uptime; 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.Strings; with Druss.Commands.Bboxes; with Druss.Commands.Get; with Druss.Commands.Status; with Druss.Commands.Wifi; with Druss.Commands.Devices; with Druss.Commands.Ping; package body Druss.Commands is function Uptime_Image (Value : in Natural) return String; Help_Command : aliased Druss.Commands.Drivers.Help_Command_Type; Bbox_Commands : aliased Druss.Commands.Bboxes.Command_Type; Get_Commands : aliased Druss.Commands.Get.Command_Type; Wifi_Commands : aliased Druss.Commands.Wifi.Command_Type; Status_Commands : aliased Druss.Commands.Status.Command_Type; Device_Commands : aliased Druss.Commands.Devices.Command_Type; Ping_Commands : aliased Druss.Commands.Ping.Command_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) is pragma Unreferenced (Command); begin if Args.Get_Count < Arg_Pos then Context.Console.Notice (N_USAGE, "Missing argument for command"); Druss.Commands.Driver.Usage (Args); end if; declare procedure Operation (Gateway : in out Druss.Gateways.Gateway_Type); Param : constant String := Args.Get_Argument (Arg_Pos); Gw : Druss.Gateways.Gateway_Ref; procedure Operation (Gateway : in out Druss.Gateways.Gateway_Type) is begin Process (Gateway, Param); end Operation; begin if Args.Get_Count = Arg_Pos then Druss.Gateways.Iterate (Context.Gateways, Gateways.ITER_ENABLE, Operation'Access); else for I in Arg_Pos + 1 .. Args.Get_Count loop Gw := Druss.Gateways.Find_IP (Context.Gateways, Args.Get_Argument (I)); if not Gw.Is_Null then Operation (Gw.Value.all); end if; end loop; end if; end; end Gateway_Command; procedure Initialize is begin Driver.Set_Description ("Druss - The Bbox master controller"); Driver.Set_Usage ("[-v] [-o file] [-c config] <command> [<args>]" & ASCII.LF & "where:" & ASCII.LF & " -v Verbose execution mode" & ASCII.LF & " -c config Use the configuration file" & " (instead of $HOME/.config/druss/druss.properties)" & ASCII.LF & " -o file The output file to use"); Driver.Add_Command ("help", Help_Command'Access); Driver.Add_Command ("bbox", Bbox_Commands'Access); Driver.Add_Command ("get", Get_Commands'Access); Driver.Add_Command ("wifi", Wifi_Commands'Access); Driver.Add_Command ("status", Status_Commands'Access); Driver.Add_Command ("devices", Device_Commands'Access); Driver.Add_Command ("ping", Ping_Commands'Access); end Initialize; -- ------------------------------ -- Print the bbox API status. -- ------------------------------ procedure Print_Status (Console : in Consoles.Console_Access; Field : in Field_Type; Value : in String) is begin if Value = "2" then Console.Print_Field (Field, "OK"); elsif Value = "-1" then Console.Print_Field (Field, "KO"); elsif Value = "1" then Console.Print_Field (Field, "Starting"); elsif Value = "0" then Console.Print_Field (Field, "Stopped"); else Console.Print_Field (Field, "?"); end if; end Print_Status; -- ------------------------------ -- Print a ON/OFF status. -- ------------------------------ procedure Print_On_Off (Console : in Consoles.Console_Access; Field : in Field_Type; Value : in String) is begin if Value = "1" then Console.Print_Field (Field, "ON"); elsif Value = "0" then Console.Print_Field (Field, "OFF"); else Console.Print_Field (Field, ""); end if; end Print_On_Off; function Uptime_Image (Value : in Natural) return String is D : constant Natural := Value / 86400; R : constant Natural := Value mod 86400; H : constant Natural := R / 3600; M : constant Natural := (R mod 3600) / 60; S : constant Natural := (R mod 3600) mod 60; begin if D > 0 then return Util.Strings.Image (D) & "d" & (if H > 0 then Natural'Image (H) & "h" else "") & (if M > 0 then Natural'Image (M) & "m" else ""); elsif H > 0 then return Util.Strings.Image (H) & "h" & (if M > 0 then Natural'Image (M) & "m" else ""); else return Util.Strings.Image (M) & "m" & Natural'Image (S) & "s"; end if; end Uptime_Image; -- ------------------------------ -- Print a uptime. -- ------------------------------ procedure Print_Uptime (Console : in Consoles.Console_Access; Field : in Field_Type; Value : in String) is begin if Value = "" then Console.Print_Field (Field, Value); else Console.Print_Field (Field, Uptime_Image (Natural'Value (Value))); end if; exception when others => Console.Print_Field (Field, Value); end Print_Uptime; -- ------------------------------ -- Print a performance measure in us or ms. -- ------------------------------ procedure Print_Perf (Console : in Consoles.Console_Access; Field : in Field_Type; Value : in String) is use Commands.Consoles; begin if Value = "" then Console.Print_Field (Field, Value); elsif Value'Length <= 3 then Console.Print_Field (Field, Value & " us", J_RIGHT); elsif Value'Length <= 6 then Console.Print_Field (Field, Value (Value'First .. Value'Last - 3) & "." & Value (Value'Last - 2 .. Value'Last) & " ms", J_RIGHT); else Console.Print_Field (Field, Value (Value'First .. Value'Last - 6) & "." & Value (Value'Last - 5 .. Value'Last - 3) & " s", J_RIGHT); end if; end Print_Perf; end Druss.Commands;
Implement the Print_Perf procedure
Implement the Print_Perf procedure
Ada
apache-2.0
stcarrez/bbox-ada-api
5f012367a1f865b2a8390a49fa1b42421b5480b5
awt/example/src/package_test.adb
awt/example/src/package_test.adb
with GL.Types; with Orka.Logging; with Orka.Resources.Locations.Directories; with Orka.Rendering.Programs.Modules; with Orka.Rendering.Drawing; with AWT.Windows; package body Package_Test is use all type Orka.Logging.Source; use all type Orka.Logging.Severity; use Orka.Logging; procedure Log is new Orka.Logging.Generic_Log (Window_System); overriding function On_Close (Object : Test_Window) return Boolean is begin Log (Debug, "User is trying to close window"); return True; end On_Close; overriding procedure On_Drag (Object : in out Test_Window; X, Y : AWT.Inputs.Fixed) is use all type AWT.Inputs.Action_Kind; use type AWT.Inputs.Fixed; begin Log (Debug, "User dragged something to " & "(" & Trim (X'Image) & ", " & Trim (Y'Image) & ")"); AWT.Drag_And_Drop.Set_Action (if X < 300.0 and Y < 300.0 then Copy else None); end On_Drag; overriding procedure On_Drop (Object : in out Test_Window) is use all type AWT.Inputs.Action_Kind; Action : constant AWT.Inputs.Action_Kind := AWT.Drag_And_Drop.Valid_Action; begin Log (Info, "User dropped something. Action is " & Action'Image); if Action /= None then Object.Drag_And_Drop_Signal.Set; end if; end On_Drop; procedure Initialize_Framebuffer (Object : in out Test_Window) is Alpha : constant Orka.Float_32 := (if Object.State.Transparent then 0.5 else 1.0); begin Object.FB := Orka.Rendering.Framebuffers.Create_Default_Framebuffer (Object.Width, Object.Height); Object.FB.Set_Default_Values ((Color => (0.0, 0.0, 0.0, Alpha), others => <>)); Object.FB.Use_Framebuffer; Log (Debug, "Changed size of framebuffer to " & Trim (Object.Width'Image) & " × " & Trim (Object.Height'Image)); end Initialize_Framebuffer; procedure Post_Initialize (Object : in out Test_Window) is Location_Shaders : constant Orka.Resources.Locations.Location_Ptr := Orka.Resources.Locations.Directories.Create_Location ("data"); begin Object.Initialize_Framebuffer; Object.Program := Orka.Rendering.Programs.Create_Program (Orka.Rendering.Programs.Modules.Create_Module (Location_Shaders, VS => "cursor.vert", FS => "cursor.frag")); Object.Program.Use_Program; Object.Cursor := Object.Program.Uniform ("cursor"); end Post_Initialize; procedure Render (Object : in out Test_Window) is use type Orka.Float_32; use AWT.Inputs; Window_State : constant AWT.Windows.Window_State := Object.State; Pointer_State : constant AWT.Inputs.Pointer_State := Object.State; subtype Float_32 is Orka.Float_32; Width : constant Float_32 := Float_32 (Window_State.Width + 2 * Window_State.Margin); Height : constant Float_32 := Float_32 (Window_State.Height + 2 * Window_State.Margin); PX : constant Float_32 := Float_32 (Pointer_State.Position (X)); PY : constant Float_32 := Float_32 (Pointer_State.Position (Y)); Horizontal : constant Float_32 := PX / Width * 2.0 - 1.0; Vertical : constant Float_32 := PY / Height * 2.0 - 1.0; begin if Object.Framebuffer_Resized then Object.Initialize_Framebuffer; end if; Object.FB.Clear ((Color => True, others => False)); Object.Cursor.Set_Vector (Orka.Float_32_Array'(Horizontal, Vertical)); Orka.Rendering.Drawing.Draw (GL.Types.Points, 0, 1); Object.Swap_Buffers; end Render; overriding function Create_Window (Context : aliased Orka.Contexts.Surface_Context'Class; Width, Height : Positive; Title : String := ""; Samples : Natural := 0; Visible, Resizable : Boolean := True; Transparent : Boolean := False) return Test_Window is begin return Result : constant Test_Window := (Orka.Contexts.AWT.Create_Window (Context, Width, Height, Title, Samples, Visible => Visible, Resizable => Resizable, Transparent => Transparent) with others => <>); end Create_Window; end Package_Test;
with GL.Types; with Orka.Logging.Default; with Orka.Resources.Locations.Directories; with Orka.Rendering.Programs.Modules; with Orka.Rendering.Drawing; with AWT.Windows; package body Package_Test is use all type Orka.Logging.Default_Module; use all type Orka.Logging.Severity; use Orka.Logging; procedure Log is new Orka.Logging.Default.Generic_Log (Window_System); overriding function On_Close (Object : Test_Window) return Boolean is begin Log (Debug, "User is trying to close window"); return True; end On_Close; overriding procedure On_Drag (Object : in out Test_Window; X, Y : AWT.Inputs.Fixed) is use all type AWT.Inputs.Action_Kind; use type AWT.Inputs.Fixed; begin Log (Debug, "User dragged something to " & "(" & Trim (X'Image) & ", " & Trim (Y'Image) & ")"); AWT.Drag_And_Drop.Set_Action (if X < 300.0 and Y < 300.0 then Copy else None); end On_Drag; overriding procedure On_Drop (Object : in out Test_Window) is use all type AWT.Inputs.Action_Kind; Action : constant AWT.Inputs.Action_Kind := AWT.Drag_And_Drop.Valid_Action; begin Log (Info, "User dropped something. Action is " & Action'Image); if Action /= None then Object.Drag_And_Drop_Signal.Set; end if; end On_Drop; procedure Initialize_Framebuffer (Object : in out Test_Window) is Alpha : constant Orka.Float_32 := (if Object.State.Transparent then 0.5 else 1.0); begin Object.FB := Orka.Rendering.Framebuffers.Create_Default_Framebuffer (Object.Width, Object.Height); Object.FB.Set_Default_Values ((Color => (0.0, 0.0, 0.0, Alpha), others => <>)); Object.FB.Use_Framebuffer; Log (Debug, "Changed size of framebuffer to " & Trim (Object.Width'Image) & " × " & Trim (Object.Height'Image)); end Initialize_Framebuffer; procedure Post_Initialize (Object : in out Test_Window) is Location_Shaders : constant Orka.Resources.Locations.Location_Ptr := Orka.Resources.Locations.Directories.Create_Location ("data"); begin Object.Initialize_Framebuffer; Object.Program := Orka.Rendering.Programs.Create_Program (Orka.Rendering.Programs.Modules.Create_Module (Location_Shaders, VS => "cursor.vert", FS => "cursor.frag")); Object.Program.Use_Program; Object.Cursor := Object.Program.Uniform ("cursor"); end Post_Initialize; procedure Render (Object : in out Test_Window) is use type Orka.Float_32; use AWT.Inputs; Window_State : constant AWT.Windows.Window_State := Object.State; Pointer_State : constant AWT.Inputs.Pointer_State := Object.State; subtype Float_32 is Orka.Float_32; Width : constant Float_32 := Float_32 (Window_State.Width + 2 * Window_State.Margin); Height : constant Float_32 := Float_32 (Window_State.Height + 2 * Window_State.Margin); PX : constant Float_32 := Float_32 (Pointer_State.Position (X)); PY : constant Float_32 := Float_32 (Pointer_State.Position (Y)); Horizontal : constant Float_32 := PX / Width * 2.0 - 1.0; Vertical : constant Float_32 := PY / Height * 2.0 - 1.0; begin if Object.Framebuffer_Resized then Object.Initialize_Framebuffer; end if; Object.FB.Clear ((Color => True, others => False)); Object.Cursor.Set_Vector (Orka.Float_32_Array'(Horizontal, Vertical)); Orka.Rendering.Drawing.Draw (GL.Types.Points, 0, 1); Object.Swap_Buffers; end Render; overriding function Create_Window (Context : aliased Orka.Contexts.Surface_Context'Class; Width, Height : Positive; Title : String := ""; Samples : Natural := 0; Visible, Resizable : Boolean := True; Transparent : Boolean := False) return Test_Window is begin return Result : constant Test_Window := (Orka.Contexts.AWT.Create_Window (Context, Width, Height, Title, Samples, Visible => Visible, Resizable => Resizable, Transparent => Transparent) with others => <>); end Create_Window; end Package_Test;
Fix compile error in example due to changed API of Orka.Logging
awt: Fix compile error in example due to changed API of Orka.Logging Signed-off-by: onox <[email protected]>
Ada
apache-2.0
onox/orka
3494b3d8d926016ec5d64f5c33f870b023fedff6
src/security.ads
src/security.ads
----------------------------------------------------------------------- -- security -- Security -- Copyright (C) 2010, 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- -- == Introduction == -- The <tt>Security</tt> package provides a security framework that allows -- an application to use OpenID or OAuth security frameworks. This security -- framework was first developed within the Ada Server Faces project. -- This package defines abstractions that are close or similar to Java -- security package. -- -- The security framework uses the following abstractions: -- -- === Policy and policy manager === -- The <tt>Policy</tt> defines and implements the set of security rules that specify how to -- protect the system or resources. The <tt>Policy_Manager</tt> maintains the security policies. -- -- === Principal === -- The <tt>Principal</tt> is the entity that can be authenticated. A principal is obtained -- after successful authentication of a user or of a system through an authorization process. -- The OpenID or OAuth authentication processes generate such security principal. -- -- === Permission === -- The <tt>Permission</tt> represents an access to a system or application resource. -- A permission is checked by using the security policy manager. The policy manager uses a -- security controller to enforce the permission. -- -- === Security Context === -- The <tt>Security_Context</tt> holds the contextual information that the security controller -- can use to verify the permission. The security context is associated with a principal and -- a set of policy context. -- -- == Overview == -- An application will create a security policy manager and register one or several security -- policies (yellow). The framework defines a simple role based security policy and an URL -- security policy intended to provide security in web applications. The security policy manager -- reads some security policy configuration file which allows the security policies to configure -- and create the security controllers. These controllers will enforce the security according -- to the application security rules. All these components are built only once when -- an application starts. -- -- A user is authenticated through an authentication system which creates a <tt>Principal</tt> -- instance that identifies the user (green). The security framework provides two authentication -- systems: OpenID and OAuth. -- -- [http://ada-security.googlecode.com/svn/wiki/ModelOverview.png] -- -- When a permission must be enforced, a security context is created and linked to the -- <tt>Principal</tt> instance (blue). Additional security policy context can be added depending -- on the application context. To check the permission, the security policy manager is called -- and it will ask a security controller to verify the permission. -- -- The framework allows an application to plug its own security policy, its own policy context, -- its own principal and authentication mechanism. -- -- @include security-permissions.ads -- -- == Principal == -- A principal is created by using either the [Security_OpenID OpenID], -- the [Security_OAuth OAuth] or another authentication mechanism. The authentication produces -- an object that must implement the <tt>Principal</tt> interface. For example: -- -- P : Security.OpenID.Principal_Access := Security.OpenID.Create_Principal (Auth); -- -- or -- -- P : Security.OAuth.Clients.Access_Token_Access := Security.OAuth.Clients.Create_Access_Token -- -- The principal is then stored in a security context. -- -- @include security-contexts.ads -- -- [Security_Policies Security Policies] -- [Security_OpenID OpenID] -- [Security_OAuth OAuth] -- package Security is -- ------------------------------ -- Principal -- ------------------------------ type Principal is limited interface; type Principal_Access is access all Principal'Class; -- Get the principal name. function Get_Name (From : in Principal) return String is abstract; end Security;
----------------------------------------------------------------------- -- security -- Security -- Copyright (C) 2010, 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- -- == Introduction == -- The <tt>Security</tt> package provides a security framework that allows -- an application to use OpenID or OAuth security frameworks. This security -- framework was first developed within the Ada Server Faces project. -- This package defines abstractions that are close or similar to Java -- security package. -- -- The security framework uses the following abstractions: -- -- === Policy and policy manager === -- The <tt>Policy</tt> defines and implements the set of security rules that specify how to -- protect the system or resources. The <tt>Policy_Manager</tt> maintains the security policies. -- -- === Principal === -- The <tt>Principal</tt> is the entity that can be authenticated. A principal is obtained -- after successful authentication of a user or of a system through an authorization process. -- The OpenID or OAuth authentication processes generate such security principal. -- -- === Permission === -- The <tt>Permission</tt> represents an access to a system or application resource. -- A permission is checked by using the security policy manager. The policy manager uses a -- security controller to enforce the permission. -- -- === Security Context === -- The <tt>Security_Context</tt> holds the contextual information that the security controller -- can use to verify the permission. The security context is associated with a principal and -- a set of policy context. -- -- == Overview == -- An application will create a security policy manager and register one or several security -- policies (yellow). The framework defines a simple role based security policy and an URL -- security policy intended to provide security in web applications. The security policy manager -- reads some security policy configuration file which allows the security policies to configure -- and create the security controllers. These controllers will enforce the security according -- to the application security rules. All these components are built only once when -- an application starts. -- -- A user is authenticated through an authentication system which creates a <tt>Principal</tt> -- instance that identifies the user (green). The security framework provides two authentication -- systems: OpenID and OAuth. -- -- [http://ada-security.googlecode.com/svn/wiki/ModelOverview.png] -- -- When a permission must be enforced, a security context is created and linked to the -- <tt>Principal</tt> instance (blue). Additional security policy context can be added depending -- on the application context. To check the permission, the security policy manager is called -- and it will ask a security controller to verify the permission. -- -- The framework allows an application to plug its own security policy, its own policy context, -- its own principal and authentication mechanism. -- -- @include security-permissions.ads -- -- == Principal == -- A principal is created by using either the [Security_Auth OpenID], -- the [Security_OAuth OAuth] or another authentication mechanism. The authentication produces -- an object that must implement the <tt>Principal</tt> interface. For example: -- -- P : Security.Auth.Principal_Access := Security.Auth.Create_Principal (Auth); -- -- or -- -- P : Security.OAuth.Clients.Access_Token_Access := Security.OAuth.Clients.Create_Access_Token -- -- The principal is then stored in a security context. -- -- @include security-contexts.ads -- -- [Security_Policies Security Policies] -- [Security_Auth OpenID] -- [Security_OAuth OAuth] -- package Security is -- ------------------------------ -- Principal -- ------------------------------ type Principal is limited interface; type Principal_Access is access all Principal'Class; -- Get the principal name. function Get_Name (From : in Principal) return String is abstract; end Security;
Update the documentation
Update the documentation
Ada
apache-2.0
Letractively/ada-security
d01170f7184851f6e96e6d503164c37355f143d2
src/babel-streams.ads
src/babel-streams.ads
----------------------------------------------------------------------- -- babel-Streams -- Stream management -- Copyright (C) 2014, 2015 Stephane.Carrez -- Written by Stephane.Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Finalization; with Babel.Files.Buffers; package Babel.Streams is type Stream_Type is abstract tagged limited private; type Stream_Access is access all Stream_Type'Class; -- Read the data stream as much as possible and return the result in a buffer. -- The buffer is owned by the stream and need not be released. The same buffer may -- or may not be returned by the next <tt>Read</tt> operation. -- A null buffer is returned when the end of the data stream is reached. procedure Read (Stream : in out Stream_Type; Buffer : out Babel.Files.Buffers.Buffer_Access) is abstract; -- Write the buffer in the data stream. procedure Write (Stream : in out Stream_Type; Buffer : in Babel.Files.Buffers.Buffer_Access) is abstract; -- Flush the data stream. procedure Flush (Stream : in out Stream_Type) is null; -- Close the data stream. procedure Close (Stream : in out Stream_Type) is null; -- Prepare to read again the data stream from the beginning. procedure Rewind (Stream : in out Stream_Type) is null; private type Stream_Type is abstract limited new Ada.Finalization.Limited_Controlled with null record; end Babel.Streams;
----------------------------------------------------------------------- -- babel-Streams -- Stream management -- Copyright (C) 2014, 2015 Stephane.Carrez -- Written by Stephane.Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Finalization; with Babel.Files.Buffers; package Babel.Streams is type Stream_Type is abstract tagged limited private; type Stream_Access is access all Stream_Type'Class; -- Read the data stream as much as possible and return the result in a buffer. -- The buffer is owned by the stream and need not be released. The same buffer may -- or may not be returned by the next <tt>Read</tt> operation. -- A null buffer is returned when the end of the data stream is reached. procedure Read (Stream : in out Stream_Type; Buffer : out Babel.Files.Buffers.Buffer_Access) is abstract; -- Write the buffer in the data stream. procedure Write (Stream : in out Stream_Type; Buffer : in Babel.Files.Buffers.Buffer_Access) is abstract; -- Flush the data stream. procedure Flush (Stream : in out Stream_Type) is null; -- Close the data stream. procedure Close (Stream : in out Stream_Type) is null; -- Prepare to read again the data stream from the beginning. procedure Rewind (Stream : in out Stream_Type) is null; -- Set the internal buffer that the stream can use. procedure Set_Buffer (Stream : in out Stream_Type; Buffer : in Babel.Files.Buffers.Buffer_Access) is null; private type Stream_Type is abstract limited new Ada.Finalization.Limited_Controlled with null record; end Babel.Streams;
Declare the Set_Buffer procedure
Declare the Set_Buffer procedure
Ada
apache-2.0
stcarrez/babel
06c53e6e89176ca44e87c790950e84cc8592c9e9
awa/src/awa-components-wikis.ads
awa/src/awa-components-wikis.ads
----------------------------------------------------------------------- -- awa-components-wikis -- Wiki rendering component -- Copyright (C) 2011, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Wide_Wide_Unbounded; with Util.Beans.Basic; with Util.Beans.Objects; with ASF.Contexts.Faces; with ASF.Components; with ASF.Components.Html; with Wiki.Parsers; with Wiki.Render; package AWA.Components.Wikis is use ASF.Contexts.Faces; -- The wiki format of the wiki text. The valid values are: -- dotclear, google, creole, phpbb, mediawiki FORMAT_NAME : constant String := "format"; VALUE_NAME : constant String := ASF.Components.VALUE_NAME; -- The link renderer bean that controls the generation of page and image links. LINKS_NAME : constant String := "links"; -- ------------------------------ -- Wiki component -- ------------------------------ -- -- <awa:wiki value="wiki-text" format="dotclear|google|creole|phpbb" styleClass="class"/> -- type UIWiki is new ASF.Components.Html.UIHtmlComponent with null record; type UIWiki_Access is access all UIWiki'Class; -- Get the wiki format style. The format style is obtained from the <b>format</b> -- attribute name. function Get_Wiki_Style (UI : in UIWiki; Context : in Faces_Context'Class) return Wiki.Parsers.Wiki_Syntax_Type; -- Get the links renderer that must be used to render image and page links. function Get_Links_Renderer (UI : in UIWiki; Context : in Faces_Context'Class) return Wiki.Render.Link_Renderer_Access; -- Render the wiki text overriding procedure Encode_Begin (UI : in UIWiki; Context : in out Faces_Context'Class); use Ada.Strings.Wide_Wide_Unbounded; type Link_Renderer_Bean is new Util.Beans.Basic.Readonly_Bean and Wiki.Render.Link_Renderer with record Page_Prefix : Unbounded_Wide_Wide_String; Image_Prefix : Unbounded_Wide_Wide_String; end record; -- Make a link adding a prefix unless the link is already absolute. procedure Make_Link (Renderer : in Link_Renderer_Bean; Link : in Unbounded_Wide_Wide_String; Prefix : in Unbounded_Wide_Wide_String; URI : out Unbounded_Wide_Wide_String); -- Get the value identified by the name. overriding function Get_Value (From : in Link_Renderer_Bean; Name : in String) return Util.Beans.Objects.Object; -- Get the image link that must be rendered from the wiki image link. overriding procedure Make_Image_Link (Renderer : in Link_Renderer_Bean; Link : in Unbounded_Wide_Wide_String; URI : out Unbounded_Wide_Wide_String; Width : out Natural; Height : out Natural); -- Get the page link that must be rendered from the wiki page link. overriding procedure Make_Page_Link (Renderer : in Link_Renderer_Bean; Link : in Unbounded_Wide_Wide_String; URI : out Unbounded_Wide_Wide_String; Exists : out Boolean); private function Starts_With (Content : in Unbounded_Wide_Wide_String; Item : in String) return Boolean; end AWA.Components.Wikis;
----------------------------------------------------------------------- -- awa-components-wikis -- Wiki rendering component -- Copyright (C) 2011, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Wide_Wide_Unbounded; with Util.Beans.Basic; with Util.Beans.Objects; with ASF.Contexts.Faces; with ASF.Components; with ASF.Components.Html; with Wiki.Parsers; with Wiki.Render; package AWA.Components.Wikis is use ASF.Contexts.Faces; -- The wiki format of the wiki text. The valid values are: -- dotclear, google, creole, phpbb, mediawiki FORMAT_NAME : constant String := "format"; VALUE_NAME : constant String := ASF.Components.VALUE_NAME; -- The link renderer bean that controls the generation of page and image links. LINKS_NAME : constant String := "links"; -- ------------------------------ -- Wiki component -- ------------------------------ -- -- <awa:wiki value="wiki-text" format="dotclear|google|creole|phpbb" styleClass="class"/> -- type UIWiki is new ASF.Components.Html.UIHtmlComponent with null record; type UIWiki_Access is access all UIWiki'Class; -- Get the wiki format style. The format style is obtained from the <b>format</b> -- attribute name. function Get_Wiki_Style (UI : in UIWiki; Context : in Faces_Context'Class) return Wiki.Parsers.Wiki_Syntax_Type; -- Get the links renderer that must be used to render image and page links. function Get_Links_Renderer (UI : in UIWiki; Context : in Faces_Context'Class) return Wiki.Render.Link_Renderer_Access; -- Render the wiki text overriding procedure Encode_Begin (UI : in UIWiki; Context : in out Faces_Context'Class); use Ada.Strings.Wide_Wide_Unbounded; type Link_Renderer_Bean is new Util.Beans.Basic.Readonly_Bean and Wiki.Render.Link_Renderer with record Page_Prefix : Unbounded_Wide_Wide_String; Image_Prefix : Unbounded_Wide_Wide_String; end record; -- Return true if the link is an absolute link. function Is_Link_Absolute (Renderer : in Link_Renderer_Bean; Link : in Unbounded_Wide_Wide_String) return Boolean; -- Make a link adding a prefix unless the link is already absolute. procedure Make_Link (Renderer : in Link_Renderer_Bean; Link : in Unbounded_Wide_Wide_String; Prefix : in Unbounded_Wide_Wide_String; URI : out Unbounded_Wide_Wide_String); -- Get the value identified by the name. overriding function Get_Value (From : in Link_Renderer_Bean; Name : in String) return Util.Beans.Objects.Object; -- Get the image link that must be rendered from the wiki image link. overriding procedure Make_Image_Link (Renderer : in Link_Renderer_Bean; Link : in Unbounded_Wide_Wide_String; URI : out Unbounded_Wide_Wide_String; Width : out Natural; Height : out Natural); -- Get the page link that must be rendered from the wiki page link. overriding procedure Make_Page_Link (Renderer : in Link_Renderer_Bean; Link : in Unbounded_Wide_Wide_String; URI : out Unbounded_Wide_Wide_String; Exists : out Boolean); private function Starts_With (Content : in Unbounded_Wide_Wide_String; Item : in String) return Boolean; end AWA.Components.Wikis;
Declare Is_Link_Absolute function
Declare Is_Link_Absolute function
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
05f8fe88f9b3bfb77426cfc2a38bdb385db2cbca
src/util-log.adb
src/util-log.adb
----------------------------------------------------------------------- -- Logs -- Utility Log Package -- Copyright (C) 2001, 2002, 2003, 2006, 2008, 2009, 2010, 2011 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings; with Ada.Strings.Fixed; package body Util.Log is -- ------------------------------ -- Get the log level name. -- ------------------------------ function Get_Level_Name (Level : Level_Type) return String is begin if Level = FATAL_LEVEL then return "FATAL"; elsif Level = ERROR_LEVEL then return "ERROR"; elsif Level = WARN_LEVEL then return "WARN "; elsif Level = INFO_LEVEL then return "INFO "; elsif Level = DEBUG_LEVEL then return "DEBUG"; else return Level_Type'Image (Level); end if; end Get_Level_Name; -- ------------------------------ -- Get the log level from the property value -- ------------------------------ function Get_Level (Value : in String; Default : in Level_Type := INFO_LEVEL) return Level_Type is use Ada.Strings; Val : constant String := Fixed.Trim (Value, Both); Pos : constant Natural := Fixed.Index (Val, ","); begin if Pos > Val'First then return Get_Level (Val (Val'First .. Pos - 1), Default); elsif Val = "INFO" then return INFO_LEVEL; elsif Val = "DEBUG" then return DEBUG_LEVEL; elsif Val = "WARN" then return WARN_LEVEL; elsif Val = "ERROR" then return ERROR_LEVEL; elsif Val = "FATAL" then return FATAL_LEVEL; else return Default; end if; end Get_Level; end Util.Log;
----------------------------------------------------------------------- -- util-log -- Utility Log Package -- Copyright (C) 2001, 2002, 2003, 2006, 2008, 2009, 2010, 2011, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings; with Ada.Strings.Fixed; package body Util.Log is -- ------------------------------ -- Get the log level name. -- ------------------------------ function Get_Level_Name (Level : Level_Type) return String is begin if Level = FATAL_LEVEL then return "FATAL"; elsif Level = ERROR_LEVEL then return "ERROR"; elsif Level = WARN_LEVEL then return "WARN "; elsif Level = INFO_LEVEL then return "INFO "; elsif Level = DEBUG_LEVEL then return "DEBUG"; else return Level_Type'Image (Level); end if; end Get_Level_Name; -- ------------------------------ -- Get the log level from the property value -- ------------------------------ function Get_Level (Value : in String; Default : in Level_Type := INFO_LEVEL) return Level_Type is use Ada.Strings; Val : constant String := Fixed.Trim (Value, Both); Pos : constant Natural := Fixed.Index (Val, ","); begin if Pos > Val'First then return Get_Level (Val (Val'First .. Pos - 1), Default); elsif Val = "INFO" then return INFO_LEVEL; elsif Val = "DEBUG" then return DEBUG_LEVEL; elsif Val = "WARN" then return WARN_LEVEL; elsif Val = "ERROR" then return ERROR_LEVEL; elsif Val = "FATAL" then return FATAL_LEVEL; else return Default; end if; end Get_Level; end Util.Log;
Fix header style
Fix header style
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
4092677f70fa253f9a465a1c20007f9bda7d0d07
mat/src/events/mat-events-targets.ads
mat/src/events/mat-events-targets.ads
----------------------------------------------------------------------- -- mat-events-targets - Events received and collected from a target -- Copyright (C) 2014, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Containers.Ordered_Maps; with Ada.Containers.Vectors; with Util.Concurrent.Counters; with MAT.Frames; package MAT.Events.Targets is Not_Found : exception; type Event_Type is mod 16; type Probe_Index_Type is mod 16; type Event_Id_Type is new Natural; type Probe_Event_Type is record Id : Event_Id_Type; Event : MAT.Types.Uint16; Index : Probe_Index_Type; Time : MAT.Types.Target_Tick_Ref; Thread : MAT.Types.Target_Thread_Ref; Frame : MAT.Frames.Frame_Type; Addr : MAT.Types.Target_Addr; Size : MAT.Types.Target_Size; Old_Addr : MAT.Types.Target_Addr; end record; subtype Target_Event is Probe_Event_Type; package Target_Event_Vectors is new Ada.Containers.Vectors (Positive, Target_Event); subtype Target_Event_Vector is Target_Event_Vectors.Vector; subtype Target_Event_Cursor is Target_Event_Vectors.Cursor; type Target_Events is tagged limited private; type Target_Events_Access is access all Target_Events'Class; -- Add the event in the list of events and increment the event counter. procedure Insert (Target : in out Target_Events; Event : in Probe_Event_Type); procedure Get_Events (Target : in out Target_Events; Start : in MAT.Types.Target_Time; Finish : in MAT.Types.Target_Time; Into : in out Target_Event_Vector); -- Get the start and finish time for the events that have been received. procedure Get_Time_Range (Target : in out Target_Events; Start : out MAT.Types.Target_Time; Finish : out MAT.Types.Target_Time); -- Get the probe event with the given allocated unique id. function Get_Event (Target : in Target_Events; Id : in Event_Id_Type) return Probe_Event_Type; -- Get the current event counter. function Get_Event_Counter (Target : in Target_Events) return Integer; private EVENT_BLOCK_SIZE : constant Event_Id_Type := 1024; type Probe_Event_Array is array (1 .. EVENT_BLOCK_SIZE) of Probe_Event_Type; type Event_Block is record Start : MAT.Types.Target_Time; Finish : MAT.Types.Target_Time; Count : Event_Id_Type := 0; Events : Probe_Event_Array; end record; type Event_Block_Access is access all Event_Block; use type MAT.Types.Target_Time; package Event_Maps is new Ada.Containers.Ordered_Maps (Key_Type => MAT.Types.Target_Time, Element_Type => Event_Block_Access); subtype Event_Map is Event_Maps.Map; subtype Event_Cursor is Event_Maps.Cursor; package Event_Id_Maps is new Ada.Containers.Ordered_Maps (Key_Type => Event_Id_Type, Element_Type => Event_Block_Access); subtype Event_Id_Map is Event_Id_Maps.Map; subtype Event_Id_Cursor is Event_Id_Maps.Cursor; protected type Event_Collector is -- Add the event in the list of events. procedure Insert (Event : in Probe_Event_Type); procedure Get_Events (Start : in MAT.Types.Target_Time; Finish : in MAT.Types.Target_Time; Into : in out Target_Event_Vector); -- Get the start and finish time for the events that have been received. procedure Get_Time_Range (Start : out MAT.Types.Target_Time; Finish : out MAT.Types.Target_Time); -- Get the probe event with the given allocated unique id. function Get_Event (Id : in Event_Id_Type) return Probe_Event_Type; -- Iterate over the events starting from the <tt>Start</tt> event and until the -- <tt>Finish</tt> event is found (inclusive). Execute the <tt>Process</tt> procedure -- with each event instance. procedure Iterate (Start : in Event_Id_Type; Finish : in Event_Id_Type; Process : access procedure (Event : in Probe_Event_Type)); private Current : Event_Block_Access := null; Events : Event_Map; Ids : Event_Id_Map; Last_Id : Event_Id_Type := 0; end Event_Collector; type Target_Events is tagged limited record Events : Event_Collector; Event_Count : Util.Concurrent.Counters.Counter; end record; end MAT.Events.Targets;
----------------------------------------------------------------------- -- mat-events-targets - Events received and collected from a target -- Copyright (C) 2014, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Containers.Ordered_Maps; with Ada.Containers.Vectors; with Util.Concurrent.Counters; with MAT.Frames; package MAT.Events.Targets is Not_Found : exception; type Event_Type is mod 16; type Probe_Index_Type is mod 16; type Event_Id_Type is new Natural; type Probe_Event_Type is record Id : Event_Id_Type; Event : MAT.Types.Uint16; Index : Probe_Index_Type; Time : MAT.Types.Target_Tick_Ref; Thread : MAT.Types.Target_Thread_Ref; Frame : MAT.Frames.Frame_Type; Addr : MAT.Types.Target_Addr; Size : MAT.Types.Target_Size; Old_Addr : MAT.Types.Target_Addr; end record; subtype Target_Event is Probe_Event_Type; package Target_Event_Vectors is new Ada.Containers.Vectors (Positive, Target_Event); subtype Target_Event_Vector is Target_Event_Vectors.Vector; subtype Target_Event_Cursor is Target_Event_Vectors.Cursor; type Target_Events is tagged limited private; type Target_Events_Access is access all Target_Events'Class; -- Add the event in the list of events and increment the event counter. procedure Insert (Target : in out Target_Events; Event : in Probe_Event_Type); procedure Get_Events (Target : in out Target_Events; Start : in MAT.Types.Target_Time; Finish : in MAT.Types.Target_Time; Into : in out Target_Event_Vector); -- Get the start and finish time for the events that have been received. procedure Get_Time_Range (Target : in out Target_Events; Start : out MAT.Types.Target_Time; Finish : out MAT.Types.Target_Time); -- Get the probe event with the given allocated unique id. function Get_Event (Target : in Target_Events; Id : in Event_Id_Type) return Probe_Event_Type; -- Get the current event counter. function Get_Event_Counter (Target : in Target_Events) return Integer; -- Iterate over the events starting from the <tt>Start</tt> event and until the -- <tt>Finish</tt> event is found (inclusive). Execute the <tt>Process</tt> procedure -- with each event instance. procedure Iterate (Target : in out Target_Events; Start : in Event_Id_Type; Finish : in Event_Id_Type; Process : access procedure (Event : in Probe_Event_Type)); private EVENT_BLOCK_SIZE : constant Event_Id_Type := 1024; type Probe_Event_Array is array (1 .. EVENT_BLOCK_SIZE) of Probe_Event_Type; type Event_Block is record Start : MAT.Types.Target_Time; Finish : MAT.Types.Target_Time; Count : Event_Id_Type := 0; Events : Probe_Event_Array; end record; type Event_Block_Access is access all Event_Block; use type MAT.Types.Target_Time; package Event_Maps is new Ada.Containers.Ordered_Maps (Key_Type => MAT.Types.Target_Time, Element_Type => Event_Block_Access); subtype Event_Map is Event_Maps.Map; subtype Event_Cursor is Event_Maps.Cursor; package Event_Id_Maps is new Ada.Containers.Ordered_Maps (Key_Type => Event_Id_Type, Element_Type => Event_Block_Access); subtype Event_Id_Map is Event_Id_Maps.Map; subtype Event_Id_Cursor is Event_Id_Maps.Cursor; protected type Event_Collector is -- Add the event in the list of events. procedure Insert (Event : in Probe_Event_Type); procedure Get_Events (Start : in MAT.Types.Target_Time; Finish : in MAT.Types.Target_Time; Into : in out Target_Event_Vector); -- Get the start and finish time for the events that have been received. procedure Get_Time_Range (Start : out MAT.Types.Target_Time; Finish : out MAT.Types.Target_Time); -- Get the probe event with the given allocated unique id. function Get_Event (Id : in Event_Id_Type) return Probe_Event_Type; -- Iterate over the events starting from the <tt>Start</tt> event and until the -- <tt>Finish</tt> event is found (inclusive). Execute the <tt>Process</tt> procedure -- with each event instance. procedure Iterate (Start : in Event_Id_Type; Finish : in Event_Id_Type; Process : access procedure (Event : in Probe_Event_Type)); private Current : Event_Block_Access := null; Events : Event_Map; Ids : Event_Id_Map; Last_Id : Event_Id_Type := 0; end Event_Collector; type Target_Events is tagged limited record Events : Event_Collector; Event_Count : Util.Concurrent.Counters.Counter; end record; end MAT.Events.Targets;
Declare the Iterate procedure
Declare the Iterate procedure
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
81c9ad8008572926f65c8914740d19ceac39b119
mat/src/memory/mat-memory-targets.ads
mat/src/memory/mat-memory-targets.ads
----------------------------------------------------------------------- -- Memory clients - Client info related to its memory -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with MAT.Frames; with MAT.Readers; with MAT.Memory.Tools; with MAT.Expressions; package MAT.Memory.Targets is -- Define some global statistics about the memory slots. type Memory_Stat is record Thread_Count : Natural; Total_Alloc : MAT.Types.Target_Size; Total_Free : MAT.Types.Target_Size; Malloc_Count : Natural; Free_Count : Natural; Realloc_Count : Natural; end record; type Target_Memory is tagged limited private; type Client_Memory_Ref is access all Target_Memory; -- Initialize the target memory object to manage the memory slots, the stack frames -- and setup the reader to analyze the memory events. procedure Initialize (Memory : in out Target_Memory; Reader : in out MAT.Readers.Manager_Base'Class); -- Take into account a malloc probe. The memory slot [Addr .. Slot.Size] is inserted -- in the used slots map. The freed slots that intersect the malloc'ed region are -- removed from the freed map. procedure Probe_Malloc (Memory : in out Target_Memory; Addr : in MAT.Types.Target_Addr; Slot : in Allocation); -- Take into account a free probe. Add the memory slot in the freed map and remove -- the slot from the used slots map. procedure Probe_Free (Memory : in out Target_Memory; Addr : in MAT.Types.Target_Addr; Slot : in Allocation); -- Take into account a realloc probe. The old memory slot represented by Old_Addr is -- removed from the used slots maps and the new memory slot [Addr .. Slot.Size] is -- inserted in the used slots map. procedure Probe_Realloc (Memory : in out Target_Memory; Addr : in MAT.Types.Target_Addr; Old_Addr : in MAT.Types.Target_Addr; Slot : in Allocation); -- Insert in the frame tree the new stack frame represented by <tt>Pc</tt>. -- If the frame is already known, the frame reference counter is incremented. -- The frame represented by <tt>Pc</tt> is returned in <tt>Result</tt>. procedure Create_Frame (Memory : in out Target_Memory; Pc : in MAT.Frames.Frame_Table; Result : out MAT.Frames.Frame_Type); -- Collect the information about memory slot sizes allocated by the application. procedure Size_Information (Memory : in out Target_Memory; Sizes : in out MAT.Memory.Tools.Size_Info_Map); -- Collect the information about threads and the memory allocations they've made. procedure Thread_Information (Memory : in out Target_Memory; Threads : in out Memory_Info_Map); -- Collect the information about frames and the memory allocations they've made. procedure Frame_Information (Memory : in out Target_Memory; Level : in Natural; Frames : in out Frame_Info_Map); -- Find from the <tt>Memory</tt> map the memory slots whose address intersects -- the region [From .. To] and which is selected by the given filter expression. -- Add the memory slot in the <tt>Into</tt> list if it does not already contains -- the memory slot. procedure Find (Memory : in out Target_Memory; From : in MAT.Types.Target_Addr; To : in MAT.Types.Target_Addr; Filter : in MAT.Expressions.Expression_Type; Into : in out MAT.Memory.Allocation_Map); private protected type Memory_Allocator is -- Take into account a malloc probe. The memory slot [Addr .. Slot.Size] is inserted -- in the used slots map. The freed slots that intersect the malloc'ed region are -- removed from the freed map. procedure Probe_Malloc (Addr : in MAT.Types.Target_Addr; Slot : in Allocation); -- Take into account a free probe. Add the memory slot in the freed map and remove -- the slot from the used slots map. procedure Probe_Free (Addr : in MAT.Types.Target_Addr; Slot : in Allocation); -- Take into account a realloc probe. The old memory slot represented by Old_Addr is -- removed from the used slots maps and the new memory slot [Addr .. Slot.Size] is -- inserted in the used slots map. procedure Probe_Realloc (Addr : in MAT.Types.Target_Addr; Old_Addr : in MAT.Types.Target_Addr; Slot : in Allocation); -- Insert in the frame tree the new stack frame represented by <tt>Pc</tt>. -- If the frame is already known, the frame reference counter is incremented. -- The frame represented by <tt>Pc</tt> is returned in <tt>Result</tt>. procedure Create_Frame (Pc : in MAT.Frames.Frame_Table; Result : out MAT.Frames.Frame_Type); -- Collect the information about memory slot sizes allocated by the application. procedure Size_Information (Sizes : in out MAT.Memory.Tools.Size_Info_Map); -- Collect the information about threads and the memory allocations they've made. procedure Thread_Information (Threads : in out Memory_Info_Map); -- Collect the information about frames and the memory allocations they've made. procedure Frame_Information (Level : in Natural; Frames : in out Frame_Info_Map); -- Find from the <tt>Memory</tt> map the memory slots whose address intersects -- the region [From .. To] and which is selected by the given filter expression. -- Add the memory slot in the <tt>Into</tt> list if it does not already contains -- the memory slot. procedure Find (From : in MAT.Types.Target_Addr; To : in MAT.Types.Target_Addr; Filter : in MAT.Expressions.Expression_Type; Into : in out MAT.Memory.Allocation_Map); -- Get the global memory and allocation statistics. procedure Stat_Information (Result : out Memory_Stat); private Used_Slots : Allocation_Map; Freed_Slots : Allocation_Map; Stats : Memory_Stat; Frames : MAT.Frames.Frame_Type := MAT.Frames.Create_Root; end Memory_Allocator; type Target_Memory is tagged limited record Reader : MAT.Readers.Reader_Access; Memory : Memory_Allocator; end record; end MAT.Memory.Targets;
----------------------------------------------------------------------- -- Memory clients - Client info related to its memory -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with MAT.Frames; with MAT.Readers; with MAT.Memory.Tools; with MAT.Expressions; package MAT.Memory.Targets is -- Define some global statistics about the memory slots. type Memory_Stat is record Thread_Count : Natural; Total_Alloc : MAT.Types.Target_Size; Total_Free : MAT.Types.Target_Size; Malloc_Count : Natural; Free_Count : Natural; Realloc_Count : Natural; end record; type Target_Memory is tagged limited private; type Client_Memory_Ref is access all Target_Memory; -- Initialize the target memory object to manage the memory slots, the stack frames -- and setup the reader to analyze the memory events. procedure Initialize (Memory : in out Target_Memory; Reader : in out MAT.Readers.Manager_Base'Class); -- Take into account a malloc probe. The memory slot [Addr .. Slot.Size] is inserted -- in the used slots map. The freed slots that intersect the malloc'ed region are -- removed from the freed map. procedure Probe_Malloc (Memory : in out Target_Memory; Addr : in MAT.Types.Target_Addr; Slot : in Allocation); -- Take into account a free probe. Add the memory slot in the freed map and remove -- the slot from the used slots map. procedure Probe_Free (Memory : in out Target_Memory; Addr : in MAT.Types.Target_Addr; Slot : in Allocation); -- Take into account a realloc probe. The old memory slot represented by Old_Addr is -- removed from the used slots maps and the new memory slot [Addr .. Slot.Size] is -- inserted in the used slots map. procedure Probe_Realloc (Memory : in out Target_Memory; Addr : in MAT.Types.Target_Addr; Old_Addr : in MAT.Types.Target_Addr; Slot : in Allocation); -- Insert in the frame tree the new stack frame represented by <tt>Pc</tt>. -- If the frame is already known, the frame reference counter is incremented. -- The frame represented by <tt>Pc</tt> is returned in <tt>Result</tt>. procedure Create_Frame (Memory : in out Target_Memory; Pc : in MAT.Frames.Frame_Table; Result : out MAT.Frames.Frame_Type); -- Collect the information about memory slot sizes allocated by the application. procedure Size_Information (Memory : in out Target_Memory; Sizes : in out MAT.Memory.Tools.Size_Info_Map); -- Collect the information about threads and the memory allocations they've made. procedure Thread_Information (Memory : in out Target_Memory; Threads : in out Memory_Info_Map); -- Collect the information about frames and the memory allocations they've made. procedure Frame_Information (Memory : in out Target_Memory; Level : in Natural; Frames : in out Frame_Info_Map); -- Get the global memory and allocation statistics. procedure Stat_Information (Memory : in out Target_Memory; Result : out Memory_Stat); -- Find from the <tt>Memory</tt> map the memory slots whose address intersects -- the region [From .. To] and which is selected by the given filter expression. -- Add the memory slot in the <tt>Into</tt> list if it does not already contains -- the memory slot. procedure Find (Memory : in out Target_Memory; From : in MAT.Types.Target_Addr; To : in MAT.Types.Target_Addr; Filter : in MAT.Expressions.Expression_Type; Into : in out MAT.Memory.Allocation_Map); private protected type Memory_Allocator is -- Take into account a malloc probe. The memory slot [Addr .. Slot.Size] is inserted -- in the used slots map. The freed slots that intersect the malloc'ed region are -- removed from the freed map. procedure Probe_Malloc (Addr : in MAT.Types.Target_Addr; Slot : in Allocation); -- Take into account a free probe. Add the memory slot in the freed map and remove -- the slot from the used slots map. procedure Probe_Free (Addr : in MAT.Types.Target_Addr; Slot : in Allocation); -- Take into account a realloc probe. The old memory slot represented by Old_Addr is -- removed from the used slots maps and the new memory slot [Addr .. Slot.Size] is -- inserted in the used slots map. procedure Probe_Realloc (Addr : in MAT.Types.Target_Addr; Old_Addr : in MAT.Types.Target_Addr; Slot : in Allocation); -- Insert in the frame tree the new stack frame represented by <tt>Pc</tt>. -- If the frame is already known, the frame reference counter is incremented. -- The frame represented by <tt>Pc</tt> is returned in <tt>Result</tt>. procedure Create_Frame (Pc : in MAT.Frames.Frame_Table; Result : out MAT.Frames.Frame_Type); -- Collect the information about memory slot sizes allocated by the application. procedure Size_Information (Sizes : in out MAT.Memory.Tools.Size_Info_Map); -- Collect the information about threads and the memory allocations they've made. procedure Thread_Information (Threads : in out Memory_Info_Map); -- Collect the information about frames and the memory allocations they've made. procedure Frame_Information (Level : in Natural; Frames : in out Frame_Info_Map); -- Find from the <tt>Memory</tt> map the memory slots whose address intersects -- the region [From .. To] and which is selected by the given filter expression. -- Add the memory slot in the <tt>Into</tt> list if it does not already contains -- the memory slot. procedure Find (From : in MAT.Types.Target_Addr; To : in MAT.Types.Target_Addr; Filter : in MAT.Expressions.Expression_Type; Into : in out MAT.Memory.Allocation_Map); -- Get the global memory and allocation statistics. procedure Stat_Information (Result : out Memory_Stat); private Used_Slots : Allocation_Map; Freed_Slots : Allocation_Map; Stats : Memory_Stat; Frames : MAT.Frames.Frame_Type := MAT.Frames.Create_Root; end Memory_Allocator; type Target_Memory is tagged limited record Reader : MAT.Readers.Reader_Access; Memory : Memory_Allocator; end record; end MAT.Memory.Targets;
Declare the Stat_Information procedure
Declare the Stat_Information procedure
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
a42100bdca2e6ac6f015b7dcc3e668e7ac1fa30f
mat/src/memory/mat-memory-targets.ads
mat/src/memory/mat-memory-targets.ads
----------------------------------------------------------------------- -- Memory clients - Client info related to its memory -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with MAT.Frames; with Util.Events; with MAT.Memory.Events; with MAT.Readers; with Ada.Containers.Ordered_Maps; package MAT.Memory.Targets is type Target_Memory is record Reader : MAT.Readers.Reader_Access; Memory_Slots : Allocation_Map; Frames : MAT.Frames.Frame; -- Event_Channel : MAT.Memory.Events.Memory_Event_Channel.Channel; end record; type Client_Memory_Ref is access all Target_Memory; -- Initialize the target memory object to manage the memory slots, the stack frames -- and setup the reader to analyze the memory events. procedure Initialize (Memory : in out Target_Memory; Reader : in out MAT.Readers.Manager_Base'Class); type Size_Info_Type is record Count : Natural; end record; use type MAT.Types.Target_Size; package Size_Info_Maps is new Ada.Containers.Ordered_Maps (Key_Type => MAT.Types.Target_Size, Element_Type => Size_Info_Type); subtype Size_Info_Map is Size_Info_Maps.Map; subtype Size_Info_Cursor is Size_Info_Maps.Cursor; -- Collect the information about memory slot sizes allocated by the application. procedure Size_Information (Memory : in Target_Memory; Sizes : in out Size_Info_Map); end MAT.Memory.Targets;
----------------------------------------------------------------------- -- Memory clients - Client info related to its memory -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with MAT.Frames; with Util.Events; with MAT.Memory.Events; with MAT.Readers; with Ada.Containers.Ordered_Maps; package MAT.Memory.Targets is type Target_Memory is record Reader : MAT.Readers.Reader_Access; Memory_Slots : Allocation_Map; Frames : MAT.Frames.Frame_Ptr; -- Event_Channel : MAT.Memory.Events.Memory_Event_Channel.Channel; end record; type Client_Memory_Ref is access all Target_Memory; -- Initialize the target memory object to manage the memory slots, the stack frames -- and setup the reader to analyze the memory events. procedure Initialize (Memory : in out Target_Memory; Reader : in out MAT.Readers.Manager_Base'Class); type Size_Info_Type is record Count : Natural; end record; use type MAT.Types.Target_Size; package Size_Info_Maps is new Ada.Containers.Ordered_Maps (Key_Type => MAT.Types.Target_Size, Element_Type => Size_Info_Type); subtype Size_Info_Map is Size_Info_Maps.Map; subtype Size_Info_Cursor is Size_Info_Maps.Cursor; -- Collect the information about memory slot sizes allocated by the application. procedure Size_Information (Memory : in Target_Memory; Sizes : in out Size_Info_Map); end MAT.Memory.Targets;
Change the frame object to a Frame_PTr
Change the frame object to a Frame_PTr
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
37074bde28e7d4ff95d783fdb5cf72427394d877
awa/plugins/awa-storages/src/awa-storages-services.ads
awa/plugins/awa-storages/src/awa-storages-services.ads
----------------------------------------------------------------------- -- awa-storages-services -- Storage service -- Copyright (C) 2012, 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Calendar; with Ada.Strings.Unbounded; with Util.Concurrent.Counters; with Security.Permissions; with ADO; with ASF.Parts; with AWA.Modules; with AWA.Modules.Lifecycles; with AWA.Storages.Models; with AWA.Storages.Stores; with AWA.Storages.Stores.Databases; -- == Storage Service == -- The <tt>Storage_Service</tt> provides the operations to access and use the persisent storage. -- It controls the permissions that grant access to the service for users. -- -- Other modules can be notified of storage changes by registering a listener -- on the storage module. -- -- @include awa-storages-stores.ads package AWA.Storages.Services is package ACL_Create_Storage is new Security.Permissions.Definition ("storage-create"); package ACL_Delete_Storage is new Security.Permissions.Definition ("storage-delete"); package ACL_Create_Folder is new Security.Permissions.Definition ("folder-create"); type Read_Mode is (READ, WRITE); type Expire_Type is (ONE_HOUR, ONE_DAY, TWO_DAYS, ONE_WEEK, ONE_YEAR, NEVER); package Storage_Lifecycle is new AWA.Modules.Lifecycles (Element_Type => AWA.Storages.Models.Storage_Ref'Class); subtype Listener is Storage_Lifecycle.Listener; -- ------------------------------ -- Storage Service -- ------------------------------ -- The <b>Storage_Service</b> defines a set of operations to store and retrieve -- a data object from the persistent storage. The data object is treated as a raw -- byte stream. The persistent storage can be implemented by a database, a file -- system or a remote service such as Amazon AWS. type Storage_Service is new AWA.Modules.Module_Manager with private; type Storage_Service_Access is access all Storage_Service'Class; -- Initializes the storage service. overriding procedure Initialize (Service : in out Storage_Service; Module : in AWA.Modules.Module'Class); -- Get the persistent store that manages the data store identified by <tt>Kind</tt>. function Get_Store (Service : in Storage_Service; Kind : in AWA.Storages.Models.Storage_Type) return AWA.Storages.Stores.Store_Access; -- Create or save the folder. procedure Save_Folder (Service : in Storage_Service; Folder : in out AWA.Storages.Models.Storage_Folder_Ref'Class); -- Load the folder instance identified by the given identifier. procedure Load_Folder (Service : in Storage_Service; Folder : in out AWA.Storages.Models.Storage_Folder_Ref'Class; Id : in ADO.Identifier); -- Save the data object contained in the <b>Data</b> part element into the -- target storage represented by <b>Into</b>. procedure Save (Service : in Storage_Service; Into : in out AWA.Storages.Models.Storage_Ref'Class; Data : in ASF.Parts.Part'Class; Storage : in AWA.Storages.Models.Storage_Type); -- Save the file described <b>File</b> in the storage -- object represented by <b>Into</b> and managed by the storage service. procedure Save (Service : in Storage_Service; Into : in out AWA.Storages.Models.Storage_Ref'Class; File : in AWA.Storages.Storage_File; Storage : in AWA.Storages.Models.Storage_Type); -- Save the file pointed to by the <b>Path</b> string in the storage -- object represented by <b>Into</b> and managed by the storage service. procedure Save (Service : in Storage_Service; Into : in out AWA.Storages.Models.Storage_Ref'Class; Path : in String; Storage : in AWA.Storages.Models.Storage_Type); -- Load the storage instance identified by the given identifier. procedure Load_Storage (Service : in Storage_Service; Storage : in out AWA.Storages.Models.Storage_Ref'Class; Id : in ADO.Identifier); -- Load the storage instance stored in a folder and identified by a name. procedure Load_Storage (Service : in Storage_Service; Storage : in out AWA.Storages.Models.Storage_Ref'Class; Folder : in ADO.Identifier; Name : in String; Found : out Boolean); -- Load the storage content identified by <b>From</b> into the blob descriptor <b>Into</b>. -- Raises the <b>NOT_FOUND</b> exception if there is no such storage. procedure Load (Service : in Storage_Service; From : in ADO.Identifier; Name : out Ada.Strings.Unbounded.Unbounded_String; Mime : out Ada.Strings.Unbounded.Unbounded_String; Date : out Ada.Calendar.Time; Into : out ADO.Blob_Ref); -- Load the storage content into a file. If the data is not stored in a file, a temporary -- file is created with the data content fetched from the store (ex: the database). -- The `Mode` parameter indicates whether the file will be read or written. -- The `Expire` parameter allows to control the expiration of the temporary file. procedure Get_Local_File (Service : in Storage_Service; From : in ADO.Identifier; Mode : in Read_Mode := READ; Into : out Storage_File); procedure Create_Local_File (Service : in out Storage_Service; Into : in out AWA.Storages.Storage_File); -- Deletes the storage instance. procedure Delete (Service : in Storage_Service; Storage : in out AWA.Storages.Models.Storage_Ref'Class); -- Deletes the storage instance. procedure Delete (Service : in Storage_Service; Storage : in ADO.Identifier); private type Store_Access_Array is array (AWA.Storages.Models.Storage_Type) of AWA.Storages.Stores.Store_Access; type Storage_Service is new AWA.Modules.Module_Manager with record Stores : Store_Access_Array; Database_Store : aliased AWA.Storages.Stores.Databases.Database_Store; Temp_Id : Util.Concurrent.Counters.Counter; end record; end AWA.Storages.Services;
----------------------------------------------------------------------- -- awa-storages-services -- Storage service -- Copyright (C) 2012, 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Calendar; with Ada.Strings.Unbounded; with Util.Concurrent.Counters; with Security.Permissions; with ADO; with ASF.Parts; with AWA.Modules; with AWA.Modules.Lifecycles; with AWA.Storages.Models; with AWA.Storages.Stores; with AWA.Storages.Stores.Databases; -- == Storage Service == -- The <tt>Storage_Service</tt> provides the operations to access and use the persisent storage. -- It controls the permissions that grant access to the service for users. -- -- Other modules can be notified of storage changes by registering a listener -- on the storage module. -- -- @include awa-storages-stores.ads package AWA.Storages.Services is package ACL_Create_Storage is new Security.Permissions.Definition ("storage-create"); package ACL_Delete_Storage is new Security.Permissions.Definition ("storage-delete"); package ACL_Create_Folder is new Security.Permissions.Definition ("folder-create"); type Read_Mode is (READ, WRITE); type Expire_Type is (ONE_HOUR, ONE_DAY, TWO_DAYS, ONE_WEEK, ONE_YEAR, NEVER); package Storage_Lifecycle is new AWA.Modules.Lifecycles (Element_Type => AWA.Storages.Models.Storage_Ref'Class); subtype Listener is Storage_Lifecycle.Listener; -- ------------------------------ -- Storage Service -- ------------------------------ -- The <b>Storage_Service</b> defines a set of operations to store and retrieve -- a data object from the persistent storage. The data object is treated as a raw -- byte stream. The persistent storage can be implemented by a database, a file -- system or a remote service such as Amazon AWS. type Storage_Service is new AWA.Modules.Module_Manager with private; type Storage_Service_Access is access all Storage_Service'Class; -- Initializes the storage service. overriding procedure Initialize (Service : in out Storage_Service; Module : in AWA.Modules.Module'Class); -- Get the persistent store that manages the data store identified by <tt>Kind</tt>. function Get_Store (Service : in Storage_Service; Kind : in AWA.Storages.Models.Storage_Type) return AWA.Storages.Stores.Store_Access; -- Create or save the folder. procedure Save_Folder (Service : in Storage_Service; Folder : in out AWA.Storages.Models.Storage_Folder_Ref'Class); -- Load the folder instance identified by the given identifier. procedure Load_Folder (Service : in Storage_Service; Folder : in out AWA.Storages.Models.Storage_Folder_Ref'Class; Id : in ADO.Identifier); -- Save the data object contained in the <b>Data</b> part element into the -- target storage represented by <b>Into</b>. procedure Save (Service : in Storage_Service; Into : in out AWA.Storages.Models.Storage_Ref'Class; Data : in ASF.Parts.Part'Class; Storage : in AWA.Storages.Models.Storage_Type); -- Save the file described <b>File</b> in the storage -- object represented by <b>Into</b> and managed by the storage service. procedure Save (Service : in Storage_Service; Into : in out AWA.Storages.Models.Storage_Ref'Class; File : in AWA.Storages.Storage_File; Storage : in AWA.Storages.Models.Storage_Type); -- Save the file pointed to by the <b>Path</b> string in the storage -- object represented by <b>Into</b> and managed by the storage service. procedure Save (Service : in Storage_Service; Into : in out AWA.Storages.Models.Storage_Ref'Class; Path : in String; Storage : in AWA.Storages.Models.Storage_Type); -- Load the storage instance identified by the given identifier. procedure Load_Storage (Service : in Storage_Service; Storage : in out AWA.Storages.Models.Storage_Ref'Class; Id : in ADO.Identifier); -- Load the storage instance stored in a folder and identified by a name. procedure Load_Storage (Service : in Storage_Service; Storage : in out AWA.Storages.Models.Storage_Ref'Class; Folder : in ADO.Identifier; Name : in String; Found : out Boolean); -- Load the storage content identified by <b>From</b> into the blob descriptor <b>Into</b>. -- Raises the <b>NOT_FOUND</b> exception if there is no such storage. procedure Load (Service : in Storage_Service; From : in ADO.Identifier; Name : out Ada.Strings.Unbounded.Unbounded_String; Mime : out Ada.Strings.Unbounded.Unbounded_String; Date : out Ada.Calendar.Time; Into : out ADO.Blob_Ref); -- Load the storage content into a file. If the data is not stored in a file, a temporary -- file is created with the data content fetched from the store (ex: the database). -- The `Mode` parameter indicates whether the file will be read or written. -- The `Expire` parameter allows to control the expiration of the temporary file. procedure Get_Local_File (Service : in Storage_Service; From : in ADO.Identifier; Mode : in Read_Mode := READ; Into : in out Storage_File); procedure Create_Local_File (Service : in out Storage_Service; Into : in out AWA.Storages.Storage_File); -- Deletes the storage instance. procedure Delete (Service : in Storage_Service; Storage : in out AWA.Storages.Models.Storage_Ref'Class); -- Deletes the storage instance. procedure Delete (Service : in Storage_Service; Storage : in ADO.Identifier); private type Store_Access_Array is array (AWA.Storages.Models.Storage_Type) of AWA.Storages.Stores.Store_Access; type Storage_Service is new AWA.Modules.Module_Manager with record Stores : Store_Access_Array; Database_Store : aliased AWA.Storages.Stores.Databases.Database_Store; Temp_Id : Util.Concurrent.Counters.Counter; end record; end AWA.Storages.Services;
Change Get_Local_File to use a in out parameter for the storage file
Change Get_Local_File to use a in out parameter for the storage file
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
d544fcbcef5287ab848ebfb3ea7d5375e968d87c
asfunit/asf-tests.ads
asfunit/asf-tests.ads
----------------------------------------------------------------------- -- ASF tests - ASF Tests Framework -- Copyright (C) 2011, 2012, 2015, 2020 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Properties; with ASF.Requests.Mockup; with ASF.Responses.Mockup; with ASF.Server; with ASF.Applications.Main; with Servlet.Tests; with Util.Tests; with Util.XUnit; with EL.Contexts.Default; with EL.Variables; with GNAT.Source_Info; -- The <b>ASF.Tests</b> package provides a set of utility procedures to write a unit test -- on top of ASF. package ASF.Tests is -- Initialize the asf test framework mockup. If the application is not specified, -- a default ASF application is created. procedure Initialize (Props : in Util.Properties.Manager; Application : in ASF.Applications.Main.Application_Access := null; Factory : in out ASF.Applications.Main.Application_Factory'Class); -- Called when the testsuite execution has finished. procedure Finish (Status : in Util.XUnit.Status) renames Servlet.Tests.Finish; -- Get the server function Get_Server return access ASF.Server.Container renames Servlet.Tests.Get_Server; -- Get the test application. function Get_Application return ASF.Applications.Main.Application_Access; -- Simulate a GET request on the given URI with the request parameters. -- Get the result in the response object. procedure Do_Get (Request : in out ASF.Requests.Mockup.Request; Response : in out ASF.Responses.Mockup.Response; URI : in String; Save : in String := "") renames Servlet.Tests.Do_Get; -- Simulate a POST request on the given URI with the request parameters. -- Get the result in the response object. procedure Do_Post (Request : in out ASF.Requests.Mockup.Request'Class; Response : in out ASF.Responses.Mockup.Response'Class; URI : in String; Save : in String := "") renames Servlet.Tests.Do_Post; -- Simulate a raw request. The URI and method must have been set on the Request object. procedure Do_Req (Request : in out ASF.Requests.Mockup.Request'Class; Response : in out ASF.Responses.Mockup.Response'Class) renames Servlet.Tests.Do_Req; -- Check that the response body contains the string procedure Assert_Contains (T : in Util.Tests.Test'Class; Value : in String; Reply : in out ASF.Responses.Mockup.Response; Message : in String := "Test failed"; Source : String := GNAT.Source_Info.File; Line : Natural := GNAT.Source_Info.Line) renames Servlet.Tests.Assert_Contains; -- Check that the response body matches the regular expression procedure Assert_Matches (T : in Util.Tests.Test'Class; Pattern : in String; Reply : in out ASF.Responses.Mockup.Response; Message : in String := "Test failed"; Status : in Natural := ASF.Responses.SC_OK; Source : String := GNAT.Source_Info.File; Line : Natural := GNAT.Source_Info.Line) renames Servlet.Tests.Assert_Matches; -- Check that the response body is a redirect to the given URI. procedure Assert_Redirect (T : in Util.Tests.Test'Class; Value : in String; Reply : in out ASF.Responses.Mockup.Response; Message : in String := "Test failed"; Source : String := GNAT.Source_Info.File; Line : Natural := GNAT.Source_Info.Line) renames Servlet.Tests.Assert_Redirect; -- Check that the response contains the given header. procedure Assert_Header (T : in Util.Tests.Test'Class; Header : in String; Value : in String; Reply : in out ASF.Responses.Mockup.Response; Message : in String := "Test failed"; Status : in Natural := ASF.Responses.SC_OK; Source : String := GNAT.Source_Info.File; Line : Natural := GNAT.Source_Info.Line) renames Servlet.Tests.Assert_Header; type EL_Test is new Util.Tests.Test with record -- The ELContext, Variables, Resolver, Form area controlled object. -- Due to AUnit implementation, we cannot store a controlled object in the Test object. -- This is due to the 'for Obj'Address use Ret;' clause used by AUnit to allocate -- a test object. -- The application object is allocated dyanmically by Set_Up. ELContext : EL.Contexts.Default.Default_Context_Access; Variables : EL.Variables.Variable_Mapper_Access; Root_Resolver : EL.Contexts.Default.Default_ELResolver_Access; end record; -- Cleanup the test instance. overriding procedure Tear_Down (T : in out EL_Test); -- Setup the test instance. overriding procedure Set_Up (T : in out EL_Test); end ASF.Tests;
----------------------------------------------------------------------- -- ASF tests - ASF Tests Framework -- Copyright (C) 2011, 2012, 2015, 2020 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Properties; with ASF.Requests.Mockup; with ASF.Responses.Mockup; with ASF.Server; with ASF.Applications.Main; with Servlet.Tests; with Util.Tests; with Util.XUnit; with EL.Contexts.Default; with EL.Variables; with GNAT.Source_Info; -- The <b>ASF.Tests</b> package provides a set of utility procedures to write a unit test -- on top of ASF. package ASF.Tests is -- Initialize the asf test framework mockup. If the application is not specified, -- a default ASF application is created. procedure Initialize (Props : in Util.Properties.Manager; Application : in ASF.Applications.Main.Application_Access := null; Factory : in out ASF.Applications.Main.Application_Factory'Class); -- Called when the testsuite execution has finished. procedure Finish (Status : in Util.XUnit.Status) renames Servlet.Tests.Finish; -- Get the server function Get_Server return access ASF.Server.Container renames Servlet.Tests.Get_Server; -- Get the test application. function Get_Application return ASF.Applications.Main.Application_Access; -- Simulate a GET request on the given URI with the request parameters. -- Get the result in the response object. procedure Do_Get (Request : in out ASF.Requests.Mockup.Request'Class; Response : in out ASF.Responses.Mockup.Response'Class; URI : in String; Save : in String := "") renames Servlet.Tests.Do_Get; -- Simulate a POST request on the given URI with the request parameters. -- Get the result in the response object. procedure Do_Post (Request : in out ASF.Requests.Mockup.Request'Class; Response : in out ASF.Responses.Mockup.Response'Class; URI : in String; Save : in String := "") renames Servlet.Tests.Do_Post; -- Simulate a raw request. The URI and method must have been set on the Request object. procedure Do_Req (Request : in out ASF.Requests.Mockup.Request'Class; Response : in out ASF.Responses.Mockup.Response'Class) renames Servlet.Tests.Do_Req; -- Check that the response body contains the string procedure Assert_Contains (T : in Util.Tests.Test'Class; Value : in String; Reply : in out ASF.Responses.Mockup.Response; Message : in String := "Test failed"; Source : String := GNAT.Source_Info.File; Line : Natural := GNAT.Source_Info.Line) renames Servlet.Tests.Assert_Contains; -- Check that the response body matches the regular expression procedure Assert_Matches (T : in Util.Tests.Test'Class; Pattern : in String; Reply : in out ASF.Responses.Mockup.Response; Message : in String := "Test failed"; Status : in Natural := ASF.Responses.SC_OK; Source : String := GNAT.Source_Info.File; Line : Natural := GNAT.Source_Info.Line) renames Servlet.Tests.Assert_Matches; -- Check that the response body is a redirect to the given URI. procedure Assert_Redirect (T : in Util.Tests.Test'Class; Value : in String; Reply : in out ASF.Responses.Mockup.Response; Message : in String := "Test failed"; Source : String := GNAT.Source_Info.File; Line : Natural := GNAT.Source_Info.Line) renames Servlet.Tests.Assert_Redirect; -- Check that the response contains the given header. procedure Assert_Header (T : in Util.Tests.Test'Class; Header : in String; Value : in String; Reply : in out ASF.Responses.Mockup.Response; Message : in String := "Test failed"; Status : in Natural := ASF.Responses.SC_OK; Source : String := GNAT.Source_Info.File; Line : Natural := GNAT.Source_Info.Line) renames Servlet.Tests.Assert_Header; type EL_Test is new Util.Tests.Test with record -- The ELContext, Variables, Resolver, Form area controlled object. -- Due to AUnit implementation, we cannot store a controlled object in the Test object. -- This is due to the 'for Obj'Address use Ret;' clause used by AUnit to allocate -- a test object. -- The application object is allocated dyanmically by Set_Up. ELContext : EL.Contexts.Default.Default_Context_Access; Variables : EL.Variables.Variable_Mapper_Access; Root_Resolver : EL.Contexts.Default.Default_ELResolver_Access; end record; -- Cleanup the test instance. overriding procedure Tear_Down (T : in out EL_Test); -- Setup the test instance. overriding procedure Set_Up (T : in out EL_Test); end ASF.Tests;
Update Do_Get to allow class wide request and response
Update Do_Get to allow class wide request and response
Ada
apache-2.0
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
9ebdadb8bf4b9c5ba8816798f134780e5d8ee5d6
src/util-encoders.adb
src/util-encoders.adb
----------------------------------------------------------------------- -- util-encoders -- Encode/Decode streams and strings from one format to another -- Copyright (C) 2009, 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 Ada.Unchecked_Deallocation; with Util.Encoders.Base16; with Util.Encoders.Base64; with Util.Encoders.SHA1; package body Util.Encoders is use Ada; use Ada.Strings.Unbounded; use type Ada.Streams.Stream_Element_Offset; -- ------------------------------ -- Encodes the input string <b>Data</b> using the transformation -- rules provided by the <b>E</b> encoder. -- -- Returns the encoded string. -- -- Raises the <b>Encoding_Error</b> exception if the source string -- cannot be encoded. -- Raises the <b>Not_Supported</b> exception if the encoding is not -- supported. -- ------------------------------ function Encode (E : in Encoder; Data : in String) return String is begin if E.Encode = null then raise Not_Supported with "There is no encoder"; end if; return E.Encode.Transform (Data); end Encode; -- ------------------------------ -- Decodes the input string <b>Data</b> using the transformation -- rules provided by the <b>E</b> encoder. -- -- Returns the encoded string. -- -- Raises the <b>Encoding_Error</b> exception if the source string -- cannot be decoded. -- Raises the <b>Not_Supported</b> exception if the decoding is not -- supported. -- ------------------------------ function Decode (E : in Encoder; Data : in String) return String is begin if E.Decode = null then raise Not_Supported with "There is no decoder"; end if; return E.Decode.Transform (Data); end Decode; MIN_BUFFER_SIZE : constant Streams.Stream_Element_Offset := 64; MAX_BUFFER_SIZE : constant Streams.Stream_Element_Offset := 2_048; function Best_Size (Length : Natural) return Streams.Stream_Element_Offset; pragma Inline (Best_Size); -- ------------------------------ -- Compute a good size for allocating a buffer on the stack -- ------------------------------ function Best_Size (Length : Natural) return Streams.Stream_Element_Offset is begin if Length < Natural (MIN_BUFFER_SIZE) then return MIN_BUFFER_SIZE; elsif Length > Natural (MAX_BUFFER_SIZE) then return MAX_BUFFER_SIZE; else return Streams.Stream_Element_Offset (((Length + 15) / 16) * 16); end if; end Best_Size; -- ------------------------------ -- Transform the input string <b>Data</b> using the transformation -- rules provided by the <b>E</b> transformer. -- -- Returns the transformed string. -- -- Raises the <b>Encoding_Error</b> exception if the source string -- cannot be transformed -- ------------------------------ function Transform (E : in Transformer'Class; Data : in String) return String is Buf_Size : constant Streams.Stream_Element_Offset := Best_Size (Data'Length); Buf : Streams.Stream_Element_Array (1 .. Buf_Size); Res : Streams.Stream_Element_Array (1 .. Buf_Size); Tmp : String (1 .. Natural (Buf_Size)); Result : Ada.Strings.Unbounded.Unbounded_String; Pos : Natural := Data'First; begin while Pos <= Data'Last loop declare Last_Encoded : Streams.Stream_Element_Offset; First_Encoded : Streams.Stream_Element_Offset := 1; Last : Streams.Stream_Element_Offset; Size : Streams.Stream_Element_Offset; Next_Pos : Natural; begin -- Fill the stream buffer with our input string Size := Streams.Stream_Element_Offset (Data'Last - Pos + 1); if Size > Buf'Length then Size := Buf'Length; end if; for I in 1 .. Size loop Buf (I) := Character'Pos (Data (Natural (I) + Pos - 1)); end loop; Next_Pos := Pos + Natural (Size); -- Encode that buffer and put the result in out result string. loop E.Transform (Data => Buf (First_Encoded .. Size), Into => Res, Encoded => Last_Encoded, Last => Last); -- If the encoder generated nothing, move the position backward -- to take into account the remaining bytes not taken into account. if Last < 1 then Next_Pos := Next_Pos - Natural (Size - First_Encoded + 1); exit; end if; for I in 1 .. Last loop Tmp (Natural (I)) := Character'Val (Res (I)); end loop; Append (Result, Tmp (1 .. Natural (Last))); exit when Last_Encoded = Size; First_Encoded := Last_Encoded + 1; end loop; -- The encoder cannot encode the data if Pos = Next_Pos then raise Encoding_Error with "Encoding cannot proceed"; end if; Pos := Next_Pos; end; end loop; return To_String (Result); end Transform; -- ------------------------------ -- Transform the input string <b>Data</b> using the transformation -- rules provided by the <b>E</b> transformer and return the data in -- the <b>Into</b> array, setting <b>Last</b> to the last index. -- -- Raises the <b>Encoding_Error</b> exception if the source string -- cannot be transformed -- ------------------------------ procedure Transform (E : in Transformer'Class; Data : in String; Into : out Ada.Streams.Stream_Element_Array; Last : out Ada.Streams.Stream_Element_Offset) is Buf_Size : constant Streams.Stream_Element_Offset := Best_Size (Data'Length); Buf : Streams.Stream_Element_Array (1 .. Buf_Size); Pos : Natural := Data'First; First : Streams.Stream_Element_Offset := Into'First; begin Last := Into'First - 1; while Pos <= Data'Last and Last < Into'Last loop declare Last_Encoded : Streams.Stream_Element_Offset; Size : Streams.Stream_Element_Offset; Next_Pos : Natural; begin -- Fill the stream buffer with our input string Size := Streams.Stream_Element_Offset (Data'Last - Pos + 1); if Size > Buf'Length then Size := Buf'Length; end if; for I in 1 .. Size loop Buf (I) := Character'Pos (Data (Natural (I) + Pos - 1)); end loop; Next_Pos := Pos + Natural (Size); -- Encode that buffer and put the result in the output data array. E.Transform (Data => Buf (1 .. Size), Into => Into (First .. Into'Last), Encoded => Last_Encoded, Last => Last); -- If the encoded has not used all the data, update the position for the next run. if Last_Encoded /= Size then Next_Pos := Next_Pos - Natural (Size - Last_Encoded + 1); end if; -- The encoder cannot encode the data if Pos = Next_Pos then raise Encoding_Error with "Encoding cannot proceed"; end if; First := Last; Pos := Next_Pos; end; end loop; if Pos <= Data'Last then raise Encoding_Error with "Not enough space for encoding"; end if; end Transform; -- ------------------------------ -- Transform the input string <b>Data</b> using the transformation -- rules provided by the <b>E</b> transformer. -- -- Returns the transformed string. -- -- Raises the <b>Encoding_Error</b> exception if the source string -- cannot be transformed -- ------------------------------ function Transform (E : in Transformer'Class; Data : in Streams.Stream_Element_Array) return String is Buf_Size : constant Streams.Stream_Element_Offset := Best_Size (Data'Length); Res : Streams.Stream_Element_Array (1 .. Buf_Size); Tmp : String (1 .. Natural (Buf_Size)); Result : Ada.Strings.Unbounded.Unbounded_String; Last_Encoded : Streams.Stream_Element_Offset; Last : Streams.Stream_Element_Offset; begin -- Encode that buffer and put the result in out result string. E.Transform (Data => Data, Into => Res, Encoded => Last_Encoded, Last => Last); for I in 1 .. Last loop Tmp (Natural (I)) := Character'Val (Res (I)); end loop; Append (Result, Tmp (1 .. Natural (Last))); return To_String (Result); end Transform; -- ------------------------------ -- Encode the value represented by <tt>Val</tt> in the stream array <tt>Into</tt> starting -- at position <tt>Pos</tt> in that array. The value is encoded using LEB128 format, 7-bits -- at a time until all non zero bits are written. The <tt>Last</tt> parameter is updated -- to indicate the position of the last valid byte written in <tt>Into</tt>. -- ------------------------------ procedure Encode_LEB128 (Into : in out Ada.Streams.Stream_Element_Array; Pos : in Ada.Streams.Stream_Element_Offset; Val : in Interfaces.Unsigned_64; Last : out Ada.Streams.Stream_Element_Offset) is use type Interfaces.Unsigned_64; P : Ada.Streams.Stream_Element_Offset := Pos; V, U : Interfaces.Unsigned_64; begin V := Val; loop if V < 16#07F# then Into (P) := Ada.Streams.Stream_Element (V); Last := P; return; end if; U := V and 16#07F#; Into (P) := Ada.Streams.Stream_Element (U or 16#80#); P := P + 1; V := Interfaces.Shift_Right (V, 7); end loop; end Encode_LEB128; -- ------------------------------ -- Decode from the byte array <tt>From</tt> the value represented as LEB128 format starting -- at position <tt>Pos</tt> in that array. After decoding, the <tt>Last</tt> index is updated -- to indicate the last position in the byte array. -- ------------------------------ procedure Decode_LEB128 (From : in Ada.Streams.Stream_Element_Array; Pos : in Ada.Streams.Stream_Element_Offset; Val : out Interfaces.Unsigned_64; Last : out Ada.Streams.Stream_Element_Offset) is use type Interfaces.Unsigned_64; use type Interfaces.Unsigned_8; P : Ada.Streams.Stream_Element_Offset := Pos; Value : Interfaces.Unsigned_64 := 0; V : Interfaces.Unsigned_8; Shift : Integer := 0; begin loop V := Interfaces.Unsigned_8 (From (P)); if (V and 16#80#) = 0 then Val := Interfaces.Shift_Left (Interfaces.Unsigned_64 (V), Shift) or Value; Last := P + 1; return; end if; V := V and 16#07F#; Value := Interfaces.Shift_Left (Interfaces.Unsigned_64 (V), Shift) or Value; P := P + 1; Shift := Shift + 7; end loop; end Decode_LEB128; -- ------------------------------ -- Create the encoder object for the specified algorithm. -- ------------------------------ function Create (Name : String) return Encoder is begin if Name = BASE_16 or Name = HEX then return E : Encoder do E.Encode := new Util.Encoders.Base16.Encoder; E.Decode := new Util.Encoders.Base16.Decoder; end return; elsif Name = BASE_64 then return E : Encoder do E.Encode := new Util.Encoders.Base64.Encoder; E.Decode := new Util.Encoders.Base64.Decoder; end return; elsif Name = BASE_64_URL then return E : Encoder do E.Encode := Util.Encoders.Base64.Create_URL_Encoder; E.Decode := Util.Encoders.Base64.Create_URL_Decoder; end return; elsif Name = HASH_SHA1 then return E : Encoder do E.Encode := new Util.Encoders.SHA1.Encoder; E.Decode := new Util.Encoders.Base64.Decoder; end return; end if; raise Not_Supported with "Invalid encoder: " & Name; end Create; -- ------------------------------ -- Delete the transformers -- ------------------------------ overriding procedure Finalize (E : in out Encoder) is procedure Free is new Ada.Unchecked_Deallocation (Transformer'Class, Transformer_Access); begin Free (E.Encode); Free (E.Decode); end Finalize; end Util.Encoders;
----------------------------------------------------------------------- -- util-encoders -- Encode/Decode streams and strings from one format to another -- Copyright (C) 2009, 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 Ada.Strings.Unbounded; with Ada.Unchecked_Deallocation; with Util.Encoders.Base16; with Util.Encoders.Base64; with Util.Encoders.SHA1; package body Util.Encoders is use Ada; use Ada.Strings.Unbounded; use type Ada.Streams.Stream_Element_Offset; -- ------------------------------ -- Encodes the input string <b>Data</b> using the transformation -- rules provided by the <b>E</b> encoder. -- -- Returns the encoded string. -- -- Raises the <b>Encoding_Error</b> exception if the source string -- cannot be encoded. -- Raises the <b>Not_Supported</b> exception if the encoding is not -- supported. -- ------------------------------ function Encode (E : in Encoder; Data : in String) return String is begin if E.Encode = null then raise Not_Supported with "There is no encoder"; end if; return E.Encode.Transform (Data); end Encode; -- ------------------------------ -- Decodes the input string <b>Data</b> using the transformation -- rules provided by the <b>E</b> encoder. -- -- Returns the encoded string. -- -- Raises the <b>Encoding_Error</b> exception if the source string -- cannot be decoded. -- Raises the <b>Not_Supported</b> exception if the decoding is not -- supported. -- ------------------------------ function Decode (E : in Encoder; Data : in String) return String is begin if E.Decode = null then raise Not_Supported with "There is no decoder"; end if; return E.Decode.Transform (Data); end Decode; MIN_BUFFER_SIZE : constant Streams.Stream_Element_Offset := 64; MAX_BUFFER_SIZE : constant Streams.Stream_Element_Offset := 2_048; function Best_Size (Length : Natural) return Streams.Stream_Element_Offset; pragma Inline (Best_Size); -- ------------------------------ -- Compute a good size for allocating a buffer on the stack -- ------------------------------ function Best_Size (Length : Natural) return Streams.Stream_Element_Offset is begin if Length < Natural (MIN_BUFFER_SIZE) then return MIN_BUFFER_SIZE; elsif Length > Natural (MAX_BUFFER_SIZE) then return MAX_BUFFER_SIZE; else return Streams.Stream_Element_Offset (((Length + 15) / 16) * 16); end if; end Best_Size; -- ------------------------------ -- Transform the input string <b>Data</b> using the transformation -- rules provided by the <b>E</b> transformer. -- -- Returns the transformed string. -- -- Raises the <b>Encoding_Error</b> exception if the source string -- cannot be transformed -- ------------------------------ function Transform (E : in out Transformer'Class; Data : in String) return String is Buf_Size : constant Streams.Stream_Element_Offset := Best_Size (Data'Length); Buf : Streams.Stream_Element_Array (1 .. Buf_Size); Res : Streams.Stream_Element_Array (1 .. Buf_Size); Tmp : String (1 .. Natural (Buf_Size)); Result : Ada.Strings.Unbounded.Unbounded_String; Pos : Natural := Data'First; begin while Pos <= Data'Last loop declare Last_Encoded : Streams.Stream_Element_Offset; First_Encoded : Streams.Stream_Element_Offset := 1; Last : Streams.Stream_Element_Offset; Size : Streams.Stream_Element_Offset; Next_Pos : Natural; begin -- Fill the stream buffer with our input string Size := Streams.Stream_Element_Offset (Data'Last - Pos + 1); if Size > Buf'Length then Size := Buf'Length; end if; for I in 1 .. Size loop Buf (I) := Character'Pos (Data (Natural (I) + Pos - 1)); end loop; Next_Pos := Pos + Natural (Size); -- Encode that buffer and put the result in out result string. loop E.Transform (Data => Buf (First_Encoded .. Size), Into => Res, Encoded => Last_Encoded, Last => Last); -- If the encoder generated nothing, move the position backward -- to take into account the remaining bytes not taken into account. if Last < 1 then Next_Pos := Next_Pos - Natural (Size - First_Encoded + 1); exit; end if; for I in 1 .. Last loop Tmp (Natural (I)) := Character'Val (Res (I)); end loop; Append (Result, Tmp (1 .. Natural (Last))); exit when Last_Encoded = Size; First_Encoded := Last_Encoded + 1; end loop; -- The encoder cannot encode the data if Pos = Next_Pos then raise Encoding_Error with "Encoding cannot proceed"; end if; Pos := Next_Pos; end; end loop; return To_String (Result); end Transform; -- ------------------------------ -- Transform the input string <b>Data</b> using the transformation -- rules provided by the <b>E</b> transformer and return the data in -- the <b>Into</b> array, setting <b>Last</b> to the last index. -- -- Raises the <b>Encoding_Error</b> exception if the source string -- cannot be transformed -- ------------------------------ procedure Transform (E : in out Transformer'Class; Data : in String; Into : out Ada.Streams.Stream_Element_Array; Last : out Ada.Streams.Stream_Element_Offset) is Buf_Size : constant Streams.Stream_Element_Offset := Best_Size (Data'Length); Buf : Streams.Stream_Element_Array (1 .. Buf_Size); Pos : Natural := Data'First; First : Streams.Stream_Element_Offset := Into'First; begin Last := Into'First - 1; while Pos <= Data'Last and Last < Into'Last loop declare Last_Encoded : Streams.Stream_Element_Offset; Size : Streams.Stream_Element_Offset; Next_Pos : Natural; begin -- Fill the stream buffer with our input string Size := Streams.Stream_Element_Offset (Data'Last - Pos + 1); if Size > Buf'Length then Size := Buf'Length; end if; for I in 1 .. Size loop Buf (I) := Character'Pos (Data (Natural (I) + Pos - 1)); end loop; Next_Pos := Pos + Natural (Size); -- Encode that buffer and put the result in the output data array. E.Transform (Data => Buf (1 .. Size), Into => Into (First .. Into'Last), Encoded => Last_Encoded, Last => Last); -- If the encoded has not used all the data, update the position for the next run. if Last_Encoded /= Size then Next_Pos := Next_Pos - Natural (Size - Last_Encoded + 1); end if; -- The encoder cannot encode the data if Pos = Next_Pos then raise Encoding_Error with "Encoding cannot proceed"; end if; First := Last; Pos := Next_Pos; end; end loop; if Pos <= Data'Last then raise Encoding_Error with "Not enough space for encoding"; end if; end Transform; -- ------------------------------ -- Transform the input string <b>Data</b> using the transformation -- rules provided by the <b>E</b> transformer. -- -- Returns the transformed string. -- -- Raises the <b>Encoding_Error</b> exception if the source string -- cannot be transformed -- ------------------------------ function Transform (E : in out Transformer'Class; Data : in Streams.Stream_Element_Array) return String is Buf_Size : constant Streams.Stream_Element_Offset := Best_Size (Data'Length); Res : Streams.Stream_Element_Array (1 .. Buf_Size); Tmp : String (1 .. Natural (Buf_Size)); Result : Ada.Strings.Unbounded.Unbounded_String; Last_Encoded : Streams.Stream_Element_Offset; Last : Streams.Stream_Element_Offset; begin -- Encode that buffer and put the result in out result string. E.Transform (Data => Data, Into => Res, Encoded => Last_Encoded, Last => Last); for I in 1 .. Last loop Tmp (Natural (I)) := Character'Val (Res (I)); end loop; Append (Result, Tmp (1 .. Natural (Last))); return To_String (Result); end Transform; -- ------------------------------ -- Encode the value represented by <tt>Val</tt> in the stream array <tt>Into</tt> starting -- at position <tt>Pos</tt> in that array. The value is encoded using LEB128 format, 7-bits -- at a time until all non zero bits are written. The <tt>Last</tt> parameter is updated -- to indicate the position of the last valid byte written in <tt>Into</tt>. -- ------------------------------ procedure Encode_LEB128 (Into : in out Ada.Streams.Stream_Element_Array; Pos : in Ada.Streams.Stream_Element_Offset; Val : in Interfaces.Unsigned_64; Last : out Ada.Streams.Stream_Element_Offset) is use type Interfaces.Unsigned_64; P : Ada.Streams.Stream_Element_Offset := Pos; V, U : Interfaces.Unsigned_64; begin V := Val; loop if V < 16#07F# then Into (P) := Ada.Streams.Stream_Element (V); Last := P; return; end if; U := V and 16#07F#; Into (P) := Ada.Streams.Stream_Element (U or 16#80#); P := P + 1; V := Interfaces.Shift_Right (V, 7); end loop; end Encode_LEB128; -- ------------------------------ -- Decode from the byte array <tt>From</tt> the value represented as LEB128 format starting -- at position <tt>Pos</tt> in that array. After decoding, the <tt>Last</tt> index is updated -- to indicate the last position in the byte array. -- ------------------------------ procedure Decode_LEB128 (From : in Ada.Streams.Stream_Element_Array; Pos : in Ada.Streams.Stream_Element_Offset; Val : out Interfaces.Unsigned_64; Last : out Ada.Streams.Stream_Element_Offset) is use type Interfaces.Unsigned_64; use type Interfaces.Unsigned_8; P : Ada.Streams.Stream_Element_Offset := Pos; Value : Interfaces.Unsigned_64 := 0; V : Interfaces.Unsigned_8; Shift : Integer := 0; begin loop V := Interfaces.Unsigned_8 (From (P)); if (V and 16#80#) = 0 then Val := Interfaces.Shift_Left (Interfaces.Unsigned_64 (V), Shift) or Value; Last := P + 1; return; end if; V := V and 16#07F#; Value := Interfaces.Shift_Left (Interfaces.Unsigned_64 (V), Shift) or Value; P := P + 1; Shift := Shift + 7; end loop; end Decode_LEB128; -- ------------------------------ -- Create the encoder object for the specified algorithm. -- ------------------------------ function Create (Name : String) return Encoder is begin if Name = BASE_16 or Name = HEX then return E : Encoder do E.Encode := new Util.Encoders.Base16.Encoder; E.Decode := new Util.Encoders.Base16.Decoder; end return; elsif Name = BASE_64 then return E : Encoder do E.Encode := new Util.Encoders.Base64.Encoder; E.Decode := new Util.Encoders.Base64.Decoder; end return; elsif Name = BASE_64_URL then return E : Encoder do E.Encode := Util.Encoders.Base64.Create_URL_Encoder; E.Decode := Util.Encoders.Base64.Create_URL_Decoder; end return; elsif Name = HASH_SHA1 then return E : Encoder do E.Encode := new Util.Encoders.SHA1.Encoder; E.Decode := new Util.Encoders.Base64.Decoder; end return; end if; raise Not_Supported with "Invalid encoder: " & Name; end Create; -- ------------------------------ -- Delete the transformers -- ------------------------------ overriding procedure Finalize (E : in out Encoder) is procedure Free is new Ada.Unchecked_Deallocation (Transformer'Class, Transformer_Access); begin Free (E.Encode); Free (E.Decode); end Finalize; end Util.Encoders;
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
1189e4e81af8f77a3a294afdf6e992409c479b99
mat/src/mat-formats.adb
mat/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"; -- ------------------------------ -- 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 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 : 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 (Msec)) & 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 a short description of the event. -- ------------------------------ function Event (Item : in MAT.Events.Targets.Probe_Event_Type) return String is begin case Item.Index is when MAT.Events.Targets.MSG_MALLOC => return "malloc(" & Size (Item.Size) & ") = " & Addr (Item.Addr); when MAT.Events.Targets.MSG_REALLOC => return "realloc(" & Addr (Item.Old_Addr) & "," & Size (Item.Size) & ") = " & Addr (Item.Addr); when MAT.Events.Targets.MSG_FREE => return "free(" & Addr (Item.Addr) & ")"; when MAT.Events.Targets.MSG_BEGIN => return "begin"; when MAT.Events.Targets.MSG_END => return "end"; when MAT.Events.Targets.MSG_LIBRARY => return "library"; when others => return "unknown"; end case; end Event; function Event_Malloc (Item : in MAT.Events.Targets.Probe_Event_Type; Related : in MAT.Events.Targets.Target_Event_Vector; Start_Time : in MAT.Types.Target_Tick_Ref) return String is Iter : MAT.Events.Targets.Target_Event_Cursor := Related.First; Free_Event : MAT.Events.Targets.Probe_Event_Type; begin Free_Event := MAT.Events.Targets.Find (Related, MAT.Events.Targets.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.Targets.Event_Id_Type'Image (Free_Event.Id) ; exception when MAT.Events.Targets.Not_Found => return Size (Item.Size) & " bytes allocated (never freed)"; end Event_Malloc; function Event_Free (Item : in MAT.Events.Targets.Probe_Event_Type; Related : in MAT.Events.Targets.Target_Event_Vector; Start_Time : in MAT.Types.Target_Tick_Ref) return String is Iter : MAT.Events.Targets.Target_Event_Cursor := Related.First; Alloc_Event : MAT.Events.Targets.Probe_Event_Type; begin Alloc_Event := MAT.Events.Targets.Find (Related, MAT.Events.Targets.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.Targets.Event_Id_Type'Image (Alloc_Event.Id) ; exception when MAT.Events.Targets.Not_Found => return Size (Item.Size) & " bytes freed"; end Event_Free; -- Format a short description of the event. function Event (Item : in MAT.Events.Targets.Probe_Event_Type; Related : in MAT.Events.Targets.Target_Event_Vector; Start_Time : in MAT.Types.Target_Tick_Ref) return String is begin case Item.Index is when MAT.Events.Targets.MSG_MALLOC => return Event_Malloc (Item, Related, Start_Time); when MAT.Events.Targets.MSG_REALLOC => return Size (Item.Size) & " bytes reallocated"; when MAT.Events.Targets.MSG_FREE => return Event_Free (Item, Related, Start_Time); when MAT.Events.Targets.MSG_BEGIN => return "Begin event"; when MAT.Events.Targets.MSG_END => return "End event"; when MAT.Events.Targets.MSG_LIBRARY => return "Library information event"; when others => return "unknown"; 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.Targets.Probe_Event_Type; Related : in MAT.Events.Targets.Target_Event_Vector; Start_Time : in MAT.Types.Target_Tick_Ref) return String; function Event_Free (Item : in MAT.Events.Targets.Probe_Event_Type; Related : in MAT.Events.Targets.Target_Event_Vector; Start_Time : in MAT.Types.Target_Tick_Ref) return String; -- ------------------------------ -- 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 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 (Msec)) & 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 a short description of the event. -- ------------------------------ function Event (Item : in MAT.Events.Targets.Probe_Event_Type) return String is begin case Item.Index is when MAT.Events.Targets.MSG_MALLOC => return "malloc(" & Size (Item.Size) & ") = " & Addr (Item.Addr); when MAT.Events.Targets.MSG_REALLOC => return "realloc(" & Addr (Item.Old_Addr) & "," & Size (Item.Size) & ") = " & Addr (Item.Addr); when MAT.Events.Targets.MSG_FREE => return "free(" & Addr (Item.Addr) & ")"; when MAT.Events.Targets.MSG_BEGIN => return "begin"; when MAT.Events.Targets.MSG_END => return "end"; when MAT.Events.Targets.MSG_LIBRARY => return "library"; end case; end Event; function Event_Malloc (Item : in MAT.Events.Targets.Probe_Event_Type; Related : in MAT.Events.Targets.Target_Event_Vector; Start_Time : in MAT.Types.Target_Tick_Ref) return String is Free_Event : MAT.Events.Targets.Probe_Event_Type; begin Free_Event := MAT.Events.Targets.Find (Related, MAT.Events.Targets.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.Targets.Event_Id_Type'Image (Free_Event.Id) ; exception when MAT.Events.Targets.Not_Found => return Size (Item.Size) & " bytes allocated (never freed)"; end Event_Malloc; function Event_Free (Item : in MAT.Events.Targets.Probe_Event_Type; Related : in MAT.Events.Targets.Target_Event_Vector; Start_Time : in MAT.Types.Target_Tick_Ref) return String is Alloc_Event : MAT.Events.Targets.Probe_Event_Type; begin Alloc_Event := MAT.Events.Targets.Find (Related, MAT.Events.Targets.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.Targets.Event_Id_Type'Image (Alloc_Event.Id); exception when MAT.Events.Targets.Not_Found => return Size (Item.Size) & " bytes freed"; end Event_Free; -- ------------------------------ -- Format a short description of the event. -- ------------------------------ function Event (Item : in MAT.Events.Targets.Probe_Event_Type; Related : in MAT.Events.Targets.Target_Event_Vector; Start_Time : in MAT.Types.Target_Tick_Ref) return String is begin case Item.Index is when MAT.Events.Targets.MSG_MALLOC => return Event_Malloc (Item, Related, Start_Time); when MAT.Events.Targets.MSG_REALLOC => return Size (Item.Size) & " bytes reallocated"; when MAT.Events.Targets.MSG_FREE => return Event_Free (Item, Related, Start_Time); when MAT.Events.Targets.MSG_BEGIN => return "Begin event"; when MAT.Events.Targets.MSG_END => return "End event"; when MAT.Events.Targets.MSG_LIBRARY => return "Library information event"; end case; end Event; end MAT.Formats;
Fix compilation warnings
Fix compilation warnings
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
d56f5b9693dc412b1635ab0011d3a1848d1f5308
src/ado-sessions-factory.adb
src/ado-sessions-factory.adb
----------------------------------------------------------------------- -- factory -- Session Factory -- Copyright (C) 2009, 2010, 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with ADO.Sequences.Hilo; with Ada.Unchecked_Deallocation; -- The <b>ADO.Sessions.Factory</b> package defines the factory for creating -- sessions. package body ADO.Sessions.Factory is use ADO.Databases; -- ------------------------------ -- Open a session -- ------------------------------ procedure Open_Session (Factory : in out Session_Factory; Database : out Session) is S : constant Session_Record_Access := new Session_Record; DB : constant Master_Connection'Class := Factory.Source.Get_Connection; begin S.Database := Master_Connection (DB); S.Entities := Factory.Entities; Database.Impl := S; end Open_Session; -- ------------------------------ -- Get a read-only session from the factory. -- ------------------------------ function Get_Session (Factory : in Session_Factory) return Session is R : Session; S : constant Session_Record_Access := new Session_Record; DB : constant Master_Connection'Class := Factory.Source.Get_Connection; begin S.Database := Master_Connection (DB); S.Entities := Factory.Entities; R.Impl := S; return R; end Get_Session; -- ------------------------------ -- Get a read-only session from the session proxy. -- If the session has been invalidated, raise the SESSION_EXPIRED exception. -- ------------------------------ function Get_Session (Proxy : in Session_Proxy_Access) return Session is R : Session; begin if Proxy = null then raise ADO.Objects.SESSION_EXPIRED; end if; if Proxy.Session = null then raise ADO.Objects.SESSION_EXPIRED; end if; R.Impl := Proxy.Session; R.Impl.Counter := R.Impl.Counter + 1; return R; end Get_Session; -- ------------------------------ -- Get a read-only session from the session proxy. -- If the session has been invalidated, raise the SESSION_EXPIRED exception. -- ------------------------------ function Get_Session (Proxy : in Session_Record_Access) return Session is R : Session; begin if Proxy = null then raise ADO.Objects.SESSION_EXPIRED; end if; -- if Proxy.Session = null then -- raise ADO.Objects.SESSION_EXPIRED; -- end if; R.Impl := Proxy; R.Impl.Counter := R.Impl.Counter + 1; return R; end Get_Session; -- ------------------------------ -- Get a read-write session from the factory. -- ------------------------------ function Get_Master_Session (Factory : in Session_Factory) return Master_Session is R : Master_Session; S : constant Session_Record_Access := new Session_Record; DB : constant Master_Connection'Class := Factory.Source.Get_Connection; begin S.Database := Master_Connection (DB); S.Entities := Factory.Entities; R.Impl := S; R.Sequences := Factory.Sequences; return R; end Get_Master_Session; -- ------------------------------ -- Open a session -- ------------------------------ procedure Open_Session (Factory : in Session_Factory; Database : out Master_Session) is begin null; end Open_Session; -- ------------------------------ -- Initialize the sequence factory associated with the session factory. -- ------------------------------ procedure Initialize_Sequences (Factory : in out Session_Factory) is use ADO.Sequences; begin Factory.Sequences := Factory.Seq_Factory'Unchecked_Access; Set_Default_Generator (Factory.Seq_Factory, ADO.Sequences.Hilo.Create_HiLo_Generator'Access, Factory'Unchecked_Access); end Initialize_Sequences; -- ------------------------------ -- Create the session factory to connect to the database represented -- by the data source. -- ------------------------------ procedure Create (Factory : out Session_Factory; Source : in ADO.Databases.DataSource) is begin Factory.Source := Source; Factory.Entities := Factory.Entity_Cache'Unchecked_Access; Initialize_Sequences (Factory); if Factory.Source.Get_Database /= "" then declare S : Session := Factory.Get_Session; begin ADO.Schemas.Entities.Initialize (Factory.Entity_Cache, S); end; end if; end Create; -- ------------------------------ -- Create the session factory to connect to the database identified -- by the URI. -- ------------------------------ procedure Create (Factory : out Session_Factory; URI : in String) is begin Factory.Source.Set_Connection (URI); Factory.Entities := Factory.Entity_Cache'Unchecked_Access; Initialize_Sequences (Factory); if Factory.Source.Get_Database /= "" then declare S : Session := Factory.Get_Session; begin ADO.Schemas.Entities.Initialize (Factory.Entity_Cache, S); end; end if; end Create; end ADO.Sessions.Factory;
----------------------------------------------------------------------- -- factory -- Session Factory -- Copyright (C) 2009, 2010, 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with ADO.Sequences.Hilo; with Ada.Unchecked_Deallocation; -- The <b>ADO.Sessions.Factory</b> package defines the factory for creating -- sessions. package body ADO.Sessions.Factory is use ADO.Databases; -- ------------------------------ -- Open a session -- ------------------------------ procedure Open_Session (Factory : in out Session_Factory; Database : out Session) is S : constant Session_Record_Access := new Session_Record; DB : constant Master_Connection'Class := Factory.Source.Get_Connection; begin S.Database := Master_Connection (DB); S.Entities := Factory.Entities; Database.Impl := S; end Open_Session; -- ------------------------------ -- Get a read-only session from the factory. -- ------------------------------ function Get_Session (Factory : in Session_Factory) return Session is R : Session; S : constant Session_Record_Access := new Session_Record; DB : constant Master_Connection'Class := Factory.Source.Get_Connection; begin S.Database := Master_Connection (DB); S.Entities := Factory.Entities; R.Impl := S; return R; end Get_Session; -- ------------------------------ -- Get a read-only session from the session proxy. -- If the session has been invalidated, raise the SESSION_EXPIRED exception. -- ------------------------------ function Get_Session (Proxy : in Session_Proxy_Access) return Session is R : Session; begin if Proxy = null then raise ADO.Objects.SESSION_EXPIRED; end if; if Proxy.Session = null then raise ADO.Objects.SESSION_EXPIRED; end if; R.Impl := Proxy.Session; R.Impl.Counter := R.Impl.Counter + 1; return R; end Get_Session; -- ------------------------------ -- Get a read-only session from the session proxy. -- If the session has been invalidated, raise the SESSION_EXPIRED exception. -- ------------------------------ function Get_Session (Proxy : in Session_Record_Access) return Session is R : Session; begin if Proxy = null then raise ADO.Objects.SESSION_EXPIRED; end if; -- if Proxy.Session = null then -- raise ADO.Objects.SESSION_EXPIRED; -- end if; R.Impl := Proxy; R.Impl.Counter := R.Impl.Counter + 1; return R; end Get_Session; -- ------------------------------ -- Get a read-write session from the factory. -- ------------------------------ function Get_Master_Session (Factory : in Session_Factory) return Master_Session is R : Master_Session; DB : constant Master_Connection'Class := Factory.Source.Get_Connection; S : constant Session_Record_Access := new Session_Record; begin R.Impl := S; R.Sequences := Factory.Sequences; S.Database := Master_Connection (DB); S.Entities := Factory.Entities; return R; end Get_Master_Session; -- ------------------------------ -- Open a session -- ------------------------------ procedure Open_Session (Factory : in Session_Factory; Database : out Master_Session) is begin null; end Open_Session; -- ------------------------------ -- Initialize the sequence factory associated with the session factory. -- ------------------------------ procedure Initialize_Sequences (Factory : in out Session_Factory) is use ADO.Sequences; begin Factory.Sequences := Factory.Seq_Factory'Unchecked_Access; Set_Default_Generator (Factory.Seq_Factory, ADO.Sequences.Hilo.Create_HiLo_Generator'Access, Factory'Unchecked_Access); end Initialize_Sequences; -- ------------------------------ -- Create the session factory to connect to the database represented -- by the data source. -- ------------------------------ procedure Create (Factory : out Session_Factory; Source : in ADO.Databases.DataSource) is begin Factory.Source := Source; Factory.Entities := Factory.Entity_Cache'Unchecked_Access; Initialize_Sequences (Factory); if Factory.Source.Get_Database /= "" then declare S : Session := Factory.Get_Session; begin ADO.Schemas.Entities.Initialize (Factory.Entity_Cache, S); end; end if; end Create; -- ------------------------------ -- Create the session factory to connect to the database identified -- by the URI. -- ------------------------------ procedure Create (Factory : out Session_Factory; URI : in String) is begin Factory.Source.Set_Connection (URI); Factory.Entities := Factory.Entity_Cache'Unchecked_Access; Initialize_Sequences (Factory); if Factory.Source.Get_Database /= "" then declare S : Session := Factory.Get_Session; begin ADO.Schemas.Entities.Initialize (Factory.Entity_Cache, S); end; end if; end Create; end ADO.Sessions.Factory;
Fix possible memory leak if the connection cannot be obtained: create the Session_Record only after having created the database connection.
Fix possible memory leak if the connection cannot be obtained: create the Session_Record only after having created the database connection.
Ada
apache-2.0
Letractively/ada-ado
6772547b2c98e2fb4a97338da99ffae5faa787c3
src/ado-sessions-factory.adb
src/ado-sessions-factory.adb
----------------------------------------------------------------------- -- factory -- Session Factory -- Copyright (C) 2009, 2010, 2011, 2012, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with ADO.Sequences.Hilo; -- The <b>ADO.Sessions.Factory</b> package defines the factory for creating -- sessions. package body ADO.Sessions.Factory is use ADO.Databases; -- ------------------------------ -- Open a session -- ------------------------------ procedure Open_Session (Factory : in out Session_Factory; Database : out Session) is S : constant Session_Record_Access := new Session_Record; DB : constant Master_Connection'Class := Factory.Source.Get_Connection; begin S.Database := Master_Connection (DB); S.Entities := Factory.Entities; S.Values := Factory.Cache_Values; Database.Impl := S; end Open_Session; -- ------------------------------ -- Get a read-only session from the factory. -- ------------------------------ function Get_Session (Factory : in Session_Factory) return Session is R : Session; S : constant Session_Record_Access := new Session_Record; DB : constant Master_Connection'Class := Factory.Source.Get_Connection; begin S.Database := Master_Connection (DB); S.Entities := Factory.Entities; S.Values := Factory.Cache_Values; R.Impl := S; return R; end Get_Session; -- ------------------------------ -- Get a read-only session from the session proxy. -- If the session has been invalidated, raise the SESSION_EXPIRED exception. -- ------------------------------ function Get_Session (Proxy : in Session_Record_Access) return Session is R : Session; begin if Proxy = null then raise ADO.Objects.SESSION_EXPIRED; end if; R.Impl := Proxy; Util.Concurrent.Counters.Increment (R.Impl.Counter); return R; end Get_Session; -- ------------------------------ -- Get a read-write session from the factory. -- ------------------------------ function Get_Master_Session (Factory : in Session_Factory) return Master_Session is R : Master_Session; DB : constant Master_Connection'Class := Factory.Source.Get_Connection; S : constant Session_Record_Access := new Session_Record; begin R.Impl := S; R.Sequences := Factory.Sequences; S.Database := Master_Connection (DB); S.Entities := Factory.Entities; S.Values := Factory.Cache_Values; return R; end Get_Master_Session; -- ------------------------------ -- Open a session -- ------------------------------ procedure Open_Session (Factory : in Session_Factory; Database : out Master_Session) is begin null; end Open_Session; -- ------------------------------ -- Initialize the sequence factory associated with the session factory. -- ------------------------------ procedure Initialize_Sequences (Factory : in out Session_Factory) is use ADO.Sequences; begin Factory.Sequences := Factory.Seq_Factory'Unchecked_Access; Set_Default_Generator (Factory.Seq_Factory, ADO.Sequences.Hilo.Create_HiLo_Generator'Access, Factory'Unchecked_Access); end Initialize_Sequences; -- ------------------------------ -- Create the session factory to connect to the database represented -- by the data source. -- ------------------------------ procedure Create (Factory : out Session_Factory; Source : in ADO.Databases.DataSource) is begin Factory.Source := Source; Factory.Entities := new ADO.Schemas.Entities.Entity_Cache; Factory.Cache_Values := Factory.Cache'Unchecked_Access; Factory.Cache.Add_Cache (ENTITY_CACHE_NAME, Factory.Entities.all'Access); Initialize_Sequences (Factory); if Factory.Source.Get_Database /= "" then declare S : Session := Factory.Get_Session; begin ADO.Schemas.Entities.Initialize (Factory.Entities.all, S); end; end if; end Create; -- ------------------------------ -- Create the session factory to connect to the database identified -- by the URI. -- ------------------------------ procedure Create (Factory : out Session_Factory; URI : in String) is begin Factory.Source.Set_Connection (URI); Factory.Entities := new ADO.Schemas.Entities.Entity_Cache; Factory.Cache_Values := Factory.Cache'Unchecked_Access; Factory.Cache.Add_Cache (ENTITY_CACHE_NAME, Factory.Entities.all'Access); Initialize_Sequences (Factory); if Factory.Source.Get_Database /= "" then declare S : Session := Factory.Get_Session; begin ADO.Schemas.Entities.Initialize (Factory.Entities.all, S); end; end if; end Create; end ADO.Sessions.Factory;
----------------------------------------------------------------------- -- factory -- Session Factory -- Copyright (C) 2009, 2010, 2011, 2012, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with ADO.Sequences.Hilo; package body ADO.Sessions.Factory is -- ------------------------------ -- Open a session -- ------------------------------ procedure Open_Session (Factory : in out Session_Factory; Database : out Session) is S : constant Session_Record_Access := new Session_Record; begin Factory.Source.Create_Connection (S.Database); S.Entities := Factory.Entities; S.Values := Factory.Cache_Values; Database.Impl := S; end Open_Session; -- ------------------------------ -- Get a read-only session from the factory. -- ------------------------------ function Get_Session (Factory : in Session_Factory) return Session is R : Session; S : constant Session_Record_Access := new Session_Record; begin Factory.Source.Create_Connection (S.Database); S.Entities := Factory.Entities; S.Values := Factory.Cache_Values; R.Impl := S; return R; end Get_Session; -- ------------------------------ -- Get a read-only session from the session proxy. -- If the session has been invalidated, raise the SESSION_EXPIRED exception. -- ------------------------------ function Get_Session (Proxy : in Session_Record_Access) return Session is R : Session; begin if Proxy = null then raise ADO.Objects.SESSION_EXPIRED; end if; R.Impl := Proxy; Util.Concurrent.Counters.Increment (R.Impl.Counter); return R; end Get_Session; -- ------------------------------ -- Get a read-write session from the factory. -- ------------------------------ function Get_Master_Session (Factory : in Session_Factory) return Master_Session is R : Master_Session; S : constant Session_Record_Access := new Session_Record; begin R.Impl := S; R.Sequences := Factory.Sequences; Factory.Source.Create_Connection (S.Database); S.Entities := Factory.Entities; S.Values := Factory.Cache_Values; return R; end Get_Master_Session; -- ------------------------------ -- Open a session -- ------------------------------ procedure Open_Session (Factory : in Session_Factory; Database : out Master_Session) is begin null; end Open_Session; -- ------------------------------ -- Initialize the sequence factory associated with the session factory. -- ------------------------------ procedure Initialize_Sequences (Factory : in out Session_Factory) is use ADO.Sequences; begin Factory.Sequences := Factory.Seq_Factory'Unchecked_Access; Set_Default_Generator (Factory.Seq_Factory, ADO.Sequences.Hilo.Create_HiLo_Generator'Access, Factory'Unchecked_Access); end Initialize_Sequences; -- ------------------------------ -- Create the session factory to connect to the database represented -- by the data source. -- ------------------------------ procedure Create (Factory : out Session_Factory; Source : in ADO.Sessions.Sources.Data_Source) is begin Factory.Source := Source; Factory.Entities := new ADO.Schemas.Entities.Entity_Cache; Factory.Cache_Values := Factory.Cache'Unchecked_Access; Factory.Cache.Add_Cache (ENTITY_CACHE_NAME, Factory.Entities.all'Access); Initialize_Sequences (Factory); if Factory.Source.Get_Database /= "" then declare S : Session := Factory.Get_Session; begin ADO.Schemas.Entities.Initialize (Factory.Entities.all, S); end; end if; end Create; -- ------------------------------ -- Create the session factory to connect to the database identified -- by the URI. -- ------------------------------ procedure Create (Factory : out Session_Factory; URI : in String) is begin Factory.Source.Set_Connection (URI); Factory.Entities := new ADO.Schemas.Entities.Entity_Cache; Factory.Cache_Values := Factory.Cache'Unchecked_Access; Factory.Cache.Add_Cache (ENTITY_CACHE_NAME, Factory.Entities.all'Access); Initialize_Sequences (Factory); if Factory.Source.Get_Database /= "" then declare S : Session := Factory.Get_Session; begin ADO.Schemas.Entities.Initialize (Factory.Entities.all, S); end; end if; end Create; end ADO.Sessions.Factory;
Refactor the session management and use the data source types in ADO.Sessions.Sources
Refactor the session management and use the data source types in ADO.Sessions.Sources
Ada
apache-2.0
stcarrez/ada-ado
81b84d90dd28356cf732ee36e17be3796b9cc1e9
src/gen-artifacts-docs.ads
src/gen-artifacts-docs.ads
----------------------------------------------------------------------- -- gen-artifacts-docs -- Artifact for documentation -- Copyright (C) 2012, 2015, 2017, 2018, 2019 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Containers.Indefinite_Vectors; with Ada.Containers.Indefinite_Hashed_Maps; with Ada.Strings.Hash; with Ada.Strings.Unbounded; with Ada.Text_IO; with Gen.Model.Packages; private with Util.Strings.Maps; -- with Asis; -- with Asis.Text; -- with Asis.Elements; -- with Asis.Exceptions; -- with Asis.Errors; -- with Asis.Implementation; -- with Asis.Elements; -- with Asis.Declarations; -- The <b>Gen.Artifacts.Docs</b> package is an artifact for the generation of -- application documentation. Its purpose is to scan the project source files -- and extract some interesting information for a developer's guide. The artifact -- scans the Ada source files, the XML configuration files, the XHTML files. -- -- The generated documentation is intended to be published on a web site. -- The Google Wiki style is generated by default. -- -- 1/ In the first step, the project files are scanned and the useful -- documentation is extracted. -- -- 2/ In the second step, the documentation is merged and reconciled. Links to -- documentation pages and references are setup and the final pages are generated. -- -- Ada -- --- -- The documentation starts at the first '== TITLE ==' marker and finishes before the -- package specification. -- -- XHTML -- ----- -- Same as Ada. -- -- XML Files -- ---------- -- The documentation is part of the XML and the <b>documentation</b> or <b>description</b> -- tags are extracted. package Gen.Artifacts.Docs is -- Tag marker (same as Java). TAG_CHAR : constant Character := '@'; -- Specific tags recognized when analyzing the documentation. TAG_AUTHOR : constant String := "author"; TAG_TITLE : constant String := "title"; TAG_INCLUDE : constant String := "include"; TAG_INCLUDE_CONFIG : constant String := "include-config"; TAG_INCLUDE_BEAN : constant String := "include-bean"; TAG_INCLUDE_QUERY : constant String := "include-query"; TAG_INCLUDE_PERM : constant String := "include-permission"; TAG_SEE : constant String := "see"; Unknown_Tag : exception; type Doc_Format is (DOC_MARKDOWN, DOC_WIKI_GOOGLE); -- ------------------------------ -- Documentation artifact -- ------------------------------ type Artifact is new Gen.Artifacts.Artifact with private; -- Prepare the model after all the configuration files have been read and before -- actually invoking the generation. overriding procedure Prepare (Handler : in out Artifact; Model : in out Gen.Model.Packages.Model_Definition'Class; Context : in out Generator'Class); -- Set the output document format to generate. procedure Set_Format (Handler : in out Artifact; Format : in Doc_Format; Footer : in Boolean); -- Load from the file a list of link definitions which can be injected in the generated doc. -- This allows to avoid polluting the Ada code with external links. procedure Read_Links (Handler : in out Artifact; Path : in String); private type Line_Kind is (L_TEXT, L_LIST, L_LIST_ITEM, L_SEE, L_INCLUDE, L_INCLUDE_CONFIG, L_INCLUDE_BEAN, L_INCLUDE_PERMISSION, L_INCLUDE_QUERY, L_START_CODE, L_END_CODE, L_HEADER_1, L_HEADER_2, L_HEADER_3, L_HEADER_4); subtype Line_Include_Kind is Line_Kind range L_INCLUDE .. L_INCLUDE_QUERY; type Line_Type (Len : Natural) is record Kind : Line_Kind := L_TEXT; Content : String (1 .. Len); end record; package Line_Vectors is new Ada.Containers.Indefinite_Vectors (Index_Type => Positive, Element_Type => Line_Type); type Line_Group_Vector is array (Line_Include_Kind) of Line_Vectors.Vector; type Doc_State is (IN_PARA, IN_SEPARATOR, IN_CODE, IN_CODE_SEPARATOR, IN_LIST); type Document_Formatter is abstract tagged record Links : Util.Strings.Maps.Map; end record; type Document_Formatter_Access is access all Document_Formatter'Class; type File_Document is record Name : Ada.Strings.Unbounded.Unbounded_String; Title : Ada.Strings.Unbounded.Unbounded_String; State : Doc_State := IN_PARA; Line_Number : Natural := 0; Lines : Line_Group_Vector; Was_Included : Boolean := False; Print_Footer : Boolean := True; Formatter : Document_Formatter_Access; end record; -- Get the document name from the file document (ex: <name>.wiki or <name>.md). function Get_Document_Name (Formatter : in Document_Formatter; Document : in File_Document) return String is abstract; -- Start a new document. procedure Start_Document (Formatter : in out Document_Formatter; Document : in File_Document; File : in Ada.Text_IO.File_Type) is abstract; -- Write a line in the target document formatting the line if necessary. procedure Write_Line (Formatter : in out Document_Formatter; File : in Ada.Text_IO.File_Type; Line : in Line_Type) is abstract; -- Finish the document. procedure Finish_Document (Formatter : in out Document_Formatter; Document : in File_Document; File : in Ada.Text_IO.File_Type; Source : in String) is abstract; package Doc_Maps is new Ada.Containers.Indefinite_Hashed_Maps (Key_Type => String, Element_Type => File_Document, Hash => Ada.Strings.Hash, Equivalent_Keys => "="); -- Include the document extract represented by <b>Name</b> into the document <b>Into</b>. -- The included document is marked so that it will not be generated. procedure Include (Docs : in out Doc_Maps.Map; Into : in out File_Document; Name : in String; Mode : in Line_Include_Kind; Position : in Natural); -- Generate the project documentation that was collected in <b>Docs</b>. -- The documentation is merged so that the @include tags are replaced by the matching -- document extracts. procedure Generate (Docs : in out Doc_Maps.Map; Dir : in String); -- Returns True if the line indicates a bullet or numbered list. function Is_List (Line : in String) return Boolean; -- Returns True if the line indicates a code sample. function Is_Code (Line : in String) return Boolean; -- Append a raw text line to the document. procedure Append_Line (Doc : in out File_Document; Line : in String); -- Look and analyze the tag defined on the line. procedure Append_Tag (Doc : in out File_Document; Tag : in String); -- Analyse the documentation line and collect the documentation text. procedure Append (Doc : in out File_Document; Line : in String); -- After having collected the documentation, terminate the document by making sure -- the opened elements are closed. procedure Finish (Doc : in out File_Document); -- Set the name associated with the document extract. procedure Set_Name (Doc : in out File_Document; Name : in String); -- Set the title associated with the document extract. procedure Set_Title (Doc : in out File_Document; Title : in String); -- Scan the files in the directory refered to by <b>Path</b> and collect the documentation -- in the <b>Docs</b> hashed map. procedure Scan_Files (Handler : in out Artifact; Path : in String; Docs : in out Doc_Maps.Map); -- Read the Ada specification/body file and collect the useful documentation. -- To keep the implementation simple, we don't use the ASIS packages to scan and extract -- the documentation. We don't need to look at the Ada specification itself. Instead, -- we assume that the Ada source follows some Ada style guidelines. procedure Read_Ada_File (Handler : in out Artifact; File : in String; Result : in out File_Document); procedure Read_Xml_File (Handler : in out Artifact; File : in String; Result : in out File_Document); type Artifact is new Gen.Artifacts.Artifact with record Xslt_Command : Ada.Strings.Unbounded.Unbounded_String; Format : Doc_Format := DOC_WIKI_GOOGLE; Print_Footer : Boolean := True; Formatter : Document_Formatter_Access; end record; end Gen.Artifacts.Docs;
----------------------------------------------------------------------- -- gen-artifacts-docs -- Artifact for documentation -- Copyright (C) 2012, 2015, 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.Containers.Indefinite_Vectors; with Ada.Containers.Indefinite_Hashed_Maps; with Ada.Strings.Hash; with Ada.Strings.Unbounded; with Ada.Text_IO; with Gen.Model.Packages; private with Util.Strings.Maps; -- with Asis; -- with Asis.Text; -- with Asis.Elements; -- with Asis.Exceptions; -- with Asis.Errors; -- with Asis.Implementation; -- with Asis.Elements; -- with Asis.Declarations; -- The <b>Gen.Artifacts.Docs</b> package is an artifact for the generation of -- application documentation. Its purpose is to scan the project source files -- and extract some interesting information for a developer's guide. The artifact -- scans the Ada source files, the XML configuration files, the XHTML files. -- -- The generated documentation is intended to be published on a web site. -- The Google Wiki style is generated by default. -- -- 1/ In the first step, the project files are scanned and the useful -- documentation is extracted. -- -- 2/ In the second step, the documentation is merged and reconciled. Links to -- documentation pages and references are setup and the final pages are generated. -- -- Ada -- --- -- The documentation starts at the first '== TITLE ==' marker and finishes before the -- package specification. -- -- XHTML -- ----- -- Same as Ada. -- -- XML Files -- ---------- -- The documentation is part of the XML and the <b>documentation</b> or <b>description</b> -- tags are extracted. package Gen.Artifacts.Docs is -- Tag marker (same as Java). TAG_CHAR : constant Character := '@'; -- Specific tags recognized when analyzing the documentation. TAG_AUTHOR : constant String := "author"; TAG_TITLE : constant String := "title"; TAG_INCLUDE : constant String := "include"; TAG_INCLUDE_CONFIG : constant String := "include-config"; TAG_INCLUDE_BEAN : constant String := "include-bean"; TAG_INCLUDE_QUERY : constant String := "include-query"; TAG_INCLUDE_PERM : constant String := "include-permission"; TAG_INCLUDE_DOC : constant String := "include-doc"; TAG_SEE : constant String := "see"; Unknown_Tag : exception; type Doc_Format is (DOC_MARKDOWN, DOC_WIKI_GOOGLE); -- ------------------------------ -- Documentation artifact -- ------------------------------ type Artifact is new Gen.Artifacts.Artifact with private; -- Prepare the model after all the configuration files have been read and before -- actually invoking the generation. overriding procedure Prepare (Handler : in out Artifact; Model : in out Gen.Model.Packages.Model_Definition'Class; Context : in out Generator'Class); -- Set the output document format to generate. procedure Set_Format (Handler : in out Artifact; Format : in Doc_Format; Footer : in Boolean); -- Load from the file a list of link definitions which can be injected in the generated doc. -- This allows to avoid polluting the Ada code with external links. procedure Read_Links (Handler : in out Artifact; Path : in String); private type Line_Kind is (L_TEXT, L_LIST, L_LIST_ITEM, L_SEE, L_INCLUDE, L_INCLUDE_CONFIG, L_INCLUDE_BEAN, L_INCLUDE_PERMISSION, L_INCLUDE_QUERY, L_INCLUDE_DOC, L_START_CODE, L_END_CODE, L_HEADER_1, L_HEADER_2, L_HEADER_3, L_HEADER_4); subtype Line_Include_Kind is Line_Kind range L_INCLUDE .. L_INCLUDE_QUERY; type Line_Type (Len : Natural) is record Kind : Line_Kind := L_TEXT; Content : String (1 .. Len); end record; package Line_Vectors is new Ada.Containers.Indefinite_Vectors (Index_Type => Positive, Element_Type => Line_Type); type Line_Group_Vector is array (Line_Include_Kind) of Line_Vectors.Vector; type Doc_State is (IN_PARA, IN_SEPARATOR, IN_CODE, IN_CODE_SEPARATOR, IN_LIST); type Document_Formatter is abstract tagged record Links : Util.Strings.Maps.Map; end record; type Document_Formatter_Access is access all Document_Formatter'Class; type File_Document is record Name : Ada.Strings.Unbounded.Unbounded_String; Title : Ada.Strings.Unbounded.Unbounded_String; State : Doc_State := IN_PARA; Line_Number : Natural := 0; Lines : Line_Group_Vector; Was_Included : Boolean := False; Print_Footer : Boolean := True; Formatter : Document_Formatter_Access; end record; -- Get the document name from the file document (ex: <name>.wiki or <name>.md). function Get_Document_Name (Formatter : in Document_Formatter; Document : in File_Document) return String is abstract; -- Start a new document. procedure Start_Document (Formatter : in out Document_Formatter; Document : in File_Document; File : in Ada.Text_IO.File_Type) is abstract; -- Write a line in the target document formatting the line if necessary. procedure Write_Line (Formatter : in out Document_Formatter; File : in Ada.Text_IO.File_Type; Line : in Line_Type) is abstract; -- Finish the document. procedure Finish_Document (Formatter : in out Document_Formatter; Document : in File_Document; File : in Ada.Text_IO.File_Type; Source : in String) is abstract; package Doc_Maps is new Ada.Containers.Indefinite_Hashed_Maps (Key_Type => String, Element_Type => File_Document, Hash => Ada.Strings.Hash, Equivalent_Keys => "="); -- Include the document extract represented by <b>Name</b> into the document <b>Into</b>. -- The included document is marked so that it will not be generated. procedure Include (Docs : in out Doc_Maps.Map; Into : in out File_Document; Name : in String; Mode : in Line_Include_Kind; Position : in Natural); procedure Include (Docs : in out Doc_Maps.Map; Into : in out File_Document; Name : in String; Position : in Natural); -- Generate the project documentation that was collected in <b>Docs</b>. -- The documentation is merged so that the @include tags are replaced by the matching -- document extracts. procedure Generate (Docs : in out Doc_Maps.Map; Dir : in String); -- Returns True if the line indicates a bullet or numbered list. function Is_List (Line : in String) return Boolean; -- Returns True if the line indicates a code sample. function Is_Code (Line : in String) return Boolean; -- Append a raw text line to the document. procedure Append_Line (Doc : in out File_Document; Line : in String); -- Look and analyze the tag defined on the line. procedure Append_Tag (Doc : in out File_Document; Tag : in String); -- Analyse the documentation line and collect the documentation text. procedure Append (Doc : in out File_Document; Line : in String); -- After having collected the documentation, terminate the document by making sure -- the opened elements are closed. procedure Finish (Doc : in out File_Document); -- Set the name associated with the document extract. procedure Set_Name (Doc : in out File_Document; Name : in String); -- Set the title associated with the document extract. procedure Set_Title (Doc : in out File_Document; Title : in String); -- Scan the files in the directory refered to by <b>Path</b> and collect the documentation -- in the <b>Docs</b> hashed map. procedure Scan_Files (Handler : in out Artifact; Path : in String; Docs : in out Doc_Maps.Map); -- Read the Ada specification/body file and collect the useful documentation. -- To keep the implementation simple, we don't use the ASIS packages to scan and extract -- the documentation. We don't need to look at the Ada specification itself. Instead, -- we assume that the Ada source follows some Ada style guidelines. procedure Read_Ada_File (Handler : in out Artifact; File : in String; Result : in out File_Document); procedure Read_Xml_File (Handler : in out Artifact; File : in String; Result : in out File_Document); type Artifact is new Gen.Artifacts.Artifact with record Xslt_Command : Ada.Strings.Unbounded.Unbounded_String; Format : Doc_Format := DOC_WIKI_GOOGLE; Print_Footer : Boolean := True; Formatter : Document_Formatter_Access; end record; end Gen.Artifacts.Docs;
Add TAG_INCLUDE_DOC (@include-doc) and procedure Include to handle it
Add TAG_INCLUDE_DOC (@include-doc) and procedure Include to handle it
Ada
apache-2.0
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
607ee03d2045e7dc1000196769c0ef6fa4ac68c3
regtests/ado-statements-tests.adb
regtests/ado-statements-tests.adb
----------------------------------------------------------------------- -- ado-statements-tests -- Test statements package -- Copyright (C) 2015, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Test_Caller; with Util.Strings.Transforms; with ADO.Utils; with ADO.Sessions; with Regtests.Statements.Model; package body ADO.Statements.Tests is use Util.Tests; procedure Populate (Tst : in out Test); function Get_Sum (T : in Test; Table : in String) return Natural; -- Test the query statement Get_Xxx operation for various types. generic type T (<>) is private; with function Get_Value (Stmt : in ADO.Statements.Query_Statement; Column : in Natural) return T is <>; Name : String; Column : String; procedure Test_Query_Get_Value_T (Tst : in out Test); procedure Populate (Tst : in out Test) is DB : ADO.Sessions.Master_Session := Regtests.Get_Master_Database; begin DB.Begin_Transaction; for I in 1 .. 10 loop declare Item : Regtests.Statements.Model.Table_Ref; begin Item.Set_Id_Value (ADO.Identifier (I * I)); Item.Set_Int_Value (I); Item.Set_Bool_Value ((I mod 2) = 0); Item.Set_String_Value ("Item" & Integer'Image (I)); Item.Set_Time_Value (Ada.Calendar.Clock); Item.Set_Entity_Value (ADO.Entity_Type (10 - I)); Item.Save (DB); Tst.Assert (Item.Is_Inserted, "Item inserted in database"); end; end loop; DB.Commit; end Populate; -- ------------------------------ -- Test the query statement Get_Xxx operation for various types. -- ------------------------------ procedure Test_Query_Get_Value_T (Tst : in out Test) is Stmt : ADO.Statements.Query_Statement; DB : constant ADO.Sessions.Session := Regtests.Get_Database; begin Populate (Tst); -- Check that Get_Value raises an exception if the statement is invalid. begin declare V : T := Get_Value (Stmt, 0); pragma Unreferenced (V); begin Util.Tests.Fail (Tst, "No Invalid_Statement exception raised for " & Name); end; exception when Invalid_Statement => null; end; -- Execute a query to fetch one column. Stmt := DB.Create_Statement ("SELECT " & Column & " FROM test_table WHERE id = 1"); Stmt.Execute; -- Verify the query result and the Get_Value operation. Tst.Assert (Stmt.Has_Elements, "The query statement must return a value for " & Name & ":" & Column); Tst.Assert (not Stmt.Is_Null (0), "The query statement must return a non null value for " & Name & ":" & Column); Util.Tests.Assert_Equals (Tst, Column, Util.Strings.Transforms.To_Lower_Case (Stmt.Get_Column_Name (0)), "The query returns an invalid column name"); declare V : T := Get_Value (Stmt, 0); pragma Unreferenced (V); begin Stmt.Clear; end; end Test_Query_Get_Value_T; procedure Test_Query_Get_Int64 is new Test_Query_Get_Value_T (Int64, ADO.Statements.Get_Int64, "Get_Int64", "id_value"); procedure Test_Query_Get_Integer is new Test_Query_Get_Value_T (Integer, ADO.Statements.Get_Integer, "Get_Integer", "int_value"); procedure Test_Query_Get_Nullable_Integer is new Test_Query_Get_Value_T (Nullable_Integer, ADO.Statements.Get_Nullable_Integer, "Get_Nullable_Integer", "int_value"); procedure Test_Query_Get_Nullable_Entity_Type is new Test_Query_Get_Value_T (Nullable_Entity_Type, ADO.Statements.Get_Nullable_Entity_Type, "Get_Nullable_Entity_Type", "entity_value"); procedure Test_Query_Get_Natural is new Test_Query_Get_Value_T (Natural, ADO.Statements.Get_Natural, "Get_Natural", "int_value"); procedure Test_Query_Get_Identifier is new Test_Query_Get_Value_T (ADO.Identifier, ADO.Statements.Get_Identifier, "Get_Identifier", "id_value"); procedure Test_Query_Get_Boolean is new Test_Query_Get_Value_T (Boolean, ADO.Statements.Get_Boolean, "Get_Boolean", "bool_value"); procedure Test_Query_Get_String is new Test_Query_Get_Value_T (String, ADO.Statements.Get_String, "Get_String", "string_value"); package Caller is new Util.Test_Caller (Test, "ADO.Statements"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test ADO.Statements.Save", Test_Save'Access); Caller.Add_Test (Suite, "Test ADO.Statements.Get_Int64", Test_Query_Get_Int64'Access); Caller.Add_Test (Suite, "Test ADO.Statements.Get_Integer", Test_Query_Get_Integer'Access); Caller.Add_Test (Suite, "Test ADO.Statements.Get_Nullable_Integer", Test_Query_Get_Nullable_Integer'Access); Caller.Add_Test (Suite, "Test ADO.Statements.Get_Natural", Test_Query_Get_Natural'Access); Caller.Add_Test (Suite, "Test ADO.Statements.Get_Identifier", Test_Query_Get_Identifier'Access); Caller.Add_Test (Suite, "Test ADO.Statements.Get_Boolean", Test_Query_Get_Boolean'Access); Caller.Add_Test (Suite, "Test ADO.Statements.Get_String", Test_Query_Get_String'Access); Caller.Add_Test (Suite, "Test ADO.Statements.Get_Nullable_Entity_Type", Test_Query_Get_Nullable_Entity_Type'Access); Caller.Add_Test (Suite, "Test ADO.Statements.Create_Statement (using $entity_type[])", Test_Entity_Types'Access); end Add_Tests; function Get_Sum (T : in Test; Table : in String) return Natural is DB : constant ADO.Sessions.Session := Regtests.Get_Database; Stmt : ADO.Statements.Query_Statement := DB.Create_Statement ("SELECT SUM(id_value) FROM " & Table); begin Stmt.Execute; T.Assert (Stmt.Has_Elements, "The query statement must return a value for table " & Table); return Stmt.Get_Integer (0); end Get_Sum; function Get_Sum (T : in Test; Table : in String; Ids : in ADO.Utils.Identifier_Vector) return Natural is DB : constant ADO.Sessions.Session := Regtests.Get_Database; Stmt : ADO.Statements.Query_Statement := DB.Create_Statement ("SELECT SUM(id_value) FROM " & Table & " WHERE id IN (:ids)"); begin Stmt.Bind_Param ("ids", Ids); Stmt.Execute; T.Assert (Stmt.Has_Elements, "The query statement must return a value for table " & Table); return Stmt.Get_Integer (0); end Get_Sum; -- ------------------------------ -- Test creation of several rows in test_table with different column type. -- ------------------------------ procedure Test_Save (T : in out Test) is First : constant Natural := Get_Sum (T, "test_table"); DB : ADO.Sessions.Master_Session := Regtests.Get_Master_Database; List : ADO.Utils.Identifier_Vector; begin DB.Begin_Transaction; for I in 1 .. 10 loop declare Item : Regtests.Statements.Model.Table_Ref; begin Item.Set_Id_Value (ADO.Identifier (I * I)); Item.Set_Int_Value (I); Item.Set_Bool_Value ((I mod 2) = 0); Item.Set_String_Value ("Item" & Integer'Image (I)); Item.Set_Time_Value (Ada.Calendar.Clock); Item.Set_Entity_Value (ADO.Entity_Type (10 - I)); Item.Save (DB); List.Append (Item.Get_Id); end; end loop; DB.Commit; Util.Tests.Assert_Equals (T, First + 385, Get_Sum (T, "test_table"), "The SUM query returns an invalid value for test_table"); Util.Tests.Assert_Equals (T, 385, Get_Sum (T, "test_table", List), "The SUM query returns an invalid value for test_table"); end Test_Save; -- ------------------------------ -- Test queries using the $entity_type[] cache group. -- ------------------------------ procedure Test_Entity_Types (T : in out Test) is DB : ADO.Sessions.Master_Session := Regtests.Get_Master_Database; Stmt : ADO.Statements.Query_Statement; Count : Natural := 0; begin Stmt := DB.Create_Statement ("SELECT name FROM entity_type " & "WHERE entity_type.id = $entity_type[test_user]"); Stmt.Execute; while Stmt.Has_Elements loop Util.Tests.Assert_Equals (T, "test_user", Stmt.Get_String (0), "Invalid query response"); Count := Count + 1; Stmt.Next; end loop; Util.Tests.Assert_Equals (T, 1, Count, "Query must return one row"); end Test_Entity_Types; end ADO.Statements.Tests;
----------------------------------------------------------------------- -- ado-statements-tests -- Test statements package -- Copyright (C) 2015, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Test_Caller; with Util.Strings.Transforms; with ADO.Utils; with ADO.Sessions; with Regtests.Statements.Model; package body ADO.Statements.Tests is use Util.Tests; procedure Populate (Tst : in out Test); function Get_Sum (T : in Test; Table : in String) return Natural; -- Test the query statement Get_Xxx operation for various types. generic type T (<>) is private; with function Get_Value (Stmt : in ADO.Statements.Query_Statement; Column : in Natural) return T is <>; Name : String; Column : String; procedure Test_Query_Get_Value_T (Tst : in out Test); procedure Populate (Tst : in out Test) is DB : ADO.Sessions.Master_Session := Regtests.Get_Master_Database; begin DB.Begin_Transaction; for I in 1 .. 10 loop declare Item : Regtests.Statements.Model.Table_Ref; begin Item.Set_Id_Value (ADO.Identifier (I * I)); Item.Set_Int_Value (I); Item.Set_Bool_Value ((I mod 2) = 0); Item.Set_String_Value ("Item" & Integer'Image (I)); Item.Set_Time_Value (Ada.Calendar.Clock); Item.Set_Entity_Value (ADO.Entity_Type (10 - I)); Item.Save (DB); Tst.Assert (Item.Is_Inserted, "Item inserted in database"); end; end loop; DB.Commit; end Populate; -- ------------------------------ -- Test the query statement Get_Xxx operation for various types. -- ------------------------------ procedure Test_Query_Get_Value_T (Tst : in out Test) is Stmt : ADO.Statements.Query_Statement; DB : constant ADO.Sessions.Session := Regtests.Get_Database; begin Populate (Tst); -- Check that Get_Value raises an exception if the statement is invalid. begin declare V : T := Get_Value (Stmt, 0); pragma Unreferenced (V); begin Util.Tests.Fail (Tst, "No Invalid_Statement exception raised for " & Name); end; exception when Invalid_Statement => null; end; -- Execute a query to fetch one column. Stmt := DB.Create_Statement ("SELECT " & Column & " FROM test_table WHERE id = 1"); Stmt.Execute; -- Verify the query result and the Get_Value operation. Tst.Assert (Stmt.Has_Elements, "The query statement must return a value for " & Name & ":" & Column); Tst.Assert (not Stmt.Is_Null (0), "The query statement must return a non null value for " & Name & ":" & Column); Util.Tests.Assert_Equals (Tst, Column, Util.Strings.Transforms.To_Lower_Case (Stmt.Get_Column_Name (0)), "The query returns an invalid column name"); declare V : T := Get_Value (Stmt, 0); pragma Unreferenced (V); begin Stmt.Clear; end; end Test_Query_Get_Value_T; procedure Test_Query_Get_Int64 is new Test_Query_Get_Value_T (Int64, ADO.Statements.Get_Int64, "Get_Int64", "id_value"); procedure Test_Query_Get_Integer is new Test_Query_Get_Value_T (Integer, ADO.Statements.Get_Integer, "Get_Integer", "int_value"); procedure Test_Query_Get_Nullable_Integer is new Test_Query_Get_Value_T (Nullable_Integer, ADO.Statements.Get_Nullable_Integer, "Get_Nullable_Integer", "int_value"); procedure Test_Query_Get_Nullable_Entity_Type is new Test_Query_Get_Value_T (Nullable_Entity_Type, ADO.Statements.Get_Nullable_Entity_Type, "Get_Nullable_Entity_Type", "entity_value"); procedure Test_Query_Get_Natural is new Test_Query_Get_Value_T (Natural, ADO.Statements.Get_Natural, "Get_Natural", "int_value"); procedure Test_Query_Get_Identifier is new Test_Query_Get_Value_T (ADO.Identifier, ADO.Statements.Get_Identifier, "Get_Identifier", "id_value"); procedure Test_Query_Get_Boolean is new Test_Query_Get_Value_T (Boolean, ADO.Statements.Get_Boolean, "Get_Boolean", "bool_value"); procedure Test_Query_Get_String is new Test_Query_Get_Value_T (String, ADO.Statements.Get_String, "Get_String", "string_value"); package Caller is new Util.Test_Caller (Test, "ADO.Statements"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test ADO.Statements.Save", Test_Save'Access); Caller.Add_Test (Suite, "Test ADO.Statements.Get_Int64", Test_Query_Get_Int64'Access); Caller.Add_Test (Suite, "Test ADO.Statements.Get_Integer", Test_Query_Get_Integer'Access); Caller.Add_Test (Suite, "Test ADO.Statements.Get_Nullable_Integer", Test_Query_Get_Nullable_Integer'Access); Caller.Add_Test (Suite, "Test ADO.Statements.Get_Natural", Test_Query_Get_Natural'Access); Caller.Add_Test (Suite, "Test ADO.Statements.Get_Identifier", Test_Query_Get_Identifier'Access); Caller.Add_Test (Suite, "Test ADO.Statements.Get_Boolean", Test_Query_Get_Boolean'Access); Caller.Add_Test (Suite, "Test ADO.Statements.Get_String", Test_Query_Get_String'Access); Caller.Add_Test (Suite, "Test ADO.Statements.Get_Nullable_Entity_Type", Test_Query_Get_Nullable_Entity_Type'Access); Caller.Add_Test (Suite, "Test ADO.Statements.Create_Statement (using $entity_type[])", Test_Entity_Types'Access); end Add_Tests; function Get_Sum (T : in Test; Table : in String) return Natural is DB : constant ADO.Sessions.Session := Regtests.Get_Database; Stmt : ADO.Statements.Query_Statement := DB.Create_Statement ("SELECT SUM(id_value) FROM " & Table); begin Stmt.Execute; T.Assert (Stmt.Has_Elements, "The query statement must return a value for table " & Table); return Stmt.Get_Integer (0); end Get_Sum; function Get_Sum (T : in Test; Table : in String; Ids : in ADO.Utils.Identifier_Vector) return Natural is DB : constant ADO.Sessions.Session := Regtests.Get_Database; Stmt : ADO.Statements.Query_Statement := DB.Create_Statement ("SELECT SUM(id_value) FROM " & Table & " WHERE id IN (:ids)"); begin Stmt.Bind_Param ("ids", Ids); Stmt.Execute; T.Assert (Stmt.Has_Elements, "The query statement must return a value for table " & Table); return Stmt.Get_Integer (0); end Get_Sum; -- ------------------------------ -- Test creation of several rows in test_table with different column type. -- ------------------------------ procedure Test_Save (T : in out Test) is First : constant Natural := Get_Sum (T, "test_table"); DB : ADO.Sessions.Master_Session := Regtests.Get_Master_Database; List : ADO.Utils.Identifier_Vector; begin DB.Begin_Transaction; for I in 1 .. 10 loop declare Item : Regtests.Statements.Model.Table_Ref; begin Item.Set_Id_Value (ADO.Identifier (I * I)); Item.Set_Int_Value (I); Item.Set_Bool_Value ((I mod 2) = 0); Item.Set_String_Value ("Item" & Integer'Image (I)); Item.Set_Time_Value (Ada.Calendar.Clock); Item.Set_Entity_Value (ADO.Entity_Type (10 - I)); Item.Save (DB); List.Append (Item.Get_Id); end; end loop; DB.Commit; Util.Tests.Assert_Equals (T, First + 385, Get_Sum (T, "test_table"), "The SUM query returns an invalid value for test_table"); Util.Tests.Assert_Equals (T, 385, Get_Sum (T, "test_table", List), "The SUM query returns an invalid value for test_table"); end Test_Save; -- ------------------------------ -- Test queries using the $entity_type[] cache group. -- ------------------------------ procedure Test_Entity_Types (T : in out Test) is DB : constant ADO.Sessions.Master_Session := Regtests.Get_Master_Database; Stmt : ADO.Statements.Query_Statement; Count : Natural := 0; begin Stmt := DB.Create_Statement ("SELECT name FROM entity_type " & "WHERE entity_type.id = $entity_type[test_user]"); Stmt.Execute; while Stmt.Has_Elements loop Util.Tests.Assert_Equals (T, "test_user", Stmt.Get_String (0), "Invalid query response"); Count := Count + 1; Stmt.Next; end loop; Util.Tests.Assert_Equals (T, 1, Count, "Query must return one row"); end Test_Entity_Types; end ADO.Statements.Tests;
Fix compilation warning detected by GNAT 2017
Fix compilation warning detected by GNAT 2017
Ada
apache-2.0
stcarrez/ada-ado
da9fdd7ffc6aeac85b81379a7c4ee7fb3a47c354
ada/main.adb
ada/main.adb
with Ada.Text_IO; with Ada.Command_Line; with SDL.Video.Windows.Makers; with SDL.Video.Renderers.Makers; with SDL.Video.Surfaces.Makers; with SDL.Video.Textures.Makers; with SDL.Images.IO; with SDL.Events.Events; with SDL.Error; procedure Main is Window_Title : constant String := "Hello World!"; Image_Name : constant String := "../img/grumpy-cat.png"; use SDL.Video; use type Windows.Window_Flags; use type Renderers.Renderer_flags; use type SDL.Events.Event_Types; Win : Windows.Window; Ren : Renderers.Renderer; Bmp : Surfaces.Surface; Tex : Textures.Texture; Event : SDL.Events.Events.Events; begin -- Initialise SDL if not SDL.Initialise or not SDL.Images.Initialise then Ada.Text_IO.Put_Line (Ada.Text_IO.Standard_Error, "SDL.Initialise error: " & SDL.Error.Get); Ada.Command_Line.Set_Exit_Status (Ada.Command_Line.Failure); return; end if; -- Create window Windows.Makers.Create (Win, Title => Window_Title, Position => (100, 100), Size => (620, 387), Flags => Windows.Windowed or Windows.Shown); -- Create renderer Renderers.Makers.Create (Rend => Ren, Window => Win, Flags => Renderers.Accelerated or Renderers.Present_V_Sync); -- Create image SDL.Images.IO.Create (Surface => Bmp, File_Name => Image_Name); -- Create texture Textures.Makers.Create (Tex => Tex, Renderer => Ren, Surface => Bmp); -- Present texture Ren.Clear; Ren.Copy (Copy_From => Tex); Ren.Present; -- Event loop loop SDL.Events.Events.Wait (Event); exit when Event.Common.Event_Type = SDL.Events.Quit; delay 0.010; end loop; -- Cleanup -- Not needed really when soon out of scope Tex.Finalize; Ren.Finalize; Win.Finalize; SDL.Finalise; end Main;
with Ada.Text_IO; with Ada.Command_Line; with SDL.Video.Windows.Makers; with SDL.Video.Renderers.Makers; with SDL.Video.Surfaces.Makers; with SDL.Video.Textures.Makers; with SDL.Images.IO; with SDL.Events.Events; with SDL.Error; procedure Main is Window_Title : constant String := "Hello World!"; Image_Name : constant String := "../img/grumpy-cat.png"; use SDL.Video; use type Windows.Window_Flags; use type Renderers.Renderer_flags; use type SDL.Events.Event_Types; Win : Windows.Window; Ren : Renderers.Renderer; Bmp : Surfaces.Surface; Tex : Textures.Texture; Event : SDL.Events.Events.Events; Dummy : Boolean; begin -- Initialise SDL if not SDL.Initialise or not SDL.Images.Initialise then Ada.Text_IO.Put_Line (Ada.Text_IO.Standard_Error, "SDL.Initialise error: " & SDL.Error.Get); Ada.Command_Line.Set_Exit_Status (Ada.Command_Line.Failure); return; end if; -- Create window Windows.Makers.Create (Win, Title => Window_Title, Position => (100, 100), Size => (620, 387), Flags => Windows.Shown); -- Create renderer Renderers.Makers.Create (Rend => Ren, Window => Win, Flags => (Renderers.Accelerated or Renderers.Present_V_Sync)); -- Create image SDL.Images.IO.Create (Surface => Bmp, File_Name => Image_Name); -- Create texture Textures.Makers.Create (Tex => Tex, Renderer => Ren, Surface => Bmp); -- Present texture Ren.Clear; Ren.Copy (Copy_From => Tex); Ren.Present; -- Event loop -- Exit after 2 seconds for I in 1 .. 200 loop Dummy := SDL.Events.Events.Poll (Event); exit when Event.Common.Event_Type = SDL.Events.Quit; delay 0.010; end loop; -- Cleanup -- Not needed really when soon out of scope Tex.Finalize; Ren.Finalize; Win.Finalize; SDL.Finalise; end Main;
Stop after 2 sec. Clean window flags
Ada: Stop after 2 sec. Clean window flags
Ada
mit
xyproto/hello_sdl2,xyproto/hello_sdl2,xyproto/hello_sdl2,xyproto/hello_sdl2,xyproto/hello_sdl2,xyproto/hello_sdl2,xyproto/hello_sdl2
c8b8aa68e72913b94a315a4b91db6f274aeff89c
awa/plugins/awa-workspaces/src/awa-workspaces-modules.ads
awa/plugins/awa-workspaces/src/awa-workspaces-modules.ads
----------------------------------------------------------------------- -- awa-workspaces-module -- 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 ADO.Objects; with ADO.Sessions; with Security.Permissions; with ASF.Applications; with AWA.Modules; with AWA.Services.Contexts; with AWA.Workspaces.Models; with AWA.Users.Services; with AWA.Users.Models; with AWA.Events; private with Ada.Strings.Unbounded; -- == Events == -- The *workspaces* module provides several events that are posted when some action are performed. -- -- === invite-user === -- This event is posted when an invitation is created for a user. The event can be used to -- send the associated invitation email to the invitee. The event contains the following -- attributes: -- -- key -- email -- name -- message -- inviter -- -- === accept-invitation === -- This event is posted when an invitation is accepted by a user. package AWA.Workspaces.Modules is subtype Permission_Index_Array is Security.Permissions.Permission_Index_Array; Not_Found : exception; -- The name under which the module is registered. NAME : constant String := "workspaces"; -- The configuration parameter that defines the list of permissions to grant -- to a user when his workspace is created. PARAM_PERMISSIONS_LIST : constant String := "permissions_list"; -- Permission to create a workspace. package ACL_Create_Workspace is new Security.Permissions.Definition ("workspace-create"); package Invite_User_Event is new AWA.Events.Definition (Name => "invite-user"); package Accept_Invitation_Event is new AWA.Events.Definition (Name => "accept-invitation"); -- ------------------------------ -- Module workspaces -- ------------------------------ type Workspace_Module is new AWA.Modules.Module with private; type Workspace_Module_Access is access all Workspace_Module'Class; -- Initialize the workspaces module. overriding procedure Initialize (Plugin : in out Workspace_Module; App : in AWA.Modules.Application_Access; Props : in ASF.Applications.Config); -- Configures the module after its initialization and after having read its XML configuration. overriding procedure Configure (Plugin : in out Workspace_Module; Props : in ASF.Applications.Config); -- Get the list of permissions for the workspace owner. function Get_Owner_Permissions (Manager : in Workspace_Module) return Permission_Index_Array; -- Get the workspace module. function Get_Workspace_Module return Workspace_Module_Access; -- Get the current workspace associated with the current user. -- If the user has not workspace, create one. procedure Get_Workspace (Session : in out ADO.Sessions.Master_Session; Context : in AWA.Services.Contexts.Service_Context_Access; Workspace : out AWA.Workspaces.Models.Workspace_Ref); -- Create a workspace for the user. procedure Create_Workspace (Module : in Workspace_Module; Workspace : out AWA.Workspaces.Models.Workspace_Ref); -- Load the invitation from the access key and verify that the key is still valid. procedure Load_Invitation (Module : in Workspace_Module; Key : in String; Invitation : in out AWA.Workspaces.Models.Invitation_Ref'Class; Inviter : in out AWA.Users.Models.User_Ref); -- Accept the invitation identified by the access key. procedure Accept_Invitation (Module : in Workspace_Module; Key : in String); -- Send the invitation to the user. procedure Send_Invitation (Module : in Workspace_Module; Invitation : in out AWA.Workspaces.Models.Invitation_Ref'Class); -- Delete the member from the workspace. Remove the invitation if there is one. procedure Delete_Member (Module : in Workspace_Module; Member_Id : in ADO.Identifier); -- Add a list of permissions for all the users of the workspace that have the appropriate -- role. Workspace members will be able to access the given database entity for the -- specified list of permissions. procedure Add_Permission (Session : in out ADO.Sessions.Master_Session; User : in ADO.Identifier; Entity : in ADO.Objects.Object_Ref'Class; Workspace : in ADO.Identifier; List : in Security.Permissions.Permission_Index_Array); private type Workspace_Module is new AWA.Modules.Module with record User_Manager : AWA.Users.Services.User_Service_Access; -- The list of permissions to grant to a user who creates the workspace. Owner_Permissions : Ada.Strings.Unbounded.Unbounded_String; end record; end AWA.Workspaces.Modules;
----------------------------------------------------------------------- -- awa-workspaces-module -- 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 ADO.Objects; with ADO.Sessions; with Security.Permissions; with ASF.Applications; with AWA.Modules; with AWA.Services.Contexts; with AWA.Workspaces.Models; with AWA.Users.Services; with AWA.Users.Models; with AWA.Events; private with Ada.Strings.Unbounded; -- == Events == -- The *workspaces* module provides several events that are posted when some action are performed. -- -- === invite-user === -- This event is posted when an invitation is created for a user. The event can be used to -- send the associated invitation email to the invitee. The event contains the following -- attributes: -- -- key -- email -- name -- message -- inviter -- -- === accept-invitation === -- This event is posted when an invitation is accepted by a user. package AWA.Workspaces.Modules is subtype Permission_Index_Array is Security.Permissions.Permission_Index_Array; Not_Found : exception; -- The name under which the module is registered. NAME : constant String := "workspaces"; -- The configuration parameter that defines the list of permissions to grant -- to a user when his workspace is created. PARAM_PERMISSIONS_LIST : constant String := "permissions_list"; -- Permission to create a workspace. package ACL_Create_Workspace is new Security.Permissions.Definition ("workspace-create"); package ACL_Invite_User is new Security.Permissions.Definition ("workspace-invite-user"); package Invite_User_Event is new AWA.Events.Definition (Name => "invite-user"); package Accept_Invitation_Event is new AWA.Events.Definition (Name => "accept-invitation"); -- ------------------------------ -- Module workspaces -- ------------------------------ type Workspace_Module is new AWA.Modules.Module with private; type Workspace_Module_Access is access all Workspace_Module'Class; -- Initialize the workspaces module. overriding procedure Initialize (Plugin : in out Workspace_Module; App : in AWA.Modules.Application_Access; Props : in ASF.Applications.Config); -- Configures the module after its initialization and after having read its XML configuration. overriding procedure Configure (Plugin : in out Workspace_Module; Props : in ASF.Applications.Config); -- Get the list of permissions for the workspace owner. function Get_Owner_Permissions (Manager : in Workspace_Module) return Permission_Index_Array; -- Get the workspace module. function Get_Workspace_Module return Workspace_Module_Access; -- Get the current workspace associated with the current user. -- If the user has not workspace, create one. procedure Get_Workspace (Session : in out ADO.Sessions.Master_Session; Context : in AWA.Services.Contexts.Service_Context_Access; Workspace : out AWA.Workspaces.Models.Workspace_Ref); -- Create a workspace for the user. procedure Create_Workspace (Module : in Workspace_Module; Workspace : out AWA.Workspaces.Models.Workspace_Ref); -- Load the invitation from the access key and verify that the key is still valid. procedure Load_Invitation (Module : in Workspace_Module; Key : in String; Invitation : in out AWA.Workspaces.Models.Invitation_Ref'Class; Inviter : in out AWA.Users.Models.User_Ref); -- Accept the invitation identified by the access key. procedure Accept_Invitation (Module : in Workspace_Module; Key : in String); -- Send the invitation to the user. procedure Send_Invitation (Module : in Workspace_Module; Invitation : in out AWA.Workspaces.Models.Invitation_Ref'Class); -- Delete the member from the workspace. Remove the invitation if there is one. procedure Delete_Member (Module : in Workspace_Module; Member_Id : in ADO.Identifier); -- Add a list of permissions for all the users of the workspace that have the appropriate -- role. Workspace members will be able to access the given database entity for the -- specified list of permissions. procedure Add_Permission (Session : in out ADO.Sessions.Master_Session; User : in ADO.Identifier; Entity : in ADO.Objects.Object_Ref'Class; Workspace : in ADO.Identifier; List : in Security.Permissions.Permission_Index_Array); private type Workspace_Module is new AWA.Modules.Module with record User_Manager : AWA.Users.Services.User_Service_Access; -- The list of permissions to grant to a user who creates the workspace. Owner_Permissions : Ada.Strings.Unbounded.Unbounded_String; end record; end AWA.Workspaces.Modules;
Declare the ACL_Invite_User permission
Declare the ACL_Invite_User permission
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
fbe770625fc25f8a868042f7d00582b9024071a8
src/asf-components-core-views.ads
src/asf-components-core-views.ads
----------------------------------------------------------------------- -- components-core-views -- ASF View Components -- Copyright (C) 2009, 2010, 2011, 2012, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Beans.Objects; with Util.Locales; with ASF.Events.Faces; with ASF.Lifecycles; with ASF.Components.Html.Forms; with ASF.Components.Core; with ASF.Views.Nodes; private with Ada.Containers.Vectors; package ASF.Components.Core.Views is -- Name of the facet that holds the metadata information -- (we use the same name as JSF 2 specification). METADATA_FACET_NAME : constant String := "javax_faces_metadata"; type UIViewMetaData; type UIViewMetaData_Access is access all UIViewMetaData'Class; -- ------------------------------ -- View component -- ------------------------------ type UIView is new Core.UIComponentBase with private; type UIView_Access is access all UIView'Class; -- Get the content type returned by the view. function Get_Content_Type (UI : in UIView; Context : in Faces_Context'Class) return String; -- Set the content type returned by the view. procedure Set_Content_Type (UI : in out UIView; Value : in String); -- Get the locale to be used when rendering messages in the view. -- If a locale was set explicitly, return it. -- If the view component defines a <b>locale</b> attribute, evaluate and return its value. -- If the locale is empty, calculate the locale by using the request context and the view -- handler. function Get_Locale (UI : in UIView; Context : in Faces_Context'Class) return Util.Locales.Locale; -- Set the locale to be used when rendering messages in the view. procedure Set_Locale (UI : in out UIView; Locale : in Util.Locales.Locale); -- Encode the begining of the view. Set the response content type. overriding procedure Encode_Begin (UI : in UIView; Context : in out Faces_Context'Class); -- Encode the end of the view. overriding procedure Encode_End (UI : in UIView; Context : in out Faces_Context'Class); -- Decode any new state of the specified component from the request contained -- in the specified context and store that state on the component. -- -- During decoding, events may be enqueued for later processing -- (by event listeners that have registered an interest), by calling -- the <b>Queue_Event</b> on the associated component. overriding procedure Process_Decodes (UI : in out UIView; Context : in out Faces_Context'Class); -- Perform the component tree processing required by the <b>Process Validations</b> -- phase of the request processing lifecycle for all facets of this component, -- all children of this component, and this component itself, as follows: -- <ul> -- <li>If this component <b>rendered</b> property is false, skip further processing. -- <li>Call the <b>Process_Validators</b> of all facets and children. -- <ul> overriding procedure Process_Validators (UI : in out UIView; Context : in out Faces_Context'Class); -- Perform the component tree processing required by the <b>Update Model Values</b> -- phase of the request processing lifecycle for all facets of this component, -- all children of this component, and this component itself, as follows. -- <ul> -- <li>If this component <b>rendered</b> property is false, skip further processing. -- <li>Call the <b>Process_Updates/b> of all facets and children. -- <ul> overriding procedure Process_Updates (UI : in out UIView; Context : in out Faces_Context'Class); -- Broadcast any events that have been queued for the <b>Invoke Application</b> -- phase of the request processing lifecycle and to clear out any events -- for later phases if the event processing for this phase caused -- <b>renderResponse</b> or <b>responseComplete</b> to be called. procedure Process_Application (UI : in out UIView; Context : in out Faces_Context'Class); -- Queue an event for broadcast at the end of the current request -- processing lifecycle phase. The event object -- will be freed after being dispatched. procedure Queue_Event (UI : in out UIView; Event : not null access ASF.Events.Faces.Faces_Event'Class); -- Broadcast the events after the specified lifecycle phase. -- Events that were queued will be freed. procedure Broadcast (UI : in out UIView; Phase : in ASF.Lifecycles.Phase_Type; Context : in out Faces_Context'Class); -- Clear the events that were queued. procedure Clear_Events (UI : in out UIView); -- Set the component tree that must be rendered before this view. -- This is an internal method used by Steal_Root_Component exclusively. procedure Set_Before_View (UI : in out UIView'Class; Tree : in Base.UIComponent_Access); -- Set the component tree that must be rendered after this view. -- This is an internal method used by Steal_Root_Component exclusively. procedure Set_After_View (UI : in out UIView'Class; Tree : in Base.UIComponent_Access); -- Set the metadata facet on the UIView component. procedure Set_Metadata (UI : in out UIView; Meta : in UIViewMetaData_Access; Tag : access ASF.Views.Nodes.Tag_Node'Class); -- Finalize the object. overriding procedure Finalize (UI : in out UIView); -- ------------------------------ -- View Parameter Component -- ------------------------------ -- The <b>UIViewParameter</b> component represents a request parameter that must be mapped -- to a backed bean object. This component does not participate in the rendering. type UIViewParameter is new Html.Forms.UIInput with private; type UIViewParameter_Access is access all UIViewParameter'Class; -- Get the input parameter from the submitted context. This operation is called by -- <tt>Process_Decodes</tt> to retrieve the request parameter associated with the component. overriding function Get_Parameter (UI : in UIViewParameter; Context : in Faces_Context'Class) return String; -- ------------------------------ -- View Action Component -- ------------------------------ -- The <b>UIViewAction</b> component implements the view action tag defined by Jave Server -- Faces 2.2. This action defined by that tag will be called type UIViewAction is new Html.Forms.UICommand with private; type UIViewAction_Access is access all UIViewAction'Class; -- Decode the request and prepare for the execution for the view action. overriding procedure Process_Decodes (UI : in out UIViewAction; Context : in out Faces_Context'Class); -- ------------------------------ -- View Metadata Component -- ------------------------------ -- The <b>UIViewMetaData</b> component defines the view meta data components. -- These components defines how to handle some request parameters for a GET request -- as well as some actions that must be made upon reception of a request. -- -- From ASF lifecycle management, if the request is a GET, this component is used -- as the root of the component tree. The APPLY_REQUESTS .. INVOKE_APPLICATION actions -- are called on that component tree. It is also used for the RENDER_RESPONSE, and -- we have to propagate the rendering on the real view root. Therefore, the Encode_XXX -- operations are overriden to propagate on the real root. type UIViewMetaData is new UIView with private; -- Start encoding the UIComponent. overriding procedure Encode_Begin (UI : in UIViewMetaData; Context : in out Faces_Context'Class); -- Encode the children of this component. overriding procedure Encode_Children (UI : in UIViewMetaData; Context : in out Faces_Context'Class); -- Finish encoding the component. overriding procedure Encode_End (UI : in UIViewMetaData; Context : in out Faces_Context'Class); -- Queue an event for broadcast at the end of the current request -- processing lifecycle phase. The event object -- will be freed after being dispatched. overriding procedure Queue_Event (UI : in out UIViewMetaData; Event : not null access ASF.Events.Faces.Faces_Event'Class); -- Broadcast the events after the specified lifecycle phase. -- Events that were queued will be freed. overriding procedure Broadcast (UI : in out UIViewMetaData; Phase : in ASF.Lifecycles.Phase_Type; Context : in out Faces_Context'Class); -- Clear the events that were queued. overriding procedure Clear_Events (UI : in out UIViewMetaData); -- Get the root component. function Get_Root (UI : in UIViewMetaData) return Base.UIComponent_Access; private use ASF.Lifecycles; type Faces_Event_Access is access all ASF.Events.Faces.Faces_Event'Class; package Event_Vectors is new Ada.Containers.Vectors (Index_Type => Natural, Element_Type => Faces_Event_Access); type Event_Queues is array (Phase_Type) of Event_Vectors.Vector; type UIView is new Core.UIComponentBase with record Content_Type : Util.Beans.Objects.Object; Phase_Events : Event_Queues; Meta : UIViewMetaData_Access := null; Locale : Util.Locales.Locale := Util.Locales.NULL_LOCALE; Left_Tree : Base.UIComponent_Access := null; Right_Tree : Base.UIComponent_Access := null; end record; type UIViewParameter is new Html.Forms.UIInput with record Name : Ada.Strings.Unbounded.Unbounded_String; end record; type UIViewAction is new Html.Forms.UICommand with null record; type UIViewMetaData is new UIView with record Root : UIView_Access := null; end record; end ASF.Components.Core.Views;
----------------------------------------------------------------------- -- components-core-views -- ASF View Components -- Copyright (C) 2009, 2010, 2011, 2012, 2017, 2021 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Beans.Objects; with Util.Locales; with ASF.Events.Faces; with ASF.Lifecycles; with ASF.Components.Html.Forms; with ASF.Components.Core; with ASF.Views.Nodes; private with Ada.Containers.Vectors; package ASF.Components.Core.Views is -- Name of the facet that holds the metadata information -- (we use the same name as JSF 2 specification). METADATA_FACET_NAME : constant String := "javax_faces_metadata"; type UIViewMetaData is tagged; type UIViewMetaData_Access is access all UIViewMetaData'Class; -- ------------------------------ -- View component -- ------------------------------ type UIView is new Core.UIComponentBase with private; type UIView_Access is access all UIView'Class; -- Get the content type returned by the view. function Get_Content_Type (UI : in UIView; Context : in Faces_Context'Class) return String; -- Set the content type returned by the view. procedure Set_Content_Type (UI : in out UIView; Value : in String); -- Get the locale to be used when rendering messages in the view. -- If a locale was set explicitly, return it. -- If the view component defines a <b>locale</b> attribute, evaluate and return its value. -- If the locale is empty, calculate the locale by using the request context and the view -- handler. function Get_Locale (UI : in UIView; Context : in Faces_Context'Class) return Util.Locales.Locale; -- Set the locale to be used when rendering messages in the view. procedure Set_Locale (UI : in out UIView; Locale : in Util.Locales.Locale); -- Encode the begining of the view. Set the response content type. overriding procedure Encode_Begin (UI : in UIView; Context : in out Faces_Context'Class); -- Encode the end of the view. overriding procedure Encode_End (UI : in UIView; Context : in out Faces_Context'Class); -- Decode any new state of the specified component from the request contained -- in the specified context and store that state on the component. -- -- During decoding, events may be enqueued for later processing -- (by event listeners that have registered an interest), by calling -- the <b>Queue_Event</b> on the associated component. overriding procedure Process_Decodes (UI : in out UIView; Context : in out Faces_Context'Class); -- Perform the component tree processing required by the <b>Process Validations</b> -- phase of the request processing lifecycle for all facets of this component, -- all children of this component, and this component itself, as follows: -- <ul> -- <li>If this component <b>rendered</b> property is false, skip further processing. -- <li>Call the <b>Process_Validators</b> of all facets and children. -- <ul> overriding procedure Process_Validators (UI : in out UIView; Context : in out Faces_Context'Class); -- Perform the component tree processing required by the <b>Update Model Values</b> -- phase of the request processing lifecycle for all facets of this component, -- all children of this component, and this component itself, as follows. -- <ul> -- <li>If this component <b>rendered</b> property is false, skip further processing. -- <li>Call the <b>Process_Updates/b> of all facets and children. -- <ul> overriding procedure Process_Updates (UI : in out UIView; Context : in out Faces_Context'Class); -- Broadcast any events that have been queued for the <b>Invoke Application</b> -- phase of the request processing lifecycle and to clear out any events -- for later phases if the event processing for this phase caused -- <b>renderResponse</b> or <b>responseComplete</b> to be called. procedure Process_Application (UI : in out UIView; Context : in out Faces_Context'Class); -- Queue an event for broadcast at the end of the current request -- processing lifecycle phase. The event object -- will be freed after being dispatched. procedure Queue_Event (UI : in out UIView; Event : not null access ASF.Events.Faces.Faces_Event'Class); -- Broadcast the events after the specified lifecycle phase. -- Events that were queued will be freed. procedure Broadcast (UI : in out UIView; Phase : in ASF.Lifecycles.Phase_Type; Context : in out Faces_Context'Class); -- Clear the events that were queued. procedure Clear_Events (UI : in out UIView); -- Set the component tree that must be rendered before this view. -- This is an internal method used by Steal_Root_Component exclusively. procedure Set_Before_View (UI : in out UIView'Class; Tree : in Base.UIComponent_Access); -- Set the component tree that must be rendered after this view. -- This is an internal method used by Steal_Root_Component exclusively. procedure Set_After_View (UI : in out UIView'Class; Tree : in Base.UIComponent_Access); -- Set the metadata facet on the UIView component. procedure Set_Metadata (UI : in out UIView; Meta : in UIViewMetaData_Access; Tag : access ASF.Views.Nodes.Tag_Node'Class); -- Finalize the object. overriding procedure Finalize (UI : in out UIView); -- ------------------------------ -- View Parameter Component -- ------------------------------ -- The <b>UIViewParameter</b> component represents a request parameter that must be mapped -- to a backed bean object. This component does not participate in the rendering. type UIViewParameter is new Html.Forms.UIInput with private; type UIViewParameter_Access is access all UIViewParameter'Class; -- Get the input parameter from the submitted context. This operation is called by -- <tt>Process_Decodes</tt> to retrieve the request parameter associated with the component. overriding function Get_Parameter (UI : in UIViewParameter; Context : in Faces_Context'Class) return String; -- ------------------------------ -- View Action Component -- ------------------------------ -- The <b>UIViewAction</b> component implements the view action tag defined by Jave Server -- Faces 2.2. This action defined by that tag will be called type UIViewAction is new Html.Forms.UICommand with private; type UIViewAction_Access is access all UIViewAction'Class; -- Decode the request and prepare for the execution for the view action. overriding procedure Process_Decodes (UI : in out UIViewAction; Context : in out Faces_Context'Class); -- ------------------------------ -- View Metadata Component -- ------------------------------ -- The <b>UIViewMetaData</b> component defines the view meta data components. -- These components defines how to handle some request parameters for a GET request -- as well as some actions that must be made upon reception of a request. -- -- From ASF lifecycle management, if the request is a GET, this component is used -- as the root of the component tree. The APPLY_REQUESTS .. INVOKE_APPLICATION actions -- are called on that component tree. It is also used for the RENDER_RESPONSE, and -- we have to propagate the rendering on the real view root. Therefore, the Encode_XXX -- operations are overriden to propagate on the real root. type UIViewMetaData is new UIView with private; -- Start encoding the UIComponent. overriding procedure Encode_Begin (UI : in UIViewMetaData; Context : in out Faces_Context'Class); -- Encode the children of this component. overriding procedure Encode_Children (UI : in UIViewMetaData; Context : in out Faces_Context'Class); -- Finish encoding the component. overriding procedure Encode_End (UI : in UIViewMetaData; Context : in out Faces_Context'Class); -- Queue an event for broadcast at the end of the current request -- processing lifecycle phase. The event object -- will be freed after being dispatched. overriding procedure Queue_Event (UI : in out UIViewMetaData; Event : not null access ASF.Events.Faces.Faces_Event'Class); -- Broadcast the events after the specified lifecycle phase. -- Events that were queued will be freed. overriding procedure Broadcast (UI : in out UIViewMetaData; Phase : in ASF.Lifecycles.Phase_Type; Context : in out Faces_Context'Class); -- Clear the events that were queued. overriding procedure Clear_Events (UI : in out UIViewMetaData); -- Get the root component. function Get_Root (UI : in UIViewMetaData) return Base.UIComponent_Access; private use ASF.Lifecycles; type Faces_Event_Access is access all ASF.Events.Faces.Faces_Event'Class; package Event_Vectors is new Ada.Containers.Vectors (Index_Type => Natural, Element_Type => Faces_Event_Access); type Event_Queues is array (Phase_Type) of Event_Vectors.Vector; type UIView is new Core.UIComponentBase with record Content_Type : Util.Beans.Objects.Object; Phase_Events : Event_Queues; Meta : UIViewMetaData_Access := null; Locale : Util.Locales.Locale := Util.Locales.NULL_LOCALE; Left_Tree : Base.UIComponent_Access := null; Right_Tree : Base.UIComponent_Access := null; end record; type UIViewParameter is new Html.Forms.UIInput with record Name : Ada.Strings.Unbounded.Unbounded_String; end record; type UIViewAction is new Html.Forms.UICommand with null record; type UIViewMetaData is new UIView with record Root : UIView_Access := null; end record; end ASF.Components.Core.Views;
Fix compilation warning with GNAT 2021
Fix compilation warning with GNAT 2021
Ada
apache-2.0
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
0681e87c114604ba51f6ee329fe4d3374594296f
awa/src/awa-permissions.adb
awa/src/awa-permissions.adb
----------------------------------------------------------------------- -- awa-permissions -- Permissions module -- Copyright (C) 2011, 2012, 2013, 2014, 2016, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Log.Loggers; with Util.Serialize.Mappers.Record_Mapper; with ADO.Schemas.Entities; with ADO.Sessions.Entities; with Security.Contexts; with AWA.Services.Contexts; with AWA.Permissions.Controllers; package body AWA.Permissions is Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("AWA.Permissions"); -- ------------------------------ -- Verify that the permission represented by <b>Permission</b> is granted. -- ------------------------------ procedure Check (Permission : in Security.Permissions.Permission_Index) is begin if not (Security.Contexts.Has_Permission (Permission)) then raise NO_PERMISSION; end if; end Check; -- ------------------------------ -- Verify that the permission represented by <b>Permission</b> is granted to access the -- database entity represented by <b>Entity</b>. -- ------------------------------ procedure Check (Permission : in Security.Permissions.Permission_Index; Entity : in ADO.Identifier) is use type Security.Contexts.Security_Context_Access; Context : constant Security.Contexts.Security_Context_Access := Security.Contexts.Current; Perm : Entity_Permission (Permission); begin if Context = null then Log.Debug ("Permission is refused because there is no security context"); raise NO_PERMISSION; end if; Perm.Entity := Entity; if not Context.Has_Permission (Perm) then Log.Debug ("Permission is refused by the security controller"); raise NO_PERMISSION; end if; end Check; -- ------------------------------ -- Verify that the permission represented by <b>Permission</b> is granted to access the -- database entity represented by <b>Entity</b>. -- ------------------------------ procedure Check (Permission : in Security.Permissions.Permission_Index; Entity : in ADO.Objects.Object_Ref'Class) is begin if Entity.Is_Null then Log.Debug ("Permission is refused because the entity is null."); raise NO_PERMISSION; end if; Check (Permission, ADO.Objects.Get_Value (Entity.Get_Key)); end Check; type Config_Fields is (FIELD_NAME, FIELD_ENTITY_TYPE, FIELD_ENTITY_PERMISSION, FIELD_SQL); type Controller_Config_Access is access all Controller_Config; procedure Set_Member (Into : in out Controller_Config; Field : in Config_Fields; Value : in Util.Beans.Objects.Object); -- ------------------------------ -- Called while parsing the XML policy file when the <name>, <entity-type>, <sql> and -- <entity-permission> XML entities are found. Create the new permission when the complete -- permission definition has been parsed and save the permission in the security manager. -- ------------------------------ procedure Set_Member (Into : in out Controller_Config; Field : in Config_Fields; Value : in Util.Beans.Objects.Object) is use AWA.Permissions.Controllers; use type ADO.Entity_Type; begin case Field is when FIELD_NAME => Into.Name := Value; when FIELD_SQL => Into.SQL := Value; when FIELD_ENTITY_TYPE => declare Name : constant String := Util.Beans.Objects.To_String (Value); begin if Into.Count = MAX_ENTITY_TYPES then raise Util.Serialize.Mappers.Field_Error with "Too many entity types."; end if; Into.Count := Into.Count + 1; Into.Entities (Into.Count) := ADO.Sessions.Entities.Find_Entity_Type (Into.Session, Name); exception when ADO.Schemas.Entities.No_Entity_Type => raise Util.Serialize.Mappers.Field_Error with "Invalid entity type: " & Name; end; when FIELD_ENTITY_PERMISSION => declare Name : constant String := Util.Beans.Objects.To_String (Into.Name); begin if Into.Count = 0 then raise Util.Serialize.Mappers.Field_Error with "Permission '" & Name & "' ignored: missing entity type"; end if; declare SQL : constant String := Util.Beans.Objects.To_String (Into.SQL); Perm : constant Entity_Controller_Access := new Entity_Controller '(Len => SQL'Length, SQL => SQL, Entities => Into.Entities); begin Into.Manager.Add_Permission (Name, Perm.all'Access); Into.Count := 0; Into.Entities := (others => ADO.NO_ENTITY_TYPE); end; end; end case; end Set_Member; package Config_Mapper is new Util.Serialize.Mappers.Record_Mapper (Element_Type => Controller_Config, Element_Type_Access => Controller_Config_Access, Fields => Config_Fields, Set_Member => Set_Member); Mapper : aliased Config_Mapper.Mapper; -- ------------------------------ -- Setup the XML parser to read the <b>entity-permission</b> description. For example: -- -- <entity-permission> -- <name>create-workspace</name> -- <entity-type>WORKSPACE</entity-type> -- <sql>select acl.id from acl where ...</sql> -- </entity-permission> -- -- This defines a permission <b>create-workspace</b> that will be granted if the -- SQL statement returns a non empty list. -- ------------------------------ -- ------------------------------ -- Get the policy name. -- ------------------------------ overriding function Get_Name (From : in Entity_Policy) return String is pragma Unreferenced (From); begin return NAME; end Get_Name; -- ------------------------------ -- Setup the XML parser to read the <b>policy</b> description. -- ------------------------------ overriding procedure Prepare_Config (Policy : in out Entity_Policy; Reader : in out Util.Serialize.IO.XML.Parser) is Config : constant Controller_Config_Access := Policy.Config'Unchecked_Access; begin Reader.Add_Mapping ("policy-rules", Mapper'Access); Reader.Add_Mapping ("module", Mapper'Access); Config.Manager := Policy'Unchecked_Access; Config.Session := AWA.Services.Contexts.Get_Session (AWA.Services.Contexts.Current); Config_Mapper.Set_Context (Reader, Config); end Prepare_Config; begin Mapper.Add_Mapping ("entity-permission", FIELD_ENTITY_PERMISSION); Mapper.Add_Mapping ("entity-permission/name", FIELD_NAME); Mapper.Add_Mapping ("entity-permission/entity-type", FIELD_ENTITY_TYPE); Mapper.Add_Mapping ("entity-permission/sql", FIELD_SQL); end AWA.Permissions;
----------------------------------------------------------------------- -- awa-permissions -- Permissions module -- Copyright (C) 2011, 2012, 2013, 2014, 2016, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Log.Loggers; with Util.Serialize.Mappers.Record_Mapper; with ADO.Schemas.Entities; with ADO.Sessions.Entities; with Security.Contexts; with AWA.Services.Contexts; with AWA.Permissions.Controllers; package body AWA.Permissions is Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("AWA.Permissions"); -- ------------------------------ -- Verify that the permission represented by <b>Permission</b> is granted. -- ------------------------------ procedure Check (Permission : in Security.Permissions.Permission_Index) is begin if not (Security.Contexts.Has_Permission (Permission)) then raise NO_PERMISSION; end if; end Check; -- ------------------------------ -- Verify that the permission represented by <b>Permission</b> is granted to access the -- database entity represented by <b>Entity</b>. -- ------------------------------ procedure Check (Permission : in Security.Permissions.Permission_Index; Entity : in ADO.Identifier) is use type Security.Contexts.Security_Context_Access; Context : constant Security.Contexts.Security_Context_Access := Security.Contexts.Current; Perm : Entity_Permission (Permission); begin if Context = null then Log.Debug ("Permission is refused because there is no security context"); raise NO_PERMISSION; end if; Perm.Entity := Entity; if not Context.Has_Permission (Perm) then Log.Debug ("Permission is refused by the security controller"); raise NO_PERMISSION; end if; end Check; -- ------------------------------ -- Verify that the permission represented by <b>Permission</b> is granted to access the -- database entity represented by <b>Entity</b>. -- ------------------------------ procedure Check (Permission : in Security.Permissions.Permission_Index; Entity : in ADO.Objects.Object_Ref'Class) is begin if Entity.Is_Null then Log.Debug ("Permission is refused because the entity is null."); raise NO_PERMISSION; end if; Check (Permission, ADO.Objects.Get_Value (Entity.Get_Key)); end Check; type Config_Fields is (FIELD_NAME, FIELD_ENTITY_TYPE, FIELD_ENTITY_PERMISSION, FIELD_SQL, FIELD_GRANT); type Controller_Config_Access is access all Controller_Config; procedure Set_Member (Into : in out Controller_Config; Field : in Config_Fields; Value : in Util.Beans.Objects.Object); -- ------------------------------ -- Called while parsing the XML policy file when the <name>, <entity-type>, <sql> and -- <entity-permission> XML entities are found. Create the new permission when the complete -- permission definition has been parsed and save the permission in the security manager. -- ------------------------------ procedure Set_Member (Into : in out Controller_Config; Field : in Config_Fields; Value : in Util.Beans.Objects.Object) is use AWA.Permissions.Controllers; use type ADO.Entity_Type; begin case Field is when FIELD_NAME => Into.Name := Value; when FIELD_SQL => Into.SQL := Value; when FIELD_GRANT => Into.Grant := Value; when FIELD_ENTITY_TYPE => declare Name : constant String := Util.Beans.Objects.To_String (Value); begin if Into.Count = MAX_ENTITY_TYPES then raise Util.Serialize.Mappers.Field_Error with "Too many entity types."; end if; Into.Count := Into.Count + 1; Into.Entities (Into.Count) := ADO.Sessions.Entities.Find_Entity_Type (Into.Session, Name); exception when ADO.Schemas.Entities.No_Entity_Type => raise Util.Serialize.Mappers.Field_Error with "Invalid entity type: " & Name; end; when FIELD_ENTITY_PERMISSION => declare Name : constant String := Util.Beans.Objects.To_String (Into.Name); begin if Into.Count = 0 then raise Util.Serialize.Mappers.Field_Error with "Permission '" & Name & "' ignored: missing entity type"; end if; declare SQL : constant String := Util.Beans.Objects.To_String (Into.SQL); Perm : constant Entity_Controller_Access := new Entity_Controller '(Len => SQL'Length, SQL => SQL, Entities => Into.Entities); begin Into.Manager.Add_Permission (Name, Perm.all'Access); Into.Count := 0; Into.Entities := (others => ADO.NO_ENTITY_TYPE); end; end; end case; end Set_Member; package Config_Mapper is new Util.Serialize.Mappers.Record_Mapper (Element_Type => Controller_Config, Element_Type_Access => Controller_Config_Access, Fields => Config_Fields, Set_Member => Set_Member); Perm_Mapper : aliased Config_Mapper.Mapper; -- ------------------------------ -- Setup the XML parser to read the <b>entity-permission</b> description. For example: -- -- <entity-permission> -- <name>create-workspace</name> -- <entity-type>WORKSPACE</entity-type> -- <sql>select acl.id from acl where ...</sql> -- </entity-permission> -- -- This defines a permission <b>create-workspace</b> that will be granted if the -- SQL statement returns a non empty list. -- ------------------------------ -- ------------------------------ -- Get the policy name. -- ------------------------------ overriding function Get_Name (From : in Entity_Policy) return String is pragma Unreferenced (From); begin return NAME; end Get_Name; -- ------------------------------ -- Setup the XML parser to read the <b>policy</b> description. -- ------------------------------ overriding procedure Prepare_Config (Policy : in out Entity_Policy; Mapper : in out Util.Serialize.Mappers.Processing) is Config : constant Controller_Config_Access := Policy.Config'Unchecked_Access; begin Mapper.Add_Mapping ("policy-rules", Perm_Mapper'Access); Mapper.Add_Mapping ("module", Perm_Mapper'Access); Config.Manager := Policy'Unchecked_Access; Config.Session := AWA.Services.Contexts.Get_Session (AWA.Services.Contexts.Current); Config_Mapper.Set_Context (Mapper, Config); end Prepare_Config; begin Perm_Mapper.Add_Mapping ("entity-permission", FIELD_ENTITY_PERMISSION); Perm_Mapper.Add_Mapping ("entity-permission/name", FIELD_NAME); Perm_Mapper.Add_Mapping ("entity-permission/entity-type", FIELD_ENTITY_TYPE); Perm_Mapper.Add_Mapping ("entity-permission/sql", FIELD_SQL); Perm_Mapper.Add_Mapping ("entity-permission/grant", FIELD_GRANT); end AWA.Permissions;
Update the Prepare_Config to use the new parser/mapper interface
Update the Prepare_Config to use the new parser/mapper interface
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
85ff8bcdb87522eaffdf0ef7955ac2a5db681c8f
src/sys/encoders/util-encoders-hmac-sha1.ads
src/sys/encoders/util-encoders-hmac-sha1.ads
----------------------------------------------------------------------- -- util-encoders-hmac-sha1 -- Compute HMAC-SHA1 authentication code -- Copyright (C) 2011, 2012, 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.SHA1; -- The <b>Util.Encodes.HMAC.SHA1</b> package generates HMAC-SHA1 authentication -- (See RFC 2104 - HMAC: Keyed-Hashing for Message Authentication). package Util.Encoders.HMAC.SHA1 is pragma Preelaborate; -- Sign the data string with the key and return the HMAC-SHA1 code in binary. function Sign (Key : in String; Data : in String) return Util.Encoders.SHA1.Hash_Array; -- Sign the data string with the key and return the HMAC-SHA1 code as hexadecimal string. function Sign (Key : in String; Data : in String) return Util.Encoders.SHA1.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.SHA1.Hash_Array); -- Sign the data string with the key and return the HMAC-SHA1 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.SHA1.Base64_Digest; -- ------------------------------ -- HMAC-SHA1 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-SHA1 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.SHA1.Hash_Array); -- Computes the HMAC-SHA1 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.SHA1.Digest); -- Computes the HMAC-SHA1 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.SHA1.Base64_Digest; URL : in Boolean := False); -- ------------------------------ -- HMAC-SHA1 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; type Context is new Ada.Finalization.Limited_Controlled with record SHA : Util.Encoders.SHA1.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.SHA1;
----------------------------------------------------------------------- -- util-encoders-hmac-sha1 -- Compute HMAC-SHA1 authentication code -- Copyright (C) 2011, 2012, 2017, 2019, 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.Streams; with Ada.Finalization; with Util.Encoders.SHA1; -- The <b>Util.Encodes.HMAC.SHA1</b> package generates HMAC-SHA1 authentication -- (See RFC 2104 - HMAC: Keyed-Hashing for Message Authentication). package Util.Encoders.HMAC.SHA1 is pragma Preelaborate; -- Sign the data string with the key and return the HMAC-SHA1 code in binary. function Sign (Key : in String; Data : in String) return Util.Encoders.SHA1.Hash_Array; -- Sign the data string with the key and return the HMAC-SHA1 code as hexadecimal string. function Sign (Key : in String; Data : in String) return Util.Encoders.SHA1.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.SHA1.Hash_Array); -- Sign the data string with the key and return the HMAC-SHA1 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.SHA1.Base64_Digest; -- ------------------------------ -- HMAC-SHA1 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-SHA1 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.SHA1.Hash_Array); -- Computes the HMAC-SHA1 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.SHA1.Digest); -- Computes the HMAC-SHA1 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.SHA1.Base64_Digest; URL : in Boolean := False); private type Encoder is new Util.Encoders.Transformer with null record; type Context is new Ada.Finalization.Limited_Controlled with record SHA : Util.Encoders.SHA1.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.SHA1;
Remove the Encoder type and its operation because it was never implemented
Remove the Encoder type and its operation because it was never implemented
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
c3d2609bf86ce2ee9b4a2b00359d63a5b9c2540a
mat/src/mat-readers-marshaller.ads
mat/src/mat-readers-marshaller.ads
----------------------------------------------------------------------- -- mat-readers-marshaller -- Marshalling of data in communication buffer -- 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.Events; package MAT.Readers.Marshaller is Buffer_Underflow_Error : exception; Buffer_Overflow_Error : exception; -- Get an 8-bit value from the buffer. function Get_Uint8 (Buffer : in Buffer_Ptr) return MAT.Types.Uint8; -- Get a 16-bit value either from big-endian or little endian. function Get_Uint16 (Buffer : in Buffer_Ptr) return MAT.Types.Uint16; -- Get a 32-bit value either from big-endian or little endian. function Get_Uint32 (Buffer : in Buffer_Ptr) return MAT.Types.Uint32; -- Get a 64-bit value either from big-endian or little endian. function Get_Uint64 (Buffer : in Buffer_Ptr) return MAT.Types.Uint64; -- Extract a string from the buffer. The string starts with a byte that -- indicates the string length. function Get_String (Buffer : in Buffer_Ptr) return String; -- Extract a string from the buffer. The string starts with a byte that -- indicates the string length. function Get_String (Msg : in Buffer_Ptr) return Ada.Strings.Unbounded.Unbounded_String; generic type Target_Type is mod <>; function Get_Target_Value (Msg : in Buffer_Ptr; Kind : in MAT.Events.Attribute_Type) return Target_Type; function Get_Target_Size (Msg : in Buffer_Ptr; Kind : in MAT.Events.Attribute_Type) return MAT.Types.Target_Size; function Get_Target_Addr (Msg : in Buffer_Ptr; Kind : in MAT.Events.Attribute_Type) return MAT.Types.Target_Addr; function Get_Target_Uint32 (Msg : in Buffer_Ptr; Kind : in MAT.Events.Attribute_Type) return MAT.Types.Uint32; -- Skip the given number of bytes from the message. procedure Skip (Buffer : in Buffer_Ptr; Size : in Natural); end MAT.Readers.Marshaller;
----------------------------------------------------------------------- -- mat-readers-marshaller -- Marshalling of data in communication buffer -- 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.Events; package MAT.Readers.Marshaller is Buffer_Underflow_Error : exception; Buffer_Overflow_Error : exception; -- Get an 8-bit value from the buffer. function Get_Uint8 (Buffer : in Buffer_Ptr) return MAT.Types.Uint8; -- Get a 16-bit value either from big-endian or little endian. function Get_Uint16 (Buffer : in Buffer_Ptr) return MAT.Types.Uint16; -- Get a 32-bit value either from big-endian or little endian. function Get_Uint32 (Buffer : in Buffer_Ptr) return MAT.Types.Uint32; -- Get a 64-bit value either from big-endian or little endian. function Get_Uint64 (Buffer : in Buffer_Ptr) return MAT.Types.Uint64; -- Extract a string from the buffer. The string starts with a byte that -- indicates the string length. function Get_String (Buffer : in Message_Type) return String; -- Extract a string from the buffer. The string starts with a byte that -- indicates the string length. function Get_String (Msg : in Message_Type) return Ada.Strings.Unbounded.Unbounded_String; generic type Target_Type is mod <>; function Get_Target_Value (Msg : in Message_Type; Kind : in MAT.Events.Attribute_Type) return Target_Type; function Get_Target_Size (Msg : in Message_Type; Kind : in MAT.Events.Attribute_Type) return MAT.Types.Target_Size; function Get_Target_Addr (Msg : in Message_Type; Kind : in MAT.Events.Attribute_Type) return MAT.Types.Target_Addr; function Get_Target_Uint32 (Msg : in Message_Type; Kind : in MAT.Events.Attribute_Type) return MAT.Types.Uint32; -- Skip the given number of bytes from the message. procedure Skip (Buffer : in Message_Type; Size : in Natural); end MAT.Readers.Marshaller;
Change the Get_xx operation to use the Message_Type as parameter
Change the Get_xx operation to use the Message_Type as parameter
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
6284a86a55796b70843eb838e449fe3ebc7bcfd0
src/babel-streams.ads
src/babel-streams.ads
----------------------------------------------------------------------- -- babel-Streams -- Stream management -- Copyright (C) 2014, 2015 Stephane.Carrez -- Written by Stephane.Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Finalization; with Babel.Files.Buffers; package Babel.Streams is type Stream_Type is abstract tagged limited private; type Stream_Access is access all Stream_Type'Class; -- Read the data stream as much as possible and return the result in a buffer. -- The buffer is owned by the stream and need not be released. The same buffer may -- or may not be returned by the next <tt>Read</tt> operation. -- A null buffer is returned when the end of the data stream is reached. procedure Read (Stream : in out Stream_Type; Buffer : out Babel.Files.Buffers.Buffer_Access) is abstract; -- Write the buffer in the data stream. procedure Write (Stream : in out Stream_Type; Buffer : in Babel.Files.Buffers.Buffer_Access) is abstract; -- Flush the data stream. procedure Flush (Stream : in out Stream_Type) is null; -- Close the data stream. procedure Close (Stream : in out Stream_Type) is null; -- Prepare to read again the data stream from the beginning. procedure Rewind (Stream : in out Stream_Type) is null; -- Set the internal buffer that the stream can use. procedure Set_Buffer (Stream : in out Stream_Type; Buffer : in Babel.Files.Buffers.Buffer_Access); private type Stream_Type is abstract limited new Ada.Finalization.Limited_Controlled with record Buffer : Babel.Files.Buffers.Buffer_Access; end record; -- Release the stream buffer if there is one. overriding procedure Finalize (Stream : in out Stream_Type); end Babel.Streams;
----------------------------------------------------------------------- -- babel-Streams -- Stream management -- Copyright (C) 2014, 2015, 2016 Stephane.Carrez -- Written by Stephane.Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Finalization; with Util.Refs; with Babel.Files.Buffers; package Babel.Streams is type Stream_Type is abstract limited new Util.Refs.Ref_Entity with private; type Stream_Access is access all Stream_Type'Class; -- Read the data stream as much as possible and return the result in a buffer. -- The buffer is owned by the stream and need not be released. The same buffer may -- or may not be returned by the next <tt>Read</tt> operation. -- A null buffer is returned when the end of the data stream is reached. procedure Read (Stream : in out Stream_Type; Buffer : out Babel.Files.Buffers.Buffer_Access) is abstract; -- Write the buffer in the data stream. procedure Write (Stream : in out Stream_Type; Buffer : in Babel.Files.Buffers.Buffer_Access) is abstract; -- Flush the data stream. procedure Flush (Stream : in out Stream_Type) is null; -- Close the data stream. procedure Close (Stream : in out Stream_Type) is null; -- Prepare to read again the data stream from the beginning. procedure Rewind (Stream : in out Stream_Type) is null; -- Set the internal buffer that the stream can use. procedure Set_Buffer (Stream : in out Stream_Type; Buffer : in Babel.Files.Buffers.Buffer_Access); private type Stream_Type is abstract limited new Util.Refs.Ref_Entity with record Buffer : Babel.Files.Buffers.Buffer_Access; end record; -- Release the stream buffer if there is one. overriding procedure Finalize (Stream : in out Stream_Type); end Babel.Streams;
Use the Util.Refs.Ref_Entity for reference counting
Use the Util.Refs.Ref_Entity for reference counting
Ada
apache-2.0
stcarrez/babel
95f27e5fa951a5a1ceee425ae13d2f505514e073
src/ado-sessions.adb
src/ado-sessions.adb
----------------------------------------------------------------------- -- ADO Sessions -- Sessions Management -- Copyright (C) 2009, 2010, 2011, 2012, 2013, 2014, 2015, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Log; with Util.Log.Loggers; with Ada.Unchecked_Deallocation; with ADO.Drivers; with ADO.Sequences; with ADO.Statements.Create; package body ADO.Sessions is Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("ADO.Sessions"); procedure Check_Session (Database : in Session'Class; Message : in String := "") is begin if Database.Impl = null then Log.Error ("Session is closed or not initialized"); raise NOT_OPEN; end if; if Message'Length > 0 then Log.Info (Message, Database.Impl.Database.Value.Ident); end if; end Check_Session; -- --------- -- Session -- --------- -- ------------------------------ -- Get the session status. -- ------------------------------ function Get_Status (Database : in Session) return Connection_Status is begin if Database.Impl = null or else Database.Impl.Database.Is_Null then return CLOSED; else return OPEN; end if; end Get_Status; -- ------------------------------ -- Get the database driver which manages this connection. -- ------------------------------ function Get_Driver (Database : in Session) return ADO.Drivers.Connections.Driver_Access is begin if Database.Impl = null or else Database.Impl.Database.Is_Null then return null; else return Database.Impl.Database.Value.Get_Driver; end if; end Get_Driver; -- ------------------------------ -- Close the session. -- ------------------------------ procedure Close (Database : in out Session) is procedure Free is new Ada.Unchecked_Deallocation (Object => Session_Record, Name => Session_Record_Access); Is_Zero : Boolean; begin Log.Info ("Closing session"); if Database.Impl /= null then ADO.Objects.Release_Proxy (Database.Impl.Proxy); Database.Impl.Database.Value.Close; Util.Concurrent.Counters.Decrement (Database.Impl.Counter, Is_Zero); if Is_Zero then Free (Database.Impl); end if; Database.Impl := null; end if; end Close; -- ------------------------------ -- Insert a new cache in the manager. The cache is identified by the given name. -- ------------------------------ procedure Add_Cache (Database : in out Session; Name : in String; Cache : in ADO.Caches.Cache_Type_Access) is begin Check_Session (Database); Database.Impl.Values.Add_Cache (Name, Cache); end Add_Cache; -- ------------------------------ -- Attach the object to the session. -- ------------------------------ procedure Attach (Database : in out Session; Object : in ADO.Objects.Object_Ref'Class) is pragma Unreferenced (Object); begin Check_Session (Database); end Attach; -- ------------------------------ -- Check if the session contains the object identified by the given key. -- ------------------------------ function Contains (Database : in Session; Item : in ADO.Objects.Object_Key) return Boolean is begin Check_Session (Database); return ADO.Objects.Cache.Contains (Database.Impl.Cache, Item); end Contains; -- ------------------------------ -- Remove the object from the session cache. -- ------------------------------ procedure Evict (Database : in out Session; Item : in ADO.Objects.Object_Key) is begin Check_Session (Database); ADO.Objects.Cache.Remove (Database.Impl.Cache, Item); end Evict; -- ------------------------------ -- Create a query statement. The statement is not prepared -- ------------------------------ function Create_Statement (Database : in Session; Table : in ADO.Schemas.Class_Mapping_Access) return Query_Statement is begin Check_Session (Database); declare Query : constant Query_Statement_Access := Database.Impl.Database.Value.all.Create_Statement (Table); begin return ADO.Statements.Create.Create_Statement (Query, Database.Impl.Values.all'Access); end; end Create_Statement; -- ------------------------------ -- Create a query statement. The statement is not prepared -- ------------------------------ function Create_Statement (Database : in Session; Query : in String) return Query_Statement is begin Check_Session (Database); declare Stmt : constant Query_Statement_Access := Database.Impl.Database.Value.all.Create_Statement (Query); begin return ADO.Statements.Create.Create_Statement (Stmt, Database.Impl.Values.all'Access); end; end Create_Statement; -- ------------------------------ -- Create a query statement. The statement is not prepared -- ------------------------------ function Create_Statement (Database : in Session; Query : in ADO.Queries.Context'Class) return Query_Statement is begin Check_Session (Database); declare SQL : constant String := Query.Get_SQL (Database.Impl.Queries.all); Stmt : Query_Statement := Database.Create_Statement (SQL); begin Stmt.Set_Parameters (Query); return Stmt; end; end Create_Statement; -- ------------------------------ -- Create a query statement and initialize the SQL statement with the query definition. -- ------------------------------ function Create_Statement (Database : in Session; Query : in ADO.Queries.Query_Definition_Access) return Query_Statement is begin Check_Session (Database); declare SQL : constant String := ADO.Queries.Get_SQL (Query, Database.Impl.Queries.all, False); begin return Database.Create_Statement (SQL); end; end Create_Statement; -- ------------------------------ -- Create a query statement. The statement is not prepared -- ------------------------------ function Create_Statement (Database : in Session; Query : in ADO.SQL.Query'Class; Table : in ADO.Schemas.Class_Mapping_Access) return Query_Statement is begin Check_Session (Database); declare Stmt : Query_Statement := Database.Create_Statement (Table); begin if Query in ADO.Queries.Context'Class then declare SQL : constant String := ADO.Queries.Context'Class (Query).Get_SQL (Database.Impl.Queries.all); begin ADO.SQL.Append (Stmt.Get_Query.SQL, SQL); end; end if; Stmt.Set_Parameters (Query); return Stmt; end; end Create_Statement; -- ------------------------------ -- Load the database schema definition for the current database. -- ------------------------------ procedure Load_Schema (Database : in Session; Schema : out ADO.Schemas.Schema_Definition) is begin Check_Session (Database, "Loading schema {0}"); Database.Impl.Database.Value.Load_Schema (Schema); end Load_Schema; -- --------- -- Master Session -- --------- -- ------------------------------ -- Start a transaction. -- ------------------------------ procedure Begin_Transaction (Database : in out Master_Session) is begin Check_Session (Database, "Begin transaction {0}"); Database.Impl.Database.Value.Begin_Transaction; end Begin_Transaction; -- ------------------------------ -- Commit the current transaction. -- ------------------------------ procedure Commit (Database : in out Master_Session) is begin Check_Session (Database, "Commit transaction {0}"); Database.Impl.Database.Value.Commit; end Commit; -- ------------------------------ -- Rollback the current transaction. -- ------------------------------ procedure Rollback (Database : in out Master_Session) is begin Check_Session (Database, "Rollback transaction {0}"); Database.Impl.Database.Value.Rollback; end Rollback; -- ------------------------------ -- Allocate an identifier for the table. -- ------------------------------ procedure Allocate (Database : in out Master_Session; Id : in out ADO.Objects.Object_Record'Class) is begin Check_Session (Database); ADO.Sequences.Allocate (Database.Sequences.all, Id); end Allocate; -- ------------------------------ -- Flush the objects that were modified. -- ------------------------------ procedure Flush (Database : in out Master_Session) is begin Check_Session (Database); end Flush; overriding procedure Adjust (Object : in out Session) is begin if Object.Impl /= null then Util.Concurrent.Counters.Increment (Object.Impl.Counter); end if; end Adjust; overriding procedure Finalize (Object : in out Session) is procedure Free is new Ada.Unchecked_Deallocation (Object => Session_Record, Name => Session_Record_Access); Is_Zero : Boolean; begin if Object.Impl /= null then Util.Concurrent.Counters.Decrement (Object.Impl.Counter, Is_Zero); if Is_Zero then ADO.Objects.Release_Proxy (Object.Impl.Proxy, Detach => True); if not Object.Impl.Database.Is_Null then Object.Impl.Database.Value.Close; end if; Free (Object.Impl); end if; Object.Impl := null; end if; end Finalize; -- ------------------------------ -- Create a delete statement -- ------------------------------ function Create_Statement (Database : in Master_Session; Table : in ADO.Schemas.Class_Mapping_Access) return Delete_Statement is begin Check_Session (Database); declare Stmt : constant Delete_Statement_Access := Database.Impl.Database.Value.all.Create_Statement (Table); begin return ADO.Statements.Create.Create_Statement (Stmt.all'Access, Database.Impl.Values.all'Access); end; end Create_Statement; -- ------------------------------ -- Create an update statement -- ------------------------------ function Create_Statement (Database : in Master_Session; Table : in ADO.Schemas.Class_Mapping_Access) return Update_Statement is begin Check_Session (Database); declare Stmt : constant Update_Statement_Access := Database.Impl.Database.Value.all.Create_Statement (Table); begin return ADO.Statements.Create.Create_Statement (Stmt.all'Access, Database.Impl.Values.all'Access); end; end Create_Statement; -- ------------------------------ -- Create an insert statement -- ------------------------------ function Create_Statement (Database : in Master_Session; Table : in ADO.Schemas.Class_Mapping_Access) return Insert_Statement is begin Check_Session (Database); declare Stmt : constant Insert_Statement_Access := Database.Impl.Database.Value.all.Create_Statement (Table); begin return ADO.Statements.Create.Create_Statement (Stmt.all'Access, Database.Impl.Values.all'Access); end; end Create_Statement; -- ------------------------------ -- Internal method to get the session proxy associated with the given database session. -- The session proxy is associated with some ADO objects to be able to retrieve the database -- session for the implementation of lazy loading. The session proxy is kept until the -- session exist and at least one ADO object is refering to it. -- ------------------------------ function Get_Session_Proxy (Database : in Session) return ADO.Objects.Session_Proxy_Access is use type ADO.Objects.Session_Proxy_Access; begin Check_Session (Database); if Database.Impl.Proxy = null then Database.Impl.Proxy := ADO.Objects.Create_Session_Proxy (Database.Impl); end if; return Database.Impl.Proxy; end Get_Session_Proxy; end ADO.Sessions;
----------------------------------------------------------------------- -- ADO Sessions -- Sessions Management -- Copyright (C) 2009, 2010, 2011, 2012, 2013, 2014, 2015, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Log; with Util.Log.Loggers; with Ada.Unchecked_Deallocation; with ADO.Drivers; with ADO.Sequences; with ADO.Statements.Create; package body ADO.Sessions is Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("ADO.Sessions"); procedure Check_Session (Database : in Session'Class; Message : in String := "") is begin if Database.Impl = null then Log.Error ("Session is closed or not initialized"); raise NOT_OPEN; end if; if Message'Length > 0 then Log.Info (Message, Database.Impl.Database.Value.Ident); end if; end Check_Session; -- --------- -- Session -- --------- -- ------------------------------ -- Get the session status. -- ------------------------------ function Get_Status (Database : in Session) return Connection_Status is begin if Database.Impl = null or else Database.Impl.Database.Is_Null then return CLOSED; else return OPEN; end if; end Get_Status; -- ------------------------------ -- Get the database driver which manages this connection. -- ------------------------------ function Get_Driver (Database : in Session) return ADO.Drivers.Connections.Driver_Access is begin if Database.Impl = null or else Database.Impl.Database.Is_Null then return null; else return Database.Impl.Database.Value.Get_Driver; end if; end Get_Driver; -- ------------------------------ -- Close the session. -- ------------------------------ procedure Close (Database : in out Session) is procedure Free is new Ada.Unchecked_Deallocation (Object => Session_Record, Name => Session_Record_Access); Is_Zero : Boolean; begin Log.Info ("Closing session"); if Database.Impl /= null then ADO.Objects.Release_Proxy (Database.Impl.Proxy); Database.Impl.Database.Value.Close; Util.Concurrent.Counters.Decrement (Database.Impl.Counter, Is_Zero); if Is_Zero then Free (Database.Impl); end if; Database.Impl := null; end if; end Close; -- ------------------------------ -- Insert a new cache in the manager. The cache is identified by the given name. -- ------------------------------ procedure Add_Cache (Database : in out Session; Name : in String; Cache : in ADO.Caches.Cache_Type_Access) is begin Check_Session (Database); Database.Impl.Values.Add_Cache (Name, Cache); end Add_Cache; -- ------------------------------ -- Attach the object to the session. -- ------------------------------ procedure Attach (Database : in out Session; Object : in ADO.Objects.Object_Ref'Class) is pragma Unreferenced (Object); begin Check_Session (Database); end Attach; -- ------------------------------ -- Check if the session contains the object identified by the given key. -- ------------------------------ function Contains (Database : in Session; Item : in ADO.Objects.Object_Key) return Boolean is begin Check_Session (Database); return ADO.Objects.Cache.Contains (Database.Impl.Cache, Item); end Contains; -- ------------------------------ -- Remove the object from the session cache. -- ------------------------------ procedure Evict (Database : in out Session; Item : in ADO.Objects.Object_Key) is begin Check_Session (Database); ADO.Objects.Cache.Remove (Database.Impl.Cache, Item); end Evict; -- ------------------------------ -- Create a query statement. The statement is not prepared -- ------------------------------ function Create_Statement (Database : in Session; Table : in ADO.Schemas.Class_Mapping_Access) return Query_Statement is begin Check_Session (Database); declare Query : constant Query_Statement_Access := Database.Impl.Database.Value.all.Create_Statement (Table); begin return ADO.Statements.Create.Create_Statement (Query, Database.Impl.Values.all'Access); end; end Create_Statement; -- ------------------------------ -- Create a query statement. The statement is not prepared -- ------------------------------ function Create_Statement (Database : in Session; Query : in String) return Query_Statement is begin Check_Session (Database); declare Stmt : constant Query_Statement_Access := Database.Impl.Database.Value.all.Create_Statement (Query); begin return ADO.Statements.Create.Create_Statement (Stmt, Database.Impl.Values.all'Access); end; end Create_Statement; -- ------------------------------ -- Create a query statement. The statement is not prepared -- ------------------------------ function Create_Statement (Database : in Session; Query : in ADO.Queries.Context'Class) return Query_Statement is begin Check_Session (Database); declare SQL : constant String := Query.Get_SQL (Database.Impl.Queries.all); Stmt : Query_Statement := Database.Create_Statement (SQL); begin Stmt.Set_Parameters (Query); return Stmt; end; end Create_Statement; -- ------------------------------ -- Create a query statement and initialize the SQL statement with the query definition. -- ------------------------------ function Create_Statement (Database : in Session; Query : in ADO.Queries.Query_Definition_Access) return Query_Statement is begin Check_Session (Database); declare SQL : constant String := ADO.Queries.Get_SQL (Query, Database.Impl.Queries.all, False); begin return Database.Create_Statement (SQL); end; end Create_Statement; -- ------------------------------ -- Create a query statement. The statement is not prepared -- ------------------------------ function Create_Statement (Database : in Session; Query : in ADO.SQL.Query'Class; Table : in ADO.Schemas.Class_Mapping_Access) return Query_Statement is begin Check_Session (Database); declare Stmt : Query_Statement := Database.Create_Statement (Table); begin if Query in ADO.Queries.Context'Class then declare SQL : constant String := ADO.Queries.Context'Class (Query).Get_SQL (Database.Impl.Queries.all); begin ADO.SQL.Append (Stmt.Get_Query.SQL, SQL); end; end if; Stmt.Set_Parameters (Query); return Stmt; end; end Create_Statement; -- ------------------------------ -- Load the database schema definition for the current database. -- ------------------------------ procedure Load_Schema (Database : in Session; Schema : out ADO.Schemas.Schema_Definition) is begin Check_Session (Database, "Loading schema {0}"); Database.Impl.Database.Value.Load_Schema (Schema); end Load_Schema; -- --------- -- Master Session -- --------- -- ------------------------------ -- Start a transaction. -- ------------------------------ procedure Begin_Transaction (Database : in out Master_Session) is begin Check_Session (Database, "Begin transaction {0}"); Database.Impl.Database.Value.Begin_Transaction; end Begin_Transaction; -- ------------------------------ -- Commit the current transaction. -- ------------------------------ procedure Commit (Database : in out Master_Session) is begin Check_Session (Database, "Commit transaction {0}"); Database.Impl.Database.Value.Commit; end Commit; -- ------------------------------ -- Rollback the current transaction. -- ------------------------------ procedure Rollback (Database : in out Master_Session) is begin Check_Session (Database, "Rollback transaction {0}"); Database.Impl.Database.Value.Rollback; end Rollback; -- ------------------------------ -- Allocate an identifier for the table. -- ------------------------------ procedure Allocate (Database : in out Master_Session; Id : in out ADO.Objects.Object_Record'Class) is begin Check_Session (Database); ADO.Sequences.Allocate (Database.Sequences.all, Id); end Allocate; -- ------------------------------ -- Flush the objects that were modified. -- ------------------------------ procedure Flush (Database : in out Master_Session) is begin Check_Session (Database); end Flush; overriding procedure Adjust (Object : in out Session) is begin if Object.Impl /= null then Util.Concurrent.Counters.Increment (Object.Impl.Counter); end if; end Adjust; overriding procedure Finalize (Object : in out Session) is procedure Free is new Ada.Unchecked_Deallocation (Object => Session_Record, Name => Session_Record_Access); Is_Zero : Boolean; begin if Object.Impl /= null then Util.Concurrent.Counters.Decrement (Object.Impl.Counter, Is_Zero); if Is_Zero then ADO.Objects.Release_Proxy (Object.Impl.Proxy, Detach => True); if not Object.Impl.Database.Is_Null then Object.Impl.Database.Value.Close; end if; Free (Object.Impl); end if; Object.Impl := null; end if; end Finalize; -- ------------------------------ -- Create a delete statement -- ------------------------------ function Create_Statement (Database : in Master_Session; Table : in ADO.Schemas.Class_Mapping_Access) return Delete_Statement is begin Check_Session (Database); declare Stmt : constant Delete_Statement_Access := Database.Impl.Database.Value.all.Create_Statement (Table); begin return ADO.Statements.Create.Create_Statement (Stmt.all'Access, Database.Impl.Values.all'Access); end; end Create_Statement; -- ------------------------------ -- Create an update statement -- ------------------------------ function Create_Statement (Database : in Master_Session; Table : in ADO.Schemas.Class_Mapping_Access) return Update_Statement is begin Check_Session (Database); declare Stmt : constant Update_Statement_Access := Database.Impl.Database.Value.all.Create_Statement (Table); begin return ADO.Statements.Create.Create_Statement (Stmt.all'Access, Database.Impl.Values.all'Access); end; end Create_Statement; -- ------------------------------ -- Create an insert statement -- ------------------------------ function Create_Statement (Database : in Master_Session; Table : in ADO.Schemas.Class_Mapping_Access) return Insert_Statement is begin Check_Session (Database); declare Stmt : constant Insert_Statement_Access := Database.Impl.Database.Value.all.Create_Statement (Table); begin return ADO.Statements.Create.Create_Statement (Stmt.all'Access, Database.Impl.Values.all'Access); end; end Create_Statement; -- ------------------------------ -- Internal method to get the session proxy associated with the given database session. -- The session proxy is associated with some ADO objects to be able to retrieve the database -- session for the implementation of lazy loading. The session proxy is kept until the -- session exist and at least one ADO object is refering to it. -- ------------------------------ function Get_Session_Proxy (Database : in Session) return ADO.Objects.Session_Proxy_Access is use type ADO.Objects.Session_Proxy_Access; begin Check_Session (Database); if Database.Impl.Proxy = null then Database.Impl.Proxy := ADO.Objects.Create_Session_Proxy (Database.Impl); end if; return Database.Impl.Proxy; end Get_Session_Proxy; end ADO.Sessions;
Fix style compilation warning
Fix style compilation warning
Ada
apache-2.0
stcarrez/ada-ado
2d1cdbbfe866448b653754055e91d9c5d30ad753
src/gen-model-xmi.ads
src/gen-model-xmi.ads
----------------------------------------------------------------------- -- gen-model-xmi -- UML-XMI model -- 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.Containers.Hashed_Maps; with Ada.Strings.Unbounded; with Ada.Strings.Unbounded.Hash; with Ada.Containers.Vectors; with Util.Beans.Objects; with Gen.Model.Tables; package Gen.Model.XMI is use Ada.Strings.Unbounded; type Element_Type is (XMI_UNKNOWN, XMI_PACKAGE, XMI_CLASS, XMI_ASSOCIATION, XMI_ASSOCIATION_END, XMI_ATTRIBUTE, XMI_OPERATION, XMI_ENUMERATION, XMI_ENUMERATION_LITERAL, XMI_TAGGED_VALUE, XMI_TAG_DEFINITION, XMI_DATA_TYPE, XMI_STEREOTYPE, XMI_COMMENT); -- Defines the visibility of an element (a package, class, attribute, operation). type Visibility_Type is (VISIBILITY_PUBLIC, VISIBILITY_PACKAGE, VISIBILITY_PROTECTED, VISIBILITY_PRIVATE); -- Defines whether an attribute or association changes. type Changeability_Type is (CHANGEABILITY_INSERT, CHANGEABILITY_CHANGEABLE, CHANGEABILITY_FROZEN); type Model_Element; type Tagged_Value_Element; type Model_Element_Access is access all Model_Element'Class; type Tagged_Value_Element_Access is access all Tagged_Value_Element'Class; -- Define a list of model elements. package Model_Vectors is new Ada.Containers.Vectors (Index_Type => Positive, Element_Type => Model_Element_Access); subtype Model_Vector is Model_Vectors.Vector; subtype Model_Cursor is Model_Vectors.Cursor; -- Define a map to search an element from its XMI ID. package Model_Map is new Ada.Containers.Hashed_Maps (Key_Type => Unbounded_String, Element_Type => Model_Element_Access, Hash => Ada.Strings.Unbounded.Hash, Equivalent_Keys => "="); subtype Model_Map_Cursor is Model_Map.Cursor; type Model_Map_Access is access all Model_Map.Map; -- Returns true if the table cursor contains a valid table function Has_Element (Position : in Model_Map_Cursor) return Boolean renames Model_Map.Has_Element; -- Returns the table definition. function Element (Position : in Model_Map_Cursor) return Model_Element_Access renames Model_Map.Element; -- Move the iterator to the next table definition. procedure Next (Position : in out Model_Map_Cursor) renames Model_Map.Next; -- Iterate on the model element of the type <tt>On</tt> and execute the <tt>Process</tt> -- procedure. procedure Iterate (Model : in Model_Map.Map; On : in Element_Type; Process : not null access procedure (Id : in Unbounded_String; Node : in Model_Element_Access)); -- Generic procedure to iterate over the XMI elements of a vector -- and having the entity name <b>name</b>. generic type T (<>) is limited private; procedure Iterate_Elements (Closure : in out T; List : in Model_Vector; Process : not null access procedure (Closure : in out T; Node : in Model_Element_Access)); -- Map of UML models indexed on the model name. package UML_Model_Map is new Ada.Containers.Hashed_Maps (Key_Type => Unbounded_String, Element_Type => Model_Map.Map, Hash => Ada.Strings.Unbounded.Hash, Equivalent_Keys => "=", "=" => Model_Map."="); subtype UML_Model is UML_Model_Map.Map; type Search_Type is (BY_NAME, BY_ID); -- Find the model element with the given XMI id. -- Returns null if the model element is not found. function Find (Model : in Model_Map.Map; Key : in String; Mode : in Search_Type := BY_ID) return Model_Element_Access; -- Find the model element within all loaded UML models. -- Returns null if the model element is not found. function Find (Model : in UML_Model; Current : in Model_Map.Map; Id : in Ada.Strings.Unbounded.Unbounded_String) return Model_Element_Access; -- Dump the XMI model elements. procedure Dump (Map : in Model_Map.Map); -- Reconcile all the UML model elements by resolving all the references to UML elements. procedure Reconcile (Model : in out UML_Model); -- ------------------------------ -- Model Element -- ------------------------------ type Model_Element (Model : Model_Map_Access) is abstract new Definition with record -- Element XMI id. XMI_Id : Ada.Strings.Unbounded.Unbounded_String; -- List of tagged values for the element. Tagged_Values : Model_Vector; -- Elements contained. Elements : Model_Vector; -- Stereotypes associated with the element. Stereotypes : Model_Vector; -- The parent model element; Parent : Model_Element_Access; end record; -- Get the element type. function Get_Type (Node : in Model_Element) return Element_Type is abstract; -- Reconcile the element by resolving the references to other elements in the model. procedure Reconcile (Node : in out Model_Element; Model : in UML_Model); -- Find the element with the given name. If the name is a qualified name, navigate -- down the package/class to find the appropriate element. -- Returns null if the element was not found. function Find (Node : in Model_Element; Name : in String) return Model_Element_Access; -- Set the model name. procedure Set_Name (Node : in out Model_Element; Value : in Util.Beans.Objects.Object); -- Set the model XMI unique id. procedure Set_XMI_Id (Node : in out Model_Element; Value : in Util.Beans.Objects.Object); -- Find the tag value element with the given name. -- Returns null if there is no such tag. function Find_Tag_Value (Node : in Model_Element; Name : in String) return Tagged_Value_Element_Access; -- Get the documentation and comment associated with the model element. -- Returns the empty string if there is no comment. function Get_Comment (Node : in Model_Element) return String; -- Get the full qualified name for the element. function Get_Qualified_Name (Node : in Model_Element) return String; -- Find from the model file identified by <tt>Name</tt>, the model element with the -- identifier or name represented by <tt>Key</tt>. -- Returns null if the model element is not found. generic type Element_Type is new Model_Element with private; type Element_Type_Access is access all Element_Type'Class; function Find_Element (Model : in UML_Model; Name : in String; Key : in String; Mode : in Search_Type := BY_ID) return Element_Type_Access; -- ------------------------------ -- Data type -- ------------------------------ type Ref_Type_Element is new Model_Element with record Href : Unbounded_String; Ref : Model_Element_Access; end record; type Ref_Type_Element_Access is access all Ref_Type_Element'Class; -- Get the element type. overriding function Get_Type (Node : in Ref_Type_Element) return Element_Type; -- Reconcile the element by resolving the references to other elements in the model. overriding procedure Reconcile (Node : in out Ref_Type_Element; Model : in UML_Model); -- ------------------------------ -- Data type -- ------------------------------ type Data_Type_Element is new Model_Element with null record; type Data_Type_Element_Access is access all Data_Type_Element'Class; -- Get the element type. overriding function Get_Type (Node : in Data_Type_Element) return Element_Type; -- ------------------------------ -- Enum -- ------------------------------ type Enum_Element is new Model_Element with null record; type Enum_Element_Access is access all Enum_Element'Class; -- Get the element type. overriding function Get_Type (Node : in Enum_Element) return Element_Type; procedure Add_Literal (Node : in out Enum_Element; Id : in Util.Beans.Objects.Object; Name : in Util.Beans.Objects.Object); -- ------------------------------ -- Literal -- ------------------------------ -- The literal describes a possible value for an enum. type Literal_Element is new Model_Element with null record; type Literal_Element_Access is access all Literal_Element'Class; -- Get the element type. overriding function Get_Type (Node : in Literal_Element) return Element_Type; -- ------------------------------ -- Stereotype -- ------------------------------ type Stereotype_Element is new Model_Element with null record; type Stereotype_Element_Access is access all Stereotype_Element'Class; -- Get the element type. overriding function Get_Type (Node : in Stereotype_Element) return Element_Type; -- Returns True if the model element has the stereotype with the given name. function Has_Stereotype (Node : in Model_Element'Class; Stereotype : in Stereotype_Element_Access) return Boolean; -- ------------------------------ -- Comment -- ------------------------------ type Comment_Element is new Model_Element with record Text : Ada.Strings.Unbounded.Unbounded_String; Ref_Id : Ada.Strings.Unbounded.Unbounded_String; end record; type Comment_Element_Access is access all Comment_Element'Class; -- Get the element type. overriding function Get_Type (Node : in Comment_Element) return Element_Type; -- ------------------------------ -- An operation -- ------------------------------ type Operation_Element is new Model_Element with record Visibility : Visibility_Type := VISIBILITY_PUBLIC; end record; type Operation_Element_Access is access all Operation_Element'Class; -- Get the element type. overriding function Get_Type (Node : in Operation_Element) return Element_Type; -- ------------------------------ -- An attribute -- ------------------------------ type Attribute_Element is new Model_Element with record Ref_Id : Ada.Strings.Unbounded.Unbounded_String; Data_Type : Data_Type_Element_Access; Visibility : Visibility_Type := VISIBILITY_PUBLIC; Changeability : Changeability_Type := CHANGEABILITY_CHANGEABLE; Initial_Value : Util.Beans.Objects.Object; Multiplicity_Lower : Integer := 0; Multiplicity_Upper : Integer := 1; end record; type Attribute_Element_Access is access all Attribute_Element'Class; -- Get the element type. overriding function Get_Type (Node : in Attribute_Element) return Element_Type; -- Reconcile the element by resolving the references to other elements in the model. overriding procedure Reconcile (Node : in out Attribute_Element; Model : in UML_Model); -- ------------------------------ -- An association end -- ------------------------------ type Association_End_Element is new Model_Element with record Visibility : Visibility_Type := VISIBILITY_PUBLIC; end record; type Association_End_Element_Access is access all Association_End_Element'Class; -- Get the element type. overriding function Get_Type (Node : in Association_End_Element) return Element_Type; -- ------------------------------ -- An association -- ------------------------------ type Association_Element is new Model_Element with record Visibility : Visibility_Type := VISIBILITY_PUBLIC; end record; type Association_Element_Access is access all Association_Element'Class; -- Get the element type. overriding function Get_Type (Node : in Association_Element) return Element_Type; -- ------------------------------ -- Tag Definition -- ------------------------------ TAG_DOCUMENTATION : constant String := "documentation"; TAG_AUTHOR : constant String := "author"; type Tag_Definition_Element is new Model_Element with record Multiplicity_Lower : Natural := 0; Multiplicity_Upper : Natural := 0; end record; type Tag_Definition_Element_Access is access all Tag_Definition_Element'Class; -- Get the element type. overriding function Get_Type (Node : in Tag_Definition_Element) return Element_Type; -- ------------------------------ -- Tagged value -- ------------------------------ type Tagged_Value_Element is new Model_Element with record Value : Ada.Strings.Unbounded.Unbounded_String; Value_Type : Ada.Strings.Unbounded.Unbounded_String; Ref_Id : Ada.Strings.Unbounded.Unbounded_String; Tag_Def : Tag_Definition_Element_Access; end record; -- Get the element type. overriding function Get_Type (Node : in Tagged_Value_Element) return Element_Type; -- Reconcile the element by resolving the references to other elements in the model. overriding procedure Reconcile (Node : in out Tagged_Value_Element; Model : in UML_Model); -- ------------------------------ -- A class -- ------------------------------ type Class_Element is new Model_Element with record Operations : Model_Vector; Attributes : Model_Vector; Associations : Model_Vector; Visibility : Visibility_Type := VISIBILITY_PUBLIC; end record; type Class_Element_Access is access all Class_Element'Class; -- Get the element type. overriding function Get_Type (Node : in Class_Element) return Element_Type; -- ------------------------------ -- A package -- ------------------------------ type Package_Element; type Package_Element_Access is access all Package_Element'Class; type Package_Element is new Model_Element with record Classes : Model_Vector; end record; -- Get the element type. overriding function Get_Type (Node : in Package_Element) return Element_Type; end Gen.Model.XMI;
----------------------------------------------------------------------- -- gen-model-xmi -- UML-XMI model -- 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.Containers.Hashed_Maps; with Ada.Strings.Unbounded; with Ada.Strings.Unbounded.Hash; with Ada.Containers.Vectors; with Util.Beans.Objects; with Gen.Model.Tables; package Gen.Model.XMI is use Ada.Strings.Unbounded; type Element_Type is (XMI_UNKNOWN, XMI_PACKAGE, XMI_CLASS, XMI_ASSOCIATION, XMI_ASSOCIATION_END, XMI_ATTRIBUTE, XMI_OPERATION, XMI_ENUMERATION, XMI_ENUMERATION_LITERAL, XMI_TAGGED_VALUE, XMI_TAG_DEFINITION, XMI_DATA_TYPE, XMI_STEREOTYPE, XMI_COMMENT); -- Defines the visibility of an element (a package, class, attribute, operation). type Visibility_Type is (VISIBILITY_PUBLIC, VISIBILITY_PACKAGE, VISIBILITY_PROTECTED, VISIBILITY_PRIVATE); -- Defines whether an attribute or association changes. type Changeability_Type is (CHANGEABILITY_INSERT, CHANGEABILITY_CHANGEABLE, CHANGEABILITY_FROZEN); type Model_Element; type Tagged_Value_Element; type Model_Element_Access is access all Model_Element'Class; type Tagged_Value_Element_Access is access all Tagged_Value_Element'Class; -- Define a list of model elements. package Model_Vectors is new Ada.Containers.Vectors (Index_Type => Positive, Element_Type => Model_Element_Access); subtype Model_Vector is Model_Vectors.Vector; subtype Model_Cursor is Model_Vectors.Cursor; -- Define a map to search an element from its XMI ID. package Model_Map is new Ada.Containers.Hashed_Maps (Key_Type => Unbounded_String, Element_Type => Model_Element_Access, Hash => Ada.Strings.Unbounded.Hash, Equivalent_Keys => "="); subtype Model_Map_Cursor is Model_Map.Cursor; type Model_Map_Access is access all Model_Map.Map; -- Returns true if the table cursor contains a valid table function Has_Element (Position : in Model_Map_Cursor) return Boolean renames Model_Map.Has_Element; -- Returns the table definition. function Element (Position : in Model_Map_Cursor) return Model_Element_Access renames Model_Map.Element; -- Move the iterator to the next table definition. procedure Next (Position : in out Model_Map_Cursor) renames Model_Map.Next; -- Iterate on the model element of the type <tt>On</tt> and execute the <tt>Process</tt> -- procedure. procedure Iterate (Model : in Model_Map.Map; On : in Element_Type; Process : not null access procedure (Id : in Unbounded_String; Node : in Model_Element_Access)); -- Generic procedure to iterate over the XMI elements of a vector -- and having the entity name <b>name</b>. generic type T (<>) is limited private; procedure Iterate_Elements (Closure : in out T; List : in Model_Vector; Process : not null access procedure (Closure : in out T; Node : in Model_Element_Access)); -- Map of UML models indexed on the model name. package UML_Model_Map is new Ada.Containers.Hashed_Maps (Key_Type => Unbounded_String, Element_Type => Model_Map.Map, Hash => Ada.Strings.Unbounded.Hash, Equivalent_Keys => "=", "=" => Model_Map."="); subtype UML_Model is UML_Model_Map.Map; type Search_Type is (BY_NAME, BY_ID); -- Find the model element with the given XMI id. -- Returns null if the model element is not found. function Find (Model : in Model_Map.Map; Key : in String; Mode : in Search_Type := BY_ID) return Model_Element_Access; -- Find the model element within all loaded UML models. -- Returns null if the model element is not found. function Find (Model : in UML_Model; Current : in Model_Map.Map; Id : in Ada.Strings.Unbounded.Unbounded_String) return Model_Element_Access; -- Dump the XMI model elements. procedure Dump (Map : in Model_Map.Map); -- Reconcile all the UML model elements by resolving all the references to UML elements. procedure Reconcile (Model : in out UML_Model); -- ------------------------------ -- Model Element -- ------------------------------ type Model_Element (Model : Model_Map_Access) is abstract new Definition with record -- Element XMI id. XMI_Id : Ada.Strings.Unbounded.Unbounded_String; -- List of tagged values for the element. Tagged_Values : Model_Vector; -- Elements contained. Elements : Model_Vector; -- Stereotypes associated with the element. Stereotypes : Model_Vector; -- The parent model element; Parent : Model_Element_Access; end record; -- Get the element type. function Get_Type (Node : in Model_Element) return Element_Type is abstract; -- Reconcile the element by resolving the references to other elements in the model. procedure Reconcile (Node : in out Model_Element; Model : in UML_Model); -- Find the element with the given name. If the name is a qualified name, navigate -- down the package/class to find the appropriate element. -- Returns null if the element was not found. function Find (Node : in Model_Element; Name : in String) return Model_Element_Access; -- Set the model name. procedure Set_Name (Node : in out Model_Element; Value : in Util.Beans.Objects.Object); -- Set the model XMI unique id. procedure Set_XMI_Id (Node : in out Model_Element; Value : in Util.Beans.Objects.Object); -- Find the tag value element with the given name. -- Returns null if there is no such tag. function Find_Tag_Value (Node : in Model_Element; Name : in String) return Tagged_Value_Element_Access; -- Get the documentation and comment associated with the model element. -- Returns the empty string if there is no comment. function Get_Comment (Node : in Model_Element) return String; -- Get the full qualified name for the element. function Get_Qualified_Name (Node : in Model_Element) return String; -- Find from the model file identified by <tt>Name</tt>, the model element with the -- identifier or name represented by <tt>Key</tt>. -- Returns null if the model element is not found. generic type Element_Type is new Model_Element with private; type Element_Type_Access is access all Element_Type'Class; function Find_Element (Model : in UML_Model; Name : in String; Key : in String; Mode : in Search_Type := BY_ID) return Element_Type_Access; -- ------------------------------ -- Data type -- ------------------------------ type Ref_Type_Element is new Model_Element with record Href : Unbounded_String; Ref : Model_Element_Access; end record; type Ref_Type_Element_Access is access all Ref_Type_Element'Class; -- Get the element type. overriding function Get_Type (Node : in Ref_Type_Element) return Element_Type; -- Reconcile the element by resolving the references to other elements in the model. overriding procedure Reconcile (Node : in out Ref_Type_Element; Model : in UML_Model); -- ------------------------------ -- Data type -- ------------------------------ type Data_Type_Element is new Model_Element with null record; type Data_Type_Element_Access is access all Data_Type_Element'Class; -- Get the element type. overriding function Get_Type (Node : in Data_Type_Element) return Element_Type; -- ------------------------------ -- Enum -- ------------------------------ type Enum_Element is new Data_Type_Element with null record; type Enum_Element_Access is access all Enum_Element'Class; -- Get the element type. overriding function Get_Type (Node : in Enum_Element) return Element_Type; procedure Add_Literal (Node : in out Enum_Element; Id : in Util.Beans.Objects.Object; Name : in Util.Beans.Objects.Object); -- ------------------------------ -- Literal -- ------------------------------ -- The literal describes a possible value for an enum. type Literal_Element is new Model_Element with null record; type Literal_Element_Access is access all Literal_Element'Class; -- Get the element type. overriding function Get_Type (Node : in Literal_Element) return Element_Type; -- ------------------------------ -- Stereotype -- ------------------------------ type Stereotype_Element is new Model_Element with null record; type Stereotype_Element_Access is access all Stereotype_Element'Class; -- Get the element type. overriding function Get_Type (Node : in Stereotype_Element) return Element_Type; -- Returns True if the model element has the stereotype with the given name. function Has_Stereotype (Node : in Model_Element'Class; Stereotype : in Stereotype_Element_Access) return Boolean; -- ------------------------------ -- Comment -- ------------------------------ type Comment_Element is new Model_Element with record Text : Ada.Strings.Unbounded.Unbounded_String; Ref_Id : Ada.Strings.Unbounded.Unbounded_String; end record; type Comment_Element_Access is access all Comment_Element'Class; -- Get the element type. overriding function Get_Type (Node : in Comment_Element) return Element_Type; -- ------------------------------ -- An operation -- ------------------------------ type Operation_Element is new Model_Element with record Visibility : Visibility_Type := VISIBILITY_PUBLIC; end record; type Operation_Element_Access is access all Operation_Element'Class; -- Get the element type. overriding function Get_Type (Node : in Operation_Element) return Element_Type; -- ------------------------------ -- An attribute -- ------------------------------ type Attribute_Element is new Model_Element with record Ref_Id : Ada.Strings.Unbounded.Unbounded_String; Data_Type : Data_Type_Element_Access; Visibility : Visibility_Type := VISIBILITY_PUBLIC; Changeability : Changeability_Type := CHANGEABILITY_CHANGEABLE; Initial_Value : Util.Beans.Objects.Object; Multiplicity_Lower : Integer := 0; Multiplicity_Upper : Integer := 1; end record; type Attribute_Element_Access is access all Attribute_Element'Class; -- Get the element type. overriding function Get_Type (Node : in Attribute_Element) return Element_Type; -- Reconcile the element by resolving the references to other elements in the model. overriding procedure Reconcile (Node : in out Attribute_Element; Model : in UML_Model); -- ------------------------------ -- An association end -- ------------------------------ type Association_End_Element is new Model_Element with record Visibility : Visibility_Type := VISIBILITY_PUBLIC; end record; type Association_End_Element_Access is access all Association_End_Element'Class; -- Get the element type. overriding function Get_Type (Node : in Association_End_Element) return Element_Type; -- ------------------------------ -- An association -- ------------------------------ type Association_Element is new Model_Element with record Visibility : Visibility_Type := VISIBILITY_PUBLIC; end record; type Association_Element_Access is access all Association_Element'Class; -- Get the element type. overriding function Get_Type (Node : in Association_Element) return Element_Type; -- ------------------------------ -- Tag Definition -- ------------------------------ TAG_DOCUMENTATION : constant String := "documentation"; TAG_AUTHOR : constant String := "author"; type Tag_Definition_Element is new Model_Element with record Multiplicity_Lower : Natural := 0; Multiplicity_Upper : Natural := 0; end record; type Tag_Definition_Element_Access is access all Tag_Definition_Element'Class; -- Get the element type. overriding function Get_Type (Node : in Tag_Definition_Element) return Element_Type; -- ------------------------------ -- Tagged value -- ------------------------------ type Tagged_Value_Element is new Model_Element with record Value : Ada.Strings.Unbounded.Unbounded_String; Value_Type : Ada.Strings.Unbounded.Unbounded_String; Ref_Id : Ada.Strings.Unbounded.Unbounded_String; Tag_Def : Tag_Definition_Element_Access; end record; -- Get the element type. overriding function Get_Type (Node : in Tagged_Value_Element) return Element_Type; -- Reconcile the element by resolving the references to other elements in the model. overriding procedure Reconcile (Node : in out Tagged_Value_Element; Model : in UML_Model); -- ------------------------------ -- A class -- ------------------------------ type Class_Element is new Model_Element with record Operations : Model_Vector; Attributes : Model_Vector; Associations : Model_Vector; Visibility : Visibility_Type := VISIBILITY_PUBLIC; end record; type Class_Element_Access is access all Class_Element'Class; -- Get the element type. overriding function Get_Type (Node : in Class_Element) return Element_Type; -- ------------------------------ -- A package -- ------------------------------ type Package_Element; type Package_Element_Access is access all Package_Element'Class; type Package_Element is new Model_Element with record Classes : Model_Vector; end record; -- Get the element type. overriding function Get_Type (Node : in Package_Element) return Element_Type; end Gen.Model.XMI;
Make the enumeration a data type
Make the enumeration a data type
Ada
apache-2.0
Letractively/ada-gen,Letractively/ada-gen,Letractively/ada-gen,Letractively/ada-gen
44c319c4ab59e5dabc029a4f187256e6484f58d9
src/sqlite/ado-sqlite.adb
src/sqlite/ado-sqlite.adb
----------------------------------------------------------------------- -- 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 ADO.Configs; with ADO.Connections.Sqlite; package body 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) is begin ADO.Configs.Initialize (Config); ADO.Connections.Sqlite.Initialize; end Initialize; -- ------------------------------ -- Initialize the drivers and the library and configure the runtime with the given properties. -- ------------------------------ procedure Initialize (Config : in Util.Properties.Manager'Class) is begin ADO.Configs.Initialize (Config); ADO.Connections.Sqlite.Initialize; end Initialize; 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 ADO.Configs; with ADO.Connections.Sqlite; package body ADO.Sqlite is -- ------------------------------ -- Initialize the SQLite driver. -- ------------------------------ procedure Initialize is begin ADO.Connections.Sqlite.Initialize; end Initialize; -- ------------------------------ -- Initialize the drivers and the library by reading the property file -- and configure the runtime with it. -- ------------------------------ procedure Initialize (Config : in String) is begin ADO.Configs.Initialize (Config); Initialize; end Initialize; -- ------------------------------ -- Initialize the drivers and the library and configure the runtime with the given properties. -- ------------------------------ procedure Initialize (Config : in Util.Properties.Manager'Class) is begin ADO.Configs.Initialize (Config); Initialize; end Initialize; end ADO.Sqlite;
Implement the Initialize procedure and use it
Implement the Initialize procedure and use it
Ada
apache-2.0
stcarrez/ada-ado
6290dcb3915e0928929d73b3552210446033a288
src/wiki-helpers.ads
src/wiki-helpers.ads
----------------------------------------------------------------------- -- wiki-helpers -- Helper operations for wiki parsers and renderer -- Copyright (C) 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- package Wiki.Helpers is pragma Preelaborate; LF : constant Wide_Wide_Character := Wide_Wide_Character'Val (16#0A#); HT : constant Wide_Wide_Character := Wide_Wide_Character'Val (16#09#); -- Returns True if the character is a space or tab. function Is_Space (C : in Wide_Wide_Character) return Boolean; -- Returns True if the character is a space, tab or a newline. function Is_Space_Or_Newline (C : in Wide_Wide_Character) return Boolean; -- Returns True if the text is a valid URL function Is_Url (Text : in Wide_Wide_String) return Boolean; -- Returns True if the extension part correspond to an image. -- Recognized extension are: .png, .gif, .jpg, .jpeg. -- The extension case is ignored. function Is_Image_Extension (Ext : in Wide_Wide_String) return Boolean; end Wiki.Helpers;
----------------------------------------------------------------------- -- wiki-helpers -- Helper operations for wiki parsers and renderer -- Copyright (C) 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- package Wiki.Helpers is pragma Preelaborate; LF : constant Wide_Wide_Character := Wide_Wide_Character'Val (16#0A#); CR : constant Wide_Wide_Character := Wide_Wide_Character'Val (16#0D#); HT : constant Wide_Wide_Character := Wide_Wide_Character'Val (16#09#); -- Returns True if the character is a space or tab. function Is_Space (C : in Wide_Wide_Character) return Boolean; -- Returns True if the character is a space, tab or a newline. function Is_Space_Or_Newline (C : in Wide_Wide_Character) return Boolean; -- Returns True if the text is a valid URL function Is_Url (Text : in Wide_Wide_String) return Boolean; -- Returns True if the extension part correspond to an image. -- Recognized extension are: .png, .gif, .jpg, .jpeg. -- The extension case is ignored. function Is_Image_Extension (Ext : in Wide_Wide_String) return Boolean; end Wiki.Helpers;
Declare the CR constant
Declare the CR constant
Ada
apache-2.0
stcarrez/ada-wiki,stcarrez/ada-wiki
d71d50e14888217f0225785606ca12003b6568aa
regtests/util-commands-tests.ads
regtests/util-commands-tests.ads
----------------------------------------------------------------------- -- util-commands-tests - Test for commands -- Copyright (C) 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Tests; package Util.Commands.Tests is procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite); type Test is new Util.Tests.Test with null record; -- Tests when the execution of commands. procedure Test_Execute (T : in out Test); -- Test execution of help. procedure Test_Help (T : in out Test); -- Test usage operation. procedure Test_Usage (T : in out Test); end Util.Commands.Tests;
----------------------------------------------------------------------- -- util-commands-tests - Test for commands -- Copyright (C) 2018, 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 Util.Tests; package Util.Commands.Tests is procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite); type Test is new Util.Tests.Test with null record; -- Tests when the execution of commands. procedure Test_Execute (T : in out Test); -- Test execution of help. procedure Test_Help (T : in out Test); -- Test usage operation. procedure Test_Usage (T : in out Test); -- Test command based on the No_Parser. procedure Test_Simple_Command (T : in out Test); end Util.Commands.Tests;
Add Test_Simple_Command procedure
Add Test_Simple_Command procedure
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
d7d853cf1df19ecae3ee48792ef40b7025c4c544
src/security-auth.ads
src/security-auth.ads
----------------------------------------------------------------------- -- security-auth -- Authentication Support -- Copyright (C) 2009, 2010, 2011, 2012, 2013 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Ada.Calendar; with Ada.Finalization; -- == Auth == -- The <b>Security.Auth</b> package implements an authentication framework that is -- suitable for OpenID 2.0, OAuth 2.0 and later for OpenID Connect. It allows an application -- to authenticate users using an external authorization server such as Google, Facebook, -- Google +, Twitter and others. -- -- See OpenID Authentication 2.0 - Final -- http://openid.net/specs/openid-authentication-2_0.html -- -- See OpenID Connect Standard 1.0 -- http://openid.net/specs/openid-connect-standard-1_0.html -- -- See Facebook API: The Login Flow for Web (without JavaScript SDK) -- https://developers.facebook.com/docs/facebook-login/login-flow-for-web-no-jssdk/ -- -- Despite their subtle differences, all these authentication frameworks share almost -- a common flow. The API provided by <b>Security.Auth</b> defines an abstraction suitable -- for all these frameworks. -- -- There are basically two steps that an application must implement: -- -- * <b>Discovery</b>: to resolve and use the OpenID provider and redirect the user to the -- provider authentication form. -- * <b>Verify</b>: to decode the authentication and check its result. -- -- [http://ada-security.googlecode.com/svn/wiki/OpenID.png] -- -- The authentication process is the following: -- -- * The application should redirect the user to the authentication URL. -- * The OpenID provider authenticate the user and redirects the user to the callback CB. -- * The association is decoded from the callback parameter. -- * The <b>Verify</b> procedure is called with the association to check the result and -- obtain the authentication results. -- -- === Initialization === -- The initialization process must be done before each two steps (discovery and verify). -- The Authentication manager must be declared and configured. -- -- Mgr : Security.Auth.Manager; -- -- For the configuration, the <b>Initialize</b> procedure is called to configure -- the Auth realm and set the authentication return callback URL. The return callback -- must be a valid URL that is based on the realm. Example: -- -- Mgr.Initialize (Name => "http://app.site.com/auth", -- Return_To => "http://app.site.com/auth/verify", -- Realm => "openid"); -- -- After this initialization, the authentication manager can be used in the authentication -- process. -- -- @include security-auth-openid.ads -- @include security-auth-oauth.ads -- -- === Discovery: creating the authentication URL === -- The first step is to create an authentication URL to which the user must be redirected. -- In this step, we have to create an OpenID manager, discover the OpenID provider, -- do the association and get an <b>End_Point</b>. The OpenID provider is specified as an -- URL, below is an example for Google OpenID: -- -- Provider : constant String := "https://www.google.com/accounts/o8/id"; -- OP : Security.Auth.End_Point; -- Assoc : constant Security.Auth.Association_Access := new Security.Auth.Association; -- -- The following steps are performed: -- -- * The <b>Discover</b> procedure is called to retrieve from the OpenID provider the XRDS -- stream and identify the provider. An <b>End_Point</b> is returned in <tt>OP</tt>. -- * The <b>Associate</b> procedure is called to make the association with the <b>End_Point</b>. -- The <b>Association</b> record holds session, and authentication. -- -- Mgr.Discover (Provider, OP); -- Yadis discovery (get the XRDS file). -- Mgr.Associate (OP, Assoc.all);-- Associate and get an end-point with a key. -- -- After this first step, you must manage to save the association in the HTTP session. -- Then you must redirect to the authentication URL that is obtained by using: -- -- Auth_URL : constant String := Mgr.Get_Authentication_URL (OP, Assoc.all); -- -- === Verify: acknowledge the authentication in the callback URL === -- The second step is done when the user has finished the authentication successfully or not. -- For this step, the application must get back the association that was saved in the session. -- It must also prepare a parameters object that allows the OpenID framework to get the -- URI parameters from the return callback. -- -- Assoc : Association_Access := ...; -- Get the association saved in the session. -- Credential : Security.Auth.Authentication; -- Params : Auth_Params; -- -- The auth manager must be initialized and the <b>Verify</b> procedure is called with -- the association, parameters and the authentication result. The <b>Get_Status</b> function -- must be used to check that the authentication succeeded. -- -- Mgr.Verify (Assoc.all, Params, Credential); -- if Security.Auth.Get_Status (Credential) = Security.Auth.AUTHENTICATED then ... -- Success. -- -- === Principal creation === -- After the user is successfully authenticated, a user principal can be created and saved in -- the session. The user principal can then be used to assign permissions to that user and -- enforce the application permissions using the security policy manger. -- -- P : Security.Auth.Principal_Access := Security.Auth.Create_Principal (Credential); -- package Security.Auth is -- Use an authentication server implementing OpenID 2.0. PROVIDER_OPENID : constant String := "openid"; -- Use the Facebook OAuth 2.0 - draft 12 authentication server. PROVIDER_FACEBOOK : constant String := "facebook"; Invalid_End_Point : exception; Service_Error : exception; type Parameters is limited interface; function Get_Parameter (Params : in Parameters; Name : in String) return String is abstract; -- ------------------------------ -- Auth provider -- ------------------------------ -- The <b>End_Point</b> represents the authentication provider that will authenticate -- the user. type End_Point is private; function To_String (OP : End_Point) return String; -- ------------------------------ -- Association -- ------------------------------ -- The association contains the shared secret between the relying party -- and the authentication provider. The association can be cached and reused to authenticate -- different users using the same authentication provider. The association also has an -- expiration date. type Association is private; -- Get the provider. function Get_Provider (Assoc : in Association) return String; -- Dump the association as a string (for debugging purposes) function To_String (Assoc : Association) return String; type Auth_Result is (AUTHENTICATED, CANCEL, SETUP_NEEDED, UNKNOWN, INVALID_SIGNATURE); -- ------------------------------ -- Authentication result -- ------------------------------ -- type Authentication is private; -- Get the email address function Get_Email (Auth : in Authentication) return String; -- Get the user first name. function Get_First_Name (Auth : in Authentication) return String; -- Get the user last name. function Get_Last_Name (Auth : in Authentication) return String; -- Get the user full name. function Get_Full_Name (Auth : in Authentication) return String; -- Get the user identity. function Get_Identity (Auth : in Authentication) return String; -- Get the user claimed identity. function Get_Claimed_Id (Auth : in Authentication) return String; -- Get the user language. function Get_Language (Auth : in Authentication) return String; -- Get the user country. function Get_Country (Auth : in Authentication) return String; -- Get the result of the authentication. function Get_Status (Auth : in Authentication) return Auth_Result; -- ------------------------------ -- Default principal -- ------------------------------ type Principal is new Security.Principal with private; type Principal_Access is access all Principal'Class; -- Get the principal name. function Get_Name (From : in Principal) return String; -- Get the user email address. function Get_Email (From : in Principal) return String; -- Get the authentication data. function Get_Authentication (From : in Principal) return Authentication; -- Create a principal with the given authentication results. function Create_Principal (Auth : in Authentication) return Principal_Access; -- ------------------------------ -- Authentication Manager -- ------------------------------ -- The <b>Manager</b> provides the core operations for the authentication process. type Manager is tagged limited private; -- Initialize the authentication realm. procedure Initialize (Realm : in out Manager; Params : in Parameters'Class; Provider : in String := PROVIDER_OPENID); -- Discover the authentication provider that must be used to authenticate the user. -- The <b>Name</b> can be an URL or an alias that identifies the provider. -- A cached OpenID provider can be returned. The discover step may do nothing for -- authentication providers based on OAuth. -- (See OpenID Section 7.3 Discovery) procedure Discover (Realm : in out Manager; Name : in String; Result : out End_Point); -- Associate the application (relying party) with the authentication provider. -- The association can be cached. -- (See OpenID Section 8 Establishing Associations) procedure Associate (Realm : in out Manager; OP : in End_Point; Result : out Association); -- Get the authentication URL to which the user must be redirected for authentication -- by the authentication server. function Get_Authentication_URL (Realm : in Manager; OP : in End_Point; Assoc : in Association) return String; -- Verify the authentication result procedure Verify (Realm : in out Manager; Assoc : in Association; Request : in Parameters'Class; Result : out Authentication); private use Ada.Strings.Unbounded; type Association is record Provider : Unbounded_String; Session_Type : Unbounded_String; Assoc_Type : Unbounded_String; Assoc_Handle : Unbounded_String; Mac_Key : Unbounded_String; Expired : Ada.Calendar.Time; end record; type Authentication is record Status : Auth_Result; Identity : Unbounded_String; Claimed_Id : Unbounded_String; Email : Unbounded_String; Full_Name : Unbounded_String; First_Name : Unbounded_String; Last_Name : Unbounded_String; Language : Unbounded_String; Country : Unbounded_String; Gender : Unbounded_String; Timezone : Unbounded_String; Nickname : Unbounded_String; end record; type End_Point is record URL : Unbounded_String; Alias : Unbounded_String; Expired : Ada.Calendar.Time; end record; type Manager_Access is access all Manager'Class; type Manager is new Ada.Finalization.Limited_Controlled with record Provider : Unbounded_String; Delegate : Manager_Access; end record; type Principal is new Security.Principal with record Auth : Authentication; end record; procedure Set_Result (Result : in out Authentication; Status : in Auth_Result; Message : in String); end Security.Auth;
----------------------------------------------------------------------- -- security-auth -- Authentication Support -- Copyright (C) 2009, 2010, 2011, 2012, 2013 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Ada.Calendar; with Ada.Finalization; -- == Auth == -- The <b>Security.Auth</b> package implements an authentication framework that is -- suitable for OpenID 2.0, OAuth 2.0 and later for OpenID Connect. It allows an application -- to authenticate users using an external authorization server such as Google, Facebook, -- Google +, Twitter and others. -- -- See OpenID Authentication 2.0 - Final -- http://openid.net/specs/openid-authentication-2_0.html -- -- See OpenID Connect Standard 1.0 -- http://openid.net/specs/openid-connect-standard-1_0.html -- -- See Facebook API: The Login Flow for Web (without JavaScript SDK) -- https://developers.facebook.com/docs/facebook-login/login-flow-for-web-no-jssdk/ -- -- Despite their subtle differences, all these authentication frameworks share almost -- a common flow. The API provided by <b>Security.Auth</b> defines an abstraction suitable -- for all these frameworks. -- -- There are basically two steps that an application must implement: -- -- * <b>Discovery</b>: to resolve and use the OpenID provider and redirect the user to the -- provider authentication form. -- * <b>Verify</b>: to decode the authentication and check its result. -- -- [http://ada-security.googlecode.com/svn/wiki/OpenID.png] -- -- The authentication process is the following: -- -- * The application should redirect the user to the authentication URL. -- * The OpenID provider authenticate the user and redirects the user to the callback CB. -- * The association is decoded from the callback parameter. -- * The <b>Verify</b> procedure is called with the association to check the result and -- obtain the authentication results. -- -- === Initialization === -- The initialization process must be done before each two steps (discovery and verify). -- The Authentication manager must be declared and configured. -- -- Mgr : Security.Auth.Manager; -- -- For the configuration, the <b>Initialize</b> procedure is called to configure -- the Auth realm and set the authentication return callback URL. The return callback -- must be a valid URL that is based on the realm. Example: -- -- Mgr.Initialize (Name => "http://app.site.com/auth", -- Return_To => "http://app.site.com/auth/verify", -- Realm => "openid"); -- -- After this initialization, the authentication manager can be used in the authentication -- process. -- -- @include security-auth-openid.ads -- @include security-auth-oauth.ads -- -- === Discovery: creating the authentication URL === -- The first step is to create an authentication URL to which the user must be redirected. -- In this step, we have to create an OpenID manager, discover the OpenID provider, -- do the association and get an <b>End_Point</b>. The OpenID provider is specified as an -- URL, below is an example for Google OpenID: -- -- Provider : constant String := "https://www.google.com/accounts/o8/id"; -- OP : Security.Auth.End_Point; -- Assoc : constant Security.Auth.Association_Access := new Security.Auth.Association; -- -- The following steps are performed: -- -- * The <b>Discover</b> procedure is called to retrieve from the OpenID provider the XRDS -- stream and identify the provider. An <b>End_Point</b> is returned in <tt>OP</tt>. -- * The <b>Associate</b> procedure is called to make the association with the <b>End_Point</b>. -- The <b>Association</b> record holds session, and authentication. -- -- Mgr.Discover (Provider, OP); -- Yadis discovery (get the XRDS file). -- Mgr.Associate (OP, Assoc.all);-- Associate and get an end-point with a key. -- -- After this first step, you must manage to save the association in the HTTP session. -- Then you must redirect to the authentication URL that is obtained by using: -- -- Auth_URL : constant String := Mgr.Get_Authentication_URL (OP, Assoc.all); -- -- === Verify: acknowledge the authentication in the callback URL === -- The second step is done when the user has finished the authentication successfully or not. -- For this step, the application must get back the association that was saved in the session. -- It must also prepare a parameters object that allows the OpenID framework to get the -- URI parameters from the return callback. -- -- Assoc : Association_Access := ...; -- Get the association saved in the session. -- Credential : Security.Auth.Authentication; -- Params : Auth_Params; -- -- The auth manager must be initialized and the <b>Verify</b> procedure is called with -- the association, parameters and the authentication result. The <b>Get_Status</b> function -- must be used to check that the authentication succeeded. -- -- Mgr.Verify (Assoc.all, Params, Credential); -- if Security.Auth.Get_Status (Credential) = Security.Auth.AUTHENTICATED then ... -- Success. -- -- === Principal creation === -- After the user is successfully authenticated, a user principal can be created and saved in -- the session. The user principal can then be used to assign permissions to that user and -- enforce the application permissions using the security policy manger. -- -- P : Security.Auth.Principal_Access := Security.Auth.Create_Principal (Credential); -- package Security.Auth is -- Use an authentication server implementing OpenID 2.0. PROVIDER_OPENID : constant String := "openid"; -- Use the Facebook OAuth 2.0 - draft 12 authentication server. PROVIDER_FACEBOOK : constant String := "facebook"; Invalid_End_Point : exception; Service_Error : exception; type Parameters is limited interface; function Get_Parameter (Params : in Parameters; Name : in String) return String is abstract; -- ------------------------------ -- Auth provider -- ------------------------------ -- The <b>End_Point</b> represents the authentication provider that will authenticate -- the user. type End_Point is private; function To_String (OP : End_Point) return String; -- ------------------------------ -- Association -- ------------------------------ -- The association contains the shared secret between the relying party -- and the authentication provider. The association can be cached and reused to authenticate -- different users using the same authentication provider. The association also has an -- expiration date. type Association is private; -- Get the provider. function Get_Provider (Assoc : in Association) return String; -- Dump the association as a string (for debugging purposes) function To_String (Assoc : Association) return String; type Auth_Result is (AUTHENTICATED, CANCEL, SETUP_NEEDED, UNKNOWN, INVALID_SIGNATURE); -- ------------------------------ -- Authentication result -- ------------------------------ -- type Authentication is private; -- Get the email address function Get_Email (Auth : in Authentication) return String; -- Get the user first name. function Get_First_Name (Auth : in Authentication) return String; -- Get the user last name. function Get_Last_Name (Auth : in Authentication) return String; -- Get the user full name. function Get_Full_Name (Auth : in Authentication) return String; -- Get the user identity. function Get_Identity (Auth : in Authentication) return String; -- Get the user claimed identity. function Get_Claimed_Id (Auth : in Authentication) return String; -- Get the user language. function Get_Language (Auth : in Authentication) return String; -- Get the user country. function Get_Country (Auth : in Authentication) return String; -- Get the result of the authentication. function Get_Status (Auth : in Authentication) return Auth_Result; -- ------------------------------ -- Default principal -- ------------------------------ type Principal is new Security.Principal with private; type Principal_Access is access all Principal'Class; -- Get the principal name. function Get_Name (From : in Principal) return String; -- Get the user email address. function Get_Email (From : in Principal) return String; -- Get the authentication data. function Get_Authentication (From : in Principal) return Authentication; -- Create a principal with the given authentication results. function Create_Principal (Auth : in Authentication) return Principal_Access; -- ------------------------------ -- Authentication Manager -- ------------------------------ -- The <b>Manager</b> provides the core operations for the authentication process. type Manager is tagged limited private; -- Initialize the authentication realm. procedure Initialize (Realm : in out Manager; Params : in Parameters'Class; Name : in String := PROVIDER_OPENID); -- Discover the authentication provider that must be used to authenticate the user. -- The <b>Name</b> can be an URL or an alias that identifies the provider. -- A cached OpenID provider can be returned. The discover step may do nothing for -- authentication providers based on OAuth. -- (See OpenID Section 7.3 Discovery) procedure Discover (Realm : in out Manager; Name : in String; Result : out End_Point); -- Associate the application (relying party) with the authentication provider. -- The association can be cached. -- (See OpenID Section 8 Establishing Associations) procedure Associate (Realm : in out Manager; OP : in End_Point; Result : out Association); -- Get the authentication URL to which the user must be redirected for authentication -- by the authentication server. function Get_Authentication_URL (Realm : in Manager; OP : in End_Point; Assoc : in Association) return String; -- Verify the authentication result procedure Verify (Realm : in out Manager; Assoc : in Association; Request : in Parameters'Class; Result : out Authentication); private use Ada.Strings.Unbounded; type Association is record Provider : Unbounded_String; Session_Type : Unbounded_String; Assoc_Type : Unbounded_String; Assoc_Handle : Unbounded_String; Mac_Key : Unbounded_String; Expired : Ada.Calendar.Time; end record; type Authentication is record Status : Auth_Result; Identity : Unbounded_String; Claimed_Id : Unbounded_String; Email : Unbounded_String; Full_Name : Unbounded_String; First_Name : Unbounded_String; Last_Name : Unbounded_String; Language : Unbounded_String; Country : Unbounded_String; Gender : Unbounded_String; Timezone : Unbounded_String; Nickname : Unbounded_String; end record; type End_Point is record URL : Unbounded_String; Alias : Unbounded_String; Expired : Ada.Calendar.Time; end record; type Manager_Access is access all Manager'Class; type Manager is new Ada.Finalization.Limited_Controlled with record Provider : Unbounded_String; Delegate : Manager_Access; end record; type Principal is new Security.Principal with record Auth : Authentication; end record; procedure Set_Result (Result : in out Authentication; Status : in Auth_Result; Message : in String); end Security.Auth;
Rename the Initialize parameters
Rename the Initialize parameters
Ada
apache-2.0
Letractively/ada-security
660de1598816689fd1885c7683d20ba187b88f64
src/util-commands.ads
src/util-commands.ads
----------------------------------------------------------------------- -- util-commands -- Support to make command line tools -- Copyright (C) 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- package Util.Commands is -- The argument list interface that gives access to command arguments. type Argument_List is limited interface; -- Get the number of arguments available. function Get_Count (List : in Argument_List) return Natural is abstract; -- Get the argument at the given position. function Get_Argument (List : in Argument_List; Pos : in Positive) return String is abstract; type Default_Argument_List (Offset : Natural) is new Argument_List with null record; -- Get the number of arguments available. overriding function Get_Count (List : in Default_Argument_List) return Natural; -- Get the argument at the given position. overriding function Get_Argument (List : in Default_Argument_List; Pos : in Positive) return String; end Util.Commands;
----------------------------------------------------------------------- -- util-commands -- Support to make command line tools -- Copyright (C) 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- package Util.Commands is -- The argument list interface that gives access to command arguments. type Argument_List is limited interface; -- Get the number of arguments available. function Get_Count (List : in Argument_List) return Natural is abstract; -- Get the argument at the given position. function Get_Argument (List : in Argument_List; Pos : in Positive) return String is abstract; -- Get the command name. function Get_Command_Name (List : in Argument_List) return String is abstract; type Default_Argument_List (Offset : Natural) is new Argument_List with null record; -- Get the number of arguments available. overriding function Get_Count (List : in Default_Argument_List) return Natural; -- Get the argument at the given position. overriding function Get_Argument (List : in Default_Argument_List; Pos : in Positive) return String; -- Get the command name. function Get_Command_Name (List : in Default_Argument_List) return String; end Util.Commands;
Declare the Get_Command_Name function
Declare the Get_Command_Name function
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
6b7aa510a16b9b85d72eb4ab958a30fdb3f77cbd
src/sys/encoders/util-encoders.ads
src/sys/encoders/util-encoders.ads
----------------------------------------------------------------------- -- util-encoders -- Encode/Decode streams and strings from one format to another -- Copyright (C) 2009, 2010, 2011, 2012, 2016, 2017, 2019 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Streams; with Ada.Finalization; with Interfaces; -- === Encoder and Decoders === -- The <b>Util.Encoders</b> package defines the <b>Encoder</b> and <b>Decode</b> objects -- which provide a mechanism to transform a stream from one format into -- another format. -- -- ==== Simple encoding and decoding ==== -- package Util.Encoders is pragma Preelaborate; use Ada.Streams; Not_Supported : exception; Encoding_Error : exception; -- Encoder/decoder for Base64 (RFC 4648) BASE_64 : constant String := "base64"; -- Encoder/decoder for Base64 (RFC 4648) using the URL alphabet -- (+ and / are replaced by - and _) BASE_64_URL : constant String := "base64url"; -- Encoder/decoder for Base16 (RFC 4648) BASE_16 : constant String := "base16"; HEX : constant String := "hex"; -- Encoder for SHA1 (RFC 3174) HASH_SHA1 : constant String := "sha1"; -- ------------------------------ -- Secret key -- ------------------------------ -- A secret key of the given length, it cannot be copied and is safely erased. subtype Key_Length is Stream_Element_Offset range 1 .. Stream_Element_Offset'Last; type Secret_Key (Length : Key_Length) is limited private; -- Create the secret key from the password string. function Create (Password : in String) return Secret_Key with Pre => Password'Length > 0, Post => Create'Result.Length = Password'Length; procedure Create (Password : in String; Key : out Secret_Key) with Pre => Password'Length > 0, Post => Key.Length = Password'Length; procedure Create (Password : in Stream_Element_Array; Key : out Secret_Key) with Pre => Password'Length > 0, Post => Key.Length = Password'Length; -- ------------------------------ -- Encoder context object -- ------------------------------ -- The <b>Encoder</b> provides operations to encode and decode -- strings or stream of data from one format to another. -- The <b>Encoded</b> contains two <b>Transformer</b> -- which either <i>encodes</i> or <i>decodes</i> the stream. type Encoder is tagged limited private; -- Encodes the input string <b>Data</b> using the transformation -- rules provided by the <b>E</b> encoder. -- -- Returns the encoded string. -- -- Raises the <b>Encoding_Error</b> exception if the source string -- cannot be encoded. -- Raises the <b>Not_Supported</b> exception if the encoding is not -- supported. function Encode (E : in Encoder; Data : in String) return String; function Encode_Binary (E : in Encoder; Data : in Ada.Streams.Stream_Element_Array) return String; -- Create the encoder object for the specified encoding format. function Create (Name : in String) return Encoder; type Decoder is tagged limited private; -- Decodes the input string <b>Data</b> using the transformation -- rules provided by the <b>E</b> encoder. -- -- Returns the encoded string. -- -- Raises the <b>Encoding_Error</b> exception if the source string -- cannot be decoded. -- Raises the <b>Not_Supported</b> exception if the decoding is not -- supported. function Decode (E : in Decoder; Data : in String) return String; function Decode_Binary (E : in Decoder; Data : in String) return Ada.Streams.Stream_Element_Array; -- Create the decoder object for the specified encoding format. function Create (Name : in String) return Decoder; -- ------------------------------ -- Stream Transformation interface -- ------------------------------ -- The <b>Transformer</b> interface defines the operation to transform -- a stream from one data format to another. type Transformer is limited interface; type Transformer_Access is access all Transformer'Class; -- Transform the input array represented by <b>Data</b> into -- the output array <b>Into</b>. The transformation made by -- the object can be of any nature (Hex encoding, Base64 encoding, -- Hex decoding, Base64 decoding, encryption, compression, ...). -- -- 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> array. -- -- The transformer returns in <b>Last</b> the last valid position -- in the output array <b>Into</b>. -- -- The <b>Encoding_Error</b> exception is raised if the input -- array cannot be transformed. procedure Transform (E : in out Transformer; Data : in Ada.Streams.Stream_Element_Array; Into : out Ada.Streams.Stream_Element_Array; Last : out Ada.Streams.Stream_Element_Offset; Encoded : out Ada.Streams.Stream_Element_Offset) is abstract; -- Finish encoding the input array. procedure Finish (E : in out Transformer; Into : in out Ada.Streams.Stream_Element_Array; Last : in out Ada.Streams.Stream_Element_Offset) is null; -- Transform the input string <b>Data</b> using the transformation -- rules provided by the <b>E</b> transformer. -- -- Returns the transformed string. -- -- Raises the <b>Encoding_Error</b> exception if the source string -- cannot be transformed function Transform (E : in out Transformer'Class; Data : in String) return String; -- Transform the input string <b>Data</b> using the transformation -- rules provided by the <b>E</b> transformer. -- -- Returns the transformed string. -- -- Raises the <b>Encoding_Error</b> exception if the source string -- cannot be transformed function Transform (E : in out Transformer'Class; Data : in Ada.Streams.Stream_Element_Array) return String; function Transform (E : in out Transformer'Class; Data : in Ada.Streams.Stream_Element_Array) return Ada.Streams.Stream_Element_Array; -- Transform the input string <b>Data</b> using the transformation -- rules provided by the <b>E</b> transformer and return the data in -- the <b>Into</b> array, setting <b>Last</b> to the last index. -- -- Raises the <b>Encoding_Error</b> exception if the source string -- cannot be transformed procedure Transform (E : in out Transformer'Class; Data : in String; Into : out Ada.Streams.Stream_Element_Array; Last : out Ada.Streams.Stream_Element_Offset); -- Encode the value represented by <tt>Val</tt> in the stream array <tt>Into</tt> starting -- at position <tt>Pos</tt> in that array. The value is encoded using LEB128 format, 7-bits -- at a time until all non zero bits are written. The <tt>Last</tt> parameter is updated -- to indicate the position of the last valid byte written in <tt>Into</tt>. procedure Encode_LEB128 (Into : in out Ada.Streams.Stream_Element_Array; Pos : in Ada.Streams.Stream_Element_Offset; Val : in Interfaces.Unsigned_64; Last : out Ada.Streams.Stream_Element_Offset); -- Decode from the byte array <tt>From</tt> the value represented as LEB128 format starting -- at position <tt>Pos</tt> in that array. After decoding, the <tt>Last</tt> index is updated -- to indicate the last position in the byte array. procedure Decode_LEB128 (From : in Ada.Streams.Stream_Element_Array; Pos : in Ada.Streams.Stream_Element_Offset; Val : out Interfaces.Unsigned_64; Last : out Ada.Streams.Stream_Element_Offset); private use Ada.Finalization; type Secret_Key (Length : Key_Length) is limited new Limited_Controlled with record Secret : Ada.Streams.Stream_Element_Array (1 .. Length) := (others => 0); end record; overriding procedure Finalize (Object : in out Secret_Key); -- Transform the input data into the target string. procedure Convert (E : in out Transformer'Class; Data : in Ada.Streams.Stream_Element_Array; Into : out String); type Encoder is limited new Limited_Controlled with record Encode : Transformer_Access := null; end record; -- Delete the transformers overriding procedure Finalize (E : in out Encoder); type Decoder is limited new Limited_Controlled with record Decode : Transformer_Access := null; end record; -- Delete the transformers overriding procedure Finalize (E : in out Decoder); end Util.Encoders;
----------------------------------------------------------------------- -- util-encoders -- Encode/Decode streams and strings from one format to another -- Copyright (C) 2009, 2010, 2011, 2012, 2016, 2017, 2019 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Streams; with Ada.Finalization; with Interfaces; -- === Encoder and Decoders === -- The <b>Util.Encoders</b> package defines the <b>Encoder</b> and <b>Decode</b> objects -- which provide a mechanism to transform a stream from one format into -- another format. -- -- ==== Simple encoding and decoding ==== -- package Util.Encoders is pragma Preelaborate; use Ada.Streams; Not_Supported : exception; Encoding_Error : exception; -- Encoder/decoder for Base64 (RFC 4648) BASE_64 : constant String := "base64"; -- Encoder/decoder for Base64 (RFC 4648) using the URL alphabet -- (+ and / are replaced by - and _) BASE_64_URL : constant String := "base64url"; -- Encoder/decoder for Base16 (RFC 4648) BASE_16 : constant String := "base16"; HEX : constant String := "hex"; -- Encoder for SHA1 (RFC 3174) HASH_SHA1 : constant String := "sha1"; -- ------------------------------ -- Secret key -- ------------------------------ -- A secret key of the given length, it cannot be copied and is safely erased. subtype Key_Length is Stream_Element_Offset range 1 .. Stream_Element_Offset'Last; type Secret_Key (Length : Key_Length) is limited private; -- Create the secret key from the password string. function Create (Password : in String) return Secret_Key with Pre => Password'Length > 0, Post => Create'Result.Length = Password'Length; procedure Create (Password : in String; Key : out Secret_Key) with Pre => Password'Length > 0, Post => Key.Length = Password'Length; procedure Create (Password : in Stream_Element_Array; Key : out Secret_Key) with Pre => Password'Length > 0, Post => Key.Length = Password'Length; -- ------------------------------ -- Encoder context object -- ------------------------------ -- The <b>Encoder</b> provides operations to encode and decode -- strings or stream of data from one format to another. -- The <b>Encoded</b> contains two <b>Transformer</b> -- which either <i>encodes</i> or <i>decodes</i> the stream. type Encoder is tagged limited private; -- Encodes the input string <b>Data</b> using the transformation -- rules provided by the <b>E</b> encoder. -- -- Returns the encoded string. -- -- Raises the <b>Encoding_Error</b> exception if the source string -- cannot be encoded. -- Raises the <b>Not_Supported</b> exception if the encoding is not -- supported. function Encode (E : in Encoder; Data : in String) return String; function Encode_Binary (E : in Encoder; Data : in Ada.Streams.Stream_Element_Array) return String; function Encode_Unsigned_16 (E : in Encoder; Value : in Interfaces.Unsigned_16) return String; function Encode_Unsigned_32 (E : in Encoder; Value : in Interfaces.Unsigned_32) return String; function Encode_Unsigned_64 (E : in Encoder; Value : in Interfaces.Unsigned_64) return String; -- Create the encoder object for the specified encoding format. function Create (Name : in String) return Encoder; type Decoder is tagged limited private; -- Decodes the input string <b>Data</b> using the transformation -- rules provided by the <b>E</b> encoder. -- -- Returns the encoded string. -- -- Raises the <b>Encoding_Error</b> exception if the source string -- cannot be decoded. -- Raises the <b>Not_Supported</b> exception if the decoding is not -- supported. function Decode (E : in Decoder; Data : in String) return String; function Decode_Binary (E : in Decoder; Data : in String) return Ada.Streams.Stream_Element_Array; -- Create the decoder object for the specified encoding format. function Create (Name : in String) return Decoder; -- ------------------------------ -- Stream Transformation interface -- ------------------------------ -- The <b>Transformer</b> interface defines the operation to transform -- a stream from one data format to another. type Transformer is limited interface; type Transformer_Access is access all Transformer'Class; -- Transform the input array represented by <b>Data</b> into -- the output array <b>Into</b>. The transformation made by -- the object can be of any nature (Hex encoding, Base64 encoding, -- Hex decoding, Base64 decoding, encryption, compression, ...). -- -- 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> array. -- -- The transformer returns in <b>Last</b> the last valid position -- in the output array <b>Into</b>. -- -- The <b>Encoding_Error</b> exception is raised if the input -- array cannot be transformed. procedure Transform (E : in out Transformer; Data : in Ada.Streams.Stream_Element_Array; Into : out Ada.Streams.Stream_Element_Array; Last : out Ada.Streams.Stream_Element_Offset; Encoded : out Ada.Streams.Stream_Element_Offset) is abstract; -- Finish encoding the input array. procedure Finish (E : in out Transformer; Into : in out Ada.Streams.Stream_Element_Array; Last : in out Ada.Streams.Stream_Element_Offset) is null; -- Transform the input string <b>Data</b> using the transformation -- rules provided by the <b>E</b> transformer. -- -- Returns the transformed string. -- -- Raises the <b>Encoding_Error</b> exception if the source string -- cannot be transformed function Transform (E : in out Transformer'Class; Data : in String) return String; -- Transform the input string <b>Data</b> using the transformation -- rules provided by the <b>E</b> transformer. -- -- Returns the transformed string. -- -- Raises the <b>Encoding_Error</b> exception if the source string -- cannot be transformed function Transform (E : in out Transformer'Class; Data : in Ada.Streams.Stream_Element_Array) return String; function Transform (E : in out Transformer'Class; Data : in Ada.Streams.Stream_Element_Array) return Ada.Streams.Stream_Element_Array; -- Transform the input string <b>Data</b> using the transformation -- rules provided by the <b>E</b> transformer and return the data in -- the <b>Into</b> array, setting <b>Last</b> to the last index. -- -- Raises the <b>Encoding_Error</b> exception if the source string -- cannot be transformed procedure Transform (E : in out Transformer'Class; Data : in String; Into : out Ada.Streams.Stream_Element_Array; Last : out Ada.Streams.Stream_Element_Offset); -- Encode the value represented by <tt>Val</tt> in the stream array <tt>Into</tt> starting -- at position <tt>Pos</tt> in that array. The value is encoded using LEB128 format, 7-bits -- at a time until all non zero bits are written. The <tt>Last</tt> parameter is updated -- to indicate the position of the last valid byte written in <tt>Into</tt>. procedure Encode_LEB128 (Into : in out Ada.Streams.Stream_Element_Array; Pos : in Ada.Streams.Stream_Element_Offset; Val : in Interfaces.Unsigned_64; Last : out Ada.Streams.Stream_Element_Offset); -- Decode from the byte array <tt>From</tt> the value represented as LEB128 format starting -- at position <tt>Pos</tt> in that array. After decoding, the <tt>Last</tt> index is updated -- to indicate the last position in the byte array. procedure Decode_LEB128 (From : in Ada.Streams.Stream_Element_Array; Pos : in Ada.Streams.Stream_Element_Offset; Val : out Interfaces.Unsigned_64; Last : out Ada.Streams.Stream_Element_Offset); private use Ada.Finalization; type Secret_Key (Length : Key_Length) is limited new Limited_Controlled with record Secret : Ada.Streams.Stream_Element_Array (1 .. Length) := (others => 0); end record; overriding procedure Finalize (Object : in out Secret_Key); -- Transform the input data into the target string. procedure Convert (E : in out Transformer'Class; Data : in Ada.Streams.Stream_Element_Array; Into : out String); type Encoder is limited new Limited_Controlled with record Encode : Transformer_Access := null; end record; -- Delete the transformers overriding procedure Finalize (E : in out Encoder); type Decoder is limited new Limited_Controlled with record Decode : Transformer_Access := null; end record; -- Delete the transformers overriding procedure Finalize (E : in out Decoder); end Util.Encoders;
Add Encode_Unsigned_16, Encode_Unsigned_32, Encode_Unsigned_64
Add Encode_Unsigned_16, Encode_Unsigned_32, Encode_Unsigned_64
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
95687342b51a173eb3a3c86bc560e6702294c1d0
regtests/security-auth-tests.adb
regtests/security-auth-tests.adb
----------------------------------------------------------------------- -- security-openid - Tests for OpenID -- Copyright (C) 2009, 2010, 2011, 2012, 2013, 2015Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR 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.Http.Clients.Mockups; with Util.Test_Caller; with Ada.Text_IO; package body Security.Auth.Tests is package Caller is new Util.Test_Caller (Test, "Security.Openid"); procedure Setup (M : in out Manager; Name : in String); procedure Check_Discovery (T : in out Test; Name : in String; URI : in String); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test Security.OpenID.Discover", Test_Discovery'Access); Caller.Add_Test (Suite, "Test Security.OpenID.Verify_Signature", Test_Verify_Signature'Access); end Add_Tests; overriding function Get_Parameter (Params : in Test_Parameters; Name : in String) return String is begin if Params.Params.Contains (Name) then return Params.Params.Element (Name); else return ""; end if; end Get_Parameter; procedure Set_Parameter (Params : in out Test_Parameters; Name : in String; Value : in String) is begin Params.Params.Include (Name, Value); end Set_Parameter; procedure Setup (M : in out Manager; Name : in String) is Params : Test_Parameters; begin Params.Set_Parameter ("auth.provider.google", "openid"); Params.Set_Parameter ("auth.provider.openid", "openid"); Params.Set_Parameter ("openid.realm", "http://localhost/verify"); Params.Set_Parameter ("openid.callback_url", "http://localhost/openId"); M.Initialize (Params, Name); end Setup; procedure Check_Discovery (T : in out Test; Name : in String; URI : in String) is pragma Unreferenced (URI, T); M : Manager; Dir : constant String := "regtests/files/discover/"; Path : constant String := Util.Tests.Get_Path (Dir); Result : End_Point; begin Setup (M, "openid"); Util.Http.Clients.Mockups.Register; Util.Http.Clients.Mockups.Set_File (Path & Name & ".xrds"); M.Discover (Name => Name, Result => Result); Ada.Text_IO.Put_Line ("Result: " & To_String (Result)); end Check_Discovery; -- ------------------------------ -- Test Yadis discovery using static files -- ------------------------------ procedure Test_Discovery (T : in out Test) is begin Check_Discovery (T, "google", "https://www.google.com/accounts/o8/ud"); Check_Discovery (T, "yahoo", "https://open.login.yahooapis.com/openid/op/auth"); Check_Discovery (T, "claimid", ""); Check_Discovery (T, "livejournal", ""); Check_Discovery (T, "myopenid", ""); Check_Discovery (T, "myspace", ""); Check_Discovery (T, "orange", ""); Check_Discovery (T, "verisign", ""); Check_Discovery (T, "steamcommunity", ""); end Test_Discovery; -- ------------------------------ -- Test the OpenID verify signature process -- ------------------------------ procedure Test_Verify_Signature (T : in out Test) is Assoc : Association; Req : Test_Parameters; M : Manager; Result : Authentication; begin Setup (M, "openid"); -- M.Return_To := To_Unbounded_String ("http://localhost/openId"); -- Below is a part of the authentication process on Google OpenId. -- In theory, you cannot use the following information to authenticate again... Assoc.Session_Type := To_Unbounded_String ("no-encryption"); Assoc.Assoc_Type := To_Unbounded_String ("HMAC-SHA1"); Assoc.Assoc_Handle := To_Unbounded_String ("AOQobUdTfNDRSgJLi_0mQQnCCstOsefQadOiW9LNSp4JFO815iHCHsRk"); Assoc.Mac_Key := To_Unbounded_String ("NGFpR6vWfe7O8YIhhnXQMjL0goI="); Req.Set_Parameter ("openid.ns", "http://specs.openid.net/auth/2.0"); Req.Set_Parameter ("openid.mode", "id_res"); Req.Set_Parameter ("openid.op_endpoint", "https://www.google.com/accounts/o8/ud"); Req.Set_Parameter ("openid.response_nonce", "2011-04-26T20:08:22ZJ_neiVqR0e1wZw"); Req.Set_Parameter ("openid.return_to", "http://localhost/openId"); Req.Set_Parameter ("openid.assoc_handle", "AOQobUdTfNDRSgJLi_0mQQnCCstOsefQadOiW9LNSp4JFO815iHCHsRk"); Req.Set_Parameter ("openid.signed", "op_endpoint,claimed_id,identity,return_to,response_nonce,assoc_handle,ns.ext1,ext1.mode,ext1.type.firstname,ext1.value.firstname,ext1.type.email,ext1.value.email,ext1.type.language,ext1.value.language,ext1.type.lastname,ext1.value.lastname"); Req.Set_Parameter ("openid.sig", "pV8cmScjrmgKvFn2F6Wxh/qBiIE="); Req.Set_Parameter ("openid.identity", "https://www.google.com/accounts/o8/id?id=AItOawm4O6C695XlWrS7MUWC-_V_R2zC-Ol993E"); Req.Set_Parameter ("openid.claimed_id", "https://www.google.com/accounts/o8/id?id=AItOawm4O6C695XlWrS7MUWC-_V_R2zC-Ol993E"); Req.Set_Parameter ("openid.ns.ext1", "http://openid.net/srv/ax/1.0"); Req.Set_Parameter ("openid.ext1.mode", "fetch_response"); Req.Set_Parameter ("openid.ext1.type.firstname", "http://axschema.org/namePerson/first"); Req.Set_Parameter ("openid.ext1.value.firstname", "Stephane"); Req.Set_Parameter ("openid.ext1.type.email", "http://axschema.org/contact/email"); Req.Set_Parameter ("openid.ext1.value.email", "[email protected]"); Req.Set_Parameter ("openid.ext1.type.language", "http://axschema.org/pref/language"); Req.Set_Parameter ("openid.ext1.value.language", "fr"); Req.Set_Parameter ("openid.ext1.type.lastname", "http://axschema.org/namePerson/last"); Req.Set_Parameter ("openid.ext1.value.lastname", "Carrez"); M.Verify (Assoc, Req, Result); -- If the verification is succeeds, the signature is correct, we should be authenticated. T.Assert (Get_Status (Result) = AUTHENTICATED, "Authentication status is not authenticated"); Util.Tests.Assert_Equals (T, "[email protected]", Get_Email (Result), "Invalid email"); end Test_Verify_Signature; end Security.Auth.Tests;
----------------------------------------------------------------------- -- security-auth-tests - Tests for OpenID -- Copyright (C) 2009, 2010, 2011, 2012, 2013, 2015, 2019 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Util.Http.Clients.Mockups; with Util.Test_Caller; with Ada.Text_IO; package body Security.Auth.Tests is package Caller is new Util.Test_Caller (Test, "Security.Openid"); procedure Setup (M : in out Manager; Name : in String); procedure Check_Discovery (T : in out Test; Name : in String; URI : in String); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test Security.OpenID.Discover", Test_Discovery'Access); Caller.Add_Test (Suite, "Test Security.OpenID.Verify_Signature", Test_Verify_Signature'Access); end Add_Tests; overriding function Get_Parameter (Params : in Test_Parameters; Name : in String) return String is begin if Params.Params.Contains (Name) then return Params.Params.Element (Name); else return ""; end if; end Get_Parameter; procedure Set_Parameter (Params : in out Test_Parameters; Name : in String; Value : in String) is begin Params.Params.Include (Name, Value); end Set_Parameter; procedure Setup (M : in out Manager; Name : in String) is Params : Test_Parameters; begin Params.Set_Parameter ("auth.provider.google", "openid"); Params.Set_Parameter ("auth.provider.openid", "openid"); Params.Set_Parameter ("openid.realm", "http://localhost/verify"); Params.Set_Parameter ("openid.callback_url", "http://localhost/openId"); M.Initialize (Params, Name); end Setup; procedure Check_Discovery (T : in out Test; Name : in String; URI : in String) is pragma Unreferenced (URI, T); M : Manager; Dir : constant String := "regtests/files/discover/"; Path : constant String := Util.Tests.Get_Path (Dir); Result : End_Point; begin Setup (M, "openid"); Util.Http.Clients.Mockups.Register; Util.Http.Clients.Mockups.Set_File (Path & Name & ".xrds"); M.Discover (Name => Name, Result => Result); Ada.Text_IO.Put_Line ("Result: " & To_String (Result)); end Check_Discovery; -- ------------------------------ -- Test Yadis discovery using static files -- ------------------------------ procedure Test_Discovery (T : in out Test) is begin Check_Discovery (T, "google", "https://www.google.com/accounts/o8/ud"); Check_Discovery (T, "yahoo", "https://open.login.yahooapis.com/openid/op/auth"); Check_Discovery (T, "claimid", ""); Check_Discovery (T, "livejournal", ""); Check_Discovery (T, "myopenid", ""); Check_Discovery (T, "myspace", ""); Check_Discovery (T, "orange", ""); Check_Discovery (T, "verisign", ""); Check_Discovery (T, "steamcommunity", ""); end Test_Discovery; -- ------------------------------ -- Test the OpenID verify signature process -- ------------------------------ procedure Test_Verify_Signature (T : in out Test) is Assoc : Association; Req : Test_Parameters; M : Manager; Result : Authentication; begin Setup (M, "openid"); pragma Style_Checks ("-mr"); -- M.Return_To := To_Unbounded_String ("http://localhost/openId"); -- Below is a part of the authentication process on Google OpenId. -- In theory, you cannot use the following information to authenticate again... Assoc.Session_Type := To_Unbounded_String ("no-encryption"); Assoc.Assoc_Type := To_Unbounded_String ("HMAC-SHA1"); Assoc.Assoc_Handle := To_Unbounded_String ("AOQobUdTfNDRSgJLi_0mQQnCCstOsefQadOiW9LNSp4JFO815iHCHsRk"); Assoc.Mac_Key := To_Unbounded_String ("NGFpR6vWfe7O8YIhhnXQMjL0goI="); Req.Set_Parameter ("openid.ns", "http://specs.openid.net/auth/2.0"); Req.Set_Parameter ("openid.mode", "id_res"); Req.Set_Parameter ("openid.op_endpoint", "https://www.google.com/accounts/o8/ud"); Req.Set_Parameter ("openid.response_nonce", "2011-04-26T20:08:22ZJ_neiVqR0e1wZw"); Req.Set_Parameter ("openid.return_to", "http://localhost/openId"); Req.Set_Parameter ("openid.assoc_handle", "AOQobUdTfNDRSgJLi_0mQQnCCstOsefQadOiW9LNSp4JFO815iHCHsRk"); Req.Set_Parameter ("openid.signed", "op_endpoint,claimed_id,identity,return_to,response_nonce,assoc_handle,ns.ext1,ext1.mode,ext1.type.firstname,ext1.value.firstname,ext1.type.email,ext1.value.email,ext1.type.language,ext1.value.language,ext1.type.lastname,ext1.value.lastname"); Req.Set_Parameter ("openid.sig", "pV8cmScjrmgKvFn2F6Wxh/qBiIE="); Req.Set_Parameter ("openid.identity", "https://www.google.com/accounts/o8/id?id=AItOawm4O6C695XlWrS7MUWC-_V_R2zC-Ol993E"); Req.Set_Parameter ("openid.claimed_id", "https://www.google.com/accounts/o8/id?id=AItOawm4O6C695XlWrS7MUWC-_V_R2zC-Ol993E"); Req.Set_Parameter ("openid.ns.ext1", "http://openid.net/srv/ax/1.0"); Req.Set_Parameter ("openid.ext1.mode", "fetch_response"); Req.Set_Parameter ("openid.ext1.type.firstname", "http://axschema.org/namePerson/first"); Req.Set_Parameter ("openid.ext1.value.firstname", "Stephane"); Req.Set_Parameter ("openid.ext1.type.email", "http://axschema.org/contact/email"); Req.Set_Parameter ("openid.ext1.value.email", "[email protected]"); Req.Set_Parameter ("openid.ext1.type.language", "http://axschema.org/pref/language"); Req.Set_Parameter ("openid.ext1.value.language", "fr"); Req.Set_Parameter ("openid.ext1.type.lastname", "http://axschema.org/namePerson/last"); Req.Set_Parameter ("openid.ext1.value.lastname", "Carrez"); M.Verify (Assoc, Req, Result); -- If the verification is succeeds, the signature is correct, we should be authenticated. T.Assert (Get_Status (Result) = AUTHENTICATED, "Authentication status is not authenticated"); Util.Tests.Assert_Equals (T, "[email protected]", Get_Email (Result), "Invalid email"); end Test_Verify_Signature; end Security.Auth.Tests;
Fix style compilation warning
Fix style compilation warning
Ada
apache-2.0
stcarrez/ada-security
06b7340e0729cfb2d4d7aab672b25cbc5bd9627f
awa/src/awa-blogs-beans.adb
awa/src/awa-blogs-beans.adb
----------------------------------------------------------------------- -- awa-blogs-beans -- Beans for blog 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 AWA.Services.Contexts; with AWA.Blogs.Services; with ADO.Queries; with ADO.Sessions; with ADO.Sessions.Entities; with ASF.Contexts.Faces; with ASF.Applications.Messages.Factory; with ASF.Events.Faces.Actions; package body AWA.Blogs.Beans is use Ada.Strings.Unbounded; BLOG_ID_PARAMETER : constant String := "blog_id"; POST_ID_PARAMETER : constant String := "post_id"; -- ------------------------------ -- Get the parameter identified by the given name and return it as an identifier. -- Returns NO_IDENTIFIER if the parameter does not exist or is not valid. -- ------------------------------ function Get_Parameter (Name : in String) return ADO.Identifier is Ctx : constant ASF.Contexts.Faces.Faces_Context_Access := ASF.Contexts.Faces.Current; P : constant String := Ctx.Get_Parameter (Name); begin if P = "" then return ADO.NO_IDENTIFIER; else return ADO.Identifier'Value (P); end if; exception when others => return ADO.NO_IDENTIFIER; end Get_Parameter; -- ------------------------------ -- Get the value identified by the name. -- ------------------------------ overriding function Get_Value (From : in Blog_Bean; Name : in String) return Util.Beans.Objects.Object is begin return AWA.Blogs.Models.Blog_Ref (From).Get_Value (Name); end Get_Value; -- ------------------------------ -- 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) is begin if Name = "name" then From.Set_Name (Util.Beans.Objects.To_String (Value)); end if; end Set_Value; package Create_Blog_Binding is new ASF.Events.Faces.Actions.Action_Method.Bind (Bean => Blog_Bean, Method => Create_Blog, Name => "create"); Blog_Bean_Binding : aliased constant Util.Beans.Methods.Method_Binding_Array := (1 => Create_Blog_Binding.Proxy'Access); -- This bean provides some methods that can be used in a Method_Expression overriding function Get_Method_Bindings (From : in Blog_Bean) return Util.Beans.Methods.Method_Binding_Array_Access is pragma Unreferenced (From); begin return Blog_Bean_Binding'Access; end Get_Method_Bindings; overriding function Copy (Bean : in Blog_Bean) return Blog_Bean is pragma Unreferenced (Bean); Ref : Blog_Bean; begin return Ref; end Copy; -- ------------------------------ -- Create a new blog. -- ------------------------------ procedure Create_Blog (Bean : in out Blog_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is Manager : constant AWA.Blogs.Services.Blog_Service_Access := Bean.Module.Get_Blog_Manager; Result : ADO.Identifier; begin Manager.Create_Blog (Workspace_Id => 0, Title => Bean.Get_Name, Result => Result); Outcome := To_Unbounded_String ("success"); exception when Services.Not_Found => Outcome := To_Unbounded_String ("failure"); ASF.Applications.Messages.Factory.Add_Message ("users.signup_error_message"); end Create_Blog; -- ------------------------------ -- Create the Blog_Bean bean instance. -- ------------------------------ function Create_Blog_Bean (Module : in AWA.Blogs.Module.Blog_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is use type ADO.Identifier; Blog_Id : constant ADO.Identifier := Get_Parameter (BLOG_ID_PARAMETER); Object : constant Blog_Bean_Access := new Blog_Bean; Session : ADO.Sessions.Session := Module.Get_Session; begin if Blog_Id > 0 then Object.Load (Session, Blog_Id); end if; Object.Module := Module; return Object.all'Access; end Create_Blog_Bean; -- ------------------------------ -- Example of action method. -- ------------------------------ procedure Create_Post (Bean : in out Post_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is use type ADO.Identifier; Manager : constant AWA.Blogs.Services.Blog_Service_Access := Bean.Module.Get_Blog_Manager; Result : ADO.Identifier; Blog_Id : constant ADO.Identifier := Get_Parameter (BLOG_ID_PARAMETER); Post_Id : constant ADO.Identifier := Get_Parameter (POST_ID_PARAMETER); begin if Post_Id < 0 then Manager.Create_Post (Blog_Id => Blog_Id, Title => Bean.Post.Get_Title, URI => Bean.Post.Get_URI, Text => Bean.Post.Get_Text, Result => Result); else Manager.Update_Post (Post_Id => Post_Id, Title => To_String (Bean.Title), Text => To_String (Bean.Text)); end if; Outcome := To_Unbounded_String ("success"); exception when Services.Not_Found => Outcome := To_Unbounded_String ("failure"); ASF.Applications.Messages.Factory.Add_Message ("users.signup_error_message"); end Create_Post; package Create_Post_Binding is new ASF.Events.Faces.Actions.Action_Method.Bind (Bean => Post_Bean, Method => Create_Post, Name => "create"); package Save_Post_Binding is new ASF.Events.Faces.Actions.Action_Method.Bind (Bean => Post_Bean, Method => Create_Post, Name => "save"); Post_Bean_Binding : aliased constant Util.Beans.Methods.Method_Binding_Array := (1 => Create_Post_Binding.Proxy'Access, 2 => Save_Post_Binding.Proxy'Access); -- ------------------------------ -- Get the value identified by the name. -- ------------------------------ overriding function Get_Value (From : in Post_Bean; Name : in String) return Util.Beans.Objects.Object is begin if Name = BLOG_ID_ATTR then return Util.Beans.Objects.To_Object (Long_Long_Integer (From.Blog_Id)); elsif Name = POST_ID_ATTR then return Util.Beans.Objects.To_Object (Long_Long_Integer (From.Post.Get_Id)); else return From.Post.Get_Value (Name); end if; end Get_Value; -- ------------------------------ -- 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) is begin if Name = BLOG_ID_ATTR then From.Blog_Id := ADO.Identifier (Util.Beans.Objects.To_Integer (Value)); elsif Name = POST_ID_ATTR then From.Blog_Id := ADO.Identifier (Util.Beans.Objects.To_Integer (Value)); elsif Name = POST_TEXT_ATTR then From.Post.Set_Text (Util.Beans.Objects.To_Unbounded_String (Value)); elsif Name = POST_TITLE_ATTR then From.Post.Set_Title (Util.Beans.Objects.To_Unbounded_String (Value)); elsif Name = POST_URI_ATTR then From.Post.Set_URI (Util.Beans.Objects.To_Unbounded_String (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 Post_Bean) return Util.Beans.Methods.Method_Binding_Array_Access is pragma Unreferenced (From); begin return Post_Bean_Binding'Access; end Get_Method_Bindings; -- ------------------------------ -- Create the Workspaces_Bean bean instance. -- ------------------------------ function Create_Post_Bean (Module : in AWA.Blogs.Module.Blog_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is use type ADO.Identifier; Object : constant Post_Bean_Access := new Post_Bean; Post_Id : constant ADO.Identifier := Get_Parameter (POST_ID_PARAMETER); begin if Post_Id > 0 then declare Session : ADO.Sessions.Session := Module.Get_Session; begin Object.Post.Load (Session, Post_Id); Object.Title := Object.Post.Get_Title; Object.Text := Object.Post.Get_Text; Object.URI := Object.Post.Get_URI; end; end if; Object.Module := Module; return Object.all'Access; end Create_Post_Bean; -- ------------------------------ -- Create the Post_List_Bean bean instance. -- ------------------------------ function Create_Post_List_Bean (Module : in AWA.Blogs.Module.Blog_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is use AWA.Blogs.Models; Object : constant Post_Info_List_Bean_Access := new Post_Info_List_Bean; Session : ADO.Sessions.Session := Module.Get_Session; Query : ADO.Queries.Context; begin Query.Set_Query (AWA.Blogs.Models.Query_Blog_Post_List); AWA.Blogs.Models.List (Object.all, Session, Query); return Object.all'Access; end Create_Post_List_Bean; -- ------------------------------ -- Create the Admin_Post_List_Bean bean instance. -- ------------------------------ function Create_Admin_Post_List_Bean (Module : in AWA.Blogs.Module.Blog_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is use AWA.Blogs.Models; use AWA.Services; use type ADO.Identifier; Ctx : constant Contexts.Service_Context_Access := AWA.Services.Contexts.Current; User : constant ADO.Identifier := Ctx.Get_User_Identifier; Object : constant Admin_Post_Info_List_Bean_Access := new Admin_Post_Info_List_Bean; Session : ADO.Sessions.Session := Module.Get_Session; Query : ADO.Queries.Context; Blog_Id : constant ADO.Identifier := Get_Parameter (BLOG_ID_PARAMETER); begin if Blog_Id > 0 then Query.Set_Query (AWA.Blogs.Models.Query_Blog_Admin_Post_List); Query.Bind_Param ("blog_id", Blog_Id); Query.Bind_Param ("user_id", User); ADO.Sessions.Entities.Bind_Param (Query, "table", AWA.Blogs.Models.BLOG_TABLE'Access, Session); AWA.Blogs.Models.List (Object.all, Session, Query); end if; return Object.all'Access; end Create_Admin_Post_List_Bean; -- ------------------------------ -- Create the Blog_List_Bean bean instance. -- ------------------------------ function Create_Blog_List_Bean (Module : in AWA.Blogs.Module.Blog_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is use AWA.Blogs.Models; use AWA.Services; use type ADO.Identifier; Ctx : constant Contexts.Service_Context_Access := AWA.Services.Contexts.Current; User : constant ADO.Identifier := Ctx.Get_User_Identifier; Object : constant Blog_Info_List_Bean_Access := new Blog_Info_List_Bean; Session : ADO.Sessions.Session := Module.Get_Session; Query : ADO.Queries.Context; begin Query.Set_Query (AWA.Blogs.Models.Query_Blog_List); Query.Bind_Param ("user_id", User); ADO.Sessions.Entities.Bind_Param (Query, "table", AWA.Blogs.Models.BLOG_TABLE'Access, Session); AWA.Blogs.Models.List (Object.all, Session, Query); return Object.all'Access; end Create_Blog_List_Bean; end AWA.Blogs.Beans;
----------------------------------------------------------------------- -- awa-blogs-beans -- Beans for blog 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 AWA.Services.Contexts; with AWA.Blogs.Services; with ADO.Queries; with ADO.Sessions; with ADO.Sessions.Entities; with ASF.Contexts.Faces; with ASF.Applications.Messages.Factory; with ASF.Events.Faces.Actions; package body AWA.Blogs.Beans is use Ada.Strings.Unbounded; BLOG_ID_PARAMETER : constant String := "blog_id"; POST_ID_PARAMETER : constant String := "post_id"; -- ------------------------------ -- Get the parameter identified by the given name and return it as an identifier. -- Returns NO_IDENTIFIER if the parameter does not exist or is not valid. -- ------------------------------ function Get_Parameter (Name : in String) return ADO.Identifier is Ctx : constant ASF.Contexts.Faces.Faces_Context_Access := ASF.Contexts.Faces.Current; P : constant String := Ctx.Get_Parameter (Name); begin if P = "" then return ADO.NO_IDENTIFIER; else return ADO.Identifier'Value (P); end if; exception when others => return ADO.NO_IDENTIFIER; end Get_Parameter; -- ------------------------------ -- Get the value identified by the name. -- ------------------------------ overriding function Get_Value (From : in Blog_Bean; Name : in String) return Util.Beans.Objects.Object is begin return AWA.Blogs.Models.Blog_Ref (From).Get_Value (Name); end Get_Value; -- ------------------------------ -- 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) is begin if Name = "name" then From.Set_Name (Util.Beans.Objects.To_String (Value)); end if; end Set_Value; package Create_Blog_Binding is new ASF.Events.Faces.Actions.Action_Method.Bind (Bean => Blog_Bean, Method => Create_Blog, Name => "create"); Blog_Bean_Binding : aliased constant Util.Beans.Methods.Method_Binding_Array := (1 => Create_Blog_Binding.Proxy'Access); -- This bean provides some methods that can be used in a Method_Expression overriding function Get_Method_Bindings (From : in Blog_Bean) return Util.Beans.Methods.Method_Binding_Array_Access is pragma Unreferenced (From); begin return Blog_Bean_Binding'Access; end Get_Method_Bindings; overriding function Copy (Bean : in Blog_Bean) return Blog_Bean is pragma Unreferenced (Bean); Ref : Blog_Bean; begin return Ref; end Copy; -- ------------------------------ -- Create a new blog. -- ------------------------------ procedure Create_Blog (Bean : in out Blog_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is Manager : constant AWA.Blogs.Services.Blog_Service_Access := Bean.Module.Get_Blog_Manager; Result : ADO.Identifier; begin Manager.Create_Blog (Workspace_Id => 0, Title => Bean.Get_Name, Result => Result); Outcome := To_Unbounded_String ("success"); exception when Services.Not_Found => Outcome := To_Unbounded_String ("failure"); ASF.Applications.Messages.Factory.Add_Message ("users.signup_error_message"); end Create_Blog; -- ------------------------------ -- Create the Blog_Bean bean instance. -- ------------------------------ function Create_Blog_Bean (Module : in AWA.Blogs.Module.Blog_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is use type ADO.Identifier; Blog_Id : constant ADO.Identifier := Get_Parameter (BLOG_ID_PARAMETER); Object : constant Blog_Bean_Access := new Blog_Bean; Session : ADO.Sessions.Session := Module.Get_Session; begin if Blog_Id > 0 then Object.Load (Session, Blog_Id); end if; Object.Module := Module; return Object.all'Access; end Create_Blog_Bean; -- ------------------------------ -- Example of action method. -- ------------------------------ procedure Create_Post (Bean : in out Post_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is use type ADO.Identifier; Manager : constant AWA.Blogs.Services.Blog_Service_Access := Bean.Module.Get_Blog_Manager; Result : ADO.Identifier; Blog_Id : constant ADO.Identifier := Get_Parameter (BLOG_ID_PARAMETER); Post_Id : constant ADO.Identifier := Get_Parameter (POST_ID_PARAMETER); begin if Post_Id < 0 then Manager.Create_Post (Blog_Id => Blog_Id, Title => Bean.Post.Get_Title, URI => Bean.Post.Get_URI, Text => Bean.Post.Get_Text, Result => Result); else Manager.Update_Post (Post_Id => Post_Id, Title => Bean.Post.Get_Title, Text => Bean.Post.Get_Text); end if; Outcome := To_Unbounded_String ("success"); exception when Services.Not_Found => Outcome := To_Unbounded_String ("failure"); ASF.Applications.Messages.Factory.Add_Message ("users.signup_error_message"); end Create_Post; package Create_Post_Binding is new ASF.Events.Faces.Actions.Action_Method.Bind (Bean => Post_Bean, Method => Create_Post, Name => "create"); package Save_Post_Binding is new ASF.Events.Faces.Actions.Action_Method.Bind (Bean => Post_Bean, Method => Create_Post, Name => "save"); Post_Bean_Binding : aliased constant Util.Beans.Methods.Method_Binding_Array := (1 => Create_Post_Binding.Proxy'Access, 2 => Save_Post_Binding.Proxy'Access); -- ------------------------------ -- Get the value identified by the name. -- ------------------------------ overriding function Get_Value (From : in Post_Bean; Name : in String) return Util.Beans.Objects.Object is begin if Name = BLOG_ID_ATTR then return Util.Beans.Objects.To_Object (Long_Long_Integer (From.Blog_Id)); elsif Name = POST_ID_ATTR then return Util.Beans.Objects.To_Object (Long_Long_Integer (From.Post.Get_Id)); else return From.Post.Get_Value (Name); end if; end Get_Value; -- ------------------------------ -- 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) is begin if Name = BLOG_ID_ATTR then From.Blog_Id := ADO.Identifier (Util.Beans.Objects.To_Integer (Value)); elsif Name = POST_ID_ATTR then From.Blog_Id := ADO.Identifier (Util.Beans.Objects.To_Integer (Value)); elsif Name = POST_TEXT_ATTR then From.Post.Set_Text (Util.Beans.Objects.To_Unbounded_String (Value)); elsif Name = POST_TITLE_ATTR then From.Post.Set_Title (Util.Beans.Objects.To_Unbounded_String (Value)); elsif Name = POST_URI_ATTR then From.Post.Set_URI (Util.Beans.Objects.To_Unbounded_String (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 Post_Bean) return Util.Beans.Methods.Method_Binding_Array_Access is pragma Unreferenced (From); begin return Post_Bean_Binding'Access; end Get_Method_Bindings; -- ------------------------------ -- Create the Workspaces_Bean bean instance. -- ------------------------------ function Create_Post_Bean (Module : in AWA.Blogs.Module.Blog_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is use type ADO.Identifier; Object : constant Post_Bean_Access := new Post_Bean; Post_Id : constant ADO.Identifier := Get_Parameter (POST_ID_PARAMETER); begin if Post_Id > 0 then declare Session : ADO.Sessions.Session := Module.Get_Session; begin Object.Post.Load (Session, Post_Id); Object.Title := Object.Post.Get_Title; Object.Text := Object.Post.Get_Text; Object.URI := Object.Post.Get_URI; end; end if; Object.Module := Module; return Object.all'Access; end Create_Post_Bean; -- ------------------------------ -- Create the Post_List_Bean bean instance. -- ------------------------------ function Create_Post_List_Bean (Module : in AWA.Blogs.Module.Blog_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is use AWA.Blogs.Models; Object : constant Post_Info_List_Bean_Access := new Post_Info_List_Bean; Session : ADO.Sessions.Session := Module.Get_Session; Query : ADO.Queries.Context; begin Query.Set_Query (AWA.Blogs.Models.Query_Blog_Post_List); AWA.Blogs.Models.List (Object.all, Session, Query); return Object.all'Access; end Create_Post_List_Bean; -- ------------------------------ -- Create the Admin_Post_List_Bean bean instance. -- ------------------------------ function Create_Admin_Post_List_Bean (Module : in AWA.Blogs.Module.Blog_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is use AWA.Blogs.Models; use AWA.Services; use type ADO.Identifier; Ctx : constant Contexts.Service_Context_Access := AWA.Services.Contexts.Current; User : constant ADO.Identifier := Ctx.Get_User_Identifier; Object : constant Admin_Post_Info_List_Bean_Access := new Admin_Post_Info_List_Bean; Session : ADO.Sessions.Session := Module.Get_Session; Query : ADO.Queries.Context; Blog_Id : constant ADO.Identifier := Get_Parameter (BLOG_ID_PARAMETER); begin if Blog_Id > 0 then Query.Set_Query (AWA.Blogs.Models.Query_Blog_Admin_Post_List); Query.Bind_Param ("blog_id", Blog_Id); Query.Bind_Param ("user_id", User); ADO.Sessions.Entities.Bind_Param (Query, "table", AWA.Blogs.Models.BLOG_TABLE'Access, Session); AWA.Blogs.Models.List (Object.all, Session, Query); end if; return Object.all'Access; end Create_Admin_Post_List_Bean; -- ------------------------------ -- Create the Blog_List_Bean bean instance. -- ------------------------------ function Create_Blog_List_Bean (Module : in AWA.Blogs.Module.Blog_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is use AWA.Blogs.Models; use AWA.Services; use type ADO.Identifier; Ctx : constant Contexts.Service_Context_Access := AWA.Services.Contexts.Current; User : constant ADO.Identifier := Ctx.Get_User_Identifier; Object : constant Blog_Info_List_Bean_Access := new Blog_Info_List_Bean; Session : ADO.Sessions.Session := Module.Get_Session; Query : ADO.Queries.Context; begin Query.Set_Query (AWA.Blogs.Models.Query_Blog_List); Query.Bind_Param ("user_id", User); ADO.Sessions.Entities.Bind_Param (Query, "table", AWA.Blogs.Models.BLOG_TABLE'Access, Session); AWA.Blogs.Models.List (Object.all, Session, Query); return Object.all'Access; end Create_Blog_List_Bean; end AWA.Blogs.Beans;
Fix updating the blog post title and content
Fix updating the blog post title and content
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
e205ea9a52c5c594e0fb427dba247c4d02cfa184
awa/src/awa-permissions.ads
awa/src/awa-permissions.ads
----------------------------------------------------------------------- -- awa-permissions -- Permissions module -- Copyright (C) 2011, 2012, 2013, 2014, 2015, 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Security.Permissions; with Security.Policies; with Util.Serialize.IO.XML; private with Util.Beans.Objects; with ADO; with ADO.Objects; private with ADO.Sessions; -- == Introduction == -- The *AWA.Permissions* framework defines and controls the permissions used by an application -- to verify and grant access to the data and application service. The framework provides a -- set of services and API that helps an application in enforcing its specific permissions. -- Permissions are verified by a permission controller which uses the service context to -- have information about the user and other context. The framework allows to use different -- kinds of permission controllers. The `Entity_Controller` is the default permission -- controller which uses the database and an XML configuration to verify a permission. -- -- === Declaration === -- To be used in the application, the first step is to declare the permission. -- This is a static definition of the permission that will be used to ask to verify the -- permission. The permission is given a unique name that will be used in configuration files: -- -- with Security.Permissions; -- ... -- package ACL_Create_Post is new Security.Permissions.Definition ("blog-create-post"); -- -- === Checking for a permission === -- A permission can be checked in Ada as well as in the presentation pages. -- This is done by using the `Check` procedure and the permission definition. This operation -- acts as a barrier: it does not return anything but returns normally if the permission is -- granted. If the permission is denied, it raises the `NO_PERMISSION` exception. -- -- Several `Check` operation exists. Some require no argument and some others need a context -- such as some entity identifier to perform the check. -- -- with AWA.Permissions; -- ... -- AWA.Permissions.Check (Permission => ACL_Create_Post.Permission, -- Entity => Blog_Id); -- -- === Configuring a permission === -- The *AWA.Permissions* framework supports a simple permission model -- The application configuration file must provide some information to help in checking the -- permission. The permission name is referenced by the `name` XML entity. The `entity-type` -- refers to the database entity (ie, the table) that the permission concerns. -- The `sql` XML entity represents the SQL statement that must be used to verify the permission. -- -- <entity-permission> -- <name>blog-create-post</name> -- <entity-type>blog</entity-type> -- <description>Permission to create a new post.</description> -- <sql> -- SELECT acl.id FROM acl -- WHERE acl.entity_type = :entity_type -- AND acl.user_id = :user_id -- AND acl.entity_id = :entity_id -- </sql> -- </entity-permission> -- -- === Adding a permission === -- Adding a permission means to create an `ACL` database record that links a given database -- entity to the user. This is done easily with the `Add_Permission` procedure: -- -- with AWA.Permissions.Services; -- ... -- AWA.Permissions.Services.Add_Permission (Session => DB, -- User => User, -- Entity => Blog); -- -- == Data Model == -- [images/awa_permissions_model.png] -- -- == Queries == -- @include permissions.xml -- package AWA.Permissions is NAME : constant String := "Entity-Policy"; -- Exception raised by the <b>Check</b> procedure if the user does not have -- the permission. NO_PERMISSION : exception; -- Maximum number of entity types that can be defined in the XML entity-permission. -- Most permission need only one entity type. Keep that number small. MAX_ENTITY_TYPES : constant Positive := 5; type Entity_Type_Array is array (1 .. MAX_ENTITY_TYPES) of ADO.Entity_Type; type Permission_Type is (READ, WRITE); type Entity_Permission is new Security.Permissions.Permission with private; -- Verify that the permission represented by <b>Permission</b> is granted. -- procedure Check (Permission : in Security.Permissions.Permission_Index); -- Verify that the permission represented by <b>Permission</b> is granted to access the -- database entity represented by <b>Entity</b>. procedure Check (Permission : in Security.Permissions.Permission_Index; Entity : in ADO.Identifier); -- Verify that the permission represented by <b>Permission</b> is granted to access the -- database entity represented by <b>Entity</b>. procedure Check (Permission : in Security.Permissions.Permission_Index; Entity : in ADO.Objects.Object_Ref'Class); private type Entity_Permission is new Security.Permissions.Permission with record Entity : ADO.Identifier; end record; type Entity_Policy; type Entity_Policy_Access is access all Entity_Policy'Class; type Controller_Config is record Name : Util.Beans.Objects.Object; SQL : Util.Beans.Objects.Object; Entity : ADO.Entity_Type := 0; Entities : Entity_Type_Array := (others => ADO.NO_ENTITY_TYPE); Count : Natural := 0; Manager : Entity_Policy_Access; Session : ADO.Sessions.Session; end record; type Entity_Policy is new Security.Policies.Policy with record Config : aliased Controller_Config; end record; -- Get the policy name. overriding function Get_Name (From : in Entity_Policy) return String; -- Setup the XML parser to read the <b>policy</b> description. overriding procedure Prepare_Config (Policy : in out Entity_Policy; Reader : in out Util.Serialize.IO.XML.Parser); end AWA.Permissions;
----------------------------------------------------------------------- -- awa-permissions -- Permissions module -- Copyright (C) 2011, 2012, 2013, 2014, 2015, 2016, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Security.Permissions; with Security.Policies; with Util.Serialize.Mappers; private with Util.Beans.Objects; with ADO; with ADO.Objects; private with ADO.Sessions; -- == Introduction == -- The *AWA.Permissions* framework defines and controls the permissions used by an application -- to verify and grant access to the data and application service. The framework provides a -- set of services and API that helps an application in enforcing its specific permissions. -- Permissions are verified by a permission controller which uses the service context to -- have information about the user and other context. The framework allows to use different -- kinds of permission controllers. The `Entity_Controller` is the default permission -- controller which uses the database and an XML configuration to verify a permission. -- -- === Declaration === -- To be used in the application, the first step is to declare the permission. -- This is a static definition of the permission that will be used to ask to verify the -- permission. The permission is given a unique name that will be used in configuration files: -- -- with Security.Permissions; -- ... -- package ACL_Create_Post is new Security.Permissions.Definition ("blog-create-post"); -- -- === Checking for a permission === -- A permission can be checked in Ada as well as in the presentation pages. -- This is done by using the `Check` procedure and the permission definition. This operation -- acts as a barrier: it does not return anything but returns normally if the permission is -- granted. If the permission is denied, it raises the `NO_PERMISSION` exception. -- -- Several `Check` operation exists. Some require no argument and some others need a context -- such as some entity identifier to perform the check. -- -- with AWA.Permissions; -- ... -- AWA.Permissions.Check (Permission => ACL_Create_Post.Permission, -- Entity => Blog_Id); -- -- === Configuring a permission === -- The *AWA.Permissions* framework supports a simple permission model -- The application configuration file must provide some information to help in checking the -- permission. The permission name is referenced by the `name` XML entity. The `entity-type` -- refers to the database entity (ie, the table) that the permission concerns. -- The `sql` XML entity represents the SQL statement that must be used to verify the permission. -- -- <entity-permission> -- <name>blog-create-post</name> -- <entity-type>blog</entity-type> -- <description>Permission to create a new post.</description> -- <sql> -- SELECT acl.id FROM acl -- WHERE acl.entity_type = :entity_type -- AND acl.user_id = :user_id -- AND acl.entity_id = :entity_id -- </sql> -- </entity-permission> -- -- === Adding a permission === -- Adding a permission means to create an `ACL` database record that links a given database -- entity to the user. This is done easily with the `Add_Permission` procedure: -- -- with AWA.Permissions.Services; -- ... -- AWA.Permissions.Services.Add_Permission (Session => DB, -- User => User, -- Entity => Blog); -- -- == Data Model == -- [images/awa_permissions_model.png] -- -- == Queries == -- @include permissions.xml -- package AWA.Permissions is NAME : constant String := "Entity-Policy"; -- Exception raised by the <b>Check</b> procedure if the user does not have -- the permission. NO_PERMISSION : exception; -- Maximum number of entity types that can be defined in the XML entity-permission. -- Most permission need only one entity type. Keep that number small. MAX_ENTITY_TYPES : constant Positive := 5; type Entity_Type_Array is array (1 .. MAX_ENTITY_TYPES) of ADO.Entity_Type; type Permission_Type is (READ, WRITE); type Entity_Permission is new Security.Permissions.Permission with private; -- Verify that the permission represented by <b>Permission</b> is granted. -- procedure Check (Permission : in Security.Permissions.Permission_Index); -- Verify that the permission represented by <b>Permission</b> is granted to access the -- database entity represented by <b>Entity</b>. procedure Check (Permission : in Security.Permissions.Permission_Index; Entity : in ADO.Identifier); -- Verify that the permission represented by <b>Permission</b> is granted to access the -- database entity represented by <b>Entity</b>. procedure Check (Permission : in Security.Permissions.Permission_Index; Entity : in ADO.Objects.Object_Ref'Class); private type Entity_Permission is new Security.Permissions.Permission with record Entity : ADO.Identifier; end record; type Entity_Policy; type Entity_Policy_Access is access all Entity_Policy'Class; type Controller_Config is record Name : Util.Beans.Objects.Object; SQL : Util.Beans.Objects.Object; Grant : Util.Beans.Objects.Object; Entity : ADO.Entity_Type := 0; Entities : Entity_Type_Array := (others => ADO.NO_ENTITY_TYPE); Count : Natural := 0; Manager : Entity_Policy_Access; Session : ADO.Sessions.Session; end record; type Entity_Policy is new Security.Policies.Policy with record Config : aliased Controller_Config; end record; -- Get the policy name. overriding function Get_Name (From : in Entity_Policy) return String; -- Setup the XML parser to read the <b>policy</b> description. overriding procedure Prepare_Config (Policy : in out Entity_Policy; Mapper : in out Util.Serialize.Mappers.Processing); end AWA.Permissions;
Update the Prepare_Config to use the new parser/mapper interface
Update the Prepare_Config to use the new parser/mapper interface
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
ca1671f8a40862288e626b6d2b830c12744d4b95
awa/plugins/awa-workspaces/src/awa-workspaces-modules.ads
awa/plugins/awa-workspaces/src/awa-workspaces-modules.ads
----------------------------------------------------------------------- -- awa-workspaces-module -- 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. ----------------------------------------------------------------------- with ADO.Sessions; with ASF.Applications; with AWA.Modules; with AWA.Services.Contexts; with AWA.Workspaces.Models; package AWA.Workspaces.Modules is -- The name under which the module is registered. NAME : constant String := "workspaces"; -- ------------------------------ -- Module workspaces -- ------------------------------ type Workspace_Module is new AWA.Modules.Module with private; type Workspace_Module_Access is access all Workspace_Module'Class; -- Initialize the workspaces module. overriding procedure Initialize (Plugin : in out Workspace_Module; App : in AWA.Modules.Application_Access; Props : in ASF.Applications.Config); -- Get the current workspace associated with the current user. -- If the user has not workspace, create one. procedure Get_Workspace (Session : in out ADO.Sessions.Master_Session; Context : in AWA.Services.Contexts.Service_Context_Access; Workspace : out AWA.Workspaces.Models.Workspace_Ref); private type Workspace_Module is new AWA.Modules.Module with null record; end AWA.Workspaces.Modules;
----------------------------------------------------------------------- -- awa-workspaces-module -- 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 ADO.Sessions; with ASF.Applications; with AWA.Modules; with AWA.Services.Contexts; with AWA.Workspaces.Models; package AWA.Workspaces.Modules is -- The name under which the module is registered. NAME : constant String := "workspaces"; -- ------------------------------ -- Module workspaces -- ------------------------------ type Workspace_Module is new AWA.Modules.Module with private; type Workspace_Module_Access is access all Workspace_Module'Class; -- Initialize the workspaces module. overriding procedure Initialize (Plugin : in out Workspace_Module; App : in AWA.Modules.Application_Access; Props : in ASF.Applications.Config); -- Get the current workspace associated with the current user. -- If the user has not workspace, create one. procedure Get_Workspace (Session : in out ADO.Sessions.Master_Session; Context : in AWA.Services.Contexts.Service_Context_Access; Workspace : out AWA.Workspaces.Models.Workspace_Ref); -- Send the invitation to the user. procedure Send_Invitation (Module : in Workspace_Module; Invitation : in out AWA.Workspaces.Models.Invitation_Ref'Class); private type Workspace_Module is new AWA.Modules.Module with null record; end AWA.Workspaces.Modules;
Declare the Send_Invitation procedure to send an invitation to someone
Declare the Send_Invitation procedure to send an invitation to someone
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
8c5858c3859a982abaed7ea3b2aebe1e92667ad1
src/babel-base.ads
src/babel-base.ads
----------------------------------------------------------------------- -- babel-base -- Database for files -- Copyright (C) 2014 Stephane.Carrez -- Written by Stephane.Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Finalization; with ADO; with Babel.Files; package Babel.Base is type Database is abstract new Ada.Finalization.Limited_Controlled with private; type Database_Access is access all Database'Class; -- Insert the file in the database. procedure Insert (Into : in out Database; File : in Babel.Files.File_Type) is abstract; private type Database is abstract new Ada.Finalization.Limited_Controlled with record Name : Integer; end record; end Babel.Base;
----------------------------------------------------------------------- -- babel-base -- Database for files -- Copyright (C) 2014 Stephane.Carrez -- Written by Stephane.Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Finalization; with ADO; with Babel.Files; package Babel.Base is type Database is abstract new Ada.Finalization.Limited_Controlled with private; type Database_Access is access all Database'Class; -- Insert the file in the database. procedure Insert (Into : in out Database; File : in Babel.Files.File_Type) is abstract; procedure Iterate (From : in Database; Process : not null access procedure (File : in Babel.Files.File_Type)) is abstract; procedure Copy (Into : in out Database'Class; From : in Database'Class); private type Database is abstract new Ada.Finalization.Limited_Controlled with record Name : Integer; end record; end Babel.Base;
Declare the Iterate and Copy procedures
Declare the Iterate and Copy procedures
Ada
apache-2.0
stcarrez/babel
cb1081d3e2cf140abc8dc3c98341923df094801e
src/os-linux/util-systems-os.ads
src/os-linux/util-systems-os.ads
----------------------------------------------------------------------- -- util-system-os -- Unix system operations -- Copyright (C) 2011, 2012, 2014, 2015, 2016, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with System; with Interfaces.C; with Interfaces.C.Strings; with Util.Processes; with Util.Systems.Constants; with Util.Systems.Types; -- The <b>Util.Systems.Os</b> package defines various types and operations which are specific -- to the OS (Unix). package Util.Systems.Os is -- The directory separator. Directory_Separator : constant Character := '/'; -- The path separator. Path_Separator : constant Character := ':'; subtype Ptr is Interfaces.C.Strings.chars_ptr; subtype Ptr_Array is Interfaces.C.Strings.chars_ptr_array; type Ptr_Ptr_Array is access all Ptr_Array; type File_Type is new Integer; -- Standard file streams Posix, X/Open standard values. STDIN_FILENO : constant File_Type := 0; STDOUT_FILENO : constant File_Type := 1; STDERR_FILENO : constant File_Type := 2; -- File is not opened NO_FILE : constant File_Type := -1; -- The following values should be externalized. They are valid for GNU/Linux. F_SETFL : constant Interfaces.C.int := Util.Systems.Constants.F_SETFL; FD_CLOEXEC : constant Interfaces.C.int := Util.Systems.Constants.FD_CLOEXEC; -- These values are specific to Linux. O_RDONLY : constant Interfaces.C.int := Util.Systems.Constants.O_RDONLY; O_WRONLY : constant Interfaces.C.int := Util.Systems.Constants.O_WRONLY; O_RDWR : constant Interfaces.C.int := Util.Systems.Constants.O_RDWR; O_CREAT : constant Interfaces.C.int := Util.Systems.Constants.O_CREAT; O_EXCL : constant Interfaces.C.int := Util.Systems.Constants.O_EXCL; O_TRUNC : constant Interfaces.C.int := Util.Systems.Constants.O_TRUNC; O_APPEND : constant Interfaces.C.int := Util.Systems.Constants.O_APPEND; type Size_T is mod 2 ** Standard'Address_Size; type Ssize_T is range -(2 ** (Standard'Address_Size - 1)) .. +(2 ** (Standard'Address_Size - 1)) - 1; function Close (Fd : in File_Type) return Integer; pragma Import (C, Close, "close"); function Read (Fd : in File_Type; Buf : in System.Address; Size : in Size_T) return Ssize_T; pragma Import (C, Read, "read"); function Write (Fd : in File_Type; Buf : in System.Address; Size : in Size_T) return Ssize_T; pragma Import (C, Write, "write"); -- System exit without any process cleaning. -- (destructors, finalizers, atexit are not called) procedure Sys_Exit (Code : in Integer); pragma Import (C, Sys_Exit, "_exit"); -- Fork a new process function Sys_Fork return Util.Processes.Process_Identifier; pragma Import (C, Sys_Fork, "fork"); -- Fork a new process (vfork implementation) function Sys_VFork return Util.Processes.Process_Identifier; pragma Import (C, Sys_VFork, "fork"); -- Execute a process with the given arguments. function Sys_Execvp (File : in Ptr; Args : in Ptr_Array) return Integer; pragma Import (C, Sys_Execvp, "execvp"); -- Wait for the process <b>Pid</b> to finish and return function Sys_Waitpid (Pid : in Integer; Status : in System.Address; Options : in Integer) return Integer; pragma Import (C, Sys_Waitpid, "waitpid"); -- Create a bi-directional pipe function Sys_Pipe (Fds : in System.Address) return Integer; pragma Import (C, Sys_Pipe, "pipe"); -- Make <b>fd2</b> the copy of <b>fd1</b> function Sys_Dup2 (Fd1, Fd2 : in File_Type) return Integer; pragma Import (C, Sys_Dup2, "dup2"); -- Close a file function Sys_Close (Fd : in File_Type) return Integer; pragma Import (C, Sys_Close, "close"); -- Open a file function Sys_Open (Path : in Ptr; Flags : in Interfaces.C.int; Mode : in Util.Systems.Types.mode_t) return File_Type; pragma Import (C, Sys_Open, "open"); -- Change the file settings function Sys_Fcntl (Fd : in File_Type; Cmd : in Interfaces.C.int; Flags : in Interfaces.C.int) return Integer; pragma Import (C, Sys_Fcntl, "fcntl"); function Sys_Kill (Pid : in Integer; Signal : in Integer) return Integer; pragma Import (C, Sys_Kill, "kill"); function Sys_Stat (Path : in Ptr; Stat : access Util.Systems.Types.Stat_Type) return Integer; pragma Import (C, Sys_Stat, Util.Systems.Types.STAT_NAME); function Sys_Fstat (Fs : in File_Type; Stat : access Util.Systems.Types.Stat_Type) return Integer; pragma Import (C, Sys_Fstat, Util.Systems.Types.FSTAT_NAME); function Sys_Lseek (Fs : in File_Type; Offset : in Util.Systems.Types.off_t; Mode : in Util.Systems.Types.Seek_Mode) return Util.Systems.Types.off_t; pragma Import (C, Sys_Lseek, "lseek"); function Sys_Fchmod (Fd : in File_Type; Mode : in Util.Systems.Types.mode_t) return Integer; pragma Import (C, Sys_Fchmod, "fchmod"); -- Change permission of a file. function Sys_Chmod (Path : in Ptr; Mode : in Util.Systems.Types.mode_t) return Integer; pragma Import (C, Sys_Chmod, "chmod"); -- Rename a file (the Ada.Directories.Rename does not allow to use -- the Unix atomic file rename!) function Sys_Rename (Oldpath : in Ptr; Newpath : in Ptr) return Integer; pragma Import (C, Sys_Rename, "rename"); -- Libc errno. The __get_errno function is provided by the GNAT runtime. function Errno return Integer; pragma Import (C, Errno, "__get_errno"); end Util.Systems.Os;
----------------------------------------------------------------------- -- util-system-os -- Unix system operations -- Copyright (C) 2011, 2012, 2014, 2015, 2016, 2017, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with System; with Interfaces.C; with Interfaces.C.Strings; with Util.Processes; with Util.Systems.Constants; with Util.Systems.Types; -- The <b>Util.Systems.Os</b> package defines various types and operations which are specific -- to the OS (Unix). package Util.Systems.Os is -- The directory separator. Directory_Separator : constant Character := '/'; -- The path separator. Path_Separator : constant Character := ':'; subtype Ptr is Interfaces.C.Strings.chars_ptr; subtype Ptr_Array is Interfaces.C.Strings.chars_ptr_array; type Ptr_Ptr_Array is access all Ptr_Array; type File_Type is new Interfaces.C.int; -- Standard file streams Posix, X/Open standard values. STDIN_FILENO : constant File_Type := 0; STDOUT_FILENO : constant File_Type := 1; STDERR_FILENO : constant File_Type := 2; -- File is not opened NO_FILE : constant File_Type := -1; -- The following values should be externalized. They are valid for GNU/Linux. F_SETFL : constant Interfaces.C.int := Util.Systems.Constants.F_SETFL; FD_CLOEXEC : constant Interfaces.C.int := Util.Systems.Constants.FD_CLOEXEC; -- These values are specific to Linux. O_RDONLY : constant Interfaces.C.int := Util.Systems.Constants.O_RDONLY; O_WRONLY : constant Interfaces.C.int := Util.Systems.Constants.O_WRONLY; O_RDWR : constant Interfaces.C.int := Util.Systems.Constants.O_RDWR; O_CREAT : constant Interfaces.C.int := Util.Systems.Constants.O_CREAT; O_EXCL : constant Interfaces.C.int := Util.Systems.Constants.O_EXCL; O_TRUNC : constant Interfaces.C.int := Util.Systems.Constants.O_TRUNC; O_APPEND : constant Interfaces.C.int := Util.Systems.Constants.O_APPEND; type Size_T is mod 2 ** Standard'Address_Size; type Ssize_T is range -(2 ** (Standard'Address_Size - 1)) .. +(2 ** (Standard'Address_Size - 1)) - 1; function Close (Fd : in File_Type) return Integer; pragma Import (C, Close, "close"); function Read (Fd : in File_Type; Buf : in System.Address; Size : in Size_T) return Ssize_T; pragma Import (C, Read, "read"); function Write (Fd : in File_Type; Buf : in System.Address; Size : in Size_T) return Ssize_T; pragma Import (C, Write, "write"); -- System exit without any process cleaning. -- (destructors, finalizers, atexit are not called) procedure Sys_Exit (Code : in Integer); pragma Import (C, Sys_Exit, "_exit"); -- Fork a new process function Sys_Fork return Util.Processes.Process_Identifier; pragma Import (C, Sys_Fork, "fork"); -- Fork a new process (vfork implementation) function Sys_VFork return Util.Processes.Process_Identifier; pragma Import (C, Sys_VFork, "fork"); -- Execute a process with the given arguments. function Sys_Execvp (File : in Ptr; Args : in Ptr_Array) return Integer; pragma Import (C, Sys_Execvp, "execvp"); -- Wait for the process <b>Pid</b> to finish and return function Sys_Waitpid (Pid : in Integer; Status : in System.Address; Options : in Integer) return Integer; pragma Import (C, Sys_Waitpid, "waitpid"); -- Create a bi-directional pipe function Sys_Pipe (Fds : in System.Address) return Integer; pragma Import (C, Sys_Pipe, "pipe"); -- Make <b>fd2</b> the copy of <b>fd1</b> function Sys_Dup2 (Fd1, Fd2 : in File_Type) return Integer; pragma Import (C, Sys_Dup2, "dup2"); -- Close a file function Sys_Close (Fd : in File_Type) return Integer; pragma Import (C, Sys_Close, "close"); -- Open a file function Sys_Open (Path : in Ptr; Flags : in Interfaces.C.int; Mode : in Util.Systems.Types.mode_t) return File_Type; pragma Import (C, Sys_Open, "open"); -- Change the file settings function Sys_Fcntl (Fd : in File_Type; Cmd : in Interfaces.C.int; Flags : in Interfaces.C.int) return Integer; pragma Import (C, Sys_Fcntl, "fcntl"); function Sys_Kill (Pid : in Integer; Signal : in Integer) return Integer; pragma Import (C, Sys_Kill, "kill"); function Sys_Stat (Path : in Ptr; Stat : access Util.Systems.Types.Stat_Type) return Integer; pragma Import (C, Sys_Stat, Util.Systems.Types.STAT_NAME); function Sys_Fstat (Fs : in File_Type; Stat : access Util.Systems.Types.Stat_Type) return Integer; pragma Import (C, Sys_Fstat, Util.Systems.Types.FSTAT_NAME); function Sys_Lseek (Fs : in File_Type; Offset : in Util.Systems.Types.off_t; Mode : in Util.Systems.Types.Seek_Mode) return Util.Systems.Types.off_t; pragma Import (C, Sys_Lseek, "lseek"); function Sys_Fchmod (Fd : in File_Type; Mode : in Util.Systems.Types.mode_t) return Integer; pragma Import (C, Sys_Fchmod, "fchmod"); -- Change permission of a file. function Sys_Chmod (Path : in Ptr; Mode : in Util.Systems.Types.mode_t) return Integer; pragma Import (C, Sys_Chmod, "chmod"); -- Rename a file (the Ada.Directories.Rename does not allow to use -- the Unix atomic file rename!) function Sys_Rename (Oldpath : in Ptr; Newpath : in Ptr) return Integer; pragma Import (C, Sys_Rename, "rename"); -- Libc errno. The __get_errno function is provided by the GNAT runtime. function Errno return Integer; pragma Import (C, Errno, "__get_errno"); end Util.Systems.Os;
Fix header and change File_Type to use the C int type
Fix header and change File_Type to use the C int type
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
a683af57fb097abd8196c8c4a02ec96268cea02a
samples/api_server.adb
samples/api_server.adb
----------------------------------------------------------------------- -- api_server -- Example of REST API server -- Copyright (C) 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with ASF.Server.Web; with ASF.Servlets.Rest; with ASF.Servlets.Files; with ASF.Applications; with Util.Log.Loggers; with Monitor; with EL.Contexts.Default; procedure API_Server is CONFIG_PATH : constant String := "samples.properties"; Api : aliased ASF.Servlets.Rest.Rest_Servlet; Files : aliased ASF.Servlets.Files.File_Servlet; App : aliased ASF.Servlets.Servlet_Registry; WS : ASF.Server.Web.AWS_Container; Ctx : EL.Contexts.Default.Default_Context; Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Api_Server"); begin Util.Log.Loggers.Initialize (CONFIG_PATH); App.Set_Init_Parameter (ASF.Applications.VIEW_DIR, "samples/web"); -- Register the servlets and filters App.Add_Servlet (Name => "api", Server => Api'Unchecked_Access); App.Add_Servlet (Name => "files", Server => Files'Unchecked_Access); -- Define servlet mappings App.Add_Mapping (Name => "api", Pattern => "/api/*"); App.Add_Mapping (Name => "files", Pattern => "*.html"); App.Add_Mapping (Name => "files", Pattern => "*.css"); App.Add_Mapping (Name => "files", Pattern => "*.js"); Monitor.Mon_API.Register (App, "api", Ctx); WS.Register_Application ("/sample", App'Unchecked_Access); Log.Info ("Connect you browser to: http://localhost:8080/sample/index.html"); WS.Start; delay 6000.0; end API_Server;
----------------------------------------------------------------------- -- api_server -- Example of REST API server -- Copyright (C) 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with ASF.Server.Web; with ASF.Servlets.Rest; with ASF.Servlets.Files; with ASF.Applications; with Util.Log.Loggers; with Monitor; with EL.Contexts.Default; procedure API_Server is CONFIG_PATH : constant String := "samples.properties"; Api : aliased ASF.Servlets.Rest.Rest_Servlet; Files : aliased ASF.Servlets.Files.File_Servlet; App : aliased ASF.Servlets.Servlet_Registry; WS : ASF.Server.Web.AWS_Container; Ctx : EL.Contexts.Default.Default_Context; Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Api_Server"); begin Util.Log.Loggers.Initialize (CONFIG_PATH); App.Set_Init_Parameter (ASF.Applications.VIEW_DIR, "samples/web/monitor"); -- Register the servlets and filters App.Add_Servlet (Name => "api", Server => Api'Unchecked_Access); App.Add_Servlet (Name => "files", Server => Files'Unchecked_Access); -- Define servlet mappings App.Add_Mapping (Name => "api", Pattern => "/api/*"); App.Add_Mapping (Name => "files", Pattern => "*.html"); App.Add_Mapping (Name => "files", Pattern => "*.css"); App.Add_Mapping (Name => "files", Pattern => "*.js"); Monitor.Mon_API.Register (App, "api", Ctx); WS.Register_Application ("/monitor", App'Unchecked_Access); Log.Info ("Connect you browser to: http://localhost:8080/monitor/index.html"); WS.Start; delay 6000.0; end API_Server;
Update the URI to use /monitor as base URI
Update the URI to use /monitor as base URI
Ada
apache-2.0
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
3c134e36149dacdb9384eaa8af2e3fcafa4973f9
src/asf-contexts-writer.ads
src/asf-contexts-writer.ads
----------------------------------------------------------------------- -- writer -- Response stream writer -- Copyright (C) 2009, 2010, 2011, 2012, 2013 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- -- The <b>ASF.Contexts.Writer</b> defines the response writer to -- write the rendered result to the response stream. The <b>IOWriter</b> -- interface defines the procedure for writing the buffer to the output -- stream. The <b>Response_Writer</b> is the main type that provides -- various methods for writing the content. -- -- The result stream is encoded according to the encoding type. -- with Unicode.Encodings; with Ada.Streams; with Ada.Strings.Unbounded; with Ada.Strings.Wide_Wide_Unbounded; with EL.Objects; with Util.Beans.Objects; with Util.Strings.Builders; with ASF.Streams; package ASF.Contexts.Writer is use Ada.Strings.Unbounded; use Ada.Strings.Wide_Wide_Unbounded; -- ------------------------------ -- IO Writer -- ------------------------------ type IOWriter is limited interface; procedure Write (Stream : in out IOWriter; Buffer : in Ada.Streams.Stream_Element_Array) is abstract; -- ------------------------------ -- Response Writer -- ------------------------------ type Response_Writer is new ASF.Streams.Print_Stream with private; type Response_Writer_Access is access all Response_Writer'Class; -- Backward compatibility subtype ResponseWriter is Response_Writer; pragma Obsolescent (Entity => ResponseWriter); subtype ResponseWriter_Access is Response_Writer_Access; pragma Obsolescent (Entity => ResponseWriter_Access); -- Initialize the response stream for the given content type and -- encoding. An internal buffer is allocated for writing the stream. procedure Initialize (Stream : in out Response_Writer; Content_Type : in String; Encoding : in String; Output : in ASF.Streams.Print_Stream); -- Get the content type. function Get_Content_Type (Stream : in Response_Writer) return String; -- Get the character encoding. function Get_Encoding (Stream : in Response_Writer) return String; -- Close the current XML entity if an entity was started procedure Close_Current (Stream : in out Response_Writer'Class); -- Start an XML element with the given name. procedure Start_Element (Stream : in out Response_Writer; Name : in String); -- Start an optional XML element with the given name. -- The element is written only if it has at least one attribute. -- The optional XML element must not contain other XML entities. procedure Start_Optional_Element (Stream : in out Response_Writer; Name : in String); -- Closes an XML element of the given name. procedure End_Element (Stream : in out Response_Writer; Name : in String); -- Closes an optional XML element of the given name. -- The ending tag is written only if the start tag was written. procedure End_Optional_Element (Stream : in out Response_Writer; Name : in String); -- Write an XML element using the given name and with the content. -- This is similar to calling <b>Start_Element</b>, <b>Write_Text</b> -- and <b>End_Element</b>. procedure Write_Element (Stream : in out Response_Writer; Name : in String; Content : in String); procedure Write_Wide_Element (Stream : in out Response_Writer; Name : in String; Content : in Wide_Wide_String); procedure Write_Wide_Element (Stream : in out Response_Writer; Name : in String; Content : in Unbounded_Wide_Wide_String); -- Write an XML attribute within an XML element. -- The attribute value is escaped according to the XML escape rules. procedure Write_Attribute (Stream : in out Response_Writer; Name : in String; Value : in String); procedure Write_Attribute (Stream : in out Response_Writer; Name : in String; Value : in Unbounded_String); procedure Write_Attribute (Stream : in out Response_Writer; Name : in String; Value : in EL.Objects.Object); procedure Write_Wide_Attribute (Stream : in out Response_Writer; Name : in String; Value : in Wide_Wide_String); procedure Write_Wide_Attribute (Stream : in out Response_Writer; Name : in String; Value : in Unbounded_Wide_Wide_String); -- Write a text escaping any character as necessary. procedure Write_Text (Stream : in out Response_Writer; Text : in String); procedure Write_Text (Stream : in out Response_Writer; Text : in Unbounded_String); procedure Write_Wide_Text (Stream : in out Response_Writer; Text : in Wide_Wide_String); procedure Write_Wide_Text (Stream : in out Response_Writer; Text : in Unbounded_Wide_Wide_String); procedure Write_Text (Stream : in out Response_Writer; Value : in EL.Objects.Object); -- Write a character on the response stream and escape that character -- as necessary. procedure Write_Char (Stream : in out Response_Writer; Char : in Character); -- Write a character on the response stream and escape that character -- as necessary. procedure Write_Wide_Char (Stream : in out Response_Writer; Char : in Wide_Wide_Character); -- Write a string on the stream. procedure Write (Stream : in out Response_Writer; Item : in Ada.Strings.Unbounded.Unbounded_String); -- Write a raw string on the stream. procedure Write_Raw (Stream : in out Response_Writer; Item : in String); -- Write a raw wide string on the stream. procedure Write_Raw (Stream : in out Response_Writer; Item : in Ada.Strings.Wide_Wide_Unbounded.Unbounded_Wide_Wide_String); -- Write a raw wide string on the stream. procedure Write_Wide_Raw (Stream : in out Response_Writer; Item : in Wide_Wide_String); -- ------------------------------ -- Javascript Support -- ------------------------------ -- To optimize the execution of Javascript page code, ASF components can queue some -- javascript code and have it merged and executed in a single <script> command. -- Write the java scripts that have been queued by <b>Queue_Script</b> procedure Write_Scripts (Stream : in out Response_Writer); -- Append the <b>Script</b> to the javascript buffer queue. The <b>Script</b> is not escaped. procedure Queue_Script (Stream : in out Response_Writer; Script : in String); -- Append the <b>Script</b> to the javascript buffer queue. The <b>Script</b> is not escaped. procedure Queue_Script (Stream : in out Response_Writer; Script : in Ada.Strings.Unbounded.Unbounded_String); -- Append the <b>Value</b> to the javascript buffer queue. The value is escaped according -- to Javascript escape rules. procedure Queue_Script (Stream : in out Response_Writer; Value : in Util.Beans.Objects.Object); -- Append a <b>script</b> include command to include the Javascript file at the given URL. -- The include scripts are flushed by <b>Flush</b> or <b>Write_Scripts</b>. procedure Queue_Include_Script (Stream : in out Response_Writer; URL : in String); -- Flush the response. -- Before flusing the response, the javascript are also flushed -- by calling <b>Write_Scripts</b>. overriding procedure Flush (Stream : in out Response_Writer); private use Ada.Streams; -- Flush the response stream and release the buffer. overriding procedure Finalize (Object : in out Response_Writer); type Buffer_Access is access Ada.Streams.Stream_Element_Array; type Response_Writer is new ASF.Streams.Print_Stream with record -- Whether an XML element must be closed (that is a '>' is necessary) Close_Start : Boolean := False; -- The encoding scheme. Encoding : Unicode.Encodings.Unicode_Encoding; -- The content type. Content_Type : Unbounded_String; -- The javascript that has been queued by <b>Queue_Script</b>. Script_Queue : Unbounded_String; -- Util.Strings.Builders.Builder (256); -- The javascript files that must be included at the end of the file. -- This javascript part is written before the Javascript that was queued. Include_Queue : Util.Strings.Builders.Builder (256); -- An optional element to write in the stream. Optional_Element : String (1 .. 32); Optional_Element_Size : Natural := 0; Optional_Element_Written : Boolean := False; end record; end ASF.Contexts.Writer;
----------------------------------------------------------------------- -- writer -- Response stream writer -- Copyright (C) 2009, 2010, 2011, 2012, 2013, 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>ASF.Contexts.Writer</b> defines the response writer to -- write the rendered result to the response stream. The <b>IOWriter</b> -- interface defines the procedure for writing the buffer to the output -- stream. The <b>Response_Writer</b> is the main type that provides -- various methods for writing the content. -- -- The result stream is encoded according to the encoding type. -- with Unicode.Encodings; with Ada.Streams; with Ada.Strings.Unbounded; with Ada.Strings.Wide_Wide_Unbounded; with EL.Objects; with Util.Beans.Objects; with Util.Strings.Builders; with ASF.Streams; package ASF.Contexts.Writer is use Ada.Strings.Unbounded; use Ada.Strings.Wide_Wide_Unbounded; -- ------------------------------ -- IO Writer -- ------------------------------ type IOWriter is limited interface; procedure Write (Stream : in out IOWriter; Buffer : in Ada.Streams.Stream_Element_Array) is abstract; -- ------------------------------ -- Response Writer -- ------------------------------ type Response_Writer is new ASF.Streams.Print_Stream with private; type Response_Writer_Access is access all Response_Writer'Class; -- Backward compatibility subtype ResponseWriter is Response_Writer; pragma Obsolescent (Entity => ResponseWriter); subtype ResponseWriter_Access is Response_Writer_Access; pragma Obsolescent (Entity => ResponseWriter_Access); -- Initialize the response stream for the given content type and -- encoding. An internal buffer is allocated for writing the stream. procedure Initialize (Stream : in out Response_Writer; Content_Type : in String; Encoding : in String; Output : in ASF.Streams.Print_Stream); -- Get the content type. function Get_Content_Type (Stream : in Response_Writer) return String; -- Get the character encoding. function Get_Encoding (Stream : in Response_Writer) return String; -- Close the current XML entity if an entity was started procedure Close_Current (Stream : in out Response_Writer'Class); -- Start an XML element with the given name. procedure Start_Element (Stream : in out Response_Writer; Name : in String); -- Start an optional XML element with the given name. -- The element is written only if it has at least one attribute. -- The optional XML element must not contain other XML entities. procedure Start_Optional_Element (Stream : in out Response_Writer; Name : in String); -- Closes an XML element of the given name. procedure End_Element (Stream : in out Response_Writer; Name : in String); -- Closes an optional XML element of the given name. -- The ending tag is written only if the start tag was written. procedure End_Optional_Element (Stream : in out Response_Writer; Name : in String); -- Write an XML element using the given name and with the content. -- This is similar to calling <b>Start_Element</b>, <b>Write_Text</b> -- and <b>End_Element</b>. procedure Write_Element (Stream : in out Response_Writer; Name : in String; Content : in String); procedure Write_Wide_Element (Stream : in out Response_Writer; Name : in String; Content : in Wide_Wide_String); procedure Write_Wide_Element (Stream : in out Response_Writer; Name : in String; Content : in Unbounded_Wide_Wide_String); -- Write an XML attribute within an XML element. -- The attribute value is escaped according to the XML escape rules. procedure Write_Attribute (Stream : in out Response_Writer; Name : in String; Value : in String); procedure Write_Attribute (Stream : in out Response_Writer; Name : in String; Value : in Unbounded_String); procedure Write_Attribute (Stream : in out Response_Writer; Name : in String; Value : in EL.Objects.Object); procedure Write_Wide_Attribute (Stream : in out Response_Writer; Name : in String; Value : in Wide_Wide_String); procedure Write_Wide_Attribute (Stream : in out Response_Writer; Name : in String; Value : in Unbounded_Wide_Wide_String); -- Write a text escaping any character as necessary. procedure Write_Text (Stream : in out Response_Writer; Text : in String); procedure Write_Text (Stream : in out Response_Writer; Text : in Unbounded_String); procedure Write_Wide_Text (Stream : in out Response_Writer; Text : in Wide_Wide_String); procedure Write_Wide_Text (Stream : in out Response_Writer; Text : in Unbounded_Wide_Wide_String); procedure Write_Text (Stream : in out Response_Writer; Value : in EL.Objects.Object); -- Write a character on the response stream and escape that character -- as necessary. procedure Write_Char (Stream : in out Response_Writer; Char : in Character); -- Write a character on the response stream and escape that character -- as necessary. procedure Write_Wide_Char (Stream : in out Response_Writer; Char : in Wide_Wide_Character); -- Write a string on the stream. procedure Write (Stream : in out Response_Writer; Item : in Ada.Strings.Unbounded.Unbounded_String); -- Write a raw string on the stream. procedure Write_Raw (Stream : in out Response_Writer; Item : in String); -- Write a raw wide string on the stream. procedure Write_Raw (Stream : in out Response_Writer; Item : in Ada.Strings.Wide_Wide_Unbounded.Unbounded_Wide_Wide_String); -- Write a raw wide string on the stream. procedure Write_Wide_Raw (Stream : in out Response_Writer; Item : in Wide_Wide_String); -- ------------------------------ -- Javascript Support -- ------------------------------ -- To optimize the execution of Javascript page code, ASF components can queue some -- javascript code and have it merged and executed in a single <script> command. -- Write the java scripts that have been queued by <b>Queue_Script</b> procedure Write_Scripts (Stream : in out Response_Writer); -- Append the <b>Script</b> to the javascript buffer queue. The <b>Script</b> is not escaped. procedure Queue_Script (Stream : in out Response_Writer; Script : in String); -- Append the <b>Script</b> to the javascript buffer queue. The <b>Script</b> is not escaped. procedure Queue_Script (Stream : in out Response_Writer; Script : in Ada.Strings.Unbounded.Unbounded_String); -- Append the <b>Value</b> to the javascript buffer queue. The value is escaped according -- to Javascript escape rules. procedure Queue_Script (Stream : in out Response_Writer; Value : in Util.Beans.Objects.Object); -- Append a <b>script</b> include command to include the Javascript file at the given URL. -- The include scripts are flushed by <b>Flush</b> or <b>Write_Scripts</b>. procedure Queue_Include_Script (Stream : in out Response_Writer; URL : in String; Async : in Boolean := False); -- Flush the response. -- Before flusing the response, the javascript are also flushed -- by calling <b>Write_Scripts</b>. overriding procedure Flush (Stream : in out Response_Writer); private use Ada.Streams; -- Flush the response stream and release the buffer. overriding procedure Finalize (Object : in out Response_Writer); type Buffer_Access is access Ada.Streams.Stream_Element_Array; type Response_Writer is new ASF.Streams.Print_Stream with record -- Whether an XML element must be closed (that is a '>' is necessary) Close_Start : Boolean := False; -- The encoding scheme. Encoding : Unicode.Encodings.Unicode_Encoding; -- The content type. Content_Type : Unbounded_String; -- The javascript that has been queued by <b>Queue_Script</b>. Script_Queue : Unbounded_String; -- Util.Strings.Builders.Builder (256); -- The javascript files that must be included at the end of the file. -- This javascript part is written before the Javascript that was queued. Include_Queue : Util.Strings.Builders.Builder (256); -- An optional element to write in the stream. Optional_Element : String (1 .. 32); Optional_Element_Size : Natural := 0; Optional_Element_Written : Boolean := False; end record; end ASF.Contexts.Writer;
Add the Async parameter to the Queue_Include_Script procedure
Add the Async parameter to the Queue_Include_Script procedure
Ada
apache-2.0
Letractively/ada-asf,Letractively/ada-asf,Letractively/ada-asf
fa109f61434ef67d55f1d7d157d4e47d62c5f051
src/ado-databases.adb
src/ado-databases.adb
----------------------------------------------------------------------- -- ADO Databases -- Database Connections -- Copyright (C) 2010 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Log; with Util.Log.Loggers; with ADO.SQL; with Ada.Unchecked_Deallocation; with System.Address_Image; package body ADO.Databases is use Util.Log; use ADO.Drivers; Log : constant Loggers.Logger := Loggers.Create ("ADO.Databases"); -- ------------------------------ -- Get the database connection status. -- ------------------------------ function Get_Status (Database : in Connection) return Connection_Status is begin if Database.Impl = null then return CLOSED; else return OPEN; end if; end Get_Status; -- ------------------------------ -- Create a query statement. The statement is not prepared -- ------------------------------ function Create_Statement (Database : in Connection; Table : in ADO.Schemas.Class_Mapping_Access) return Query_Statement is begin if Database.Impl = null then Log.Error ("Database implementation is not initialized"); raise NOT_OPEN with "No connection to the database"; end if; declare Query : Query_Statement_Access := Database.Impl.all.Create_Statement (Table); begin return ADO.Statements.Create_Statement (Query); end; end Create_Statement; -- Create a query statement. The statement is not prepared function Create_Statement (Database : in Connection; Query : in String) return Query_Statement is begin if Database.Impl = null then Log.Error ("Database implementation is not initialized"); raise NOT_OPEN with "No connection to the database"; end if; declare Stmt : Query_Statement_Access := Database.Impl.all.Create_Statement (null); begin Append (Query => Stmt.all, SQL => Query); return ADO.Statements.Create_Statement (Stmt); end; end Create_Statement; -- ------------------------------ -- Load the database schema definition for the current database. -- ------------------------------ procedure Load_Schema (Database : in Connection; Schema : out ADO.Schemas.Schema_Definition) is begin if Database.Impl = null then Log.Error ("Database connection is not initialized"); raise NOT_OPEN with "No connection to the database"; end if; Database.Impl.Load_Schema (Schema); end Load_Schema; -- ------------------------------ -- Close the database connection -- ------------------------------ procedure Close (Database : in out Connection) is begin Log.Info ("Closing database connection"); if Database.Impl /= null then Database.Impl.Close; end if; end Close; -- ------------------------------ -- Start a transaction. -- ------------------------------ procedure Begin_Transaction (Database : in out Master_Connection) is begin Log.Info ("Begin transaction"); if Database.Impl = null then Log.Error ("Database implementation is not initialized"); raise NOT_OPEN with "No connection to the database"; end if; Database.Impl.Begin_Transaction; end Begin_Transaction; -- ------------------------------ -- Commit the current transaction. -- ------------------------------ procedure Commit (Database : in out Master_Connection) is begin Log.Info ("Commit transaction"); if Database.Impl = null then Log.Error ("Database implementation is not initialized"); raise NOT_OPEN with "No connection to the database"; end if; Database.Impl.Commit; end Commit; -- ------------------------------ -- Rollback the current transaction. -- ------------------------------ procedure Rollback (Database : in out Master_Connection) is begin Log.Info ("Rollback transaction"); if Database.Impl = null then Log.Error ("Database implementation is not initialized"); raise NOT_OPEN with "Database implementation is not initialized"; end if; Database.Impl.Rollback; end Rollback; procedure Execute (Database : in Master_Connection; SQL : in Query_String) is begin Log.Info ("Execute: {0}", SQL); Database.Impl.Execute (SQL); end Execute; procedure Execute (Database : in Master_Connection; SQL : in Query_String; Id : out Identifier) is begin Log.Info ("Execute: {0}", SQL); Database.Impl.Execute (SQL, Id); end Execute; -- ------------------------------ -- Create a delete statement. -- ------------------------------ function Create_Statement (Database : in Master_Connection; Table : in ADO.Schemas.Class_Mapping_Access) return Delete_Statement is begin Log.Info ("Create delete statement"); declare Stmt : Delete_Statement_Access := Database.Impl.all.Create_Statement (Table); begin return Create_Statement (Stmt); end; end Create_Statement; -- ------------------------------ -- Create an insert statement. -- ------------------------------ function Create_Statement (Database : in Master_Connection; Table : in ADO.Schemas.Class_Mapping_Access) return Insert_Statement is begin Log.Info ("Create insert statement"); declare Stmt : constant Insert_Statement_Access := Database.Impl.all.Create_Statement (Table); begin return Create_Statement (Stmt.all'Access); end; end Create_Statement; -- ------------------------------ -- Create an update statement. -- ------------------------------ function Create_Statement (Database : in Master_Connection; Table : in ADO.Schemas.Class_Mapping_Access) return Update_Statement is begin Log.Info ("Create insert statement"); return Create_Statement (Database.Impl.all.Create_Statement (Table)); end Create_Statement; -- ------------------------------ -- Adjust the connection reference counter -- ------------------------------ overriding procedure Adjust (Object : in out Connection) is begin if Object.Impl /= null then Log.Debug ("Adjust {0} : {1}", System.Address_Image (Object.Impl.all'Address), Natural'Image (Object.Impl.Count)); Object.Impl.Count := Object.Impl.Count + 1; end if; end Adjust; -- ------------------------------ -- Releases the connection reference counter -- ------------------------------ overriding procedure Finalize (Object : in out Connection) is procedure Free is new Ada.Unchecked_Deallocation (Object => Database_Connection'Class, Name => Database_Connection_Access); begin if Object.Impl /= null then Log.Debug ("Finalize {0} : {1}", System.Address_Image (Object.Impl.all'Address), Natural'Image (Object.Impl.Count)); Object.Impl.Count := Object.Impl.Count - 1; if Object.Impl.Count = 0 then Free (Object.Impl); end if; end if; end Finalize; -- ------------------------------ -- Attempts to establish a connection with the data source -- that this DataSource object represents. -- ------------------------------ function Get_Connection (Controller : in DataSource) return Master_Connection'Class is Connection : ADO.Drivers.Database_Connection_Access; begin Log.Info ("Get master connection from data-source"); Controller.Create_Connection (Connection); return Master_Connection '(Ada.Finalization.Controlled with Impl => Connection); end Get_Connection; -- ------------------------------ -- Set the master data source -- ------------------------------ procedure Set_Master (Controller : in out Replicated_DataSource; Master : in DataSource_Access) is begin Controller.Master := Master; end Set_Master; -- ------------------------------ -- Get the master data source -- ------------------------------ function Get_Master (Controller : in Replicated_DataSource) return DataSource_Access is begin return Controller.Master; end Get_Master; -- ------------------------------ -- Set the slave data source -- ------------------------------ procedure Set_Slave (Controller : in out Replicated_DataSource; Slave : in DataSource_Access) is begin Controller.Slave := Slave; end Set_Slave; -- ------------------------------ -- Get the slave data source -- ------------------------------ function Get_Slave (Controller : in Replicated_DataSource) return DataSource_Access is begin return Controller.Slave; end Get_Slave; -- ------------------------------ -- Get a slave database connection -- ------------------------------ function Get_Slave_Connection (Controller : in Replicated_DataSource) return Connection'Class is begin return Controller.Slave.Get_Connection; end Get_Slave_Connection; end ADO.Databases;
----------------------------------------------------------------------- -- ADO Databases -- Database Connections -- Copyright (C) 2010, 2011 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Log; with Util.Log.Loggers; with Ada.Unchecked_Deallocation; with System.Address_Image; with ADO.Statements.Create; package body ADO.Databases is use Util.Log; use ADO.Drivers; Log : constant Loggers.Logger := Loggers.Create ("ADO.Databases"); -- ------------------------------ -- Get the database connection status. -- ------------------------------ function Get_Status (Database : in Connection) return Connection_Status is begin if Database.Impl = null then return CLOSED; else return OPEN; end if; end Get_Status; -- ------------------------------ -- Create a query statement. The statement is not prepared -- ------------------------------ function Create_Statement (Database : in Connection; Table : in ADO.Schemas.Class_Mapping_Access) return Query_Statement is begin if Database.Impl = null then Log.Error ("Database implementation is not initialized"); raise NOT_OPEN with "No connection to the database"; end if; declare Query : constant Query_Statement_Access := Database.Impl.all.Create_Statement (Table); begin return ADO.Statements.Create.Create_Statement (Query); end; end Create_Statement; -- ------------------------------ -- Create a query statement. The statement is not prepared -- ------------------------------ function Create_Statement (Database : in Connection; Query : in String) return Query_Statement is begin if Database.Impl = null then Log.Error ("Database implementation is not initialized"); raise NOT_OPEN with "No connection to the database"; end if; declare Stmt : constant Query_Statement_Access := Database.Impl.all.Create_Statement (null); begin Append (Query => Stmt.all, SQL => Query); return ADO.Statements.Create.Create_Statement (Stmt); end; end Create_Statement; -- ------------------------------ -- Load the database schema definition for the current database. -- ------------------------------ procedure Load_Schema (Database : in Connection; Schema : out ADO.Schemas.Schema_Definition) is begin if Database.Impl = null then Log.Error ("Database connection is not initialized"); raise NOT_OPEN with "No connection to the database"; end if; Database.Impl.Load_Schema (Schema); end Load_Schema; -- ------------------------------ -- Close the database connection -- ------------------------------ procedure Close (Database : in out Connection) is begin Log.Info ("Closing database connection"); if Database.Impl /= null then Database.Impl.Close; end if; end Close; -- ------------------------------ -- Start a transaction. -- ------------------------------ procedure Begin_Transaction (Database : in out Master_Connection) is begin Log.Info ("Begin transaction"); if Database.Impl = null then Log.Error ("Database implementation is not initialized"); raise NOT_OPEN with "No connection to the database"; end if; Database.Impl.Begin_Transaction; end Begin_Transaction; -- ------------------------------ -- Commit the current transaction. -- ------------------------------ procedure Commit (Database : in out Master_Connection) is begin Log.Info ("Commit transaction"); if Database.Impl = null then Log.Error ("Database implementation is not initialized"); raise NOT_OPEN with "No connection to the database"; end if; Database.Impl.Commit; end Commit; -- ------------------------------ -- Rollback the current transaction. -- ------------------------------ procedure Rollback (Database : in out Master_Connection) is begin Log.Info ("Rollback transaction"); if Database.Impl = null then Log.Error ("Database implementation is not initialized"); raise NOT_OPEN with "Database implementation is not initialized"; end if; Database.Impl.Rollback; end Rollback; procedure Execute (Database : in Master_Connection; SQL : in Query_String) is begin Log.Info ("Execute: {0}", SQL); Database.Impl.Execute (SQL); end Execute; procedure Execute (Database : in Master_Connection; SQL : in Query_String; Id : out Identifier) is begin Log.Info ("Execute: {0}", SQL); Database.Impl.Execute (SQL, Id); end Execute; -- ------------------------------ -- Create a delete statement. -- ------------------------------ function Create_Statement (Database : in Master_Connection; Table : in ADO.Schemas.Class_Mapping_Access) return Delete_Statement is begin Log.Info ("Create delete statement"); declare Stmt : constant Delete_Statement_Access := Database.Impl.all.Create_Statement (Table); begin return ADO.Statements.Create.Create_Statement (Stmt); end; end Create_Statement; -- ------------------------------ -- Create an insert statement. -- ------------------------------ function Create_Statement (Database : in Master_Connection; Table : in ADO.Schemas.Class_Mapping_Access) return Insert_Statement is begin Log.Info ("Create insert statement"); declare Stmt : constant Insert_Statement_Access := Database.Impl.all.Create_Statement (Table); begin return ADO.Statements.Create.Create_Statement (Stmt.all'Access); end; end Create_Statement; -- ------------------------------ -- Create an update statement. -- ------------------------------ function Create_Statement (Database : in Master_Connection; Table : in ADO.Schemas.Class_Mapping_Access) return Update_Statement is begin Log.Info ("Create update statement"); return ADO.Statements.Create.Create_Statement (Database.Impl.all.Create_Statement (Table)); end Create_Statement; -- ------------------------------ -- Adjust the connection reference counter -- ------------------------------ overriding procedure Adjust (Object : in out Connection) is begin if Object.Impl /= null then Log.Debug ("Adjust {0} : {1}", System.Address_Image (Object.Impl.all'Address), Natural'Image (Object.Impl.Count)); Object.Impl.Count := Object.Impl.Count + 1; end if; end Adjust; -- ------------------------------ -- Releases the connection reference counter -- ------------------------------ overriding procedure Finalize (Object : in out Connection) is procedure Free is new Ada.Unchecked_Deallocation (Object => Database_Connection'Class, Name => Database_Connection_Access); begin if Object.Impl /= null then Log.Debug ("Finalize {0} : {1}", System.Address_Image (Object.Impl.all'Address), Natural'Image (Object.Impl.Count)); Object.Impl.Count := Object.Impl.Count - 1; if Object.Impl.Count = 0 then Free (Object.Impl); end if; end if; end Finalize; -- ------------------------------ -- Attempts to establish a connection with the data source -- that this DataSource object represents. -- ------------------------------ function Get_Connection (Controller : in DataSource) return Master_Connection'Class is Connection : ADO.Drivers.Database_Connection_Access; begin Log.Info ("Get master connection from data-source"); Controller.Create_Connection (Connection); return Master_Connection '(Ada.Finalization.Controlled with Impl => Connection); end Get_Connection; -- ------------------------------ -- Set the master data source -- ------------------------------ procedure Set_Master (Controller : in out Replicated_DataSource; Master : in DataSource_Access) is begin Controller.Master := Master; end Set_Master; -- ------------------------------ -- Get the master data source -- ------------------------------ function Get_Master (Controller : in Replicated_DataSource) return DataSource_Access is begin return Controller.Master; end Get_Master; -- ------------------------------ -- Set the slave data source -- ------------------------------ procedure Set_Slave (Controller : in out Replicated_DataSource; Slave : in DataSource_Access) is begin Controller.Slave := Slave; end Set_Slave; -- ------------------------------ -- Get the slave data source -- ------------------------------ function Get_Slave (Controller : in Replicated_DataSource) return DataSource_Access is begin return Controller.Slave; end Get_Slave; -- ------------------------------ -- Get a slave database connection -- ------------------------------ function Get_Slave_Connection (Controller : in Replicated_DataSource) return Connection'Class is begin return Controller.Slave.Get_Connection; end Get_Slave_Connection; end ADO.Databases;
Use the Create_Statement functions now defined in ADO.Statements.Create package
Use the Create_Statement functions now defined in ADO.Statements.Create package
Ada
apache-2.0
stcarrez/ada-ado
c759209e1de6deb4c5ed6d40add2ca69ead55e7e
orka_numerics/src/orka-numerics-kalman.ads
orka_numerics/src/orka-numerics-kalman.ads
-- SPDX-License-Identifier: Apache-2.0 -- -- Copyright (c) 2022 onox <[email protected]> -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. private with Ada.Containers.Indefinite_Holders; with Orka.Numerics.Tensors; generic with package Tensors is new Orka.Numerics.Tensors (<>); type Tensor (<>) is new Tensors.Tensor with private; package Orka.Numerics.Kalman is pragma Preelaborate; use type Tensors.Tensor_Dimension; use type Tensors.Tensor_Shape; use type Tensors.Element_Type; subtype Vector is Tensor; subtype Matrix is Tensor; type Update_Phase is (Time_Update, Measurement_Update); type Filter_Kind is (Filter_UKF, Filter_CDKF); type State_Covariance is private; type Weights_Type (N : Positive; Kind : Filter_Kind) is private; type Filter (Kind : Filter_Kind; Dimension_X, Dimension_Z : Positive) is tagged private; function State (Object : Filter) return Vector with Post => State'Result.Shape = (1 => Object.Dimension_X); private subtype Element_Type is Tensors.Element_Type; package Tensor_Holders is new Ada.Containers.Indefinite_Holders (Tensor); -- These predicates cannot be applied to the formal types above subtype Vector_Holder is Tensor_Holders.Holder with Dynamic_Predicate => Tensor_Holders.Constant_Reference (Vector_Holder).Dimensions = 1; subtype Matrix_Holder is Tensor_Holders.Holder with Dynamic_Predicate => Tensor_Holders.Constant_Reference (Matrix_Holder).Dimensions = 2; type Weights_Type (N : Positive; Kind : Filter_Kind) is record Mean : Vector_Holder; Scaling_Factor : Element_Type; case Kind is when Filter_UKF => Covariance : Vector_Holder; when Filter_CDKF => Covariance_1 : Vector_Holder; Covariance_2 : Vector_Holder; end case; end record; type State_Covariance is record State : Vector_Holder; Covariance : Matrix_Holder; end record; type Filter (Kind : Filter_Kind; Dimension_X, Dimension_Z : Positive) is tagged record Process_Noise : Matrix_Holder; Measurement_Noise : Matrix_Holder; Weights : Weights_Type (Dimension_X, Kind); Estimate : State_Covariance; end record; function State (Object : Filter) return Vector is (Object.Estimate.State.Element); end Orka.Numerics.Kalman;
-- SPDX-License-Identifier: Apache-2.0 -- -- Copyright (c) 2022 onox <[email protected]> -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. private with Ada.Containers.Indefinite_Holders; with Orka.Numerics.Tensors; generic with package Tensors is new Orka.Numerics.Tensors (<>); type Tensor (<>) is new Tensors.Tensor with private; package Orka.Numerics.Kalman is pragma Preelaborate; use type Tensors.Tensor_Dimension; use type Tensors.Tensor_Shape; use type Tensors.Element_Type; subtype Vector is Tensor; subtype Matrix is Tensor; type Update_Phase is (Time_Update, Measurement_Update); type Filter_Kind is (Filter_UKF, Filter_CDKF); type State_Covariance is private; type Weights_Type (N : Positive; Kind : Filter_Kind) is private; type Filter (Kind : Filter_Kind; Dimension_X, Dimension_Z : Positive) is tagged private; function State (Object : Filter) return Vector with Post => State'Result.Shape = (1 => Object.Dimension_X); private subtype Element_Type is Tensors.Element_Type; package Tensor_Holders is new Ada.Containers.Indefinite_Holders (Tensor); -- These predicates cannot be applied to the formal types above subtype Vector_Holder is Tensor_Holders.Holder with Dynamic_Predicate => Vector_Holder.Element.Dimensions = 1; subtype Matrix_Holder is Tensor_Holders.Holder with Dynamic_Predicate => Matrix_Holder.Element.Dimensions = 2; type Weights_Type (N : Positive; Kind : Filter_Kind) is record Mean : Vector_Holder; Scaling_Factor : Element_Type; case Kind is when Filter_UKF => Covariance : Vector_Holder; when Filter_CDKF => Covariance_1 : Vector_Holder; Covariance_2 : Vector_Holder; end case; end record; type State_Covariance is record State : Vector_Holder; Covariance : Matrix_Holder; end record; type Filter (Kind : Filter_Kind; Dimension_X, Dimension_Z : Positive) is tagged record Process_Noise : Matrix_Holder; Measurement_Noise : Matrix_Holder; Weights : Weights_Type (Dimension_X, Kind); Estimate : State_Covariance; end record; function State (Object : Filter) return Vector is (Object.Estimate.State.Element); end Orka.Numerics.Kalman;
Fix Dynamic_Predicate to satisfy GNAT FSF 11
numerics: Fix Dynamic_Predicate to satisfy GNAT FSF 11 Signed-off-by: onox <[email protected]>
Ada
apache-2.0
onox/orka
4d634084b44d1b11bf4ca81dbcd94f9c00d761d8
src/wiki-streams-html-stream.adb
src/wiki-streams-html-stream.adb
----------------------------------------------------------------------- -- wiki-streams-html-stream -- Generic Wiki HTML output stream -- Copyright (C) 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.Helpers; package body Wiki.Streams.Html.Stream is -- Close the current XML entity if an entity was started procedure Close_Current (Stream : in out Html_Output_Stream'Class); -- Write the string to the stream. procedure Write_String (Stream : in out Html_Output_Stream'Class; Content : in String); -- ------------------------------ -- Set the indentation level for HTML output stream. -- ------------------------------ overriding procedure Set_Indent_Level (Writer : in out Html_Output_Stream; Indent : in Natural) is begin Writer.Indent_Level := Indent; end Set_Indent_Level; -- ------------------------------ -- Write an optional newline or space. -- ------------------------------ overriding procedure Newline (Writer : in out Html_Output_Stream) is begin if Writer.Indent_Level > 0 and Writer.Text_Length > 0 then Writer.Write (Wiki.Helpers.LF); Writer.Empty_Line := True; end if; Writer.Text_Length := 0; end Newline; -- ------------------------------ -- Close the current XML entity if an entity was started -- ------------------------------ procedure Close_Current (Stream : in out Html_Output_Stream'Class) is begin if Stream.Close_Start then Stream.Write ('>'); Stream.Close_Start := False; Stream.Empty_Line := False; end if; end Close_Current; -- ------------------------------ -- Write the string to the stream. -- ------------------------------ procedure Write_String (Stream : in out Html_Output_Stream'Class; Content : in String) is begin for I in Content'Range loop Stream.Write (Wiki.Strings.To_WChar (Content (I))); end loop; if Content'Length > 0 then Stream.Text_Length := Stream.Text_Length + Content'Length; Stream.Empty_Line := False; end if; end Write_String; -- ------------------------------ -- Write an XML attribute within an XML element. -- The attribute value is escaped according to the XML escape rules. -- ------------------------------ overriding procedure Write_Wide_Attribute (Stream : in out Html_Output_Stream; Name : in String; Content : in Wiki.Strings.UString) is begin if Stream.Close_Start then Html.Write_Escape_Attribute (Stream, Name, Wiki.Strings.To_WString (Content)); end if; end Write_Wide_Attribute; -- ------------------------------ -- Write an XML attribute within an XML element. -- The attribute value is escaped according to the XML escape rules. -- ------------------------------ overriding procedure Write_Wide_Attribute (Stream : in out Html_Output_Stream; Name : in String; Content : in Wide_Wide_String) is begin if Stream.Close_Start then Stream.Write_Escape_Attribute (Name, Content); end if; end Write_Wide_Attribute; -- ------------------------------ -- Start an XML element with the given name. -- ------------------------------ overriding procedure Start_Element (Stream : in out Html_Output_Stream; Name : in String) is begin Close_Current (Stream); Stream.Indent_Pos := Stream.Indent_Pos + Stream.Indent_Level; if Stream.Indent_Pos > 1 then if not Stream.Empty_Line then Stream.Write (Helpers.LF); end if; for I in 1 .. Stream.Indent_Pos loop Stream.Write (' '); end loop; end if; Stream.Write ('<'); Stream.Write_String (Name); Stream.Close_Start := True; Stream.Text_Length := 0; Stream.Empty_Line := False; end Start_Element; -- ------------------------------ -- Closes an XML element of the given name. -- ------------------------------ overriding procedure End_Element (Stream : in out Html_Output_Stream; Name : in String) is begin if Stream.Indent_Pos > Stream.Indent_Level then Stream.Indent_Pos := Stream.Indent_Pos - Stream.Indent_Level; end if; if Stream.Close_Start then Stream.Write (" />"); Stream.Close_Start := False; else Close_Current (Stream); if Stream.Text_Length = 0 then if not Stream.Empty_Line and Stream.Indent_Level > 0 then Stream.Write (Wiki.Helpers.LF); end if; if Stream.Indent_Pos > 1 then Stream.Write (Helpers.LF); for I in 1 .. Stream.Indent_Pos loop Stream.Write (' '); end loop; end if; end if; Stream.Write ("</"); Stream.Write_String (Name); Stream.Write ('>'); end if; if Stream.Indent_Level > 0 then Stream.Write (Wiki.Helpers.LF); Stream.Empty_Line := True; end if; Stream.Text_Length := 0; end End_Element; -- ------------------------------ -- Write a text escaping any character as necessary. -- ------------------------------ overriding procedure Write_Wide_Text (Stream : in out Html_Output_Stream; Content : in Wiki.Strings.WString) is begin Close_Current (Stream); Stream.Write_Escape (Content); if Content'Length > 0 then Stream.Text_Length := Stream.Text_Length + Content'Length; Stream.Empty_Line := False; else Stream.Write (' '); end if; end Write_Wide_Text; end Wiki.Streams.Html.Stream;
----------------------------------------------------------------------- -- wiki-streams-html-stream -- Generic Wiki HTML output stream -- Copyright (C) 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.Helpers; package body Wiki.Streams.Html.Stream is -- Close the current XML entity if an entity was started procedure Close_Current (Stream : in out Html_Output_Stream'Class); -- Write the string to the stream. procedure Write_String (Stream : in out Html_Output_Stream'Class; Content : in String); -- ------------------------------ -- Set the indentation level for HTML output stream. -- ------------------------------ overriding procedure Set_Indent_Level (Writer : in out Html_Output_Stream; Indent : in Natural) is begin Writer.Indent_Level := Indent; end Set_Indent_Level; -- ------------------------------ -- Write an optional newline or space. -- ------------------------------ overriding procedure Newline (Writer : in out Html_Output_Stream) is begin if Writer.Indent_Level > 0 and Writer.Text_Length > 0 then Writer.Write (Wiki.Helpers.LF); Writer.Empty_Line := True; end if; Writer.Text_Length := 0; end Newline; -- ------------------------------ -- Close the current XML entity if an entity was started -- ------------------------------ procedure Close_Current (Stream : in out Html_Output_Stream'Class) is begin if Stream.Close_Start then Stream.Write ('>'); Stream.Close_Start := False; Stream.Empty_Line := False; end if; end Close_Current; -- ------------------------------ -- Write the string to the stream. -- ------------------------------ procedure Write_String (Stream : in out Html_Output_Stream'Class; Content : in String) is begin for I in Content'Range loop Stream.Write (Wiki.Strings.To_WChar (Content (I))); end loop; if Content'Length > 0 then Stream.Text_Length := Stream.Text_Length + Content'Length; Stream.Empty_Line := False; end if; end Write_String; -- ------------------------------ -- Write an XML attribute within an XML element. -- The attribute value is escaped according to the XML escape rules. -- ------------------------------ overriding procedure Write_Wide_Attribute (Stream : in out Html_Output_Stream; Name : in String; Content : in Wiki.Strings.UString) is begin if Stream.Close_Start then Html.Write_Escape_Attribute (Stream, Name, Wiki.Strings.To_WString (Content)); end if; end Write_Wide_Attribute; -- ------------------------------ -- Write an XML attribute within an XML element. -- The attribute value is escaped according to the XML escape rules. -- ------------------------------ overriding procedure Write_Wide_Attribute (Stream : in out Html_Output_Stream; Name : in String; Content : in Wide_Wide_String) is begin if Stream.Close_Start then Stream.Write_Escape_Attribute (Name, Content); end if; end Write_Wide_Attribute; -- ------------------------------ -- Start an XML element with the given name. -- ------------------------------ overriding procedure Start_Element (Stream : in out Html_Output_Stream; Name : in String) is begin Close_Current (Stream); if Stream.Indent_Pos > 1 then if not Stream.Empty_Line then Stream.Write (Helpers.LF); end if; for I in 1 .. Stream.Indent_Pos loop Stream.Write (' '); end loop; end if; Stream.Write ('<'); Stream.Write_String (Name); Stream.Close_Start := True; Stream.Text_Length := 0; Stream.Empty_Line := False; Stream.Indent_Pos := Stream.Indent_Pos + Stream.Indent_Level; end Start_Element; -- ------------------------------ -- Closes an XML element of the given name. -- ------------------------------ overriding procedure End_Element (Stream : in out Html_Output_Stream; Name : in String) is begin if Stream.Indent_Pos >= Stream.Indent_Level then Stream.Indent_Pos := Stream.Indent_Pos - Stream.Indent_Level; end if; if Stream.Close_Start then Stream.Write (" />"); Stream.Close_Start := False; else Close_Current (Stream); if Stream.Text_Length = 0 then if not Stream.Empty_Line and Stream.Indent_Level > 0 then Stream.Write (Wiki.Helpers.LF); end if; if Stream.Indent_Pos > 1 then Stream.Write (Helpers.LF); for I in 1 .. Stream.Indent_Pos loop Stream.Write (' '); end loop; end if; end if; Stream.Write ("</"); Stream.Write_String (Name); Stream.Write ('>'); end if; if Stream.Indent_Level > 0 then Stream.Write (Wiki.Helpers.LF); Stream.Empty_Line := True; end if; Stream.Text_Length := 0; end End_Element; -- ------------------------------ -- Write a text escaping any character as necessary. -- ------------------------------ overriding procedure Write_Wide_Text (Stream : in out Html_Output_Stream; Content : in Wiki.Strings.WString) is begin Close_Current (Stream); Stream.Write_Escape (Content); if Content'Length > 0 then Stream.Text_Length := Stream.Text_Length + Content'Length; Stream.Empty_Line := False; else Stream.Write (' '); end if; end Write_Wide_Text; end Wiki.Streams.Html.Stream;
Update indentation of output HTML stream
Update indentation of output HTML stream
Ada
apache-2.0
stcarrez/ada-wiki,stcarrez/ada-wiki
f41f4a4bb6e7d063353f0423607bd413c4e0d24e
src/wiki-documents.adb
src/wiki-documents.adb
----------------------------------------------------------------------- -- wiki-nodes -- Wiki Document Internal representation -- Copyright (C) 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- package body Wiki.Documents is use Wiki.Nodes; -- ------------------------------ -- 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) is Node : constant Node_Type_Access := new Node_Type '(Kind => N_TAG_START, Len => 0, Tag_Start => Tag, Attributes => Attributes, Children => null, Parent => Into.Current); begin Append (Into, Node); Into.Current := Node; end Push_Node; -- ------------------------------ -- Pop the HTML tag. -- ------------------------------ procedure Pop_Node (From : in out Document; Tag : in Html_Tag) is pragma Unreferenced (Tag); begin if From.Current /= null then From.Current := From.Current.Parent; end if; end Pop_Node; -- ------------------------------ -- Append a section header at end of the document. -- ------------------------------ procedure Append (Into : in out Document; Header : in Wiki.Strings.WString; Level : in Positive) is begin Append (Into, new Node_Type '(Kind => N_HEADER, Len => Header'Length, Header => Header, Level => Level)); end Append; -- ------------------------------ -- Append a node to the document. -- ------------------------------ procedure Append (Into : in out Document; Node : in Wiki.Nodes.Node_Type_Access) is begin if Into.Current = null then Append (Into.Nodes, Node); else Append (Into.Current, Node); end if; end Append; -- ------------------------------ -- Append a simple node such as N_LINE_BREAK, N_HORIZONTAL_RULE or N_PARAGRAPH. -- ------------------------------ procedure Append (Into : in out Document; Kind : in Simple_Node_Kind) is begin case Kind is when N_LINE_BREAK => Append (Into, new Node_Type '(Kind => N_LINE_BREAK, Len => 0)); when N_HORIZONTAL_RULE => Append (Into, new Node_Type '(Kind => N_HORIZONTAL_RULE, Len => 0)); when N_PARAGRAPH => Append (Into, new Node_Type '(Kind => N_PARAGRAPH, Len => 0)); when N_TOC_DISPLAY => Append (Into, new Node_Type '(Kind => N_TOC_DISPLAY, Len => 0)); Into.Using_TOC := True; end case; end Append; -- ------------------------------ -- 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) is begin Append (Into, new Node_Type '(Kind => N_TEXT, Len => Text'Length, Text => Text, Format => Format)); end Append; -- ------------------------------ -- Add a link. -- ------------------------------ procedure Add_Link (Into : in out Document; Name : in Wiki.Strings.WString; Attributes : in out Wiki.Attributes.Attribute_List) is begin Append (Into, new Node_Type '(Kind => N_LINK, Len => Name'Length, Title => Name, Link_Attr => Attributes)); end Add_Link; -- ------------------------------ -- Add an image. -- ------------------------------ procedure Add_Image (Into : in out Document; Name : in Wiki.Strings.WString; Attributes : in out Wiki.Attributes.Attribute_List) is begin Append (Into, new Node_Type '(Kind => N_IMAGE, Len => Name'Length, Title => Name, Link_Attr => Attributes)); end Add_Image; -- ------------------------------ -- Add a quote. -- ------------------------------ procedure Add_Quote (Into : in out Document; Name : in Wiki.Strings.WString; Attributes : in out Wiki.Attributes.Attribute_List) is begin Append (Into, new Node_Type '(Kind => N_QUOTE, Len => Name'Length, Title => Name, Link_Attr => Attributes)); end Add_Quote; -- ------------------------------ -- 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) is begin if Ordered then Append (Into, new Node_Type '(Kind => N_NUM_LIST, Len => 0, Level => Level, others => <>)); else Append (Into, new Node_Type '(Kind => N_LIST, Len => 0, Level => Level, others => <>)); end if; end Add_List_Item; -- ------------------------------ -- 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) is begin Append (Into, new Node_Type '(Kind => N_BLOCKQUOTE, Len => 0, Level => Level, others => <>)); end Add_Blockquote; -- 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) is begin Append (Into, new Node_Type '(Kind => N_PREFORMAT, Len => Text'Length, Preformatted => Text, others => <>)); end Add_Preformatted; -- ------------------------------ -- 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 Node_Type)) is begin Iterate (Doc.Nodes, Process); end Iterate; -- ------------------------------ -- Returns True if the document is empty. -- ------------------------------ function Is_Empty (Doc : in Document) return Boolean is begin return Wiki.Nodes.Is_Empty (Doc.Nodes); end Is_Empty; -- ------------------------------ -- Returns True if the document displays the table of contents by itself. -- ------------------------------ function Is_Using_TOC (Doc : in Document) return Boolean is begin return Doc.Using_TOC; end Is_Using_TOC; -- ------------------------------ -- Get the table of content node associated with the document. -- ------------------------------ procedure Get_TOC (Doc : in out Document; TOC : out Wiki.Nodes.Node_List_Ref) is begin if Wiki.Nodes.Is_Empty (Doc.TOC) then Append (Doc.TOC, new Node_Type '(Kind => N_TOC, Len => 0, others => <>)); end if; TOC := Doc.TOC; end Get_TOC; -- ------------------------------ -- Get the table of content node associated with the document. -- ------------------------------ function Get_TOC (Doc : in Document) return Wiki.Nodes.Node_List_Ref is begin return Doc.TOC; end Get_TOC; end Wiki.Documents;
----------------------------------------------------------------------- -- wiki-nodes -- Wiki Document Internal representation -- Copyright (C) 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- package body Wiki.Documents is use Wiki.Nodes; -- ------------------------------ -- 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) is Node : constant Node_Type_Access := new Node_Type '(Kind => N_TAG_START, Len => 0, Tag_Start => Tag, Attributes => Attributes, Children => null, Parent => Into.Current); begin Append (Into, Node); Into.Current := Node; end Push_Node; -- ------------------------------ -- Pop the HTML tag. -- ------------------------------ procedure Pop_Node (From : in out Document; Tag : in Html_Tag) is pragma Unreferenced (Tag); begin if From.Current /= null then From.Current := From.Current.Parent; end if; end Pop_Node; -- ------------------------------ -- Returns True if the current node is the root document node. -- ------------------------------ function Is_Root_Node (Doc : in Document) return Boolean is begin return Doc.Current = null; end Is_Root_Node; -- ------------------------------ -- Append a section header at end of the document. -- ------------------------------ procedure Append (Into : in out Document; Header : in Wiki.Strings.WString; Level : in Positive) is begin Append (Into, new Node_Type '(Kind => N_HEADER, Len => Header'Length, Header => Header, Level => Level)); end Append; -- ------------------------------ -- Append a node to the document. -- ------------------------------ procedure Append (Into : in out Document; Node : in Wiki.Nodes.Node_Type_Access) is begin if Into.Current = null then Append (Into.Nodes, Node); else Append (Into.Current, Node); end if; end Append; -- ------------------------------ -- Append a simple node such as N_LINE_BREAK, N_HORIZONTAL_RULE or N_PARAGRAPH. -- ------------------------------ procedure Append (Into : in out Document; Kind : in Simple_Node_Kind) is begin case Kind is when N_LINE_BREAK => Append (Into, new Node_Type '(Kind => N_LINE_BREAK, Len => 0)); when N_HORIZONTAL_RULE => Append (Into, new Node_Type '(Kind => N_HORIZONTAL_RULE, Len => 0)); when N_PARAGRAPH => Append (Into, new Node_Type '(Kind => N_PARAGRAPH, Len => 0)); when N_TOC_DISPLAY => Append (Into, new Node_Type '(Kind => N_TOC_DISPLAY, Len => 0)); Into.Using_TOC := True; end case; end Append; -- ------------------------------ -- 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) is begin Append (Into, new Node_Type '(Kind => N_TEXT, Len => Text'Length, Text => Text, Format => Format)); end Append; -- ------------------------------ -- Add a link. -- ------------------------------ procedure Add_Link (Into : in out Document; Name : in Wiki.Strings.WString; Attributes : in out Wiki.Attributes.Attribute_List) is begin Append (Into, new Node_Type '(Kind => N_LINK, Len => Name'Length, Title => Name, Link_Attr => Attributes)); end Add_Link; -- ------------------------------ -- Add an image. -- ------------------------------ procedure Add_Image (Into : in out Document; Name : in Wiki.Strings.WString; Attributes : in out Wiki.Attributes.Attribute_List) is begin Append (Into, new Node_Type '(Kind => N_IMAGE, Len => Name'Length, Title => Name, Link_Attr => Attributes)); end Add_Image; -- ------------------------------ -- Add a quote. -- ------------------------------ procedure Add_Quote (Into : in out Document; Name : in Wiki.Strings.WString; Attributes : in out Wiki.Attributes.Attribute_List) is begin Append (Into, new Node_Type '(Kind => N_QUOTE, Len => Name'Length, Title => Name, Link_Attr => Attributes)); end Add_Quote; -- ------------------------------ -- 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) is begin if Ordered then Append (Into, new Node_Type '(Kind => N_NUM_LIST, Len => 0, Level => Level, others => <>)); else Append (Into, new Node_Type '(Kind => N_LIST, Len => 0, Level => Level, others => <>)); end if; end Add_List_Item; -- ------------------------------ -- 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) is begin Append (Into, new Node_Type '(Kind => N_BLOCKQUOTE, Len => 0, Level => Level, others => <>)); end Add_Blockquote; -- 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) is begin Append (Into, new Node_Type '(Kind => N_PREFORMAT, Len => Text'Length, Preformatted => Text, others => <>)); end Add_Preformatted; -- ------------------------------ -- 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 Node_Type)) is begin Iterate (Doc.Nodes, Process); end Iterate; -- ------------------------------ -- Returns True if the document is empty. -- ------------------------------ function Is_Empty (Doc : in Document) return Boolean is begin return Wiki.Nodes.Is_Empty (Doc.Nodes); end Is_Empty; -- ------------------------------ -- Returns True if the document displays the table of contents by itself. -- ------------------------------ function Is_Using_TOC (Doc : in Document) return Boolean is begin return Doc.Using_TOC; end Is_Using_TOC; -- ------------------------------ -- Get the table of content node associated with the document. -- ------------------------------ procedure Get_TOC (Doc : in out Document; TOC : out Wiki.Nodes.Node_List_Ref) is begin if Wiki.Nodes.Is_Empty (Doc.TOC) then Append (Doc.TOC, new Node_Type '(Kind => N_TOC, Len => 0, others => <>)); end if; TOC := Doc.TOC; end Get_TOC; -- ------------------------------ -- Get the table of content node associated with the document. -- ------------------------------ function Get_TOC (Doc : in Document) return Wiki.Nodes.Node_List_Ref is begin return Doc.TOC; end Get_TOC; end Wiki.Documents;
Implement Is_Root_Node function
Implement Is_Root_Node function
Ada
apache-2.0
stcarrez/ada-wiki,stcarrez/ada-wiki
4157c5ad014c3f7fb9895aa7717173e43928ee65
mat/src/mat-readers-marshaller.ads
mat/src/mat-readers-marshaller.ads
----------------------------------------------------------------------- -- mat-readers-marshaller -- Marshalling of data in communication buffer -- 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.Events; package MAT.Readers.Marshaller is Buffer_Underflow_Error : exception; Buffer_Overflow_Error : exception; -- Get an 8-bit value from the buffer. function Get_Uint8 (Buffer : in Buffer_Ptr) return MAT.Types.Uint8; -- Get a 16-bit value either from big-endian or little endian. function Get_Uint16 (Buffer : in Buffer_Ptr) return MAT.Types.Uint16; -- Get a 32-bit value either from big-endian or little endian. function Get_Uint32 (Buffer : in Buffer_Ptr) return MAT.Types.Uint32; -- Get a 64-bit value either from big-endian or little endian. function Get_Uint64 (Buffer : in Buffer_Ptr) return MAT.Types.Uint64; -- Extract a string from the buffer. The string starts with a byte that -- indicates the string length. function Get_String (Buffer : in Message_Type) return String; -- Extract a string from the buffer. The string starts with a byte that -- indicates the string length. function Get_String (Msg : in Message_Type) return Ada.Strings.Unbounded.Unbounded_String; generic type Target_Type is mod <>; function Get_Target_Value (Msg : in Message_Type; Kind : in MAT.Events.Attribute_Type) return Target_Type; function Get_Target_Size (Msg : in Message_Type; Kind : in MAT.Events.Attribute_Type) return MAT.Types.Target_Size; function Get_Target_Addr (Msg : in Message_Type; Kind : in MAT.Events.Attribute_Type) return MAT.Types.Target_Addr; function Get_Target_Uint32 (Msg : in Message_Type; Kind : in MAT.Events.Attribute_Type) return MAT.Types.Uint32; -- Skip the given number of bytes from the message. procedure Skip (Buffer : in Message_Type; Size : in Natural); end MAT.Readers.Marshaller;
----------------------------------------------------------------------- -- mat-readers-marshaller -- Marshalling of data in communication buffer -- 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; with MAT.Events; package MAT.Readers.Marshaller is Buffer_Underflow_Error : exception; Buffer_Overflow_Error : exception; -- Get an 8-bit value from the buffer. function Get_Uint8 (Buffer : in Buffer_Ptr) return MAT.Types.Uint8; -- Get a 16-bit value either from big-endian or little endian. function Get_Uint16 (Buffer : in Buffer_Ptr) return MAT.Types.Uint16; -- Get a 32-bit value either from big-endian or little endian. function Get_Uint32 (Buffer : in Buffer_Ptr) return MAT.Types.Uint32; -- Get a 64-bit value either from big-endian or little endian. function Get_Uint64 (Buffer : in Buffer_Ptr) return MAT.Types.Uint64; -- Extract a string from the buffer. The string starts with a byte that -- indicates the string length. function Get_String (Buffer : in Message_Type) return String; -- Extract a string from the buffer. The string starts with a byte that -- indicates the string length. function Get_String (Msg : in Message_Type) return Ada.Strings.Unbounded.Unbounded_String; generic type Target_Type is mod <>; function Get_Target_Value (Msg : in Message_Type; Kind : in MAT.Events.Attribute_Type) return Target_Type; function Get_Target_Size (Msg : in Message_Type; Kind : in MAT.Events.Attribute_Type) return MAT.Types.Target_Size; function Get_Target_Addr (Msg : in Message_Type; Kind : in MAT.Events.Attribute_Type) return MAT.Types.Target_Addr; function Get_Target_Uint32 (Msg : in Message_Type; Kind : in MAT.Events.Attribute_Type) return MAT.Types.Uint32; function Get_Target_Process_Ref (Msg : in Message_Type; Kind : in MAT.Events.Attribute_Type) return MAT.Types.Target_Process_Ref; -- Skip the given number of bytes from the message. procedure Skip (Buffer : in Message_Type; Size : in Natural); end MAT.Readers.Marshaller;
Declare Get_Target_Process_Ref function
Declare Get_Target_Process_Ref function
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
50d921307cd5233bbdb8bb55d205f837d683fd94
src/asf-components-util-factory.adb
src/asf-components-util-factory.adb
----------------------------------------------------------------------- -- core-factory -- Factory for Core UI Components -- 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 ASF.Components.Html.Text; with ASF.Components.Html.Lists; with ASF.Components.Core; with ASF.Views.Nodes; with Util.Strings.Escapes; use Util.Strings; with EL.Functions.Default; package body ASF.Components.Util.Factory is function Create_View return UIComponent_Access; function Create_Parameter return UIComponent_Access; -- ------------------------------ -- Create an UIView component -- ------------------------------ function Create_View return UIComponent_Access is begin return new ASF.Components.Core.UIView; end Create_View; -- ------------------------------ -- Create an UIParameter component -- ------------------------------ function Create_Parameter return UIComponent_Access is begin return new ASF.Components.Core.UIParameter; end Create_Parameter; use ASF.Views.Nodes; URI : aliased constant String := "http://code.google.com/p/ada-asf/util"; VIEW_TAG : aliased constant String := "view"; PARAM_TAG : aliased constant String := "param"; LIST_TAG : aliased constant String := "list"; Core_Bindings : aliased constant ASF.Factory.Binding_Array := (1 => (Name => PARAM_TAG'Access, Component => Create_Parameter'Access, Tag => Create_Component_Node'Access), 2 => (Name => VIEW_TAG'Access, Component => Create_View'Access, Tag => Create_Component_Node'Access) ); Core_Factory : aliased constant ASF.Factory.Factory_Bindings := (URI => URI'Access, Bindings => Core_Bindings'Access); -- ------------------------------ -- Get the HTML component factory. -- ------------------------------ function Definition return ASF.Factory.Factory_Bindings_Access is begin return Core_Factory'Access; end Definition; -- Truncate the string representation represented by <b>Value</b> to -- the length specified by <b>Size</b>. function Escape_Javascript (Value : EL.Objects.Object) return EL.Objects.Object; procedure Set_Functions (Mapper : in out EL.Functions.Function_Mapper'Class) is begin Mapper.Set_Function (Name => "escapeJavaScript", Namespace => URI, Func => Escape_Javascript'Access); end Set_Functions; function Escape_Javascript (Value : EL.Objects.Object) return EL.Objects.Object is Result : Ada.Strings.Unbounded.Unbounded_String; Content : constant String := EL.Objects.To_String (Value); begin Escapes.Escape_Javascript (Content => Content, Into => Result); return EL.Objects.To_Object (Result); end Escape_Javascript; begin ASF.Factory.Check (Core_Factory); end ASF.Components.Util.Factory;
----------------------------------------------------------------------- -- core-factory -- Factory for Core UI Components -- 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 ASF.Components.Core; with ASF.Views.Nodes; with Util.Strings.Transforms; use Util.Strings; with EL.Functions.Default; package body ASF.Components.Util.Factory is function Create_View return UIComponent_Access; function Create_Parameter return UIComponent_Access; -- ------------------------------ -- Create an UIView component -- ------------------------------ function Create_View return UIComponent_Access is begin return new ASF.Components.Core.UIView; end Create_View; -- ------------------------------ -- Create an UIParameter component -- ------------------------------ function Create_Parameter return UIComponent_Access is begin return new ASF.Components.Core.UIParameter; end Create_Parameter; use ASF.Views.Nodes; URI : aliased constant String := "http://code.google.com/p/ada-asf/util"; VIEW_TAG : aliased constant String := "view"; PARAM_TAG : aliased constant String := "param"; LIST_TAG : aliased constant String := "list"; Core_Bindings : aliased constant ASF.Factory.Binding_Array := (1 => (Name => PARAM_TAG'Access, Component => Create_Parameter'Access, Tag => Create_Component_Node'Access), 2 => (Name => VIEW_TAG'Access, Component => Create_View'Access, Tag => Create_Component_Node'Access) ); Core_Factory : aliased constant ASF.Factory.Factory_Bindings := (URI => URI'Access, Bindings => Core_Bindings'Access); -- ------------------------------ -- Get the HTML component factory. -- ------------------------------ function Definition return ASF.Factory.Factory_Bindings_Access is begin return Core_Factory'Access; end Definition; -- Truncate the string representation represented by <b>Value</b> to -- the length specified by <b>Size</b>. function Escape_Javascript (Value : EL.Objects.Object) return EL.Objects.Object; -- Escape the string using XML escape rules. function Escape_Xml (Value : EL.Objects.Object) return EL.Objects.Object; procedure Set_Functions (Mapper : in out EL.Functions.Function_Mapper'Class) is begin Mapper.Set_Function (Name => "escapeJavaScript", Namespace => URI, Func => Escape_Javascript'Access); Mapper.Set_Function (Name => "escapeXml", Namespace => URI, Func => Escape_Xml'Access); end Set_Functions; function Escape_Javascript (Value : EL.Objects.Object) return EL.Objects.Object is Result : Ada.Strings.Unbounded.Unbounded_String; Content : constant String := EL.Objects.To_String (Value); begin Transforms.Escape_Javascript (Content => Content, Into => Result); return EL.Objects.To_Object (Result); end Escape_Javascript; function Escape_Xml (Value : EL.Objects.Object) return EL.Objects.Object is Result : Ada.Strings.Unbounded.Unbounded_String; Content : constant String := EL.Objects.To_String (Value); begin Transforms.Escape_Xml (Content => Content, Into => Result); return EL.Objects.To_Object (Result); end Escape_Xml; begin ASF.Factory.Check (Core_Factory); end ASF.Components.Util.Factory;
Add escapeXml function
Add escapeXml function
Ada
apache-2.0
Letractively/ada-asf,Letractively/ada-asf,Letractively/ada-asf
43856141ae5771c21c8705bed62c6fe66d617c04
src/asf-server.ads
src/asf-server.ads
----------------------------------------------------------------------- -- asf.server -- ASF Server -- Copyright (C) 2009, 2010, 2011, 2012, 2015, 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Finalization; with Ada.Strings.Unbounded; with ASF.Requests; with ASF.Responses; with ASF.Servlets; package ASF.Server is type Container is tagged limited private; -- Register the application to serve requests procedure Register_Application (Server : in out Container; URI : in String; Context : in ASF.Servlets.Servlet_Registry_Access); -- Remove the application procedure Remove_Application (Server : in out Container; Context : in ASF.Servlets.Servlet_Registry_Access); -- Start the applications that have been registered. procedure Start (Server : in out Container); -- Receives standard HTTP requests from the public service method and dispatches -- them to the Do_XXX methods defined in this class. This method is an HTTP-specific -- version of the Servlet.service(Request, Response) method. There's no need -- to override this method. procedure Service (Server : in Container; Request : in out Requests.Request'Class; Response : in out Responses.Response'Class); -- Get the current registry associated with the current request being processed -- by the current thread. Returns null if there is no current request. function Current return ASF.Servlets.Servlet_Registry_Access; -- Give access to the current request and response object to the <b>Process</b> -- procedure. If there is no current request for the thread, do nothing. procedure Update_Context (Process : not null access procedure (Request : in out Requests.Request'Class; Response : in out Responses.Response'Class)); private -- Binding to record the ASF applications and bind them to URI prefixes. -- It is expected that the number of ASF applications is small (1-10 per server). type Binding is record Context : ASF.Servlets.Servlet_Registry_Access; Base_URI : Ada.Strings.Unbounded.Unbounded_String; end record; type Binding_Array is array (Natural range <>) of Binding; type Binding_Array_Access is access all Binding_Array; type Container is new Ada.Finalization.Limited_Controlled with record Nb_Bindings : Natural := 0; Applications : Binding_Array_Access := null; Default : ASF.Servlets.Servlet_Registry; Is_Started : Boolean := False; end record; type Request_Context is record Application : ASF.Servlets.Servlet_Registry_Access; Request : ASF.Requests.Request_Access; Response : ASF.Responses.Response_Access; end record; -- Set the current registry. This is called by <b>Service</b> once the -- registry is identified from the URI. procedure Set_Context (Context : in Request_Context); -- Release the storage. overriding procedure Finalize (Server : in out Container); end ASF.Server;
----------------------------------------------------------------------- -- asf-server -- ASF Server -- Copyright (C) 2009, 2010, 2011, 2012, 2015, 2016, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Servlet.Server; package ASF.Server renames Servlet.Server;
Package ASF.Server moved to Servlet.Server
Package ASF.Server moved to Servlet.Server
Ada
apache-2.0
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
3da90526a7830bcc41043bf3218988210432bf40
src/natools-s_expressions-atom_buffers.adb
src/natools-s_expressions-atom_buffers.adb
------------------------------------------------------------------------------ -- Copyright (c) 2014, Natacha Porté -- -- -- -- Permission to use, copy, modify, and distribute this software for any -- -- purpose with or without fee is hereby granted, provided that the above -- -- copyright notice and this permission notice appear in all copies. -- -- -- -- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES -- -- WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -- -- MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR -- -- ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -- -- WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -- -- ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF -- -- OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -- ------------------------------------------------------------------------------ package body Natools.S_Expressions.Atom_Buffers is procedure Preallocate (Buffer : in out Atom_Buffer; Length : in Count) is Old_Size, New_Size : Count := 0; begin if Buffer.Used + Length <= Buffer.Available then return; end if; Old_Size := Buffer.Available; New_Size := Buffer.Used + Length; if Buffer.Ref.Is_Empty then declare function Create return Atom; function Create return Atom is begin return Atom'(1 .. New_Size => <>); end Create; begin Buffer.Ref.Replace (Create'Access); end; else declare function Create return Atom; Old_Accessor : constant Atom_Refs.Accessor := Buffer.Ref.Query; function Create return Atom is begin return Result : Atom (1 .. New_Size) do Result (1 .. Old_Size) := Old_Accessor.Data.all; end return; end Create; begin Buffer.Ref.Replace (Create'Access); end; end if; Buffer.Available := New_Size; end Preallocate; procedure Append (Buffer : in out Atom_Buffer; Data : in Atom) is begin Preallocate (Buffer, Data'Length); Buffer.Ref.Update.Data.all (Buffer.Used + 1 .. Buffer.Used + Data'Length) := Data; Buffer.Used := Buffer.Used + Data'Length; end Append; procedure Append (Buffer : in out Atom_Buffer; Data : in Octet) is begin Preallocate (Buffer, 1); Buffer.Ref.Update.Data.all (Buffer.Used + 1) := Data; Buffer.Used := Buffer.Used + 1; end Append; procedure Append_Reverse (Buffer : in out Atom_Buffer; Data : in Atom) is procedure Process (Target : in out Atom); procedure Process (Target : in out Atom) is begin for I in reverse Data'Range loop Buffer.Used := Buffer.Used + 1; Target (Buffer.Used) := Data (I); end loop; end Process; begin Preallocate (Buffer, Data'Length); Buffer.Ref.Update (Process'Access); end Append_Reverse; procedure Invert (Buffer : in out Atom_Buffer) is procedure Process (Data : in out Atom); procedure Process (Data : in out Atom) is Low : Count := Data'First; High : Count := Buffer.Used; Tmp : Octet; begin while Low < High loop Tmp := Data (Low); Data (Low) := Data (High); Data (High) := Tmp; Low := Low + 1; High := High - 1; end loop; end Process; begin if not Buffer.Ref.Is_Empty then Buffer.Ref.Update (Process'Access); end if; end Invert; function Length (Buffer : Atom_Buffer) return Count is begin return Buffer.Used; end Length; function Data (Buffer : Atom_Buffer) return Atom is begin if Buffer.Ref.Is_Empty then pragma Assert (Buffer.Available = 0 and Buffer.Used = 0); return Null_Atom; else return Buffer.Ref.Query.Data.all (1 .. Buffer.Used); end if; end Data; function Raw_Query (Buffer : Atom_Buffer) return Atom_Refs.Accessor is function Create return Atom; function Create return Atom is begin return Null_Atom; end Create; begin if Buffer.Ref.Is_Empty then return Atom_Refs.Create (Create'Access).Query; else return Buffer.Ref.Query; end if; end Raw_Query; procedure Query (Buffer : in Atom_Buffer; Process : not null access procedure (Data : in Atom)) is begin if Buffer.Ref.Is_Empty then Process.all (Null_Atom); else Process.all (Buffer.Ref.Query.Data.all (1 .. Buffer.Used)); end if; end Query; procedure Read (Buffer : in Atom_Buffer; Data : out Atom; Length : out Count) is Transmit : constant Count := Count'Min (Data'Length, Buffer.Used); begin Length := Buffer.Used; if Buffer.Ref.Is_Empty then pragma Assert (Length = 0); null; else Data (Data'First .. Data'First + Transmit - 1) := Buffer.Ref.Query.Data.all (1 .. Transmit); end if; end Read; function Element (Buffer : Atom_Buffer; Position : Count) return Octet is begin return Buffer.Ref.Query.Data.all (Position); end Element; procedure Pop (Buffer : in out Atom_Buffer; Data : out Octet) is begin Data := Buffer.Ref.Query.Data.all (Buffer.Used); Buffer.Used := Buffer.Used - 1; end Pop; procedure Hard_Reset (Buffer : in out Atom_Buffer) is begin Buffer.Ref.Reset; Buffer.Available := 0; Buffer.Used := 0; end Hard_Reset; procedure Soft_Reset (Buffer : in out Atom_Buffer) is begin Buffer.Used := 0; end Soft_Reset; end Natools.S_Expressions.Atom_Buffers;
------------------------------------------------------------------------------ -- Copyright (c) 2014, Natacha Porté -- -- -- -- Permission to use, copy, modify, and distribute this software for any -- -- purpose with or without fee is hereby granted, provided that the above -- -- copyright notice and this permission notice appear in all copies. -- -- -- -- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES -- -- WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -- -- MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR -- -- ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -- -- WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -- -- ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF -- -- OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -- ------------------------------------------------------------------------------ package body Natools.S_Expressions.Atom_Buffers is procedure Preallocate (Buffer : in out Atom_Buffer; Length : in Count) is Old_Size, New_Size : Count := 0; begin if Buffer.Used + Length <= Buffer.Available then return; end if; Old_Size := Buffer.Available; New_Size := Buffer.Used + Length; if Buffer.Ref.Is_Empty then declare function Create return Atom; function Create return Atom is begin return Atom'(1 .. New_Size => <>); end Create; begin Buffer.Ref.Replace (Create'Access); end; else declare function Create return Atom; Old_Accessor : constant Atom_Refs.Accessor := Buffer.Ref.Query; function Create return Atom is begin return Result : Atom (1 .. New_Size) do Result (1 .. Old_Size) := Old_Accessor.Data.all; end return; end Create; begin Buffer.Ref.Replace (Create'Access); end; end if; Buffer.Available := New_Size; end Preallocate; procedure Append (Buffer : in out Atom_Buffer; Data : in Atom) is begin if Data'Length > 0 then Preallocate (Buffer, Data'Length); Buffer.Ref.Update.Data.all (Buffer.Used + 1 .. Buffer.Used + Data'Length) := Data; Buffer.Used := Buffer.Used + Data'Length; end if; end Append; procedure Append (Buffer : in out Atom_Buffer; Data : in Octet) is begin Preallocate (Buffer, 1); Buffer.Ref.Update.Data.all (Buffer.Used + 1) := Data; Buffer.Used := Buffer.Used + 1; end Append; procedure Append_Reverse (Buffer : in out Atom_Buffer; Data : in Atom) is procedure Process (Target : in out Atom); procedure Process (Target : in out Atom) is begin for I in reverse Data'Range loop Buffer.Used := Buffer.Used + 1; Target (Buffer.Used) := Data (I); end loop; end Process; begin Preallocate (Buffer, Data'Length); Buffer.Ref.Update (Process'Access); end Append_Reverse; procedure Invert (Buffer : in out Atom_Buffer) is procedure Process (Data : in out Atom); procedure Process (Data : in out Atom) is Low : Count := Data'First; High : Count := Buffer.Used; Tmp : Octet; begin while Low < High loop Tmp := Data (Low); Data (Low) := Data (High); Data (High) := Tmp; Low := Low + 1; High := High - 1; end loop; end Process; begin if not Buffer.Ref.Is_Empty then Buffer.Ref.Update (Process'Access); end if; end Invert; function Length (Buffer : Atom_Buffer) return Count is begin return Buffer.Used; end Length; function Data (Buffer : Atom_Buffer) return Atom is begin if Buffer.Ref.Is_Empty then pragma Assert (Buffer.Available = 0 and Buffer.Used = 0); return Null_Atom; else return Buffer.Ref.Query.Data.all (1 .. Buffer.Used); end if; end Data; function Raw_Query (Buffer : Atom_Buffer) return Atom_Refs.Accessor is function Create return Atom; function Create return Atom is begin return Null_Atom; end Create; begin if Buffer.Ref.Is_Empty then return Atom_Refs.Create (Create'Access).Query; else return Buffer.Ref.Query; end if; end Raw_Query; procedure Query (Buffer : in Atom_Buffer; Process : not null access procedure (Data : in Atom)) is begin if Buffer.Ref.Is_Empty then Process.all (Null_Atom); else Process.all (Buffer.Ref.Query.Data.all (1 .. Buffer.Used)); end if; end Query; procedure Read (Buffer : in Atom_Buffer; Data : out Atom; Length : out Count) is Transmit : constant Count := Count'Min (Data'Length, Buffer.Used); begin Length := Buffer.Used; if Buffer.Ref.Is_Empty then pragma Assert (Length = 0); null; else Data (Data'First .. Data'First + Transmit - 1) := Buffer.Ref.Query.Data.all (1 .. Transmit); end if; end Read; function Element (Buffer : Atom_Buffer; Position : Count) return Octet is begin return Buffer.Ref.Query.Data.all (Position); end Element; procedure Pop (Buffer : in out Atom_Buffer; Data : out Octet) is begin Data := Buffer.Ref.Query.Data.all (Buffer.Used); Buffer.Used := Buffer.Used - 1; end Pop; procedure Hard_Reset (Buffer : in out Atom_Buffer) is begin Buffer.Ref.Reset; Buffer.Available := 0; Buffer.Used := 0; end Hard_Reset; procedure Soft_Reset (Buffer : in out Atom_Buffer) is begin Buffer.Used := 0; end Soft_Reset; end Natools.S_Expressions.Atom_Buffers;
fix exception when appending an empty atom to an empty buffer
s_expressions-atom_buffers: fix exception when appending an empty atom to an empty buffer
Ada
isc
faelys/natools
eecf94a23b9fc2279c1e766136cc545b4a6cf711
mat/src/frames/mat-frames.ads
mat/src/frames/mat-frames.ads
----------------------------------------------------------------------- -- Frames - Representation of stack frames -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with MAT.Types; use MAT.Types; with MAT.Events; package MAT.Frames is Not_Found : exception; type Frame is limited private; type Frame_Ptr is access all Frame; subtype PC_Table is MAT.Events.Frame_Table; function Parent (F : in Frame_Ptr) return Frame_Ptr; -- Return the parent frame. function Backtrace (F : in Frame_Ptr) return PC_Table; -- Returns the backtrace of the current frame (up to the root). function Calls (F : in Frame_Ptr) return PC_Table; -- Returns all the direct calls made by the current frame. function Count_Children (F : in Frame_Ptr; Recursive : in Boolean := False) return Natural; -- Returns the number of children in the frame. -- When recursive is true, compute in the sub-tree. function Current_Depth (F : in Frame_Ptr) return Natural; -- Returns the current stack depth (# of calls from the root -- to reach the frame). function Create_Root return Frame_Ptr; -- Create a root for stack frame representation. procedure Destroy (Tree : in out Frame_Ptr); -- Destroy the frame tree recursively. procedure Release (F : in Frame_Ptr); -- Release the frame when its reference is no longer necessary. procedure Insert (F : in Frame_Ptr; Pc : in Pc_Table; Result : out Frame_Ptr); function Find (F : in Frame_Ptr; Pc : in Target_Addr) return Frame_Ptr; -- Find the child frame which has the given PC address. -- Returns that frame pointer or raises the Not_Found exception. function Find (F : in Frame_Ptr; Pc : in Pc_Table) return Frame_Ptr; -- -- Find the child frame which has the given PC address. -- Returns that frame pointer or raises the Not_Found exception. procedure Find (F : in Frame_Ptr; Pc : in PC_Table; Result : out Frame_Ptr; Last_Pc : out Natural); private Frame_Group_Size : constant Natural := 4; subtype Local_Depth_Type is Natural range 0 .. Frame_Group_Size; subtype Frame_Table is Pc_Table (1 .. Local_Depth_Type'Last); type Frame is record Parent : Frame_Ptr := null; Next : Frame_Ptr := null; Children : Frame_Ptr := null; Used : Natural := 0; Depth : Natural := 0; Calls : Frame_Table; Local_Depth : Local_Depth_Type := 0; end record; end MAT.Frames;
----------------------------------------------------------------------- -- mat-frames - Representation of stack frames -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with MAT.Types; with MAT.Events; package MAT.Frames is Not_Found : exception; type Frame_Type is private; subtype Frame_Table is MAT.Events.Frame_Table; -- Return the parent frame. function Parent (Frame : in Frame_Type) return Frame_Type; -- Returns the backtrace of the current frame (up to the root). function Backtrace (Frame : in Frame_Type) return Frame_Table; -- Returns all the direct calls made by the current frame. function Calls (Frame : in Frame_Type) return Frame_Table; -- Returns the number of children in the frame. -- When recursive is true, compute in the sub-tree. function Count_Children (Frame : in Frame_Type; Recursive : in Boolean := False) return Natural; -- Returns the current stack depth (# of calls from the root -- to reach the frame). function Current_Depth (F : in Frame_Type) return Natural; -- Create a root for stack frame representation. function Create_Root return Frame_Type; -- Destroy the frame tree recursively. procedure Destroy (Tree : in out Frame_Type); -- Release the frame when its reference is no longer necessary. procedure Release (Frame : in Frame_Type); procedure Insert (Frame : in Frame_Type; Pc : in Frame_Table; Result : out Frame_Type); -- Find the child frame which has the given PC address. -- Returns that frame pointer or raises the Not_Found exception. function Find (Frame : in Frame_Type; Pc : in MAT.Types.Target_Addr) return Frame_Type; function Find (Frame : in Frame_Type; Pc : in Frame_Table) return Frame_Type; -- Find the child frame which has the given PC address. -- Returns that frame pointer or raises the Not_Found exception. procedure Find (Frame : in Frame_Type; Pc : in Frame_Table; Result : out Frame_Type; Last_Pc : out Natural); private Frame_Group_Size : constant Natural := 4; subtype Local_Depth_Type is Natural range 0 .. Frame_Group_Size; subtype Mini_Frame_Table is Frame_Table (1 .. Local_Depth_Type'Last); type Frame; type Frame_Type is access all Frame; type Frame is record Parent : Frame_Type := null; Next : Frame_Type := null; Children : Frame_Type := null; Used : Natural := 0; Depth : Natural := 0; Calls : Mini_Frame_Table; Local_Depth : Local_Depth_Type := 0; end record; end MAT.Frames;
Refactor the frame implementation - Define Frame_Type - Keep Frame a private type - Fix parameter names
Refactor the frame implementation - Define Frame_Type - Keep Frame a private type - Fix parameter names
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
e036206a982a26268e11d9958ee6f55c7eb566f3
mat/src/mat-consoles-text.adb
mat/src/mat-consoles-text.adb
----------------------------------------------------------------------- -- mat-consoles-text - Text console interface -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- package body MAT.Consoles.Text is -- ------------------------------ -- Print the field value for the given field. -- ------------------------------ overriding procedure Print_Field (Console : in out Console_Type; Field : in Field_Type; Value : in String) is begin Ada.Text_IO.Put (Value); end Print_Field; -- ------------------------------ -- Print the title for the given field. -- ------------------------------ overriding procedure Print_Title (Console : in out Console_Type; Field : in Field_Type; Title : in String) is begin Ada.Text_IO.Put (Title); end Print_Title; -- ------------------------------ -- Start a new title in a report. -- ------------------------------ overriding procedure Start_Title (Console : in out Console_Type) is begin null; end Start_Title; -- ------------------------------ -- Start a new row in a report. -- ------------------------------ overriding procedure Start_Row (Console : in out Console_Type) is begin null; end Start_Row; -- ------------------------------ -- Finish a new row in a report. -- ------------------------------ overriding procedure End_Row (Console : in out Console_Type) is begin Ada.Text_IO.New_Line; end End_Row; end MAT.Consoles.Text;
----------------------------------------------------------------------- -- mat-consoles-text - Text console interface -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- package body MAT.Consoles.Text is -- ------------------------------ -- Print the field value for the given field. -- ------------------------------ overriding procedure Print_Field (Console : in out Console_Type; Field : in Field_Type; Value : in String) is begin Ada.Text_IO.Put (Value); end Print_Field; -- ------------------------------ -- Print the title for the given field. -- ------------------------------ overriding procedure Print_Title (Console : in out Console_Type; Field : in Field_Type; Title : in String) is begin Ada.Text_IO.Put (Title); end Print_Title; -- ------------------------------ -- Start a new title in a report. -- ------------------------------ overriding procedure Start_Title (Console : in out Console_Type) is begin null; end Start_Title; -- ------------------------------ -- Finish a new title in a report. -- ------------------------------ procedure End_Title (Console : in out Console_Type) is begin Ada.Text_IO.New_Line; end End_Title; -- ------------------------------ -- Start a new row in a report. -- ------------------------------ overriding procedure Start_Row (Console : in out Console_Type) is begin null; end Start_Row; -- ------------------------------ -- Finish a new row in a report. -- ------------------------------ overriding procedure End_Row (Console : in out Console_Type) is begin Ada.Text_IO.New_Line; end End_Row; end MAT.Consoles.Text;
Implement the End_Title procedure
Implement the End_Title procedure
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
b22bd13ea11286595b43cff3921b6c361c9459d7
awa/plugins/awa-mail/src/awa-mail-modules.ads
awa/plugins/awa-mail/src/awa-mail-modules.ads
----------------------------------------------------------------------- -- awa-mail -- Mail module -- 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.Beans.Objects.Maps; with ASF.Applications; with AWA.Modules; with AWA.Events; with AWA.Mail.Clients; -- == Documentation == -- The *mail* module allows an application to format and send a mail -- to users. This module does not define any web interface. It provides -- a set of services and methods to send a mail when an event is -- received. All this is done through configuration. The module -- defines a set of specific ASF components to format and prepare the -- email. -- -- == Configuration == -- The *mail* module needs some properties to configure the SMTP -- server. -- -- ||mail.smtp.host||localhost||Defines the SMTP server host name|| -- ||mail.smtp.port||25||Defines the SMTP connection port|| -- ||mail.smtp.enable||1|||Defines whether sending email is enabled or not|| -- -- == Sending an email == -- Sending an email when an event is posted can be done by using -- an XML configuration. Basically, the *mail* module uses the event -- framework provided by AWA. The XML definition looks like: -- -- <on-event name="user-register"> -- <action>#{userMail.send}</action> -- <property name="template">/mail/register-user-message.xhtml</property> -- </on-event> -- -- With this definition, the mail template `/mail/register-user-message.xhtml` -- is formatted by using the event and application context when the -- `user-register` event is posted. -- -- @include awa-mail-components.ads -- @include awa-mail-components-recipients.ads -- @include awa-mail-components-messages.ads -- -- == Ada Beans == -- @include mail.xml -- package AWA.Mail.Modules is NAME : constant String := "mail"; type Mail_Module is new AWA.Modules.Module with private; type Mail_Module_Access is access all Mail_Module'Class; -- Initialize the mail module. overriding procedure Initialize (Plugin : in out Mail_Module; App : in AWA.Modules.Application_Access; Props : in ASF.Applications.Config); -- Configures the module after its initialization and after having read its XML configuration. overriding procedure Configure (Plugin : in out Mail_Module; Props : in ASF.Applications.Config); -- Create a new mail message. function Create_Message (Plugin : in Mail_Module) return AWA.Mail.Clients.Mail_Message_Access; -- Get the mail template that must be used for the given event name. -- The mail template is configured by the property: <i>module</i>.template.<i>event</i>. function Get_Template (Plugin : in Mail_Module; Name : in String) return String; -- Format and send an email. procedure Send_Mail (Plugin : in Mail_Module; Template : in String; Props : in Util.Beans.Objects.Maps.Map; Content : in AWA.Events.Module_Event'Class); -- Get the mail module instance associated with the current application. function Get_Mail_Module return Mail_Module_Access; private type Mail_Module is new AWA.Modules.Module with record Mailer : AWA.Mail.Clients.Mail_Manager_Access; end record; end AWA.Mail.Modules;
----------------------------------------------------------------------- -- awa-mail -- Mail module -- 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.Beans.Objects.Maps; with ASF.Applications; with AWA.Modules; with AWA.Events; with AWA.Mail.Clients; -- == Documentation == -- The *mail* module allows an application to format and send a mail -- to users. This module does not define any web interface. It provides -- a set of services and methods to send a mail when an event is -- received. All this is done through configuration. The module -- defines a set of specific ASF components to format and prepare the -- email. -- -- == Configuration == -- The *mail* module needs some properties to configure the SMTP -- server. -- -- ||mail.smtp.host||localhost||Defines the SMTP server host name|| -- ||mail.smtp.port||25||Defines the SMTP connection port|| -- ||mail.smtp.enable||1|||Defines whether sending email is enabled or not|| -- -- == Sending an email == -- Sending an email when an event is posted can be done by using -- an XML configuration. Basically, the *mail* module uses the event -- framework provided by AWA. The XML definition looks like: -- -- <on-event name="user-register"> -- <action>#{userMail.send}</action> -- <property name="template">/mail/register-user-message.xhtml</property> -- </on-event> -- -- With this definition, the mail template `/mail/register-user-message.xhtml` -- is formatted by using the event and application context when the -- `user-register` event is posted. -- -- @include awa-mail-components.ads -- @include awa-mail-components-recipients.ads -- @include awa-mail-components-messages.ads -- -- == Ada Beans == -- @include mail.xml -- package AWA.Mail.Modules is NAME : constant String := "mail"; type Mail_Module is new AWA.Modules.Module with private; type Mail_Module_Access is access all Mail_Module'Class; -- Initialize the mail module. overriding procedure Initialize (Plugin : in out Mail_Module; App : in AWA.Modules.Application_Access; Props : in ASF.Applications.Config); -- Configures the module after its initialization and after having read its XML configuration. overriding procedure Configure (Plugin : in out Mail_Module; Props : in ASF.Applications.Config); -- Create a new mail message. function Create_Message (Plugin : in Mail_Module) return AWA.Mail.Clients.Mail_Message_Access; -- Format and send an email. procedure Send_Mail (Plugin : in Mail_Module; Template : in String; Props : in Util.Beans.Objects.Maps.Map; Content : in AWA.Events.Module_Event'Class); -- Get the mail module instance associated with the current application. function Get_Mail_Module return Mail_Module_Access; private type Mail_Module is new AWA.Modules.Module with record Mailer : AWA.Mail.Clients.Mail_Manager_Access; end record; end AWA.Mail.Modules;
Remove the Get_Template function that is not used
Remove the Get_Template function that is not used
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
8d6ad48b6cbe49d53c2e84474cc7226e395620ee
regtests/util-texts-builders_tests.adb
regtests/util-texts-builders_tests.adb
----------------------------------------------------------------------- -- util-texts-builders_tests -- Unit tests for text builders -- Copyright (C) 2013, 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Ada.Text_IO; with Util.Test_Caller; with Util.Texts.Builders; with Util.Measures; package body Util.Texts.Builders_Tests is package String_Builder is new Util.Texts.Builders (Element_Type => Character, Input => String, Chunk_Size => 100); package Caller is new Util.Test_Caller (Test, "Texts.Builders"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test Util.Texts.Builders.Length", Test_Length'Access); Caller.Add_Test (Suite, "Test Util.Texts.Builders.Append", Test_Append'Access); Caller.Add_Test (Suite, "Test Util.Texts.Builders.Clear", Test_Clear'Access); Caller.Add_Test (Suite, "Test Util.Texts.Builders.Iterate", Test_Iterate'Access); Caller.Add_Test (Suite, "Test Util.Texts.Builders.Tail", Test_Tail'Access); Caller.Add_Test (Suite, "Test Util.Texts.Builders.Perf", Test_Perf'Access); end Add_Tests; -- ------------------------------ -- Test the length operation. -- ------------------------------ procedure Test_Length (T : in out Test) is B : String_Builder.Builder (10); begin Util.Tests.Assert_Equals (T, 0, String_Builder.Length (B), "Invalid length"); Util.Tests.Assert_Equals (T, 10, String_Builder.Capacity (B), "Invalid capacity"); end Test_Length; -- ------------------------------ -- Test the append operation. -- ------------------------------ procedure Test_Append (T : in out Test) is S : constant String := "0123456789"; B : String_Builder.Builder (3); begin String_Builder.Append (B, "a string"); Util.Tests.Assert_Equals (T, 8, String_Builder.Length (B), "Invalid length"); Util.Tests.Assert_Equals (T, "a string", String_Builder.To_Array (B), "Invalid content"); Util.Tests.Assert_Equals (T, 100 + 3, String_Builder.Capacity (B), "Invalid capacity"); -- Append new string and check content. String_Builder.Append (B, " b string"); Util.Tests.Assert_Equals (T, 17, String_Builder.Length (B), "Invalid length"); Util.Tests.Assert_Equals (T, "a string b string", String_Builder.To_Array (B), "Invalid content"); Util.Tests.Assert_Equals (T, 100 + 3, String_Builder.Capacity (B), "Invalid capacity"); String_Builder.Clear (B); for I in S'Range loop String_Builder.Append (B, S (I)); end loop; Util.Tests.Assert_Equals (T, 10, String_Builder.Length (B), "Invalid length"); Util.Tests.Assert_Equals (T, S, String_Builder.To_Array (B), "Invalid append"); end Test_Append; -- ------------------------------ -- Test the clear operation. -- ------------------------------ procedure Test_Clear (T : in out Test) is B : String_Builder.Builder (7); begin for I in 1 .. 10 loop String_Builder.Append (B, "a string"); end loop; Util.Tests.Assert_Equals (T, 8 * 10, String_Builder.Length (B), "Invalid length"); Util.Tests.Assert_Equals (T, 100 + 7, String_Builder.Capacity (B), "Invalid capacity"); String_Builder.Clear (B); Util.Tests.Assert_Equals (T, 0, String_Builder.Length (B), "Invalid length after clear"); Util.Tests.Assert_Equals (T, 7, String_Builder.Capacity (B), "Invalid capacity after clear"); end Test_Clear; -- ------------------------------ -- Test the tail operation. -- ------------------------------ procedure Test_Tail (T : in out Test) is procedure Check_Tail (Min : in Positive; Max : in Positive; L : in Natural); procedure Check_Tail (Min : in Positive; Max : in Positive; L : in Natural) is P : constant String := "0123456789"; B : String_Builder.Builder (Min); begin for I in 1 .. Max loop String_Builder.Append (B, P (1 + (I mod 10))); end loop; declare S : constant String := String_Builder.Tail (B, L); S2 : constant String := String_Builder.To_Array (B); begin Util.Tests.Assert_Equals (T, Max, S2'Length, "Invalid length"); if L >= Max then Util.Tests.Assert_Equals (T, S2, S, "Invalid Tail result"); else Util.Tests.Assert_Equals (T, S2 (S2'Last - L + 1.. S2'Last), S, "Invalid Tail result {" & Positive'Image (Min) & "," & Positive'Image (Max) & "," & Positive'Image (L) & "]"); end if; end; end Check_Tail; begin for I in 1 .. 100 loop for J in 1 .. 8 loop for K in 1 .. I + 3 loop Check_Tail (J, I, K); end loop; end loop; end loop; end Test_Tail; -- ------------------------------ -- Test the iterate operation. -- ------------------------------ procedure Test_Iterate (T : in out Test) is procedure Process (S : in String); B : String_Builder.Builder (13); R : Ada.Strings.Unbounded.Unbounded_String; procedure Process (S : in String) is begin Ada.Strings.Unbounded.Append (R, S); end Process; begin for I in 1 .. 100 loop String_Builder.Append (B, "The Iterate procedure avoids the string copy " & "on the secondary stack"); end loop; String_Builder.Iterate (B, Process'Access); Util.Tests.Assert_Equals (T, String_Builder.Length (B), Ada.Strings.Unbounded.Length (R), "Invalid length in iterate string"); Util.Tests.Assert_Equals (T, String_Builder.To_Array (B), Ada.Strings.Unbounded.To_String (R), "Invalid Iterate"); end Test_Iterate; -- ------------------------------ -- Test the append and iterate performance. -- ------------------------------ procedure Test_Perf (T : in out Test) is Perf : Ada.Text_IO.File_Type; begin Ada.Text_IO.Create (File => Perf, Name => Util.Tests.Get_Test_Path ("string-append.csv")); Ada.Text_IO.Put_Line (Perf, "Block_Size,Append Time,To_Array Time,Iterate Time"); for Block_Size in 1 .. 300 loop declare B : String_Builder.Builder (10); N : constant String := Natural'Image (Block_Size * 10) & ","; begin String_Builder.Set_Block_Size (B, Block_Size * 10); declare S : Util.Measures.Stamp; begin for I in 1 .. 1000 loop String_Builder.Append (B, "some item"); end loop; Util.Measures.Report (S, Perf, N, Util.Measures.Microseconds); end; declare S : Util.Measures.Stamp; R : constant String := String_Builder.To_Array (B); begin Util.Measures.Report (S, Perf, ",", Util.Measures.Microseconds); T.Assert (R'Length > 0, "Invalid string length"); end; declare Count : Natural := 0; procedure Process (Item : in String); procedure Process (Item : in String) is pragma Unreferenced (Item); begin Count := Count + 1; end Process; S : Util.Measures.Stamp; begin String_Builder.Iterate (B, Process'Access); Util.Measures.Report (S, Perf, ",", Util.Measures.Microseconds); T.Assert (Count > 0, "The string builder was empty"); end; end; Ada.Text_IO.New_Line (Perf); end loop; Ada.Text_IO.Close (Perf); Ada.Text_IO.Create (File => Perf, Name => Util.Tests.Get_Test_Path ("string.csv")); Ada.Text_IO.Put_Line (Perf, "Size,Append (100),Append (512)," & "Append (1024),Unbounded,Iterate Time"); for I in 1 .. 4000 loop declare N : constant String := Natural'Image (I) & ","; B : String_Builder.Builder (10); B2 : String_Builder.Builder (10); B3 : String_Builder.Builder (10); U : Ada.Strings.Unbounded.Unbounded_String; S : Util.Measures.Stamp; begin for J in 1 .. I loop String_Builder.Append (B, "some item"); end loop; Util.Measures.Report (S, Perf, N, Util.Measures.Microseconds); String_Builder.Set_Block_Size (B2, 512); for J in 1 .. I loop String_Builder.Append (B2, "some item"); end loop; Util.Measures.Report (S, Perf, ",", Util.Measures.Microseconds); String_Builder.Set_Block_Size (B3, 1024); for J in 1 .. I loop String_Builder.Append (B3, "some item"); end loop; Util.Measures.Report (S, Perf, ",", Util.Measures.Microseconds); for J in 1 .. I loop Ada.Strings.Unbounded.Append (U, "some item"); end loop; Util.Measures.Report (S, Perf, ",", Util.Measures.Microseconds); declare R : constant String := String_Builder.To_Array (B); pragma Unreferenced (R); begin Util.Measures.Report (S, Perf, ",", Util.Measures.Microseconds); end; declare R : constant String := Ada.Strings.Unbounded.To_String (U); pragma Unreferenced (R); begin Util.Measures.Report (S, Perf, ",", Util.Measures.Microseconds); end; end; Ada.Text_IO.New_Line (Perf); end loop; end Test_Perf; end Util.Texts.Builders_Tests;
----------------------------------------------------------------------- -- util-texts-builders_tests -- Unit tests for text builders -- Copyright (C) 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.Strings.Unbounded; with Ada.Text_IO; with Util.Test_Caller; with Util.Texts.Builders; with Util.Measures; package body Util.Texts.Builders_Tests is package String_Builder is new Util.Texts.Builders (Element_Type => Character, Input => String, Chunk_Size => 100); package Caller is new Util.Test_Caller (Test, "Texts.Builders"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test Util.Texts.Builders.Length", Test_Length'Access); Caller.Add_Test (Suite, "Test Util.Texts.Builders.Append", Test_Append'Access); Caller.Add_Test (Suite, "Test Util.Texts.Builders.Clear", Test_Clear'Access); Caller.Add_Test (Suite, "Test Util.Texts.Builders.Iterate", Test_Iterate'Access); Caller.Add_Test (Suite, "Test Util.Texts.Builders.Tail", Test_Tail'Access); Caller.Add_Test (Suite, "Test Util.Texts.Builders.Perf", Test_Perf'Access); end Add_Tests; -- ------------------------------ -- Test the length operation. -- ------------------------------ procedure Test_Length (T : in out Test) is B : String_Builder.Builder (10); begin Util.Tests.Assert_Equals (T, 0, String_Builder.Length (B), "Invalid length"); Util.Tests.Assert_Equals (T, 10, String_Builder.Capacity (B), "Invalid capacity"); end Test_Length; -- ------------------------------ -- Test the append operation. -- ------------------------------ procedure Test_Append (T : in out Test) is S : constant String := "0123456789"; B : String_Builder.Builder (3); begin String_Builder.Append (B, "a string"); Util.Tests.Assert_Equals (T, 8, String_Builder.Length (B), "Invalid length"); Util.Tests.Assert_Equals (T, "a string", String_Builder.To_Array (B), "Invalid content"); Util.Tests.Assert_Equals (T, 100 + 3, String_Builder.Capacity (B), "Invalid capacity"); -- Append new string and check content. String_Builder.Append (B, " b string"); Util.Tests.Assert_Equals (T, 17, String_Builder.Length (B), "Invalid length"); Util.Tests.Assert_Equals (T, "a string b string", String_Builder.To_Array (B), "Invalid content"); Util.Tests.Assert_Equals (T, 100 + 3, String_Builder.Capacity (B), "Invalid capacity"); String_Builder.Clear (B); for I in S'Range loop String_Builder.Append (B, S (I)); end loop; Util.Tests.Assert_Equals (T, 10, String_Builder.Length (B), "Invalid length"); Util.Tests.Assert_Equals (T, S, String_Builder.To_Array (B), "Invalid append"); end Test_Append; -- ------------------------------ -- Test the clear operation. -- ------------------------------ procedure Test_Clear (T : in out Test) is B : String_Builder.Builder (7); begin for I in 1 .. 10 loop String_Builder.Append (B, "a string"); end loop; Util.Tests.Assert_Equals (T, 8 * 10, String_Builder.Length (B), "Invalid length"); Util.Tests.Assert_Equals (T, 100 + 7, String_Builder.Capacity (B), "Invalid capacity"); String_Builder.Clear (B); Util.Tests.Assert_Equals (T, 0, String_Builder.Length (B), "Invalid length after clear"); Util.Tests.Assert_Equals (T, 7, String_Builder.Capacity (B), "Invalid capacity after clear"); end Test_Clear; -- ------------------------------ -- Test the tail operation. -- ------------------------------ procedure Test_Tail (T : in out Test) is procedure Check_Tail (Min : in Positive; Max : in Positive; L : in Natural); procedure Check_Tail (Min : in Positive; Max : in Positive; L : in Natural) is P : constant String := "0123456789"; B : String_Builder.Builder (Min); begin for I in 1 .. Max loop String_Builder.Append (B, P (1 + (I mod 10))); end loop; declare S : constant String := String_Builder.Tail (B, L); S2 : constant String := String_Builder.To_Array (B); begin Util.Tests.Assert_Equals (T, Max, S2'Length, "Invalid length"); if L >= Max then Util.Tests.Assert_Equals (T, S2, S, "Invalid Tail result"); else Util.Tests.Assert_Equals (T, S2 (S2'Last - L + 1 .. S2'Last), S, "Invalid Tail result {" & Positive'Image (Min) & "," & Positive'Image (Max) & "," & Positive'Image (L) & "]"); end if; end; end Check_Tail; begin for I in 1 .. 100 loop for J in 1 .. 8 loop for K in 1 .. I + 3 loop Check_Tail (J, I, K); end loop; end loop; end loop; end Test_Tail; -- ------------------------------ -- Test the iterate operation. -- ------------------------------ procedure Test_Iterate (T : in out Test) is procedure Process (S : in String); B : String_Builder.Builder (13); R : Ada.Strings.Unbounded.Unbounded_String; procedure Process (S : in String) is begin Ada.Strings.Unbounded.Append (R, S); end Process; begin for I in 1 .. 100 loop String_Builder.Append (B, "The Iterate procedure avoids the string copy " & "on the secondary stack"); end loop; String_Builder.Iterate (B, Process'Access); Util.Tests.Assert_Equals (T, String_Builder.Length (B), Ada.Strings.Unbounded.Length (R), "Invalid length in iterate string"); Util.Tests.Assert_Equals (T, String_Builder.To_Array (B), Ada.Strings.Unbounded.To_String (R), "Invalid Iterate"); end Test_Iterate; -- ------------------------------ -- Test the append and iterate performance. -- ------------------------------ procedure Test_Perf (T : in out Test) is Perf : Ada.Text_IO.File_Type; begin Ada.Text_IO.Create (File => Perf, Name => Util.Tests.Get_Test_Path ("string-append.csv")); Ada.Text_IO.Put_Line (Perf, "Block_Size,Append Time,To_Array Time,Iterate Time"); for Block_Size in 1 .. 300 loop declare B : String_Builder.Builder (10); N : constant String := Natural'Image (Block_Size * 10) & ","; begin String_Builder.Set_Block_Size (B, Block_Size * 10); declare S : Util.Measures.Stamp; begin for I in 1 .. 1000 loop String_Builder.Append (B, "some item"); end loop; Util.Measures.Report (S, Perf, N, Util.Measures.Microseconds); end; declare S : Util.Measures.Stamp; R : constant String := String_Builder.To_Array (B); begin Util.Measures.Report (S, Perf, ",", Util.Measures.Microseconds); T.Assert (R'Length > 0, "Invalid string length"); end; declare Count : Natural := 0; procedure Process (Item : in String); procedure Process (Item : in String) is pragma Unreferenced (Item); begin Count := Count + 1; end Process; S : Util.Measures.Stamp; begin String_Builder.Iterate (B, Process'Access); Util.Measures.Report (S, Perf, ",", Util.Measures.Microseconds); T.Assert (Count > 0, "The string builder was empty"); end; end; Ada.Text_IO.New_Line (Perf); end loop; Ada.Text_IO.Close (Perf); Ada.Text_IO.Create (File => Perf, Name => Util.Tests.Get_Test_Path ("string.csv")); Ada.Text_IO.Put_Line (Perf, "Size,Append (100),Append (512)," & "Append (1024),Unbounded,Iterate Time"); for I in 1 .. 4000 loop declare N : constant String := Natural'Image (I) & ","; B : String_Builder.Builder (10); B2 : String_Builder.Builder (10); B3 : String_Builder.Builder (10); U : Ada.Strings.Unbounded.Unbounded_String; S : Util.Measures.Stamp; begin for J in 1 .. I loop String_Builder.Append (B, "some item"); end loop; Util.Measures.Report (S, Perf, N, Util.Measures.Microseconds); String_Builder.Set_Block_Size (B2, 512); for J in 1 .. I loop String_Builder.Append (B2, "some item"); end loop; Util.Measures.Report (S, Perf, ",", Util.Measures.Microseconds); String_Builder.Set_Block_Size (B3, 1024); for J in 1 .. I loop String_Builder.Append (B3, "some item"); end loop; Util.Measures.Report (S, Perf, ",", Util.Measures.Microseconds); for J in 1 .. I loop Ada.Strings.Unbounded.Append (U, "some item"); end loop; Util.Measures.Report (S, Perf, ",", Util.Measures.Microseconds); declare R : constant String := String_Builder.To_Array (B); pragma Unreferenced (R); begin Util.Measures.Report (S, Perf, ",", Util.Measures.Microseconds); end; declare R : constant String := Ada.Strings.Unbounded.To_String (U); pragma Unreferenced (R); begin Util.Measures.Report (S, Perf, ",", Util.Measures.Microseconds); end; end; Ada.Text_IO.New_Line (Perf); end loop; end Test_Perf; end Util.Texts.Builders_Tests;
Fix style compilation warning
Fix style compilation warning
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
b0e51d253569d8cba333d9ad8243e59af9d86f31
src/gen-commands-docs.adb
src/gen-commands-docs.adb
----------------------------------------------------------------------- -- gen-commands-docs -- Extract and generate documentation for the project -- Copyright (C) 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 GNAT.Command_Line; with Ada.Text_IO; with Ada.Directories; with Gen.Artifacts.Docs; with Gen.Model.Packages; package body Gen.Commands.Docs is use GNAT.Command_Line; -- ------------------------------ -- 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); Doc : Gen.Artifacts.Docs.Artifact; M : Gen.Model.Packages.Model_Definition; Arg1 : constant String := Get_Argument; Arg2 : constant String := Get_Argument; Footer : Boolean := True; Fmt : Gen.Artifacts.Docs.Doc_Format := Gen.Artifacts.Docs.DOC_WIKI_GOOGLE; begin if Ada.Directories.Exists ("dynamo.xml") then Generator.Read_Project ("dynamo.xml", False); end if; if Arg1'Length = 0 then Generator.Error ("Missing target directory"); return; elsif Arg1 (Arg1'First) /= '-' then if Arg2'Length /= 0 then Generator.Error ("Invalid markup option " & Arg1); return; end if; -- Setup the target directory where the distribution is created. Generator.Set_Result_Directory (Arg1); else if Arg1 = "-markdown" then Fmt := Gen.Artifacts.Docs.DOC_MARKDOWN; elsif Arg1 = "-google" then Fmt := Gen.Artifacts.Docs.DOC_WIKI_GOOGLE; elsif Arg1 = "-pandoc" then Fmt := Gen.Artifacts.Docs.DOC_MARKDOWN; Footer := False; else Generator.Error ("Invalid markup option " & Arg1); return; end if; if Arg2'Length = 0 then Generator.Error ("Missing target directory"); return; end if; Generator.Set_Result_Directory (Arg2); end if; Doc.Set_Format (Fmt, Footer); Doc.Read_Links (Generator.Get_Project_Property ("links", "links.txt")); Doc.Prepare (M, Generator); 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); use Ada.Text_IO; begin Put_Line ("build-doc: Extract and generate the project documentation"); Put_Line ("Usage: build-doc [-markdown|-google|-pandoc] target-dir"); New_Line; Put_Line (" Extract the documentation from the project source files and generate the"); Put_Line (" project documentation. The following files are scanned:"); Put_Line (" - Ada specifications (src/*.ads)"); Put_Line (" - XML configuration files (config/*.xml)"); Put_Line (" - XML database model files (db/*.xml)"); end Help; end Gen.Commands.Docs;
----------------------------------------------------------------------- -- gen-commands-docs -- Extract and generate documentation for the project -- Copyright (C) 2012, 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 GNAT.Command_Line; with Ada.Text_IO; with Ada.Directories; with Gen.Artifacts.Docs; with Gen.Model.Packages; package body Gen.Commands.Docs is use GNAT.Command_Line; -- ------------------------------ -- 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); Doc : Gen.Artifacts.Docs.Artifact; M : Gen.Model.Packages.Model_Definition; Arg1 : constant String := Get_Argument; Arg2 : constant String := Get_Argument; Footer : Boolean := True; Fmt : Gen.Artifacts.Docs.Doc_Format := Gen.Artifacts.Docs.DOC_WIKI_GOOGLE; begin if Ada.Directories.Exists ("dynamo.xml") then Generator.Read_Project ("dynamo.xml", False); end if; if Arg1'Length = 0 then Generator.Error ("Missing target directory"); return; elsif Arg1 (Arg1'First) /= '-' then if Arg2'Length /= 0 then Generator.Error ("Invalid markup option " & Arg1); return; end if; -- Setup the target directory where the distribution is created. Generator.Set_Result_Directory (Arg1); else if Arg1 = "-markdown" then Fmt := Gen.Artifacts.Docs.DOC_MARKDOWN; elsif Arg1 = "-google" then Fmt := Gen.Artifacts.Docs.DOC_WIKI_GOOGLE; elsif Arg1 = "-pandoc" then Fmt := Gen.Artifacts.Docs.DOC_MARKDOWN; Footer := False; else Generator.Error ("Invalid markup option " & Arg1); return; end if; if Arg2'Length = 0 then Generator.Error ("Missing target directory"); return; end if; Generator.Set_Result_Directory (Arg2); end if; Doc.Set_Format (Fmt, Footer); Doc.Read_Links (Generator.Get_Project_Property ("links", "links.txt")); Doc.Prepare (M, Generator); 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); use Ada.Text_IO; begin Put_Line ("build-doc: Extract and generate the project documentation"); Put_Line ("Usage: build-doc [-markdown|-google|-pandoc] target-dir"); New_Line; Put_Line (" Extract the documentation from the project source files and generate the"); Put_Line (" project documentation. The following files are scanned:"); Put_Line (" - Ada specifications (src/*.ads)"); Put_Line (" - XML configuration files (config/*.xml)"); Put_Line (" - XML database model files (db/*.xml)"); end Help; end Gen.Commands.Docs;
Add Name parameter to the Help procedure
Add Name parameter to the Help procedure
Ada
apache-2.0
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
852d64afdee79beaa8fbc0fb509f2f843c94977f
asfunit/asf-tests.adb
asfunit/asf-tests.adb
----------------------------------------------------------------------- -- ASF tests - ASF Tests Framework -- 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 GNAT.Regpat; with Ada.Strings.Unbounded; with Ada.Unchecked_Deallocation; with Util.Files; with ASF.Streams; with ASF.Servlets.Faces; with ASF.Servlets.Files; with ASF.Servlets.Ajax; with ASF.Servlets.Measures; with ASF.Responses; with ASF.Responses.Tools; with ASF.Filters.Dump; with ASF.Contexts.Faces; with EL.Variables.Default; package body ASF.Tests is use Ada.Strings.Unbounded; use Util.Tests; CONTEXT_PATH : constant String := "/asfunit"; Server : access ASF.Server.Container; App : ASF.Applications.Main.Application_Access := null; Faces : aliased ASF.Servlets.Faces.Faces_Servlet; Files : aliased ASF.Servlets.Files.File_Servlet; Ajax : aliased ASF.Servlets.Ajax.Ajax_Servlet; Dump : aliased ASF.Filters.Dump.Dump_Filter; Measures : aliased ASF.Servlets.Measures.Measure_Servlet; -- Save the response headers and content in a file procedure Save_Response (Name : in String; Response : in out ASF.Responses.Mockup.Response); -- ------------------------------ -- Initialize the awa test framework mockup. -- ------------------------------ procedure Initialize (Props : in Util.Properties.Manager; Application : in ASF.Applications.Main.Application_Access := null; Factory : in out ASF.Applications.Main.Application_Factory'Class) is use type ASF.Applications.Main.Application_Access; C : ASF.Applications.Config; begin if Application /= null then App := Application; else App := new ASF.Applications.Main.Application; end if; Server := new ASF.Server.Container; Server.Register_Application (CONTEXT_PATH, App.all'Access); C.Copy (Props); App.Initialize (C, Factory); App.Register ("layoutMsg", "layout"); App.Set_Global ("contextPath", CONTEXT_PATH); -- Register the servlets and filters App.Add_Servlet (Name => "faces", Server => Faces'Access); App.Add_Servlet (Name => "files", Server => Files'Access); App.Add_Servlet (Name => "ajax", Server => Ajax'Access); App.Add_Servlet (Name => "measures", Server => Measures'Access); App.Add_Filter (Name => "dump", Filter => Dump'Access); App.Add_Filter (Name => "measures", Filter => ASF.Filters.Filter'Class (Measures)'Access); -- Define servlet mappings App.Add_Mapping (Name => "faces", Pattern => "*.html"); App.Add_Mapping (Name => "files", Pattern => "*.css"); App.Add_Mapping (Name => "files", Pattern => "*.js"); App.Add_Mapping (Name => "files", Pattern => "*.properties"); App.Add_Mapping (Name => "files", Pattern => "*.xhtml"); App.Add_Mapping (Name => "ajax", Pattern => "/ajax/*"); App.Add_Mapping (Name => "measures", Pattern => "stats.xml"); App.Add_Filter_Mapping (Name => "measures", Pattern => "*"); App.Add_Filter_Mapping (Name => "measures", Pattern => "/ajax/*"); App.Add_Filter_Mapping (Name => "measures", Pattern => "*.html"); App.Add_Filter_Mapping (Name => "measures", Pattern => "*.xhtml"); App.Add_Filter_Mapping (Name => "dump", Pattern => "*.html"); App.Add_Filter_Mapping (Name => "dump", Pattern => "*.css"); App.Add_Filter_Mapping (Name => "dump", Pattern => "/ajax/*"); end Initialize; -- ------------------------------ -- Get the server -- ------------------------------ function Get_Server return access ASF.Server.Container is begin return Server; end Get_Server; -- ------------------------------ -- Get the test application. -- ------------------------------ function Get_Application return ASF.Applications.Main.Application_Access is begin return App; end Get_Application; -- ------------------------------ -- Save the response headers and content in a file -- ------------------------------ procedure Save_Response (Name : in String; Response : in out ASF.Responses.Mockup.Response) is use ASF.Responses; Info : constant String := Tools.To_String (Reply => Response, Html => False, Print_Headers => True); Result_Path : constant String := Util.Tests.Get_Test_Path ("regtests/result"); Content : Unbounded_String; Stream : ASF.Streams.Print_Stream := Response.Get_Output_Stream; begin Response.Read_Content (Content); Stream.Write (Content); Insert (Content, 1, Info); Util.Files.Write_File (Result_Path & "/" & Name, Content); end Save_Response; -- ------------------------------ -- Simulate a raw request. The URI and method must have been set on the Request object. -- ------------------------------ procedure Do_Req (Request : in out ASF.Requests.Mockup.Request; Response : in out ASF.Responses.Mockup.Response) is begin -- For the purpose of writing tests, clear the buffer before invoking the service. Response.Clear; Server.Service (Request => Request, Response => Response); end Do_Req; -- ------------------------------ -- Simulate a GET request on the given URI with the request parameters. -- Get the result in the response object. -- ------------------------------ procedure Do_Get (Request : in out ASF.Requests.Mockup.Request; Response : in out ASF.Responses.Mockup.Response; URI : in String; Save : in String := "") is begin Request.Set_Method (Method => "GET"); Request.Set_Request_URI (URI => CONTEXT_PATH & URI); Request.Set_Protocol (Protocol => "HTTP/1.1"); Do_Req (Request, Response); if Save'Length > 0 then Save_Response (Save, Response); end if; end Do_Get; -- ------------------------------ -- Simulate a POST request on the given URI with the request parameters. -- Get the result in the response object. -- ------------------------------ procedure Do_Post (Request : in out ASF.Requests.Mockup.Request; Response : in out ASF.Responses.Mockup.Response; URI : in String; Save : in String := "") is begin Request.Set_Method (Method => "POST"); Request.Set_Request_URI (URI => CONTEXT_PATH & URI); Request.Set_Protocol (Protocol => "HTTP/1.1"); Do_Req (Request, Response); if Save'Length > 0 then Save_Response (Save, Response); end if; end Do_Post; -- ------------------------------ -- Check that the response body contains the string -- ------------------------------ procedure Assert_Contains (T : in Util.Tests.Test'Class; Value : in String; Reply : in out ASF.Responses.Mockup.Response; Message : in String := "Test failed"; Source : String := GNAT.Source_Info.File; Line : Natural := GNAT.Source_Info.Line) is Stream : ASF.Streams.Print_Stream := Reply.Get_Output_Stream; Content : Unbounded_String; begin Reply.Read_Content (Content); Stream.Write (Content); Assert_Equals (T, ASF.Responses.SC_OK, Reply.Get_Status, "Invalid response", Source, Line); T.Assert (Condition => Index (Content, Value) > 0, Message => Message & ": value '" & Value & "' not found", Source => Source, Line => Line); end Assert_Contains; -- ------------------------------ -- Check that the response body matches the regular expression -- ------------------------------ procedure Assert_Matches (T : in Util.Tests.Test'Class; Pattern : in String; Reply : in out ASF.Responses.Mockup.Response; Message : in String := "Test failed"; Status : in Natural := ASF.Responses.SC_OK; Source : String := GNAT.Source_Info.File; Line : Natural := GNAT.Source_Info.Line) is use GNAT.Regpat; Stream : ASF.Streams.Print_Stream := Reply.Get_Output_Stream; Content : Unbounded_String; Regexp : constant Pattern_Matcher := Compile (Expression => Pattern, Flags => Multiple_Lines); begin Reply.Read_Content (Content); Stream.Write (Content); Assert_Equals (T, Status, Reply.Get_Status, "Invalid response", Source, Line); T.Assert (Condition => Match (Regexp, To_String (Content)), Message => Message & ": does not match '" & Pattern & "'", Source => Source, Line => Line); end Assert_Matches; -- ------------------------------ -- Check that the response contains the given header. -- ------------------------------ procedure Assert_Header (T : in Util.Tests.Test'Class; Header : in String; Value : in String; Reply : in out ASF.Responses.Mockup.Response; Message : in String := "Test failed"; Status : in Natural := ASF.Responses.SC_OK; Source : String := GNAT.Source_Info.File; Line : Natural := GNAT.Source_Info.Line) is begin T.Assert (Condition => Reply.Contains_Header (Header), Message => Message & ": missing header '" & Header & "'", Source => Source, Line => Line); Assert_Equals (T, Value, Reply.Get_Header (Header), Message, Source, Line); end Assert_Header; -- ------------------------------ -- Check that the response body is a redirect to the given URI. -- ------------------------------ procedure Assert_Redirect (T : in Util.Tests.Test'Class; Value : in String; Reply : in out ASF.Responses.Mockup.Response; Message : in String := "Test failed"; Source : String := GNAT.Source_Info.File; Line : Natural := GNAT.Source_Info.Line) is begin Assert_Equals (T, ASF.Responses.SC_MOVED_TEMPORARILY, Reply.Get_Status, "Invalid response", Source, Line); Util.Tests.Assert_Equals (T, Value, Reply.Get_Header ("Location"), Message & ": missing Location", Source, Line); end Assert_Redirect; -- ------------------------------ -- Cleanup the test instance. -- ------------------------------ overriding procedure Tear_Down (T : in out EL_Test) is procedure Free is new Ada.Unchecked_Deallocation (EL.Contexts.Default.Default_Context'Class, EL.Contexts.Default.Default_Context_Access); procedure Free is new Ada.Unchecked_Deallocation (EL.Variables.Variable_Mapper'Class, EL.Variables.Variable_Mapper_Access); procedure Free is new Ada.Unchecked_Deallocation (EL.Contexts.Default.Default_ELResolver'Class, EL.Contexts.Default.Default_ELResolver_Access); begin ASF.Contexts.Faces.Restore (null); Free (T.ELContext); Free (T.Variables); Free (T.Root_Resolver); end Tear_Down; -- ------------------------------ -- Setup the test instance. -- ------------------------------ overriding procedure Set_Up (T : in out EL_Test) is begin T.ELContext := new EL.Contexts.Default.Default_Context; T.Root_Resolver := new EL.Contexts.Default.Default_ELResolver; T.Variables := new EL.Variables.Default.Default_Variable_Mapper; T.ELContext.Set_Resolver (T.Root_Resolver.all'Access); T.ELContext.Set_Variable_Mapper (T.Variables.all'Access); end Set_Up; end ASF.Tests;
----------------------------------------------------------------------- -- ASF tests - ASF Tests Framework -- 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 GNAT.Regpat; with Ada.Strings.Unbounded; with Ada.Unchecked_Deallocation; with Util.Files; with ASF.Streams; with ASF.Servlets.Faces; with ASF.Servlets.Files; with ASF.Servlets.Ajax; with ASF.Servlets.Measures; with ASF.Responses; with ASF.Responses.Tools; with ASF.Filters.Dump; with ASF.Contexts.Faces; with EL.Variables.Default; package body ASF.Tests is use Ada.Strings.Unbounded; use Util.Tests; CONTEXT_PATH : constant String := "/asfunit"; type Container_Access is access ASF.Server.Container; Server : Container_Access; App_Created : ASF.Applications.Main.Application_Access; App : ASF.Applications.Main.Application_Access; Faces : aliased ASF.Servlets.Faces.Faces_Servlet; Files : aliased ASF.Servlets.Files.File_Servlet; Ajax : aliased ASF.Servlets.Ajax.Ajax_Servlet; Dump : aliased ASF.Filters.Dump.Dump_Filter; Measures : aliased ASF.Servlets.Measures.Measure_Servlet; -- Save the response headers and content in a file procedure Save_Response (Name : in String; Response : in out ASF.Responses.Mockup.Response); -- ------------------------------ -- Initialize the awa test framework mockup. -- ------------------------------ procedure Initialize (Props : in Util.Properties.Manager; Application : in ASF.Applications.Main.Application_Access := null; Factory : in out ASF.Applications.Main.Application_Factory'Class) is use type ASF.Applications.Main.Application_Access; C : ASF.Applications.Config; begin if Application /= null then App := Application; else if App_Created = null then App_Created := new ASF.Applications.Main.Application; end if; App := App_Created; end if; Server := new ASF.Server.Container; Server.Register_Application (CONTEXT_PATH, App.all'Access); C.Copy (Props); App.Initialize (C, Factory); App.Register ("layoutMsg", "layout"); App.Set_Global ("contextPath", CONTEXT_PATH); -- Register the servlets and filters App.Add_Servlet (Name => "faces", Server => Faces'Access); App.Add_Servlet (Name => "files", Server => Files'Access); App.Add_Servlet (Name => "ajax", Server => Ajax'Access); App.Add_Servlet (Name => "measures", Server => Measures'Access); App.Add_Filter (Name => "dump", Filter => Dump'Access); App.Add_Filter (Name => "measures", Filter => ASF.Filters.Filter'Class (Measures)'Access); -- Define servlet mappings App.Add_Mapping (Name => "faces", Pattern => "*.html"); App.Add_Mapping (Name => "files", Pattern => "*.css"); App.Add_Mapping (Name => "files", Pattern => "*.js"); App.Add_Mapping (Name => "files", Pattern => "*.properties"); App.Add_Mapping (Name => "files", Pattern => "*.xhtml"); App.Add_Mapping (Name => "ajax", Pattern => "/ajax/*"); App.Add_Mapping (Name => "measures", Pattern => "stats.xml"); App.Add_Filter_Mapping (Name => "measures", Pattern => "*"); App.Add_Filter_Mapping (Name => "measures", Pattern => "/ajax/*"); App.Add_Filter_Mapping (Name => "measures", Pattern => "*.html"); App.Add_Filter_Mapping (Name => "measures", Pattern => "*.xhtml"); App.Add_Filter_Mapping (Name => "dump", Pattern => "*.html"); App.Add_Filter_Mapping (Name => "dump", Pattern => "*.css"); App.Add_Filter_Mapping (Name => "dump", Pattern => "/ajax/*"); end Initialize; -- ------------------------------ -- Called when the testsuite execution has finished. -- ------------------------------ procedure Finish (Status : in Util.XUnit.Status) is pragma Unreferenced (Status); procedure Free is new Ada.Unchecked_Deallocation (Object => ASF.Applications.Main.Application'Class, Name => ASF.Applications.Main.Application_Access); procedure Free is new Ada.Unchecked_Deallocation (Object => ASF.Server.Container, Name => Container_Access); begin Free (App_Created); Free (Server); end Finish; -- ------------------------------ -- Get the server -- ------------------------------ function Get_Server return access ASF.Server.Container is begin return Server; end Get_Server; -- ------------------------------ -- Get the test application. -- ------------------------------ function Get_Application return ASF.Applications.Main.Application_Access is begin return App; end Get_Application; -- ------------------------------ -- Save the response headers and content in a file -- ------------------------------ procedure Save_Response (Name : in String; Response : in out ASF.Responses.Mockup.Response) is use ASF.Responses; Info : constant String := Tools.To_String (Reply => Response, Html => False, Print_Headers => True); Result_Path : constant String := Util.Tests.Get_Test_Path ("regtests/result"); Content : Unbounded_String; Stream : ASF.Streams.Print_Stream := Response.Get_Output_Stream; begin Response.Read_Content (Content); Stream.Write (Content); Insert (Content, 1, Info); Util.Files.Write_File (Result_Path & "/" & Name, Content); end Save_Response; -- ------------------------------ -- Simulate a raw request. The URI and method must have been set on the Request object. -- ------------------------------ procedure Do_Req (Request : in out ASF.Requests.Mockup.Request; Response : in out ASF.Responses.Mockup.Response) is begin -- For the purpose of writing tests, clear the buffer before invoking the service. Response.Clear; Server.Service (Request => Request, Response => Response); end Do_Req; -- ------------------------------ -- Simulate a GET request on the given URI with the request parameters. -- Get the result in the response object. -- ------------------------------ procedure Do_Get (Request : in out ASF.Requests.Mockup.Request; Response : in out ASF.Responses.Mockup.Response; URI : in String; Save : in String := "") is begin Request.Set_Method (Method => "GET"); Request.Set_Request_URI (URI => CONTEXT_PATH & URI); Request.Set_Protocol (Protocol => "HTTP/1.1"); Do_Req (Request, Response); if Save'Length > 0 then Save_Response (Save, Response); end if; end Do_Get; -- ------------------------------ -- Simulate a POST request on the given URI with the request parameters. -- Get the result in the response object. -- ------------------------------ procedure Do_Post (Request : in out ASF.Requests.Mockup.Request; Response : in out ASF.Responses.Mockup.Response; URI : in String; Save : in String := "") is begin Request.Set_Method (Method => "POST"); Request.Set_Request_URI (URI => CONTEXT_PATH & URI); Request.Set_Protocol (Protocol => "HTTP/1.1"); Do_Req (Request, Response); if Save'Length > 0 then Save_Response (Save, Response); end if; end Do_Post; -- ------------------------------ -- Check that the response body contains the string -- ------------------------------ procedure Assert_Contains (T : in Util.Tests.Test'Class; Value : in String; Reply : in out ASF.Responses.Mockup.Response; Message : in String := "Test failed"; Source : String := GNAT.Source_Info.File; Line : Natural := GNAT.Source_Info.Line) is Stream : ASF.Streams.Print_Stream := Reply.Get_Output_Stream; Content : Unbounded_String; begin Reply.Read_Content (Content); Stream.Write (Content); Assert_Equals (T, ASF.Responses.SC_OK, Reply.Get_Status, "Invalid response", Source, Line); T.Assert (Condition => Index (Content, Value) > 0, Message => Message & ": value '" & Value & "' not found", Source => Source, Line => Line); end Assert_Contains; -- ------------------------------ -- Check that the response body matches the regular expression -- ------------------------------ procedure Assert_Matches (T : in Util.Tests.Test'Class; Pattern : in String; Reply : in out ASF.Responses.Mockup.Response; Message : in String := "Test failed"; Status : in Natural := ASF.Responses.SC_OK; Source : String := GNAT.Source_Info.File; Line : Natural := GNAT.Source_Info.Line) is use GNAT.Regpat; Stream : ASF.Streams.Print_Stream := Reply.Get_Output_Stream; Content : Unbounded_String; Regexp : constant Pattern_Matcher := Compile (Expression => Pattern, Flags => Multiple_Lines); begin Reply.Read_Content (Content); Stream.Write (Content); Assert_Equals (T, Status, Reply.Get_Status, "Invalid response", Source, Line); T.Assert (Condition => Match (Regexp, To_String (Content)), Message => Message & ": does not match '" & Pattern & "'", Source => Source, Line => Line); end Assert_Matches; -- ------------------------------ -- Check that the response contains the given header. -- ------------------------------ procedure Assert_Header (T : in Util.Tests.Test'Class; Header : in String; Value : in String; Reply : in out ASF.Responses.Mockup.Response; Message : in String := "Test failed"; Status : in Natural := ASF.Responses.SC_OK; Source : String := GNAT.Source_Info.File; Line : Natural := GNAT.Source_Info.Line) is begin T.Assert (Condition => Reply.Contains_Header (Header), Message => Message & ": missing header '" & Header & "'", Source => Source, Line => Line); Assert_Equals (T, Value, Reply.Get_Header (Header), Message, Source, Line); end Assert_Header; -- ------------------------------ -- Check that the response body is a redirect to the given URI. -- ------------------------------ procedure Assert_Redirect (T : in Util.Tests.Test'Class; Value : in String; Reply : in out ASF.Responses.Mockup.Response; Message : in String := "Test failed"; Source : String := GNAT.Source_Info.File; Line : Natural := GNAT.Source_Info.Line) is begin Assert_Equals (T, ASF.Responses.SC_MOVED_TEMPORARILY, Reply.Get_Status, "Invalid response", Source, Line); Util.Tests.Assert_Equals (T, Value, Reply.Get_Header ("Location"), Message & ": missing Location", Source, Line); end Assert_Redirect; -- ------------------------------ -- Cleanup the test instance. -- ------------------------------ overriding procedure Tear_Down (T : in out EL_Test) is procedure Free is new Ada.Unchecked_Deallocation (EL.Contexts.Default.Default_Context'Class, EL.Contexts.Default.Default_Context_Access); procedure Free is new Ada.Unchecked_Deallocation (EL.Variables.Variable_Mapper'Class, EL.Variables.Variable_Mapper_Access); procedure Free is new Ada.Unchecked_Deallocation (EL.Contexts.Default.Default_ELResolver'Class, EL.Contexts.Default.Default_ELResolver_Access); begin ASF.Contexts.Faces.Restore (null); Free (T.ELContext); Free (T.Variables); Free (T.Root_Resolver); end Tear_Down; -- ------------------------------ -- Setup the test instance. -- ------------------------------ overriding procedure Set_Up (T : in out EL_Test) is begin T.ELContext := new EL.Contexts.Default.Default_Context; T.Root_Resolver := new EL.Contexts.Default.Default_ELResolver; T.Variables := new EL.Variables.Default.Default_Variable_Mapper; T.ELContext.Set_Resolver (T.Root_Resolver.all'Access); T.ELContext.Set_Variable_Mapper (T.Variables.all'Access); end Set_Up; end ASF.Tests;
Implement the Finish procedure to release the application and server container
Implement the Finish procedure to release the application and server container
Ada
apache-2.0
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
3e84c13f93ebec1290586bb63f8daf63f8103e3e
tools/druss-tools.adb
tools/druss-tools.adb
----------------------------------------------------------------------- -- druss-tools -- Druss main tool -- 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 GNAT.Command_Line; use GNAT.Command_Line; with Ada.Command_Line; with Ada.Text_IO; with Ada.Exceptions; with Ada.Strings.Unbounded; with Util.Commands; with Util.Http.Clients.Curl; with Util.Log.Loggers; with Util.Properties; with Druss.Config; with Druss.Commands; procedure Druss.Tools is use Ada.Text_IO; use Ada.Strings.Unbounded; Log_Config : Util.Properties.Manager; Config : Ada.Strings.Unbounded.Unbounded_String; Output : Ada.Strings.Unbounded.Unbounded_String; Debug : Boolean := False; Verbose : Boolean := False; First : Natural := 0; All_Args : Util.Commands.Default_Argument_List (0); Console : aliased Druss.Commands.Text_Consoles.Console_Type; begin Log_Config.Set ("log4j.rootCategory", "DEBUG,console"); Log_Config.Set ("log4j.appender.console", "Console"); Log_Config.Set ("log4j.appender.console.level", "ERROR"); Log_Config.Set ("log4j.appender.console.layout", "level-message"); Log_Config.Set ("log4j.appender.stdout", "Console"); Log_Config.Set ("log4j.appender.stdout.level", "INFO"); Log_Config.Set ("log4j.appender.stdout.layout", "message"); Log_Config.Set ("log4j.logger.Util", "WARN"); Util.Log.Loggers.Initialize (Log_Config); Druss.Commands.Initialize; Initialize_Option_Scan (Stop_At_First_Non_Switch => True, Section_Delimiters => "targs"); -- Parse the command line loop case Getopt ("* v d o: c:") is when ASCII.NUL => exit; when 'c' => Config := Ada.Strings.Unbounded.To_Unbounded_String (Parameter); when 'o' => Output := Ada.Strings.Unbounded.To_Unbounded_String (Parameter); when 'd' => Debug := True; when 'v' => Verbose := True; when '*' => exit; when others => null; end case; First := First + 1; end loop; if Verbose then Log_Config.Set ("log4j.appender.console.level", "INFO"); end if; if Debug then Log_Config.Set ("log4j.appender.console.level", "DEBUG"); end if; Util.Log.Loggers.Initialize (Log_Config); Druss.Config.Initialize (To_String (Config)); Util.Http.Clients.Curl.Register; if First >= Ada.Command_Line.Argument_Count then Ada.Text_IO.Put_Line ("Missing command name to execute."); Druss.Commands.Driver.Usage (All_Args); Ada.Command_Line.Set_Exit_Status (Ada.Command_Line.Failure); return; end if; declare Cmd_Name : constant String := Full_Switch; Args : Util.Commands.Default_Argument_List (First + 1); Ctx : Druss.Commands.Context_Type; begin Ctx.Console := Console'Unchecked_Access; Druss.Config.Get_Gateways (Ctx.Gateways); Druss.Commands.Driver.Execute (Cmd_Name, Args, Ctx); end; exception when E : Invalid_Switch => Ada.Text_IO.Put_Line ("Invalid option: " & Ada.Exceptions.Exception_Message (E)); Ada.Command_Line.Set_Exit_Status (2); end Druss.Tools;
----------------------------------------------------------------------- -- druss-tools -- Druss main tool -- 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 GNAT.Command_Line; use GNAT.Command_Line; with Ada.Command_Line; with Ada.Text_IO; with Ada.Exceptions; with Ada.Strings.Unbounded; with Util.Commands; with Util.Http.Clients.Curl; with Util.Log.Loggers; with Util.Properties; with Druss.Config; with Druss.Commands; procedure Druss.Tools is use Ada.Text_IO; use Ada.Strings.Unbounded; Log_Config : Util.Properties.Manager; Config : Ada.Strings.Unbounded.Unbounded_String; Output : Ada.Strings.Unbounded.Unbounded_String; Debug : Boolean := False; Verbose : Boolean := False; First : Natural := 0; All_Args : Util.Commands.Default_Argument_List (0); Console : aliased Druss.Commands.Text_Consoles.Console_Type; begin Log_Config.Set ("log4j.rootCategory", "DEBUG,console"); Log_Config.Set ("log4j.appender.console", "Console"); Log_Config.Set ("log4j.appender.console.level", "ERROR"); Log_Config.Set ("log4j.appender.console.layout", "level-message"); Log_Config.Set ("log4j.appender.stdout", "Console"); Log_Config.Set ("log4j.appender.stdout.level", "INFO"); Log_Config.Set ("log4j.appender.stdout.layout", "message"); Log_Config.Set ("log4j.logger.Util", "FATAL"); Log_Config.Set ("log4j.logger.Bbox", "FATAL"); Util.Log.Loggers.Initialize (Log_Config); Druss.Commands.Initialize; Initialize_Option_Scan (Stop_At_First_Non_Switch => True, Section_Delimiters => "targs"); -- Parse the command line loop case Getopt ("* v d o: c:") is when ASCII.NUL => exit; when 'c' => Config := Ada.Strings.Unbounded.To_Unbounded_String (Parameter); when 'o' => Output := Ada.Strings.Unbounded.To_Unbounded_String (Parameter); when 'd' => Debug := True; when 'v' => Verbose := True; when '*' => exit; when others => null; end case; First := First + 1; end loop; if Verbose or Debug then Log_Config.Set ("log4j.appender.console.level", "INFO"); Log_Config.Set ("log4j.logger.Util", "WARN"); Log_Config.Set ("log4j.logger.Bbox", "ERR"); end if; if Debug then Log_Config.Set ("log4j.appender.console.level", "DEBUG"); end if; Util.Log.Loggers.Initialize (Log_Config); Druss.Config.Initialize (To_String (Config)); Util.Http.Clients.Curl.Register; if First >= Ada.Command_Line.Argument_Count then Ada.Text_IO.Put_Line ("Missing command name to execute."); Druss.Commands.Driver.Usage (All_Args); Ada.Command_Line.Set_Exit_Status (Ada.Command_Line.Failure); return; end if; declare Cmd_Name : constant String := Full_Switch; Args : Util.Commands.Default_Argument_List (First + 1); Ctx : Druss.Commands.Context_Type; begin Ctx.Console := Console'Unchecked_Access; Druss.Config.Get_Gateways (Ctx.Gateways); Druss.Commands.Driver.Execute (Cmd_Name, Args, Ctx); end; exception when E : Invalid_Switch => Ada.Text_IO.Put_Line ("Invalid option: " & Ada.Exceptions.Exception_Message (E)); Ada.Command_Line.Set_Exit_Status (2); end Druss.Tools;
Update the -v and -d option to enable more logging
Update the -v and -d option to enable more logging
Ada
apache-2.0
stcarrez/bbox-ada-api
39af4bdf9bc095601128dba3350c01d408a97f9d
regtests/ado-parameters-tests.adb
regtests/ado-parameters-tests.adb
----------------------------------------------------------------------- -- ado-parameters-tests -- Test query parameters and SQL expansion -- Copyright (C) 2011, 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.Measures; with ADO.Caches.Discrete; with ADO.Caches; package body ADO.Parameters.Tests is use Util.Tests; package Int_Cache is new ADO.Caches.Discrete (Element_Type => Integer); type Dialect is new ADO.Drivers.Dialects.Dialect with null record; -- Check if the string is a reserved keyword. overriding function Is_Reserved (D : in Dialect; Name : in String) return Boolean; -- Test the Add_Param operation for various types. generic type T (<>) is private; with procedure Add_Param (L : in out ADO.Parameters.Abstract_List; V : in T) is <>; Value : T; Name : String; procedure Test_Add_Param_T (Tst : in out Test); -- Test the Bind_Param operation for various types. generic type T (<>) is private; with procedure Bind_Param (L : in out ADO.Parameters.Abstract_List; N : in String; V : in T) is <>; Value : T; Name : String; procedure Test_Bind_Param_T (Tst : in out Test); -- Test the Add_Param operation for various types. procedure Test_Add_Param_T (Tst : in out Test) is Count : constant Positive := 100; SQL : ADO.Parameters.List; S : Util.Measures.Stamp; begin for I in 1 .. Count loop Add_Param (ADO.Parameters.Abstract_List (SQL), Value); end loop; Util.Measures.Report (S, "Add_Param " & Name & "(" & Positive'Image (Count) & " calls)"); Util.Tests.Assert_Equals (Tst, Count, SQL.Length, "Invalid param list for " & Name); end Test_Add_Param_T; -- Test the Bind_Param operation for various types. procedure Test_Bind_Param_T (Tst : in out Test) is Count : constant Positive := 100; SQL : ADO.Parameters.List; S : Util.Measures.Stamp; begin for I in 1 .. Count loop Bind_Param (ADO.Parameters.Abstract_List (SQL), "a_parameter_name", Value); end loop; Util.Measures.Report (S, "Bind_Param " & Name & "(" & Positive'Image (Count) & " calls)"); Util.Tests.Assert_Equals (Tst, 1, SQL.Length, "Invalid param list for " & Name); end Test_Bind_Param_T; procedure Test_Add_Param_Integer is new Test_Add_Param_T (Integer, Add_Param, 10, "Integer"); procedure Test_Add_Param_Long_Long_Integer is new Test_Add_Param_T (Long_Long_Integer, Add_Param, 10_000_000_000_000, "Long_Long_Integer"); procedure Test_Add_Param_Identifier is new Test_Add_Param_T (Identifier, Add_Param, 100, "Identifier"); procedure Test_Add_Param_Boolean is new Test_Add_Param_T (Boolean, Add_Param, False, "Boolean"); procedure Test_Add_Param_String is new Test_Add_Param_T (String, Add_Param, "0123456789ABCDEF", "String"); procedure Test_Add_Param_Calendar is new Test_Add_Param_T (Ada.Calendar.Time, Add_Param, Ada.Calendar.Clock, "Time"); procedure Test_Add_Param_Unbounded_String is new Test_Add_Param_T (Unbounded_String, Add_Param, To_Unbounded_String ("0123456789ABCDEF"), "Unbounded_String"); procedure Test_Bind_Param_Integer is new Test_Bind_Param_T (Integer, Bind_Param, 10, "Integer"); procedure Test_Bind_Param_Long_Long_Integer is new Test_Bind_Param_T (Long_Long_Integer, Bind_Param, 10_000_000_000_000, "Long_Long_Integer"); procedure Test_Bind_Param_Identifier is new Test_Bind_Param_T (Identifier, Bind_Param, 100, "Identifier"); procedure Test_Bind_Param_Entity_Type is new Test_Bind_Param_T (Entity_Type, Bind_Param, 100, "Entity_Type"); procedure Test_Bind_Param_Boolean is new Test_Bind_Param_T (Boolean, Bind_Param, False, "Boolean"); procedure Test_Bind_Param_String is new Test_Bind_Param_T (String, Bind_Param, "0123456789ABCDEF", "String"); procedure Test_Bind_Param_Calendar is new Test_Bind_Param_T (Ada.Calendar.Time, Bind_Param, Ada.Calendar.Clock, "Time"); procedure Test_Bind_Param_Unbounded_String is new Test_Bind_Param_T (Unbounded_String, Bind_Param, To_Unbounded_String ("0123456789ABCDEF"), "Unbounded_String"); package Caller is new Util.Test_Caller (Test, "ADO.Parameters"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test ADO.Parameters.Expand", Test_Expand_Sql'Access); Caller.Add_Test (Suite, "Test ADO.Parameters.Expand (invalid params)", Test_Expand_Error'Access); Caller.Add_Test (Suite, "Test ADO.Parameters.Expand (perf)", Test_Expand_Perf'Access); Caller.Add_Test (Suite, "Test ADO.Parameters.Add_Param (Boolean)", Test_Add_Param_Boolean'Access); Caller.Add_Test (Suite, "Test ADO.Parameters.Add_Param (Integer)", Test_Add_Param_Integer'Access); Caller.Add_Test (Suite, "Test ADO.Parameters.Add_Param (Long_Long_Integer)", Test_Add_Param_Long_Long_Integer'Access); Caller.Add_Test (Suite, "Test ADO.Parameters.Add_Param (Identifier)", Test_Add_Param_Identifier'Access); Caller.Add_Test (Suite, "Test ADO.Parameters.Add_Param (Calendar)", Test_Add_Param_Calendar'Access); Caller.Add_Test (Suite, "Test ADO.Parameters.Add_Param (String)", Test_Add_Param_String'Access); Caller.Add_Test (Suite, "Test ADO.Parameters.Add_Param (Unbounded_String)", Test_Add_Param_Unbounded_String'Access); Caller.Add_Test (Suite, "Test ADO.Parameters.Bind_Param (Boolean)", Test_Bind_Param_Boolean'Access); Caller.Add_Test (Suite, "Test ADO.Parameters.Bind_Param (Integer)", Test_Bind_Param_Integer'Access); Caller.Add_Test (Suite, "Test ADO.Parameters.Bind_Param (Long_Long_Integer)", Test_Bind_Param_Long_Long_Integer'Access); Caller.Add_Test (Suite, "Test ADO.Parameters.Bind_Param (Identifier)", Test_Bind_Param_Identifier'Access); Caller.Add_Test (Suite, "Test ADO.Parameters.Bind_Param (Calendar)", Test_Bind_Param_Calendar'Access); Caller.Add_Test (Suite, "Test ADO.Parameters.Bind_Param (String)", Test_Bind_Param_String'Access); Caller.Add_Test (Suite, "Test ADO.Parameters.Bind_Param (Unbounded_String)", Test_Bind_Param_Unbounded_String'Access); Caller.Add_Test (Suite, "Test ADO.Parameters.Bind_Param (Entity_Type)", Test_Bind_Param_Entity_Type'Access); Caller.Add_Test (Suite, "Test ADO.Parameters.Expand (cache expander)", Test_Expand_With_Expander'Access); end Add_Tests; -- ------------------------------ -- Check if the string is a reserved keyword. -- ------------------------------ overriding function Is_Reserved (D : in Dialect; Name : in String) return Boolean is pragma Unreferenced (D, Name); begin return False; end Is_Reserved; -- ------------------------------ -- Test expand SQL with parameters. -- ------------------------------ procedure Test_Expand_Sql (T : in out Test) is SQL : ADO.Parameters.List; D : aliased Dialect; procedure Check (Pattern : in String; Expect : in String); procedure Check (Pattern : in String; Expect : in String) is Result : constant String := SQL.Expand (Pattern); begin Assert_Equals (T, Expect, Result, "Invalid SQL expansion"); end Check; begin SQL.Set_Dialect (D'Unchecked_Access); SQL.Bind_Param (1, "select '"); SQL.Bind_Param (2, "from"); SQL.Bind_Param ("user_id", String '("23")); SQL.Bind_Param ("object_23_identifier", Integer (44)); SQL.Bind_Param ("bool", True); SQL.Bind_Param (6, False); SQL.Bind_Param ("_date", Ada.Calendar.Clock); SQL.Bind_Null_Param ("_null"); Check ("?", "'select '''"); Check (":2", "'from'"); Check (":6", "0"); Check (":user_id", "'23'"); Check (":bool", "1"); Check (":_null", "NULL"); Check ("select :1 :2 :3 :4 :5 :6", "select 'select ''' 'from' '23' 44 1 0"); Check ("select ? ? ? ? ? ?", "select 'select ''' 'from' '23' 44 1 0"); Check ("select ? :2 :user_id :object_23_identifier :bool :6", "select 'select ''' 'from' '23' 44 1 0"); end Test_Expand_Sql; -- ------------------------------ -- Test expand with invalid parameters. -- ------------------------------ procedure Test_Expand_Error (T : in out Test) is SQL : ADO.Parameters.List; procedure Check (Pattern : in String; Expect : in String); procedure Check (Pattern : in String; Expect : in String) is Result : constant String := SQL.Expand (Pattern); begin Assert_Equals (T, Expect, Result, "Invalid SQL expansion"); end Check; begin Check (":<", "<"); Check (":234", ""); Check (":name", ""); Check ("select :", "select :"); end Test_Expand_Error; -- ------------------------------ -- Test expand performance. -- ------------------------------ procedure Test_Expand_Perf (T : in out Test) is pragma Unreferenced (T); SQL : ADO.Parameters.List; D : aliased Dialect; begin SQL.Set_Dialect (D'Unchecked_Access); declare T : Util.Measures.Stamp; begin for I in 1 .. 1_000 loop SQL.Bind_Param (I, I); end loop; Util.Measures.Report (T, "Bind_Param (1000 calls)"); end; declare B : constant Unbounded_String := To_Unbounded_String ("select t.a, t.b, t.c, t.d, t.e, t.f " & "from T where t.b = 23"); T : Util.Measures.Stamp; begin for I in 1 .. 1_000 loop declare S : constant String := To_String (B); pragma Unreferenced (S); begin null; end; end loop; Util.Measures.Report (T, "Expand reference To_String"); end; declare T : Util.Measures.Stamp; begin for I in 1 .. 1_000 loop declare S : constant String := SQL.Expand ("select t.a, t.b, t.c, t.d, t.e, t.f " & "from T where t.b = 23"); pragma Unreferenced (S); begin null; end; end loop; Util.Measures.Report (T, "Expand (1000 calls with 0 parameter)"); end; declare T : Util.Measures.Stamp; begin for I in 1 .. 1_000 loop declare S : constant String := SQL.Expand ("select t.a, t.b, t.c, t.d, t.e, t.f " & "from T where t.b = :10"); pragma Unreferenced (S); begin null; end; end loop; Util.Measures.Report (T, "Expand (1000 calls with 1 parameter)"); end; declare T : Util.Measures.Stamp; begin for I in 1 .. 1_000 loop declare S : constant String := SQL.Expand (":10 :20 :30 :40 :50 :60 :70 :80 :90 :100"); pragma Unreferenced (S); begin null; end; end loop; Util.Measures.Report (T, "Expand (1000 calls with 10 parameters)"); end; end Test_Expand_Perf; -- ------------------------------ -- Test expand with cache expander. -- ------------------------------ procedure Test_Expand_With_Expander (T : in out Test) is procedure Check (Content : in String; Expect : in String); SQL : ADO.Parameters.List; D : aliased Dialect; C : aliased ADO.Caches.Cache_Manager; M : access Int_Cache.Cache_Type := new Int_Cache.Cache_Type; P : access Int_Cache.Cache_Type := new Int_Cache.Cache_Type; procedure Check (Content : in String; Expect : in String) is S : constant String := SQL.Expand (Content); begin Util.Tests.Assert_Equals (T, Expect, S, "Invalid expand for SQL '" & Content & "'"); end Check; begin C.Add_Cache ("test-group", M.all'Access); C.Add_Cache ("G2", P.all'Access); SQL.Expander := C'Unchecked_Access; M.Insert ("value-1", 123); M.Insert ("2", 2); M.Insert ("a name", 10); P.Insert ("1", 10); P.Insert ("a", 0); P.Insert ("c", 1); SQL.Set_Dialect (D'Unchecked_Access); Check ("$test-group[2]", "2"); Check ("$test-group[a name]", "10"); Check ("SELECT * FROM user WHERE id = $test-group[2]+$test-group[value-1]", "SELECT * FROM user WHERE id = 2+123"); Check ("SELECT * FROM user WHERE id = $G2[a]+$test-group[value-1]", "SELECT * FROM user WHERE id = 0+123"); P.Insert ("a", 1, True); Check ("SELECT * FROM user WHERE id = $G2[a]+$test-group[value-1]", "SELECT * FROM user WHERE id = 1+123"); end Test_Expand_With_Expander; end ADO.Parameters.Tests;
----------------------------------------------------------------------- -- ado-parameters-tests -- Test query parameters and SQL expansion -- Copyright (C) 2011, 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.Measures; with ADO.Caches.Discrete; with ADO.Caches; package body ADO.Parameters.Tests is use Util.Tests; package Int_Cache is new ADO.Caches.Discrete (Element_Type => Integer); type Dialect is new ADO.Drivers.Dialects.Dialect with null record; -- Check if the string is a reserved keyword. overriding function Is_Reserved (D : in Dialect; Name : in String) return Boolean; -- Test the Add_Param operation for various types. generic type T (<>) is private; with procedure Add_Param (L : in out ADO.Parameters.Abstract_List; V : in T) is <>; Value : T; Name : String; procedure Test_Add_Param_T (Tst : in out Test); -- Test the Bind_Param operation for various types. generic type T (<>) is private; with procedure Bind_Param (L : in out ADO.Parameters.Abstract_List; N : in String; V : in T) is <>; Value : T; Name : String; procedure Test_Bind_Param_T (Tst : in out Test); -- Test the Add_Param operation for various types. procedure Test_Add_Param_T (Tst : in out Test) is Count : constant Positive := 100; SQL : ADO.Parameters.List; S : Util.Measures.Stamp; begin for I in 1 .. Count loop Add_Param (ADO.Parameters.Abstract_List (SQL), Value); end loop; Util.Measures.Report (S, "Add_Param " & Name & "(" & Positive'Image (Count) & " calls)"); Util.Tests.Assert_Equals (Tst, Count, SQL.Length, "Invalid param list for " & Name); end Test_Add_Param_T; -- Test the Bind_Param operation for various types. procedure Test_Bind_Param_T (Tst : in out Test) is Count : constant Positive := 100; SQL : ADO.Parameters.List; S : Util.Measures.Stamp; begin for I in 1 .. Count loop Bind_Param (ADO.Parameters.Abstract_List (SQL), "a_parameter_name", Value); end loop; Util.Measures.Report (S, "Bind_Param " & Name & "(" & Positive'Image (Count) & " calls)"); Util.Tests.Assert_Equals (Tst, 1, SQL.Length, "Invalid param list for " & Name); end Test_Bind_Param_T; procedure Test_Add_Param_Integer is new Test_Add_Param_T (Integer, Add_Param, 10, "Integer"); procedure Test_Add_Param_Long_Long_Integer is new Test_Add_Param_T (Long_Long_Integer, Add_Param, 10_000_000_000_000, "Long_Long_Integer"); procedure Test_Add_Param_Identifier is new Test_Add_Param_T (Identifier, Add_Param, 100, "Identifier"); procedure Test_Add_Param_Boolean is new Test_Add_Param_T (Boolean, Add_Param, False, "Boolean"); procedure Test_Add_Param_String is new Test_Add_Param_T (String, Add_Param, "0123456789ABCDEF", "String"); procedure Test_Add_Param_Calendar is new Test_Add_Param_T (Ada.Calendar.Time, Add_Param, Ada.Calendar.Clock, "Time"); procedure Test_Add_Param_Unbounded_String is new Test_Add_Param_T (Unbounded_String, Add_Param, To_Unbounded_String ("0123456789ABCDEF"), "Unbounded_String"); procedure Test_Bind_Param_Integer is new Test_Bind_Param_T (Integer, Bind_Param, 10, "Integer"); procedure Test_Bind_Param_Long_Long_Integer is new Test_Bind_Param_T (Long_Long_Integer, Bind_Param, 10_000_000_000_000, "Long_Long_Integer"); procedure Test_Bind_Param_Identifier is new Test_Bind_Param_T (Identifier, Bind_Param, 100, "Identifier"); procedure Test_Bind_Param_Entity_Type is new Test_Bind_Param_T (Entity_Type, Bind_Param, 100, "Entity_Type"); procedure Test_Bind_Param_Boolean is new Test_Bind_Param_T (Boolean, Bind_Param, False, "Boolean"); procedure Test_Bind_Param_String is new Test_Bind_Param_T (String, Bind_Param, "0123456789ABCDEF", "String"); procedure Test_Bind_Param_Calendar is new Test_Bind_Param_T (Ada.Calendar.Time, Bind_Param, Ada.Calendar.Clock, "Time"); procedure Test_Bind_Param_Unbounded_String is new Test_Bind_Param_T (Unbounded_String, Bind_Param, To_Unbounded_String ("0123456789ABCDEF"), "Unbounded_String"); package Caller is new Util.Test_Caller (Test, "ADO.Parameters"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test ADO.Parameters.Expand", Test_Expand_Sql'Access); Caller.Add_Test (Suite, "Test ADO.Parameters.Expand (invalid params)", Test_Expand_Error'Access); Caller.Add_Test (Suite, "Test ADO.Parameters.Expand (perf)", Test_Expand_Perf'Access); Caller.Add_Test (Suite, "Test ADO.Parameters.Add_Param (Boolean)", Test_Add_Param_Boolean'Access); Caller.Add_Test (Suite, "Test ADO.Parameters.Add_Param (Integer)", Test_Add_Param_Integer'Access); Caller.Add_Test (Suite, "Test ADO.Parameters.Add_Param (Long_Long_Integer)", Test_Add_Param_Long_Long_Integer'Access); Caller.Add_Test (Suite, "Test ADO.Parameters.Add_Param (Identifier)", Test_Add_Param_Identifier'Access); Caller.Add_Test (Suite, "Test ADO.Parameters.Add_Param (Calendar)", Test_Add_Param_Calendar'Access); Caller.Add_Test (Suite, "Test ADO.Parameters.Add_Param (String)", Test_Add_Param_String'Access); Caller.Add_Test (Suite, "Test ADO.Parameters.Add_Param (Unbounded_String)", Test_Add_Param_Unbounded_String'Access); Caller.Add_Test (Suite, "Test ADO.Parameters.Bind_Param (Boolean)", Test_Bind_Param_Boolean'Access); Caller.Add_Test (Suite, "Test ADO.Parameters.Bind_Param (Integer)", Test_Bind_Param_Integer'Access); Caller.Add_Test (Suite, "Test ADO.Parameters.Bind_Param (Long_Long_Integer)", Test_Bind_Param_Long_Long_Integer'Access); Caller.Add_Test (Suite, "Test ADO.Parameters.Bind_Param (Identifier)", Test_Bind_Param_Identifier'Access); Caller.Add_Test (Suite, "Test ADO.Parameters.Bind_Param (Calendar)", Test_Bind_Param_Calendar'Access); Caller.Add_Test (Suite, "Test ADO.Parameters.Bind_Param (String)", Test_Bind_Param_String'Access); Caller.Add_Test (Suite, "Test ADO.Parameters.Bind_Param (Unbounded_String)", Test_Bind_Param_Unbounded_String'Access); Caller.Add_Test (Suite, "Test ADO.Parameters.Bind_Param (Entity_Type)", Test_Bind_Param_Entity_Type'Access); Caller.Add_Test (Suite, "Test ADO.Parameters.Expand (cache expander)", Test_Expand_With_Expander'Access); end Add_Tests; -- ------------------------------ -- Check if the string is a reserved keyword. -- ------------------------------ overriding function Is_Reserved (D : in Dialect; Name : in String) return Boolean is pragma Unreferenced (D, Name); begin return False; end Is_Reserved; -- ------------------------------ -- Test expand SQL with parameters. -- ------------------------------ procedure Test_Expand_Sql (T : in out Test) is SQL : ADO.Parameters.List; D : aliased Dialect; procedure Check (Pattern : in String; Expect : in String); procedure Check (Pattern : in String; Expect : in String) is Result : constant String := SQL.Expand (Pattern); begin Assert_Equals (T, Expect, Result, "Invalid SQL expansion"); end Check; begin SQL.Set_Dialect (D'Unchecked_Access); SQL.Bind_Param (1, "select '"); SQL.Bind_Param (2, "from"); SQL.Bind_Param ("user_id", String '("23")); SQL.Bind_Param ("object_23_identifier", Integer (44)); SQL.Bind_Param ("bool", True); SQL.Bind_Param (6, False); SQL.Bind_Param ("_date", Ada.Calendar.Clock); SQL.Bind_Null_Param ("_null"); Check ("?", "'select '''"); Check (":2", "'from'"); Check (":6", "0"); Check (":user_id", "'23'"); Check (":bool", "1"); Check (":_null", "NULL"); Check ("select :1 :2 :3 :4 :5 :6", "select 'select ''' 'from' '23' 44 1 0"); Check ("select ? ? ? ? ? ?", "select 'select ''' 'from' '23' 44 1 0"); Check ("select ? :2 :user_id :object_23_identifier :bool :6", "select 'select ''' 'from' '23' 44 1 0"); Check ("select \:1 \:2 \:3 \:4 \:5 \:6", "select :1 :2 :3 :4 :5 :6"); end Test_Expand_Sql; -- ------------------------------ -- Test expand with invalid parameters. -- ------------------------------ procedure Test_Expand_Error (T : in out Test) is SQL : ADO.Parameters.List; procedure Check (Pattern : in String; Expect : in String); procedure Check (Pattern : in String; Expect : in String) is Result : constant String := SQL.Expand (Pattern); begin Assert_Equals (T, Expect, Result, "Invalid SQL expansion"); end Check; begin Check (":<", "<"); Check (":234", ""); Check (":name", ""); Check ("select :", "select :"); end Test_Expand_Error; -- ------------------------------ -- Test expand performance. -- ------------------------------ procedure Test_Expand_Perf (T : in out Test) is pragma Unreferenced (T); SQL : ADO.Parameters.List; D : aliased Dialect; begin SQL.Set_Dialect (D'Unchecked_Access); declare T : Util.Measures.Stamp; begin for I in 1 .. 1_000 loop SQL.Bind_Param (I, I); end loop; Util.Measures.Report (T, "Bind_Param (1000 calls)"); end; declare B : constant Unbounded_String := To_Unbounded_String ("select t.a, t.b, t.c, t.d, t.e, t.f " & "from T where t.b = 23"); T : Util.Measures.Stamp; begin for I in 1 .. 1_000 loop declare S : constant String := To_String (B); pragma Unreferenced (S); begin null; end; end loop; Util.Measures.Report (T, "Expand reference To_String"); end; declare T : Util.Measures.Stamp; begin for I in 1 .. 1_000 loop declare S : constant String := SQL.Expand ("select t.a, t.b, t.c, t.d, t.e, t.f " & "from T where t.b = 23"); pragma Unreferenced (S); begin null; end; end loop; Util.Measures.Report (T, "Expand (1000 calls with 0 parameter)"); end; declare T : Util.Measures.Stamp; begin for I in 1 .. 1_000 loop declare S : constant String := SQL.Expand ("select t.a, t.b, t.c, t.d, t.e, t.f " & "from T where t.b = :10"); pragma Unreferenced (S); begin null; end; end loop; Util.Measures.Report (T, "Expand (1000 calls with 1 parameter)"); end; declare T : Util.Measures.Stamp; begin for I in 1 .. 1_000 loop declare S : constant String := SQL.Expand (":10 :20 :30 :40 :50 :60 :70 :80 :90 :100"); pragma Unreferenced (S); begin null; end; end loop; Util.Measures.Report (T, "Expand (1000 calls with 10 parameters)"); end; end Test_Expand_Perf; -- ------------------------------ -- Test expand with cache expander. -- ------------------------------ procedure Test_Expand_With_Expander (T : in out Test) is procedure Check (Content : in String; Expect : in String); SQL : ADO.Parameters.List; D : aliased Dialect; C : aliased ADO.Caches.Cache_Manager; M : access Int_Cache.Cache_Type := new Int_Cache.Cache_Type; P : access Int_Cache.Cache_Type := new Int_Cache.Cache_Type; procedure Check (Content : in String; Expect : in String) is S : constant String := SQL.Expand (Content); begin Util.Tests.Assert_Equals (T, Expect, S, "Invalid expand for SQL '" & Content & "'"); end Check; begin C.Add_Cache ("test-group", M.all'Access); C.Add_Cache ("G2", P.all'Access); SQL.Expander := C'Unchecked_Access; M.Insert ("value-1", 123); M.Insert ("2", 2); M.Insert ("a name", 10); P.Insert ("1", 10); P.Insert ("a", 0); P.Insert ("c", 1); SQL.Set_Dialect (D'Unchecked_Access); Check ("$test-group[2]", "2"); Check ("$test-group[a name]", "10"); Check ("SELECT * FROM user WHERE id = $test-group[2]+$test-group[value-1]", "SELECT * FROM user WHERE id = 2+123"); Check ("SELECT * FROM user WHERE id = $G2[a]+$test-group[value-1]", "SELECT * FROM user WHERE id = 0+123"); P.Insert ("a", 1, True); Check ("SELECT * FROM user WHERE id = $G2[a]+$test-group[value-1]", "SELECT * FROM user WHERE id = 1+123"); Check ("SELECT * FROM user WHERE id = 2$G2[titi]+$test[value-1]1", "SELECT * FROM user WHERE id = 2+1"); end Test_Expand_With_Expander; end ADO.Parameters.Tests;
Add more tests for the SQL expander
Add more tests for the SQL expander
Ada
apache-2.0
stcarrez/ada-ado
89d75b6f1655e6af57a1e09b59a8dbd48a82de70
src/natools-web-escapes.ads
src/natools-web-escapes.ads
------------------------------------------------------------------------------ -- Copyright (c) 2015, Natacha Porté -- -- -- -- Permission to use, copy, modify, and distribute this software for any -- -- purpose with or without fee is hereby granted, provided that the above -- -- copyright notice and this permission notice appear in all copies. -- -- -- -- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES -- -- WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -- -- MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR -- -- ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -- -- WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -- -- ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF -- -- OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -- ------------------------------------------------------------------------------ ------------------------------------------------------------------------------ -- Natools.Web.Escapes provdes primitives for HTML-style escaping. -- ------------------------------------------------------------------------------ with Ada.Streams; with Natools.S_Expressions.Atom_Refs; package Natools.Web.Escapes is pragma Preelaborate; type Escape_Set is record Gt_Lt : Boolean := False; Amp : Boolean := False; Apos : Boolean := False; Quot : Boolean := False; end record; function Is_Empty (Set : in Escape_Set) return Boolean is (Set.Gt_Lt or Set.Amp or Set.Apos or Set.Quot); HTML_Attribute : constant Escape_Set; HTML_Body : constant Escape_Set; function Escaped_Length (Data : in S_Expressions.Atom; Set : in Escape_Set) return S_Expressions.Count; -- Return the number of octet in the escaped version of Data procedure Write (Output : in out Ada.Streams.Root_Stream_Type'Class; Data : in S_Expressions.Atom; Set : in Escape_Set); -- Escape octets from Data in Set, and write them into Output procedure Write (Output : in out Ada.Streams.Root_Stream_Type'Class; Text : in String; Set : in Escape_Set); -- Escape octets from Text in Set, and write them into Output function Escape (Data : in S_Expressions.Atom; Set : in Escape_Set) return S_Expressions.Atom; -- Escape Data and return it directly as an atom function Escape (Data : in S_Expressions.Atom; Set : in Escape_Set) return S_Expressions.Atom_Refs.Immutable_Reference; -- Escape Data and return it in a newly-created reference function Escape (Data : in S_Expressions.Atom_Refs.Immutable_Reference; Set : in Escape_Set) return S_Expressions.Atom_Refs.Immutable_Reference; -- Escape Data if needed, otherwise duplicate the reference private type Atom_Stream (Data : not null access S_Expressions.Atom) is new Ada.Streams.Root_Stream_Type with record Last : S_Expressions.Offset; end record; overriding procedure Read (Stream : in out Atom_Stream; Item : out Ada.Streams.Stream_Element_Array; Last : out Ada.Streams.Stream_Element_Offset); overriding procedure Write (Stream : in out Atom_Stream; Item : in Ada.Streams.Stream_Element_Array); type Count_Stream is new Ada.Streams.Root_Stream_Type with record Count : S_Expressions.Count := 0; end record; overriding procedure Read (Stream : in out Count_Stream; Item : out Ada.Streams.Stream_Element_Array; Last : out Ada.Streams.Stream_Element_Offset); overriding procedure Write (Stream : in out Count_Stream; Item : in Ada.Streams.Stream_Element_Array); type Octet_Set is array (S_Expressions.Octet) of Boolean; procedure Update_Set (Octets : in out Octet_Set; Set : in Escape_Set); -- Convert an escape set to an octet set HTML_Attribute : constant Escape_Set := (others => True); HTML_Body : constant Escape_Set := (Gt_Lt | Amp => True, others => False); end Natools.Web.Escapes;
------------------------------------------------------------------------------ -- Copyright (c) 2015, Natacha Porté -- -- -- -- Permission to use, copy, modify, and distribute this software for any -- -- purpose with or without fee is hereby granted, provided that the above -- -- copyright notice and this permission notice appear in all copies. -- -- -- -- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES -- -- WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -- -- MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR -- -- ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -- -- WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -- -- ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF -- -- OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -- ------------------------------------------------------------------------------ ------------------------------------------------------------------------------ -- Natools.Web.Escapes provdes primitives for HTML-style escaping. -- ------------------------------------------------------------------------------ with Ada.Streams; with Natools.S_Expressions.Atom_Refs; package Natools.Web.Escapes is pragma Preelaborate; type Escape_Set is record Gt_Lt : Boolean := False; Amp : Boolean := False; Apos : Boolean := False; Quot : Boolean := False; end record; function Is_Empty (Set : in Escape_Set) return Boolean is (Set.Gt_Lt or Set.Amp or Set.Apos or Set.Quot); HTML_Attribute : constant Escape_Set; HTML_Body : constant Escape_Set; function Escaped_Length (Data : in S_Expressions.Atom; Set : in Escape_Set) return S_Expressions.Count; -- Return the number of octet in the escaped version of Data procedure Write (Output : in out Ada.Streams.Root_Stream_Type'Class; Data : in S_Expressions.Atom; Set : in Escape_Set); -- Escape octets from Data in Set, and write them into Output procedure Write (Output : in out Ada.Streams.Root_Stream_Type'Class; Text : in String; Set : in Escape_Set); -- Escape octets from Text in Set, and write them into Output function Escape (Data : in S_Expressions.Atom; Set : in Escape_Set) return S_Expressions.Atom; -- Escape Data and return it directly as an atom function Escape (Data : in S_Expressions.Atom; Set : in Escape_Set) return S_Expressions.Atom_Refs.Immutable_Reference; -- Escape Data and return it in a newly-created reference function Escape (Data : in S_Expressions.Atom_Refs.Immutable_Reference; Set : in Escape_Set) return S_Expressions.Atom_Refs.Immutable_Reference; -- Escape Data if needed, otherwise duplicate the reference private type Atom_Stream (Data : not null access S_Expressions.Atom) is new Ada.Streams.Root_Stream_Type with record Last : S_Expressions.Offset; end record; overriding procedure Read (Stream : in out Atom_Stream; Item : out Ada.Streams.Stream_Element_Array; Last : out Ada.Streams.Stream_Element_Offset); overriding procedure Write (Stream : in out Atom_Stream; Item : in Ada.Streams.Stream_Element_Array); type Count_Stream is new Ada.Streams.Root_Stream_Type with record Count : S_Expressions.Count := 0; end record; overriding procedure Read (Stream : in out Count_Stream; Item : out Ada.Streams.Stream_Element_Array; Last : out Ada.Streams.Stream_Element_Offset); overriding procedure Write (Stream : in out Count_Stream; Item : in Ada.Streams.Stream_Element_Array); type Octet_Set is array (S_Expressions.Octet) of Boolean; procedure Update_Set (Octets : in out Octet_Set; Set : in Escape_Set); -- Convert an escape set to an octet set HTML_Attribute : constant Escape_Set := (Apos => False, others => True); HTML_Body : constant Escape_Set := (Gt_Lt | Amp => True, others => False); end Natools.Web.Escapes;
remove `apos` from HTML attribute escapes to conform to strict HTML 4.01
escapes: remove `apos` from HTML attribute escapes to conform to strict HTML 4.01
Ada
isc
faelys/natools-web,faelys/natools-web
c62a4c9b80faab50256a02640800d0f9702f5455
src/el-expressions.adb
src/el-expressions.adb
----------------------------------------------------------------------- -- EL.Expressions -- Expression Language -- Copyright (C) 2009, 2010 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with EL.Expressions.Nodes; with EL.Expressions.Parser; with Util.Concurrent.Counters; package body EL.Expressions is -- ------------------------------ -- Check whether the expression is a holds a constant value. -- ------------------------------ function Is_Constant (Expr : Expression'Class) return Boolean is begin return Expr.Node = null; end Is_Constant; -- ------------------------------ -- Get the value of the expression using the given expression context. -- ------------------------------ function Get_Value (Expr : Expression; Context : ELContext'Class) return Object is begin if Expr.Node = null then return Expr.Value; end if; return EL.Expressions.Nodes.Get_Value (Expr.Node.all, Context); end Get_Value; -- ------------------------------ -- Get the value of the expression using the given expression context. -- ------------------------------ function Get_Value (Expr : ValueExpression; Context : ELContext'Class) return Object is begin if Expr.Bean = null then if Expr.Node = null then return Expr.Value; else return EL.Expressions.Nodes.Get_Value (Expr.Node.all, Context); end if; end if; return To_Object (Expr.Bean); end Get_Value; -- ------------------------------ -- Set the value of the expression to the given object value. -- ------------------------------ procedure Set_Value (Expr : in out ValueExpression; Context : in ELContext'Class; Value : in Object) is begin Expr.Value := Value; end Set_Value; -- ------------------------------ -- Returns true if the expression is read-only. -- ------------------------------ function Is_Readonly (Expr : in ValueExpression) return Boolean is begin if Expr.Bean = null then return True; end if; return not (Expr.Bean.all in EL.Beans.Bean'Class); end Is_Readonly; -- ------------------------------ -- Parse an expression and return its representation ready for evaluation. -- ------------------------------ function Create_Expression (Expr : String; Context : ELContext'Class) return Expression is use EL.Expressions.Nodes; Result : Expression; Node : EL.Expressions.Nodes.ELNode_Access; begin EL.Expressions.Parser.Parse (Expr => Expr, Context => Context, Result => Node); if Node /= null then Result.Node := Node.all'Access; end if; return Result; end Create_Expression; -- ------------------------------ -- Reduce the expression by eliminating known variables and computing -- constant expressions. The result expression is either another -- expression or a computed constant value. -- ------------------------------ function Reduce_Expression (Expr : Expression; Context : ELContext'Class) return Expression is use EL.Expressions.Nodes; use Ada.Finalization; begin if Expr.Node = null then return Expr; end if; declare Result : constant Reduction := Expr.Node.Reduce (Context); begin return Expression '(Controlled with Node => Result.Node, Value => Result.Value); end; end Reduce_Expression; function Create_ValueExpression (Bean : access EL.Beans.Readonly_Bean'Class) return ValueExpression is Result : ValueExpression; begin Result.Bean := Bean; return Result; end Create_ValueExpression; function Create_ValueExpression (Bean : EL.Objects.Object) return ValueExpression is Result : ValueExpression; begin Result.Value := Bean; return Result; end Create_ValueExpression; -- ------------------------------ -- Parse an expression and return its representation ready for evaluation. -- ------------------------------ function Create_Expression (Expr : String; Context : ELContext'Class) return ValueExpression is Result : ValueExpression; Node : EL.Expressions.Nodes.ELNode_Access; begin EL.Expressions.Parser.Parse (Expr => Expr, Context => Context, Result => Node); Result.Node := Node.all'Access; return Result; end Create_Expression; overriding function Reduce_Expression (Expr : ValueExpression; Context : ELContext'Class) return ValueExpression is pragma Unreferenced (Context); begin return Expr; end Reduce_Expression; procedure Adjust (Object : in out Expression) is begin if Object.Node /= null then Util.Concurrent.Counters.Increment (Object.Node.Ref_Counter); end if; end Adjust; procedure Finalize (Object : in out Expression) is Node : EL.Expressions.Nodes.ELNode_Access; Is_Zero : Boolean; begin if Object.Node /= null then Node := Object.Node.all'Access; Util.Concurrent.Counters.Decrement (Node.Ref_Counter, Is_Zero); if Is_Zero then EL.Expressions.Nodes.Delete (Node); Object.Node := null; end if; end if; end Finalize; -- ------------------------------ -- Evaluate the method expression and return the object and method -- binding to execute the method. The result contains a pointer -- to the bean object and a method binding. The method binding -- contains the information to invoke the method -- (such as an access to the function or procedure). -- Raises the <b>Invalid_Method</b> exception if the method -- cannot be resolved. -- ------------------------------ function Get_Method_Info (Expr : Method_Expression; Context : ELContext'Class) return Method_Info is use EL.Expressions.Nodes; begin if Expr.Node = null then raise Invalid_Expression with "Method expression is empty"; end if; declare Node : constant ELValue_Access := ELValue'Class (Expr.Node.all)'Access; begin return Node.Get_Method_Info (Context); end; end Get_Method_Info; -- ------------------------------ -- Parse an expression and return its representation ready for evaluation. -- The context is used to resolve the functions. Variables will be -- resolved during evaluation of the expression. -- Raises <b>Invalid_Expression</b> if the expression is invalid. -- ------------------------------ overriding function Create_Expression (Expr : String; Context : EL.Contexts.ELContext'Class) return Method_Expression is use type EL.Expressions.Nodes.ELNode_Access; Result : Method_Expression; Node : EL.Expressions.Nodes.ELNode_Access; begin EL.Expressions.Parser.Parse (Expr => Expr, Context => Context, Result => Node); -- The root of the method expression must be an ELValue node. if Node = null or else not (Node.all in Nodes.ELValue'Class) then raise Invalid_Expression with "Expression is not a method expression"; end if; Result.Node := Node.all'Access; return Result; end Create_Expression; -- ------------------------------ -- Reduce the expression by eliminating known variables and computing -- constant expressions. The result expression is either another -- expression or a computed constant value. -- ------------------------------ overriding function Reduce_Expression (Expr : Method_Expression; Context : EL.Contexts.ELContext'Class) return Method_Expression is pragma Unreferenced (Context); begin return Expr; end Reduce_Expression; end EL.Expressions;
----------------------------------------------------------------------- -- EL.Expressions -- Expression Language -- Copyright (C) 2009, 2010 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with EL.Expressions.Nodes; with EL.Expressions.Parser; with Util.Concurrent.Counters; package body EL.Expressions is -- ------------------------------ -- Check whether the expression is a holds a constant value. -- ------------------------------ function Is_Constant (Expr : Expression'Class) return Boolean is begin return Expr.Node = null; end Is_Constant; -- ------------------------------ -- Get the value of the expression using the given expression context. -- ------------------------------ function Get_Value (Expr : Expression; Context : ELContext'Class) return Object is begin if Expr.Node = null then return Expr.Value; end if; return EL.Expressions.Nodes.Get_Value (Expr.Node.all, Context); end Get_Value; -- ------------------------------ -- Get the value of the expression using the given expression context. -- ------------------------------ function Get_Value (Expr : ValueExpression; Context : ELContext'Class) return Object is begin if Expr.Bean = null then if Expr.Node = null then return Expr.Value; else return EL.Expressions.Nodes.Get_Value (Expr.Node.all, Context); end if; end if; return To_Object (Expr.Bean); end Get_Value; -- ------------------------------ -- Set the value of the expression to the given object value. -- ------------------------------ procedure Set_Value (Expr : in out ValueExpression; Context : in ELContext'Class; Value : in Object) is begin Expr.Value := Value; end Set_Value; -- ------------------------------ -- Returns true if the expression is read-only. -- ------------------------------ function Is_Readonly (Expr : in ValueExpression) return Boolean is begin if Expr.Bean = null then return True; end if; return not (Expr.Bean.all in EL.Beans.Bean'Class); end Is_Readonly; -- ------------------------------ -- Parse an expression and return its representation ready for evaluation. -- ------------------------------ function Create_Expression (Expr : String; Context : ELContext'Class) return Expression is use EL.Expressions.Nodes; Result : Expression; Node : EL.Expressions.Nodes.ELNode_Access; begin EL.Expressions.Parser.Parse (Expr => Expr, Context => Context, Result => Node); if Node /= null then Result.Node := Node.all'Access; end if; return Result; end Create_Expression; -- ------------------------------ -- Reduce the expression by eliminating known variables and computing -- constant expressions. The result expression is either another -- expression or a computed constant value. -- ------------------------------ function Reduce_Expression (Expr : Expression; Context : ELContext'Class) return Expression is use EL.Expressions.Nodes; use Ada.Finalization; begin if Expr.Node = null then return Expr; end if; declare Result : constant Reduction := Expr.Node.Reduce (Context); begin return Expression '(Controlled with Node => Result.Node, Value => Result.Value); end; end Reduce_Expression; function Create_ValueExpression (Bean : access EL.Beans.Readonly_Bean'Class) return ValueExpression is Result : ValueExpression; begin Result.Bean := Bean; return Result; end Create_ValueExpression; function Create_ValueExpression (Bean : EL.Objects.Object) return ValueExpression is Result : ValueExpression; begin Result.Value := Bean; return Result; end Create_ValueExpression; -- ------------------------------ -- Parse an expression and return its representation ready for evaluation. -- ------------------------------ function Create_Expression (Expr : String; Context : ELContext'Class) return ValueExpression is Result : ValueExpression; Node : EL.Expressions.Nodes.ELNode_Access; begin EL.Expressions.Parser.Parse (Expr => Expr, Context => Context, Result => Node); Result.Node := Node.all'Access; return Result; end Create_Expression; overriding function Reduce_Expression (Expr : ValueExpression; Context : ELContext'Class) return ValueExpression is pragma Unreferenced (Context); begin return Expr; end Reduce_Expression; procedure Adjust (Object : in out Expression) is begin if Object.Node /= null then Util.Concurrent.Counters.Increment (Object.Node.Ref_Counter); end if; end Adjust; procedure Finalize (Object : in out Expression) is Node : EL.Expressions.Nodes.ELNode_Access; Is_Zero : Boolean; begin if Object.Node /= null then Node := Object.Node.all'Access; Util.Concurrent.Counters.Decrement (Node.Ref_Counter, Is_Zero); if Is_Zero then EL.Expressions.Nodes.Delete (Node); Object.Node := null; end if; end if; end Finalize; -- ------------------------------ -- Evaluate the method expression and return the object and method -- binding to execute the method. The result contains a pointer -- to the bean object and a method binding. The method binding -- contains the information to invoke the method -- (such as an access to the function or procedure). -- Raises the <b>Invalid_Method</b> exception if the method -- cannot be resolved. -- ------------------------------ function Get_Method_Info (Expr : Method_Expression; Context : ELContext'Class) return Method_Info is use EL.Expressions.Nodes; begin if Expr.Node = null then raise Invalid_Expression with "Method expression is empty"; end if; declare Node : constant ELValue_Access := ELValue'Class (Expr.Node.all)'Access; begin return Node.Get_Method_Info (Context); end; end Get_Method_Info; -- ------------------------------ -- Parse an expression and return its representation ready for evaluation. -- The context is used to resolve the functions. Variables will be -- resolved during evaluation of the expression. -- Raises <b>Invalid_Expression</b> if the expression is invalid. -- ------------------------------ overriding function Create_Expression (Expr : String; Context : EL.Contexts.ELContext'Class) return Method_Expression is use type EL.Expressions.Nodes.ELNode_Access; Result : Method_Expression; Node : EL.Expressions.Nodes.ELNode_Access; begin EL.Expressions.Parser.Parse (Expr => Expr, Context => Context, Result => Node); -- The root of the method expression must be an ELValue node. if Node = null or else not (Node.all in Nodes.ELValue'Class) then EL.Expressions.Nodes.Delete (Node); raise Invalid_Expression with "Expression is not a method expression"; end if; Result.Node := Node.all'Access; return Result; end Create_Expression; -- ------------------------------ -- Reduce the expression by eliminating known variables and computing -- constant expressions. The result expression is either another -- expression or a computed constant value. -- ------------------------------ overriding function Reduce_Expression (Expr : Method_Expression; Context : EL.Contexts.ELContext'Class) return Method_Expression is pragma Unreferenced (Context); begin return Expr; end Reduce_Expression; end EL.Expressions;
Fix memory leak if the method expression is a valid EL expression but not a method expression
Fix memory leak if the method expression is a valid EL expression but not a method expression
Ada
apache-2.0
stcarrez/ada-el
88c7b89a73e972b1971de247d8c264a259c67eff
src/asf-components-html-pages.adb
src/asf-components-html-pages.adb
----------------------------------------------------------------------- -- html-pages -- HTML Page Components -- 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.Strings; with ASF.Utils; -- The <b>Pages</b> package implements various components used when building an HTML page. -- package body ASF.Components.Html.Pages is BODY_ATTRIBUTE_NAMES : Util.Strings.String_Set.Set; HEAD_ATTRIBUTE_NAMES : Util.Strings.String_Set.Set; -- ------------------------------ -- Head Component -- ------------------------------ -- ------------------------------ -- Encode the HTML head element. -- ------------------------------ overriding procedure Encode_Begin (UI : in UIHead; Context : in out Contexts.Faces.Faces_Context'Class) is Writer : constant Response_Writer_Access := Context.Get_Response_Writer; begin Writer.Start_Element ("head"); UI.Render_Attributes (Context, HEAD_ATTRIBUTE_NAMES, Writer); end Encode_Begin; -- ------------------------------ -- Terminate the HTML head element. Before closing the head, generate the resource -- links that have been queued for the head generation. -- ------------------------------ overriding procedure Encode_End (UI : in UIHead; Context : in out Contexts.Faces.Faces_Context'Class) is pragma Unreferenced (UI); Writer : constant Response_Writer_Access := Context.Get_Response_Writer; begin Writer.Write_Scripts; Writer.End_Element ("head"); end Encode_End; -- ------------------------------ -- Encode the HTML body element. -- ------------------------------ overriding procedure Encode_Begin (UI : in UIBody; Context : in out Contexts.Faces.Faces_Context'Class) is Writer : constant Response_Writer_Access := Context.Get_Response_Writer; begin Writer.Start_Element ("body"); UI.Render_Attributes (Context, BODY_ATTRIBUTE_NAMES, Writer); end Encode_Begin; -- ------------------------------ -- Terminate the HTML body element. Before closing the body, generate the inclusion -- of differed resources (pending javascript, inclusion of javascript files) -- ------------------------------ overriding procedure Encode_End (UI : in UIBody; Context : in out Contexts.Faces.Faces_Context'Class) is pragma Unreferenced (UI); Writer : constant Response_Writer_Access := Context.Get_Response_Writer; begin Writer.Write_Scripts; Writer.End_Element ("body"); end Encode_End; begin Utils.Set_Head_Attributes (HEAD_ATTRIBUTE_NAMES); Utils.Set_Text_Attributes (BODY_ATTRIBUTE_NAMES); Utils.Set_Body_Attributes (BODY_ATTRIBUTE_NAMES); end ASF.Components.Html.Pages;
----------------------------------------------------------------------- -- html-pages -- HTML Page Components -- Copyright (C) 2011, 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Strings; with Util.Beans.Objects; with ASF.Utils; -- The <b>Pages</b> package implements various components used when building an HTML page. -- package body ASF.Components.Html.Pages is BODY_ATTRIBUTE_NAMES : Util.Strings.String_Set.Set; HEAD_ATTRIBUTE_NAMES : Util.Strings.String_Set.Set; -- ------------------------------ -- Head Component -- ------------------------------ -- ------------------------------ -- Encode the HTML head element. -- ------------------------------ overriding procedure Encode_Begin (UI : in UIHead; Context : in out Contexts.Faces.Faces_Context'Class) is Writer : constant Response_Writer_Access := Context.Get_Response_Writer; begin Writer.Start_Element ("head"); UI.Render_Attributes (Context, HEAD_ATTRIBUTE_NAMES, Writer); end Encode_Begin; -- ------------------------------ -- Terminate the HTML head element. Before closing the head, generate the resource -- links that have been queued for the head generation. -- ------------------------------ overriding procedure Encode_End (UI : in UIHead; Context : in out Contexts.Faces.Faces_Context'Class) is pragma Unreferenced (UI); Writer : constant Response_Writer_Access := Context.Get_Response_Writer; begin Writer.Write_Scripts; Writer.End_Element ("head"); end Encode_End; -- ------------------------------ -- Encode the HTML body element. -- ------------------------------ overriding procedure Encode_Begin (UI : in UIBody; Context : in out Contexts.Faces.Faces_Context'Class) is Writer : constant Response_Writer_Access := Context.Get_Response_Writer; begin Writer.Start_Element ("body"); UI.Render_Attributes (Context, BODY_ATTRIBUTE_NAMES, Writer); end Encode_Begin; -- ------------------------------ -- Terminate the HTML body element. Before closing the body, generate the inclusion -- of differed resources (pending javascript, inclusion of javascript files) -- ------------------------------ overriding procedure Encode_End (UI : in UIBody; Context : in out Contexts.Faces.Faces_Context'Class) is pragma Unreferenced (UI); Writer : constant Response_Writer_Access := Context.Get_Response_Writer; begin Writer.Write_Scripts; Writer.End_Element ("body"); end Encode_End; -- ------------------------------ -- Encode the DOCTYPE element. -- ------------------------------ overriding procedure Encode_Begin (UI : in UIDoctype; Context : in out Contexts.Faces.Faces_Context'Class) is Writer : constant Response_Writer_Access := Context.Get_Response_Writer; begin if UI.Is_Rendered (Context) then Writer.Write ("<!DOCTYPE "); Writer.Write (UI.Get_Attribute ("rootElement", Context, "")); declare Public : constant Util.Beans.Objects.Object := UI.Get_Attribute (Context, "public"); System : constant Util.Beans.Objects.Object := UI.Get_Attribute (Context, "system"); begin if not Util.Beans.Objects.Is_Null (Public) then Writer.Write (" PUBLIC """); Writer.Write (Public); Writer.Write ('"'); end if; if not Util.Beans.Objects.Is_Null (System) then Writer.Write (" """); Writer.Write (System); Writer.Write ('"'); end if; end; Writer.Write ('>'); end if; end Encode_Begin; begin Utils.Set_Head_Attributes (HEAD_ATTRIBUTE_NAMES); Utils.Set_Text_Attributes (BODY_ATTRIBUTE_NAMES); Utils.Set_Body_Attributes (BODY_ATTRIBUTE_NAMES); end ASF.Components.Html.Pages;
Implement the UIDoctype component with the <!DOCTYPE> generation according to the <h:doctype> JSF 2.2 standard
Implement the UIDoctype component with the <!DOCTYPE> generation according to the <h:doctype> JSF 2.2 standard
Ada
apache-2.0
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
7a0f888d7044f1ca3fcb581499e41b48670e1469
src/gl/implementation/gl-context.adb
src/gl/implementation/gl-context.adb
-- Copyright (c) 2013 Felix Krause <[email protected]> -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. with Interfaces.C.Strings; with GL.API; with GL.Enums.Getter; with GL.Errors; package body GL.Context is function Major_Version return Int is Result : aliased Int; begin API.Get_Integer (Enums.Getter.Major_Version, Result'Access); Raise_Exception_On_OpenGL_Error; return Result; end Major_Version; function Minor_Version return Int is Result : aliased Int; begin API.Get_Integer (Enums.Getter.Minor_Version, Result'Access); Raise_Exception_On_OpenGL_Error; return Result; end Minor_Version; function Version_String return String is begin return C.Strings.Value (API.Get_String (Enums.Getter.Version)); end Version_String; function Vendor return String is begin return C.Strings.Value (API.Get_String (Enums.Getter.Vendor)); end Vendor; function Renderer return String is begin return C.Strings.Value (API.Get_String (Enums.Getter.Renderer)); end Renderer; function Extensions return String_List is use Ada.Strings.Unbounded; use type Errors.Error_Code; Count : aliased Int; begin API.Get_Integer (Enums.Getter.Num_Extensions, Count'Access); Raise_Exception_On_OpenGL_Error; pragma Assert (API.Get_Error = Errors.No_Error); -- We are on OpenGL 3 return List : String_List (1 .. Positive (Count)) do for I in List'Range loop List (I) := To_Unbounded_String (C.Strings.Value (API.Get_String_I (Enums.Getter.Extensions, UInt (I - 1)))); end loop; end return; end Extensions; function Has_Extension (Name : String) return Boolean is use type Errors.Error_Code; Count : aliased Int; begin API.Get_Integer (Enums.Getter.Num_Extensions, Count'Access); Raise_Exception_On_OpenGL_Error; pragma Assert (API.Get_Error = Errors.No_Error); -- We are on OpenGL 3 for I in 1 .. Count loop declare Extension : constant String := C.Strings.Value (API.Get_String_I (Enums.Getter.Extensions, UInt (I - 1))); begin if Extension = Name then return True; end if; end; end loop; return False; end Has_Extension; function Primary_Shading_Language_Version return String is Result : constant String := C.Strings.Value (API.Get_String (Enums.Getter.Shading_Language_Version)); begin Raise_Exception_On_OpenGL_Error; return Result; end Primary_Shading_Language_Version; function Supported_Shading_Language_Versions return String_List is use Ada.Strings.Unbounded; use type Errors.Error_Code; Count : aliased Int; begin API.Get_Integer (Enums.Getter.Num_Shading_Language_Versions, Count'Access); if API.Get_Error = Errors.Invalid_Enum then raise Feature_Not_Supported_Exception; end if; return List : String_List (1 .. Positive (Count)) do for I in List'Range loop List (I) := To_Unbounded_String (C.Strings.Value (API.Get_String_I ( Enums.Getter.Shading_Language_Version, UInt (I - 1)))); end loop; end return; end Supported_Shading_Language_Versions; function Supports_Shading_Language_Version (Name : String) return Boolean is Count : aliased Int; begin API.Get_Integer (Enums.Getter.Num_Shading_Language_Versions, Count'Access); Raise_Exception_On_OpenGL_Error; for I in 1 .. Count loop if C.Strings.Value (API.Get_String_I (Enums.Getter.Shading_Language_Version, UInt (I - 1))) = Name then return True; end if; end loop; return False; end Supports_Shading_Language_Version; end GL.Context;
-- Copyright (c) 2013 Felix Krause <[email protected]> -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. with Interfaces.C.Strings; with GL.API; with GL.Enums.Getter; with GL.Errors; package body GL.Context is function Extension (Index : Positive) return String is (C.Strings.Value (API.Get_String_I (Enums.Getter.Extensions, UInt (Index - 1)))); function GLSL_Version (Index : Positive) return String is (C.Strings.Value (API.Get_String_I (Enums.Getter.Shading_Language_Version, UInt (Index - 1)))); function Major_Version return Int is Result : aliased Int; begin API.Get_Integer (Enums.Getter.Major_Version, Result'Access); Raise_Exception_On_OpenGL_Error; return Result; end Major_Version; function Minor_Version return Int is Result : aliased Int; begin API.Get_Integer (Enums.Getter.Minor_Version, Result'Access); Raise_Exception_On_OpenGL_Error; return Result; end Minor_Version; function Version_String return String is begin return C.Strings.Value (API.Get_String (Enums.Getter.Version)); end Version_String; function Vendor return String is begin return C.Strings.Value (API.Get_String (Enums.Getter.Vendor)); end Vendor; function Renderer return String is begin return C.Strings.Value (API.Get_String (Enums.Getter.Renderer)); end Renderer; function Extensions return String_List is use Ada.Strings.Unbounded; use type Errors.Error_Code; Count : aliased Int; begin API.Get_Integer (Enums.Getter.Num_Extensions, Count'Access); Raise_Exception_On_OpenGL_Error; pragma Assert (API.Get_Error = Errors.No_Error); -- We are on OpenGL 3 return List : String_List (1 .. Positive (Count)) do for I in List'Range loop List (I) := To_Unbounded_String (Extension (I)); end loop; end return; end Extensions; function Has_Extension (Name : String) return Boolean is use type Errors.Error_Code; Count : aliased Int; begin API.Get_Integer (Enums.Getter.Num_Extensions, Count'Access); Raise_Exception_On_OpenGL_Error; pragma Assert (API.Get_Error = Errors.No_Error); -- We are on OpenGL 3 return (for some I in 1 .. Positive (Count) => Extension (I) = Name); end Has_Extension; function Primary_Shading_Language_Version return String is Result : constant String := C.Strings.Value (API.Get_String (Enums.Getter.Shading_Language_Version)); begin Raise_Exception_On_OpenGL_Error; return Result; end Primary_Shading_Language_Version; function Supported_Shading_Language_Versions return String_List is use Ada.Strings.Unbounded; use type Errors.Error_Code; Count : aliased Int; begin API.Get_Integer (Enums.Getter.Num_Shading_Language_Versions, Count'Access); if API.Get_Error = Errors.Invalid_Enum then raise Feature_Not_Supported_Exception; end if; return List : String_List (1 .. Positive (Count)) do for I in List'Range loop List (I) := To_Unbounded_String (GLSL_Version (I)); end loop; end return; end Supported_Shading_Language_Versions; function Supports_Shading_Language_Version (Name : String) return Boolean is Count : aliased Int; begin API.Get_Integer (Enums.Getter.Num_Shading_Language_Versions, Count'Access); Raise_Exception_On_OpenGL_Error; return (for some I in 1 .. Positive (Count) => GLSL_Version (I) = Name); end Supports_Shading_Language_Version; end GL.Context;
Use Ada 2012 quantified expressions in GL.Context
gl: Use Ada 2012 quantified expressions in GL.Context Signed-off-by: onox <[email protected]>
Ada
apache-2.0
onox/orka
276ff3c3fc9c18498eef044894ef35c3112b1725
src/security-oauth-file_registry.adb
src/security-oauth-file_registry.adb
----------------------------------------------------------------------- -- security-oauth-file_registry -- File Based Application and Realm -- 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.Strings; with Util.Encoders.HMAC.SHA1; package body Security.OAuth.File_Registry is -- ------------------------------ -- Get the principal name. -- ------------------------------ overriding function Get_Name (From : in File_Principal) return String is begin return To_String (From.Name); end Get_Name; -- ------------------------------ -- Find the application that correspond to the given client id. -- The <tt>Invalid_Application</tt> exception should be raised if there is no such application. -- ------------------------------ overriding function Find_Application (Realm : in File_Application_Manager; Client_Id : in String) return Servers.Application'Class is Pos : constant Application_Maps.Cursor := Realm.Applications.Find (Client_Id); begin if not Application_Maps.Has_Element (Pos) then raise Servers.Invalid_Application; end if; return Application_Maps.Element (Pos); end Find_Application; -- ------------------------------ -- Add the application to the application repository. -- ------------------------------ procedure Add_Application (Realm : in out File_Application_Manager; App : in Servers.Application) is begin Realm.Applications.Include (App.Get_Application_Identifier, App); end Add_Application; -- ------------------------------ -- Authenticate the token and find the associated authentication principal. -- The access token has been verified and the token represents the identifier -- of the Tuple (client_id, user, session) that describes the authentication. -- The <tt>Authenticate</tt> procedure should look in its database (internal -- or external) to find the authentication principal that was granted for -- the token Tuple. When the token was not found (because it was revoked), -- the procedure should return a null principal. If the authentication -- principal can be cached, the <tt>Cacheable</tt> value should be set. -- In that case, the access token and authentication principal are inserted -- in a cache. -- ------------------------------ overriding procedure Authenticate (Realm : in out File_Realm_Manager; Token : in String; Auth : out Principal_Access; Cacheable : out Boolean) is Pos : constant Token_Maps.Cursor := Realm.Tokens.Find (Token); begin if Token_Maps.Has_Element (Pos) then Auth := Token_Maps.Element (Pos).all'Access; else Auth := null; end if; Cacheable := True; end Authenticate; -- ------------------------------ -- Create an auth token string that identifies the given principal. The returned -- token will be used by <tt>Authenticate</tt> to retrieve back the principal. The -- returned token does not need to be signed. It will be inserted in the public part -- of the returned access token. -- ------------------------------ overriding function Authorize (Realm : in File_Realm_Manager; App : in Servers.Application'Class; Scope : in String; Auth : in Principal_Access) return String is begin return To_String (File_Principal (Auth.all).Token); end Authorize; overriding procedure Verify (Realm : in out File_Realm_Manager; Username : in String; Password : in String; Auth : out Principal_Access) is Result : File_Principal_Access; Pos : constant User_Maps.Cursor := Realm.Users.Find (Username); begin if not User_Maps.Has_Element (Pos) then Auth := null; return; end if; -- Verify that the crypt password with the recorded salt are the same. declare Expect : constant String := User_Maps.Element (Pos); Hash : constant String := Realm.Crypt_Password (Expect, Password); begin if Hash /= Expect then Auth := null; return; end if; end; -- Generate a random token and make the principal to record it. declare Token : constant String := Realm.Random.Generate (Realm.Token_Bits); begin Result := new File_Principal; Ada.Strings.Unbounded.Append (Result.Token, Token); Ada.Strings.Unbounded.Append (Result.Name, Username); Realm.Tokens.Insert (Token, Result); end; Auth := Result.all'Access; end Verify; overriding procedure Verify (Realm : in out File_Realm_Manager; Token : in String; Auth : out Principal_Access) is begin null; end Verify; overriding procedure Revoke (Realm : in out File_Realm_Manager; Auth : in Principal_Access) is begin if Auth /= null and then Auth.all in File_Principal'Class then Realm.Tokens.Delete (To_String (File_Principal (Auth.all).Token)); end if; end Revoke; -- ------------------------------ -- Crypt the password using the given salt and return the string composed with -- the salt in clear text and the crypted password. -- ------------------------------ function Crypt_Password (Realm : in File_Realm_Manager; Salt : in String; Password : in String) return String is Pos : Natural := Util.Strings.Index (Salt, ' '); begin if Pos = 0 then Pos := Salt'Last; else Pos := Pos - 1; end if; return Salt (Salt'First .. Pos) & " " & Util.Encoders.HMAC.SHA1.Sign_Base64 (Key => Salt (Salt'First .. Pos), Data => Password, URL => True); end Crypt_Password; -- ------------------------------ -- Add a username with the associated password. -- ------------------------------ procedure Add_User (Realm : in out File_Realm_Manager; Username : in String; Password : in String) is Salt : constant String := Realm.Random.Generate (Realm.Token_Bits); begin Realm.Users.Include (Username, Realm.Crypt_Password (Salt, Password)); end Add_User; end Security.OAuth.File_Registry;
----------------------------------------------------------------------- -- security-oauth-file_registry -- File Based Application and Realm -- Copyright (C) 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Encoders.HMAC.SHA1; package body Security.OAuth.File_Registry is -- ------------------------------ -- Get the principal name. -- ------------------------------ overriding function Get_Name (From : in File_Principal) return String is begin return To_String (From.Name); end Get_Name; -- ------------------------------ -- Find the application that correspond to the given client id. -- The <tt>Invalid_Application</tt> exception should be raised if there is no such application. -- ------------------------------ overriding function Find_Application (Realm : in File_Application_Manager; Client_Id : in String) return Servers.Application'Class is Pos : constant Application_Maps.Cursor := Realm.Applications.Find (Client_Id); begin if not Application_Maps.Has_Element (Pos) then raise Servers.Invalid_Application; end if; return Application_Maps.Element (Pos); end Find_Application; -- ------------------------------ -- Add the application to the application repository. -- ------------------------------ procedure Add_Application (Realm : in out File_Application_Manager; App : in Servers.Application) is begin Realm.Applications.Include (App.Get_Application_Identifier, App); end Add_Application; -- ------------------------------ -- Authenticate the token and find the associated authentication principal. -- The access token has been verified and the token represents the identifier -- of the Tuple (client_id, user, session) that describes the authentication. -- The <tt>Authenticate</tt> procedure should look in its database (internal -- or external) to find the authentication principal that was granted for -- the token Tuple. When the token was not found (because it was revoked), -- the procedure should return a null principal. If the authentication -- principal can be cached, the <tt>Cacheable</tt> value should be set. -- In that case, the access token and authentication principal are inserted -- in a cache. -- ------------------------------ overriding procedure Authenticate (Realm : in out File_Realm_Manager; Token : in String; Auth : out Principal_Access; Cacheable : out Boolean) is Pos : constant Token_Maps.Cursor := Realm.Tokens.Find (Token); begin if Token_Maps.Has_Element (Pos) then Auth := Token_Maps.Element (Pos).all'Access; else Auth := null; end if; Cacheable := True; end Authenticate; -- ------------------------------ -- Create an auth token string that identifies the given principal. The returned -- token will be used by <tt>Authenticate</tt> to retrieve back the principal. The -- returned token does not need to be signed. It will be inserted in the public part -- of the returned access token. -- ------------------------------ overriding function Authorize (Realm : in File_Realm_Manager; App : in Servers.Application'Class; Scope : in String; Auth : in Principal_Access) return String is begin return To_String (File_Principal (Auth.all).Token); end Authorize; overriding procedure Verify (Realm : in out File_Realm_Manager; Username : in String; Password : in String; Auth : out Principal_Access) is Result : File_Principal_Access; Pos : constant User_Maps.Cursor := Realm.Users.Find (Username); begin if not User_Maps.Has_Element (Pos) then Auth := null; return; end if; -- Verify that the crypt password with the recorded salt are the same. declare Expect : constant String := User_Maps.Element (Pos); Hash : constant String := Realm.Crypt_Password (Expect, Password); begin if Hash /= Expect then Auth := null; return; end if; end; -- Generate a random token and make the principal to record it. declare Token : constant String := Realm.Random.Generate (Realm.Token_Bits); begin Result := new File_Principal; Ada.Strings.Unbounded.Append (Result.Token, Token); Ada.Strings.Unbounded.Append (Result.Name, Username); Realm.Tokens.Insert (Token, Result); end; Auth := Result.all'Access; end Verify; overriding procedure Verify (Realm : in out File_Realm_Manager; Token : in String; Auth : out Principal_Access) is begin null; end Verify; overriding procedure Revoke (Realm : in out File_Realm_Manager; Auth : in Principal_Access) is begin if Auth /= null and then Auth.all in File_Principal'Class then Realm.Tokens.Delete (To_String (File_Principal (Auth.all).Token)); end if; end Revoke; -- ------------------------------ -- Crypt the password using the given salt and return the string composed with -- the salt in clear text and the crypted password. -- ------------------------------ function Crypt_Password (Realm : in File_Realm_Manager; Salt : in String; Password : in String) return String is pragma Unreferenced (Realm); Pos : Natural := Util.Strings.Index (Salt, ' '); begin if Pos = 0 then Pos := Salt'Last; else Pos := Pos - 1; end if; return Salt (Salt'First .. Pos) & " " & Util.Encoders.HMAC.SHA1.Sign_Base64 (Key => Salt (Salt'First .. Pos), Data => Password, URL => True); end Crypt_Password; -- ------------------------------ -- Add a username with the associated password. -- ------------------------------ procedure Add_User (Realm : in out File_Realm_Manager; Username : in String; Password : in String) is Salt : constant String := Realm.Random.Generate (Realm.Token_Bits); begin Realm.Users.Include (Username, Realm.Crypt_Password (Salt, Password)); end Add_User; end Security.OAuth.File_Registry;
Fix compilation warning for Crypt_Password
Fix compilation warning for Crypt_Password
Ada
apache-2.0
stcarrez/ada-security
66c4290ecd001bf6a006596bdbb02dd7ae3b1aec
src/wiki-documents.adb
src/wiki-documents.adb
----------------------------------------------------------------------- -- wiki-nodes -- Wiki Document Internal representation -- Copyright (C) 2016, 2019, 2020, 2022 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- package body Wiki.Documents is use Wiki.Nodes; use Wiki.Nodes.Lists; -- ------------------------------ -- 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) is Node : constant Node_Type_Access := new Node_Type '(Kind => N_TAG_START, Len => 0, Tag_Start => Tag, Attributes => Attributes, Children => null, Parent => Into.Current); begin Append (Into, Node); Into.Current := Node; end Push_Node; -- ------------------------------ -- Pop the HTML tag. -- ------------------------------ procedure Pop_Node (From : in out Document; Tag : in Html_Tag) is pragma Unreferenced (Tag); begin if From.Current /= null then From.Current := From.Current.Parent; end if; end Pop_Node; -- ------------------------------ -- Returns True if the current node is the root document node. -- ------------------------------ function Is_Root_Node (Doc : in Document) return Boolean is begin return Doc.Current = null; end Is_Root_Node; -- ------------------------------ -- Append a section header at end of the document. -- ------------------------------ procedure Append (Into : in out Document; Header : in Wiki.Strings.WString; Level : in Positive) is begin Append (Into, new Node_Type '(Kind => N_HEADER, Len => Header'Length, Parent => Into.Current, Header => Header, Level => Level)); end Append; -- ------------------------------ -- Append a node to the document. -- ------------------------------ procedure Append (Into : in out Document; Node : in Wiki.Nodes.Node_Type_Access) is begin if Into.Current = null then Append (Into.Nodes, Node); else Append (Into.Current, Node); end if; end Append; -- ------------------------------ -- Append a simple node such as N_LINE_BREAK, N_HORIZONTAL_RULE or N_PARAGRAPH. -- ------------------------------ procedure Append (Into : in out Document; Kind : in Simple_Node_Kind) is begin case Kind is when N_LINE_BREAK => Append (Into, new Node_Type '(Kind => N_LINE_BREAK, Len => 0, Parent => Into.Current)); when N_HORIZONTAL_RULE => Append (Into, new Node_Type '(Kind => N_HORIZONTAL_RULE, Len => 0, Parent => Into.Current)); when N_PARAGRAPH => Append (Into, new Node_Type '(Kind => N_PARAGRAPH, Len => 0, Parent => Into.Current)); when N_LIST_ITEM => Append (Into, new Node_Type '(Kind => N_LIST_ITEM, Len => 0, Parent => Into.Current)); when N_LIST_END => Append (Into, new Node_Type '(Kind => N_LIST_END, Len => 0, Parent => Into.Current)); when N_NUM_LIST_END => Append (Into, new Node_Type '(Kind => N_NUM_LIST_END, Len => 0, Parent => Into.Current)); when N_LIST_ITEM_END => Append (Into, new Node_Type '(Kind => N_LIST_ITEM_END, Len => 0, Parent => Into.Current)); when N_NEWLINE => Append (Into, new Node_Type '(Kind => N_NEWLINE, Len => 0, Parent => Into.Current)); when N_TOC_DISPLAY => Append (Into, new Node_Type '(Kind => N_TOC_DISPLAY, Len => 0, Parent => Into.Current)); Into.Using_TOC := True; when N_NONE => null; end case; end Append; -- ------------------------------ -- 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) is begin Append (Into, new Node_Type '(Kind => N_TEXT, Len => Text'Length, Parent => Into.Current, Text => Text, Format => Format)); end Append; -- ------------------------------ -- Add a link. -- ------------------------------ procedure Add_Link (Into : in out Document; Name : in Wiki.Strings.WString; Attributes : in out Wiki.Attributes.Attribute_List) is begin Append (Into, new Node_Type '(Kind => N_LINK, Len => Name'Length, Parent => Into.Current, Title => Name, Link_Attr => Attributes)); end Add_Link; -- ------------------------------ -- Add an image. -- ------------------------------ procedure Add_Image (Into : in out Document; Name : in Wiki.Strings.WString; Attributes : in out Wiki.Attributes.Attribute_List) is begin Append (Into, new Node_Type '(Kind => N_IMAGE, Len => Name'Length, Parent => Into.Current, Title => Name, Link_Attr => Attributes)); end Add_Image; -- ------------------------------ -- Add a quote. -- ------------------------------ procedure Add_Quote (Into : in out Document; Name : in Wiki.Strings.WString; Attributes : in out Wiki.Attributes.Attribute_List) is begin Append (Into, new Node_Type '(Kind => N_QUOTE, Len => Name'Length, Parent => Into.Current, Title => Name, Link_Attr => Attributes)); end Add_Quote; -- ------------------------------ -- Add a list (<ul> or <ol>) starting at the given number. -- ------------------------------ procedure Add_List (Into : in out Document; Level : in Positive; Ordered : in Boolean) is begin if Ordered then Append (Into, new Node_Type '(Kind => N_NUM_LIST_START, Len => 0, Parent => Into.Current, Level => Level, others => <>)); else Append (Into, new Node_Type '(Kind => N_LIST_START, Len => 0, Parent => Into.Current, Level => Level, others => <>)); end if; end Add_List; -- ------------------------------ -- 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) is begin Append (Into, new Node_Type '(Kind => N_BLOCKQUOTE, Len => 0, Parent => Into.Current, Level => Level, others => <>)); end Add_Blockquote; -- ------------------------------ -- 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) is begin Append (Into, new Node_Type '(Kind => N_PREFORMAT, Len => Text'Length, Parent => Into.Current, Preformatted => Text, Language => Strings.To_UString (Format))); end Add_Preformatted; -- ------------------------------ -- Add a new row to the current table. -- ------------------------------ procedure Add_Row (Into : in out Document) is Table : Node_Type_Access; Row : Node_Type_Access; begin -- Identify the current table. Table := Into.Current; while Table /= null and then Table.Kind /= N_TABLE loop Table := Table.Parent; end loop; -- Create the current table. if Table = null then Table := new Node_Type '(Kind => N_TABLE, Len => 0, Tag_Start => TABLE_TAG, Children => null, Parent => Into.Current, others => <>); Append (Into, Table); end if; -- Add the row. Row := new Node_Type '(Kind => N_ROW, Len => 0, Tag_Start => TR_TAG, Children => null, Parent => Table, others => <>); Append (Table, Row); Into.Current := Row; end Add_Row; -- ------------------------------ -- 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) is Row : Node_Type_Access; Col : Node_Type_Access; begin -- Identify the current row. Row := Into.Current; while Row /= null and then Row.Kind /= N_ROW loop Row := Row.Parent; end loop; -- Add the new column. Col := new Node_Type '(Kind => N_COLUMN, Len => 0, Tag_Start => TD_TAG, Children => null, Parent => Row, Attributes => Attributes); Append (Row, Col); Into.Current := Col; end Add_Column; -- ------------------------------ -- Finish the creation of the table. -- ------------------------------ procedure Finish_Table (Into : in out Document) is Table : Node_Type_Access; begin -- Identify the current table. Table := Into.Current; while Table /= null and then Table.Kind /= N_TABLE loop Table := Table.Parent; end loop; if Table /= null then Into.Current := Table.Parent; else Into.Current := null; end if; end Finish_Table; -- ------------------------------ -- 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 Node_Type)) is begin Iterate (Doc.Nodes, Process); end Iterate; -- ------------------------------ -- Returns True if the document is empty. -- ------------------------------ function Is_Empty (Doc : in Document) return Boolean is begin return Wiki.Nodes.Lists.Is_Empty (Doc.Nodes); end Is_Empty; -- ------------------------------ -- Returns True if the document displays the table of contents by itself. -- ------------------------------ function Is_Using_TOC (Doc : in Document) return Boolean is begin return Doc.Using_TOC; end Is_Using_TOC; -- ------------------------------ -- Returns True if the table of contents is visible and must be rendered. -- ------------------------------ function Is_Visible_TOC (Doc : in Document) return Boolean is begin return Doc.Visible_TOC; end Is_Visible_TOC; -- ------------------------------ -- Hide the table of contents. -- ------------------------------ procedure Hide_TOC (Doc : in out Document) is begin Doc.Visible_TOC := False; end Hide_TOC; -- ------------------------------ -- 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) is begin if Wiki.Nodes.Lists.Is_Empty (Doc.TOC) then Append (Doc.TOC, new Node_Type '(Kind => N_TOC, Len => 0, others => <>)); end if; TOC := Doc.TOC; end Get_TOC; -- ------------------------------ -- Get the table of content node associated with the document. -- ------------------------------ function Get_TOC (Doc : in Document) return Wiki.Nodes.Lists.Node_List_Ref is begin return Doc.TOC; end Get_TOC; end Wiki.Documents;
----------------------------------------------------------------------- -- wiki-nodes -- Wiki Document Internal representation -- Copyright (C) 2016, 2019, 2020, 2022 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- package body Wiki.Documents is use Wiki.Nodes; use Wiki.Nodes.Lists; -- ------------------------------ -- 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) is Node : constant Node_Type_Access := new Node_Type '(Kind => N_TAG_START, Len => 0, Tag_Start => Tag, Attributes => Attributes, Children => null, Parent => Into.Current); begin Append (Into, Node); Into.Current := Node; end Push_Node; -- ------------------------------ -- Pop the HTML tag. -- ------------------------------ procedure Pop_Node (From : in out Document; Tag : in Html_Tag) is pragma Unreferenced (Tag); begin if From.Current /= null then From.Current := From.Current.Parent; end if; end Pop_Node; -- ------------------------------ -- Returns True if the current node is the root document node. -- ------------------------------ function Is_Root_Node (Doc : in Document) return Boolean is begin return Doc.Current = null; end Is_Root_Node; -- ------------------------------ -- Append a section header at end of the document. -- ------------------------------ procedure Append (Into : in out Document; Header : in Wiki.Strings.WString; Level : in Positive) is begin Append (Into, new Node_Type '(Kind => N_HEADER, Len => Header'Length, Parent => Into.Current, Header => Header, Level => Level)); end Append; -- ------------------------------ -- Append a node to the document. -- ------------------------------ procedure Append (Into : in out Document; Node : in Wiki.Nodes.Node_Type_Access) is begin if Into.Current = null then Append (Into.Nodes, Node); else Append (Into.Current, Node); end if; end Append; -- ------------------------------ -- Append a simple node such as N_LINE_BREAK, N_HORIZONTAL_RULE or N_PARAGRAPH. -- ------------------------------ procedure Append (Into : in out Document; Kind : in Simple_Node_Kind) is begin case Kind is when N_LINE_BREAK => Append (Into, new Node_Type '(Kind => N_LINE_BREAK, Len => 0, Parent => Into.Current)); when N_HORIZONTAL_RULE => Append (Into, new Node_Type '(Kind => N_HORIZONTAL_RULE, Len => 0, Parent => Into.Current)); when N_PARAGRAPH => Append (Into, new Node_Type '(Kind => N_PARAGRAPH, Len => 0, Parent => Into.Current)); when N_LIST_ITEM => Append (Into, new Node_Type '(Kind => N_LIST_ITEM, Len => 0, Parent => Into.Current)); when N_LIST_END => Append (Into, new Node_Type '(Kind => N_LIST_END, Len => 0, Parent => Into.Current)); when N_NUM_LIST_END => Append (Into, new Node_Type '(Kind => N_NUM_LIST_END, Len => 0, Parent => Into.Current)); when N_LIST_ITEM_END => Append (Into, new Node_Type '(Kind => N_LIST_ITEM_END, Len => 0, Parent => Into.Current)); when N_NEWLINE => Append (Into, new Node_Type '(Kind => N_NEWLINE, Len => 0, Parent => Into.Current)); when N_END_DEFINITION => Append (Into, new Node_Type '(Kind => N_END_DEFINITION, Len => 0, Parent => Into.Current)); when N_TOC_DISPLAY => Append (Into, new Node_Type '(Kind => N_TOC_DISPLAY, Len => 0, Parent => Into.Current)); Into.Using_TOC := True; when N_NONE => null; end case; end Append; -- ------------------------------ -- 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) is begin Append (Into, new Node_Type '(Kind => N_TEXT, Len => Text'Length, Parent => Into.Current, Text => Text, Format => Format)); end Append; -- ------------------------------ -- Add a definition item at end of the document. -- ------------------------------ procedure Add_Definition (Into : in out Document; Definition : in Wiki.Strings.WString) is begin Append (Into, new Node_Type '(Kind => N_DEFINITION, Len => Definition'Length, Parent => Into.Current, Header => Definition, Level => 0)); end Add_Definition; -- ------------------------------ -- Add a link. -- ------------------------------ procedure Add_Link (Into : in out Document; Name : in Wiki.Strings.WString; Attributes : in out Wiki.Attributes.Attribute_List) is begin Append (Into, new Node_Type '(Kind => N_LINK, Len => Name'Length, Parent => Into.Current, Title => Name, Link_Attr => Attributes)); end Add_Link; -- ------------------------------ -- Add an image. -- ------------------------------ procedure Add_Image (Into : in out Document; Name : in Wiki.Strings.WString; Attributes : in out Wiki.Attributes.Attribute_List) is begin Append (Into, new Node_Type '(Kind => N_IMAGE, Len => Name'Length, Parent => Into.Current, Title => Name, Link_Attr => Attributes)); end Add_Image; -- ------------------------------ -- Add a quote. -- ------------------------------ procedure Add_Quote (Into : in out Document; Name : in Wiki.Strings.WString; Attributes : in out Wiki.Attributes.Attribute_List) is begin Append (Into, new Node_Type '(Kind => N_QUOTE, Len => Name'Length, Parent => Into.Current, Title => Name, Link_Attr => Attributes)); end Add_Quote; -- ------------------------------ -- Add a list (<ul> or <ol>) starting at the given number. -- ------------------------------ procedure Add_List (Into : in out Document; Level : in Positive; Ordered : in Boolean) is begin if Ordered then Append (Into, new Node_Type '(Kind => N_NUM_LIST_START, Len => 0, Parent => Into.Current, Level => Level, others => <>)); else Append (Into, new Node_Type '(Kind => N_LIST_START, Len => 0, Parent => Into.Current, Level => Level, others => <>)); end if; end Add_List; -- ------------------------------ -- 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) is begin Append (Into, new Node_Type '(Kind => N_BLOCKQUOTE, Len => 0, Parent => Into.Current, Level => Level, others => <>)); end Add_Blockquote; -- ------------------------------ -- 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) is begin Append (Into, new Node_Type '(Kind => N_PREFORMAT, Len => Text'Length, Parent => Into.Current, Preformatted => Text, Language => Strings.To_UString (Format))); end Add_Preformatted; -- ------------------------------ -- Add a new row to the current table. -- ------------------------------ procedure Add_Row (Into : in out Document) is Table : Node_Type_Access; Row : Node_Type_Access; begin -- Identify the current table. Table := Into.Current; while Table /= null and then Table.Kind /= N_TABLE loop Table := Table.Parent; end loop; -- Create the current table. if Table = null then Table := new Node_Type '(Kind => N_TABLE, Len => 0, Tag_Start => TABLE_TAG, Children => null, Parent => Into.Current, others => <>); Append (Into, Table); end if; -- Add the row. Row := new Node_Type '(Kind => N_ROW, Len => 0, Tag_Start => TR_TAG, Children => null, Parent => Table, others => <>); Append (Table, Row); Into.Current := Row; end Add_Row; -- ------------------------------ -- 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) is Row : Node_Type_Access; Col : Node_Type_Access; begin -- Identify the current row. Row := Into.Current; while Row /= null and then Row.Kind /= N_ROW loop Row := Row.Parent; end loop; -- Add the new column. Col := new Node_Type '(Kind => N_COLUMN, Len => 0, Tag_Start => TD_TAG, Children => null, Parent => Row, Attributes => Attributes); Append (Row, Col); Into.Current := Col; end Add_Column; -- ------------------------------ -- Finish the creation of the table. -- ------------------------------ procedure Finish_Table (Into : in out Document) is Table : Node_Type_Access; begin -- Identify the current table. Table := Into.Current; while Table /= null and then Table.Kind /= N_TABLE loop Table := Table.Parent; end loop; if Table /= null then Into.Current := Table.Parent; else Into.Current := null; end if; end Finish_Table; -- ------------------------------ -- 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 Node_Type)) is begin Iterate (Doc.Nodes, Process); end Iterate; -- ------------------------------ -- Returns True if the document is empty. -- ------------------------------ function Is_Empty (Doc : in Document) return Boolean is begin return Wiki.Nodes.Lists.Is_Empty (Doc.Nodes); end Is_Empty; -- ------------------------------ -- Returns True if the document displays the table of contents by itself. -- ------------------------------ function Is_Using_TOC (Doc : in Document) return Boolean is begin return Doc.Using_TOC; end Is_Using_TOC; -- ------------------------------ -- Returns True if the table of contents is visible and must be rendered. -- ------------------------------ function Is_Visible_TOC (Doc : in Document) return Boolean is begin return Doc.Visible_TOC; end Is_Visible_TOC; -- ------------------------------ -- Hide the table of contents. -- ------------------------------ procedure Hide_TOC (Doc : in out Document) is begin Doc.Visible_TOC := False; end Hide_TOC; -- ------------------------------ -- 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) is begin if Wiki.Nodes.Lists.Is_Empty (Doc.TOC) then Append (Doc.TOC, new Node_Type '(Kind => N_TOC, Len => 0, others => <>)); end if; TOC := Doc.TOC; end Get_TOC; -- ------------------------------ -- Get the table of content node associated with the document. -- ------------------------------ function Get_TOC (Doc : in Document) return Wiki.Nodes.Lists.Node_List_Ref is begin return Doc.TOC; end Get_TOC; end Wiki.Documents;
Implement the Add_Definition procedure and add support to emit the N_END_DEFINITION node
Implement the Add_Definition procedure and add support to emit the N_END_DEFINITION node
Ada
apache-2.0
stcarrez/ada-wiki,stcarrez/ada-wiki
f92a3ebac4a516bdddda99597d00b7d8b841b027
src/gen-commands-propset.adb
src/gen-commands-propset.adb
----------------------------------------------------------------------- -- gen-commands-propset -- Set a property on dynamo project -- Copyright (C) 2011, 2012, 2017, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Text_IO; package body Gen.Commands.Propset 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 begin if Args.Get_Count /= 2 then Cmd.Usage (Name, Generator); return; end if; Generator.Read_Project ("dynamo.xml", True); Generator.Set_Project_Property (Args.Get_Argument (1), Args.Get_Argument (2)); Generator.Save_Project; 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); use Ada.Text_IO; begin Put_Line ("propset: Set the value of a property in the dynamo project file"); Put_Line ("Usage: propset NAME VALUE"); New_Line; end Help; end Gen.Commands.Propset;
----------------------------------------------------------------------- -- gen-commands-propset -- Set a property on dynamo project -- Copyright (C) 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. ----------------------------------------------------------------------- with Ada.Text_IO; package body Gen.Commands.Propset 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 begin if Args.Get_Count /= 2 then Cmd.Usage (Name, Generator); return; end if; Generator.Read_Project ("dynamo.xml", True); Generator.Set_Project_Property (Args.Get_Argument (1), Args.Get_Argument (2)); Generator.Save_Project; 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); use Ada.Text_IO; begin Put_Line ("propset: Set the value of a property in the dynamo project file"); Put_Line ("Usage: propset NAME VALUE"); New_Line; end Help; end Gen.Commands.Propset;
Add Name parameter to the Help procedure
Add Name parameter to the Help procedure
Ada
apache-2.0
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
30165f58803eb157877a0dcb09d5774cddb66c67
src/el-utils.adb
src/el-utils.adb
----------------------------------------------------------------------- -- el-utils -- Utilities around EL -- 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.Strings.Unbounded; with Util.Strings; with Util.Beans.Basic; with Util.Log.Loggers; with EL.Objects; with EL.Expressions; with EL.Contexts.Default; with EL.Contexts.Properties; package body EL.Utils is use Util.Log; use Ada.Strings.Unbounded; use Util.Beans.Objects; -- The logger Log : constant Loggers.Logger := Loggers.Create ("EL.Utils"); -- ------------------------------ -- Expand the properties stored in <b>Source</b> by evaluating the EL expressions -- used in the property values. The EL context passed in <b>Context</b> can be used -- to specify the EL functions or some pre-defined beans that could be used. -- The EL context will integrate the source properties as well as properties stored -- in <b>Into</b> (only the <b>Source</b> properties will be evaluated). -- ------------------------------ procedure Expand (Source : in Util.Properties.Manager'Class; Into : in out Util.Properties.Manager'Class; Context : in EL.Contexts.ELContext'Class) is function Expand (Value : in String; Context : in EL.Contexts.ELContext'Class) return EL.Objects.Object; -- Copy the property identified by <b>Name</b> into the application config properties. -- The value passed in <b>Item</b> is expanded if it contains an EL expression. procedure Process (Name, Item : in Util.Properties.Value); type Local_Resolver is new EL.Contexts.Properties.Property_Resolver with null record; -- Get the value associated with a base object and a given property. overriding function Get_Value (Resolver : in Local_Resolver; Context : in EL.Contexts.ELContext'Class; Base : access Util.Beans.Basic.Readonly_Bean'Class; Name : in Unbounded_String) return EL.Objects.Object; -- ------------------------------ -- Get the value associated with a base object and a given property. -- ------------------------------ overriding function Get_Value (Resolver : in Local_Resolver; Context : in EL.Contexts.ELContext'Class; Base : access Util.Beans.Basic.Readonly_Bean'Class; Name : in Unbounded_String) return EL.Objects.Object is pragma Unreferenced (Resolver); begin if Base /= null then return Base.Get_Value (To_String (Name)); elsif Into.Exists (Name) then return Util.Beans.Objects.To_Object (String '(Into.Get (Name))); elsif Source.Exists (Name) then declare Value : constant String := Source.Get (Name); begin if Util.Strings.Index (Value, '{') = 0 or Util.Strings.Index (Value, '}') = 0 then return Util.Beans.Objects.To_Object (Value); end if; return Expand (Value, Context); end; else return Util.Beans.Objects.Null_Object; end if; end Get_Value; Recursion : Natural := 10; -- ------------------------------ -- Expand (recursively) the EL expression defined in <b>Value</b> by using -- the context. The recursion is provided by the above context resolver which -- invokes <b>Expand</b> if it detects that a value is a possible EL expression. -- ------------------------------ function Expand (Value : in String; Context : in EL.Contexts.ELContext'Class) return EL.Objects.Object is Expr : EL.Expressions.Expression; Result : Util.Beans.Objects.Object; begin if Recursion = 0 then Log.Error ("Too many level of recursion when evaluating expression: {0}", Value); return Util.Beans.Objects.Null_Object; end if; Recursion := Recursion - 1; Expr := EL.Expressions.Create_Expression (Value, Context); Result := Expr.Get_Value (Context); Recursion := Recursion + 1; return Result; -- Ignore any exception and copy the value verbatim. exception when others => Recursion := Recursion + 1; return Util.Beans.Objects.To_Object (Value); end Expand; Resolver : aliased Local_Resolver; Local_Context : aliased EL.Contexts.Default.Default_Context; -- ------------------------------ -- Copy the property identified by <b>Name</b> into the application config properties. -- The value passed in <b>Item</b> is expanded if it contains an EL expression. -- ------------------------------ procedure Process (Name, Item : in Util.Properties.Value) is use Ada.Strings; begin if Unbounded.Index (Item, "{") = 0 or Unbounded.Index (Item, "{") = 0 then Log.Debug ("Adding config {0} = {1}", Name, Item); Into.Set (Name, Item); else declare Value : constant Object := Expand (To_String (Item), Local_Context); Val : Unbounded_String; begin if not Util.Beans.Objects.Is_Null (Value) then Val := Util.Beans.Objects.To_Unbounded_String (Value); end if; Log.Debug ("Adding config {0} = {1}", Name, Val); Into.Set (Name, Val); end; end if; end Process; begin Resolver.Set_Properties (Source); Local_Context.Set_Function_Mapper (Context.Get_Function_Mapper); Local_Context.Set_Resolver (Resolver'Unchecked_Access); Source.Iterate (Process'Access); end Expand; -- ------------------------------ -- Evaluate the possible EL expressions used in <b>Value</b> and return the -- string that correspond to that evaluation. -- ------------------------------ function Eval (Value : in String; Context : in EL.Contexts.ELContext'Class) return String is Expr : EL.Expressions.Expression; Result : Util.Beans.Objects.Object; begin Expr := EL.Expressions.Create_Expression (Value, Context); Result := Expr.Get_Value (Context); return Util.Beans.Objects.To_String (Result); -- Ignore any exception and copy the value verbatim. exception when others => return Value; end Eval; -- ------------------------------ -- Evaluate the possible EL expressions used in <b>Value</b> and return an -- object that correspond to that evaluation. -- ------------------------------ function Eval (Value : in String; Context : in EL.Contexts.ELContext'Class) return Util.Beans.Objects.Object is Expr : EL.Expressions.Expression; begin Expr := EL.Expressions.Create_Expression (Value, Context); return Expr.Get_Value (Context); -- Ignore any exception and copy the value verbatim. exception when others => return Util.Beans.Objects.To_Object (Value); end Eval; -- ------------------------------ -- Evaluate the possible EL expressions used in <b>Value</b> and return an -- object that correspond to that evaluation. -- ------------------------------ function Eval (Value : in Util.Beans.Objects.Object; Context : in EL.Contexts.ELContext'Class) return Util.Beans.Objects.Object is begin case Util.Beans.Objects.Get_Type (Value) is when Util.Beans.Objects.TYPE_STRING | Util.Beans.Objects.TYPE_WIDE_STRING => declare S : constant String := Util.Beans.Objects.To_String (Value); Expr : EL.Expressions.Expression; begin Expr := EL.Expressions.Create_Expression (S, Context); return Expr.Get_Value (Context); end; when others => return Value; end case; -- Ignore any exception and copy the value verbatim. exception when others => return Value; end Eval; end EL.Utils;
----------------------------------------------------------------------- -- el-utils -- Utilities around EL -- 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.Strings.Unbounded; with Util.Strings; with Util.Beans.Basic; with Util.Log.Loggers; with EL.Objects; with EL.Expressions; with EL.Contexts.Default; with EL.Contexts.Properties; package body EL.Utils is use Util.Log; use Ada.Strings.Unbounded; use Util.Beans.Objects; -- The logger Log : constant Loggers.Logger := Loggers.Create ("EL.Utils"); -- ------------------------------ -- Expand the properties stored in <b>Source</b> by evaluating the EL expressions -- used in the property values. The EL context passed in <b>Context</b> can be used -- to specify the EL functions or some pre-defined beans that could be used. -- The EL context will integrate the source properties as well as properties stored -- in <b>Into</b> (only the <b>Source</b> properties will be evaluated). -- ------------------------------ procedure Expand (Source : in Util.Properties.Manager'Class; Into : in out Util.Properties.Manager'Class; Context : in EL.Contexts.ELContext'Class) is function Expand (Value : in String; Context : in EL.Contexts.ELContext'Class) return EL.Objects.Object; -- Copy the property identified by <b>Name</b> into the application config properties. -- The value passed in <b>Item</b> is expanded if it contains an EL expression. procedure Process (Name, Item : in Util.Properties.Value); type Local_Resolver is new EL.Contexts.Properties.Property_Resolver with null record; -- Get the value associated with a base object and a given property. overriding function Get_Value (Resolver : in Local_Resolver; Context : in EL.Contexts.ELContext'Class; Base : access Util.Beans.Basic.Readonly_Bean'Class; Name : in Unbounded_String) return EL.Objects.Object; -- ------------------------------ -- Get the value associated with a base object and a given property. -- ------------------------------ overriding function Get_Value (Resolver : in Local_Resolver; Context : in EL.Contexts.ELContext'Class; Base : access Util.Beans.Basic.Readonly_Bean'Class; Name : in Unbounded_String) return EL.Objects.Object is pragma Unreferenced (Resolver); begin if Base /= null then return Base.Get_Value (To_String (Name)); elsif Into.Exists (Name) then declare Value : constant String := Into.Get (Name); begin if Util.Strings.Index (Value, '{') = 0 or Util.Strings.Index (Value, '}') = 0 then return Util.Beans.Objects.To_Object (Value); end if; return Expand (Value, Context); end; elsif Source.Exists (Name) then declare Value : constant String := Source.Get (Name); begin if Util.Strings.Index (Value, '{') = 0 or Util.Strings.Index (Value, '}') = 0 then return Util.Beans.Objects.To_Object (Value); end if; return Expand (Value, Context); end; else return Util.Beans.Objects.Null_Object; end if; end Get_Value; Recursion : Natural := 10; -- ------------------------------ -- Expand (recursively) the EL expression defined in <b>Value</b> by using -- the context. The recursion is provided by the above context resolver which -- invokes <b>Expand</b> if it detects that a value is a possible EL expression. -- ------------------------------ function Expand (Value : in String; Context : in EL.Contexts.ELContext'Class) return EL.Objects.Object is Expr : EL.Expressions.Expression; Result : Util.Beans.Objects.Object; begin if Recursion = 0 then Log.Error ("Too many level of recursion when evaluating expression: {0}", Value); return Util.Beans.Objects.Null_Object; end if; Recursion := Recursion - 1; Expr := EL.Expressions.Create_Expression (Value, Context); Result := Expr.Get_Value (Context); Recursion := Recursion + 1; return Result; -- Ignore any exception and copy the value verbatim. exception when others => Recursion := Recursion + 1; return Util.Beans.Objects.To_Object (Value); end Expand; Resolver : aliased Local_Resolver; Local_Context : aliased EL.Contexts.Default.Default_Context; -- ------------------------------ -- Copy the property identified by <b>Name</b> into the application config properties. -- The value passed in <b>Item</b> is expanded if it contains an EL expression. -- ------------------------------ procedure Process (Name, Item : in Util.Properties.Value) is use Ada.Strings; begin if Unbounded.Index (Item, "{") = 0 or Unbounded.Index (Item, "{") = 0 then Log.Debug ("Adding config {0} = {1}", Name, Item); Into.Set (Name, Item); else declare Value : constant Object := Expand (To_String (Item), Local_Context); Val : Unbounded_String; begin if not Util.Beans.Objects.Is_Null (Value) then Val := Util.Beans.Objects.To_Unbounded_String (Value); end if; Log.Debug ("Adding config {0} = {1}", Name, Val); Into.Set (Name, Val); end; end if; end Process; begin Resolver.Set_Properties (Source); Local_Context.Set_Function_Mapper (Context.Get_Function_Mapper); Local_Context.Set_Resolver (Resolver'Unchecked_Access); Source.Iterate (Process'Access); end Expand; -- ------------------------------ -- Evaluate the possible EL expressions used in <b>Value</b> and return the -- string that correspond to that evaluation. -- ------------------------------ function Eval (Value : in String; Context : in EL.Contexts.ELContext'Class) return String is Expr : EL.Expressions.Expression; Result : Util.Beans.Objects.Object; begin Expr := EL.Expressions.Create_Expression (Value, Context); Result := Expr.Get_Value (Context); return Util.Beans.Objects.To_String (Result); -- Ignore any exception and copy the value verbatim. exception when others => return Value; end Eval; -- ------------------------------ -- Evaluate the possible EL expressions used in <b>Value</b> and return an -- object that correspond to that evaluation. -- ------------------------------ function Eval (Value : in String; Context : in EL.Contexts.ELContext'Class) return Util.Beans.Objects.Object is Expr : EL.Expressions.Expression; begin Expr := EL.Expressions.Create_Expression (Value, Context); return Expr.Get_Value (Context); -- Ignore any exception and copy the value verbatim. exception when others => return Util.Beans.Objects.To_Object (Value); end Eval; -- ------------------------------ -- Evaluate the possible EL expressions used in <b>Value</b> and return an -- object that correspond to that evaluation. -- ------------------------------ function Eval (Value : in Util.Beans.Objects.Object; Context : in EL.Contexts.ELContext'Class) return Util.Beans.Objects.Object is begin case Util.Beans.Objects.Get_Type (Value) is when Util.Beans.Objects.TYPE_STRING | Util.Beans.Objects.TYPE_WIDE_STRING => declare S : constant String := Util.Beans.Objects.To_String (Value); Expr : EL.Expressions.Expression; begin Expr := EL.Expressions.Create_Expression (S, Context); return Expr.Get_Value (Context); end; when others => return Value; end case; -- Ignore any exception and copy the value verbatim. exception when others => return Value; end Eval; end EL.Utils;
Fix evaluation of properties when Source and Into are the same sets If the value from Into is a possible EL expression, perform a recursive expand of that value.
Fix evaluation of properties when Source and Into are the same sets If the value from Into is a possible EL expression, perform a recursive expand of that value.
Ada
apache-2.0
Letractively/ada-el
9c20618db5a2bdf323c9066d4fcb196f9127d324
src/util-events-timers.adb
src/util-events-timers.adb
----------------------------------------------------------------------- -- util-events-timers -- Timer list management -- Copyright (C) 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Unchecked_Deallocation; with Util.Log.Loggers; package body Util.Events.Timers is use type Ada.Real_Time.Time; Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Util.Events.Timers"); procedure Free is new Ada.Unchecked_Deallocation (Object => Timer_Node, Name => Timer_Node_Access); -- ----------------------- -- Repeat the timer. -- ----------------------- procedure Repeat (Event : in out Timer_Ref; In_Time : in Ada.Real_Time.Time_Span) is Timer : constant Timer_Node_Access := Event.Value; begin if Timer /= null and then Timer.List /= null then Timer.List.Add (Timer, Timer.Deadline + In_Time); end if; end Repeat; -- ----------------------- -- Cancel the timer. -- ----------------------- procedure Cancel (Event : in out Timer_Ref) is begin if Event.Value /= null and then Event.Value.List /= null then Event.Value.List.all.Cancel (Event.Value); Event.Value.List := null; end if; end Cancel; -- ----------------------- -- Check if the timer is ready to be executed. -- ----------------------- function Is_Scheduled (Event : in Timer_Ref) return Boolean is begin return Event.Value /= null and then Event.Value.List /= null; end Is_Scheduled; -- ----------------------- -- Returns the deadline time for the timer execution. -- Returns Time'Last if the timer is not scheduled. -- ----------------------- function Time_Of_Event (Event : in Timer_Ref) return Ada.Real_Time.Time is begin return (if Event.Value /= null then Event.Value.Deadline else Ada.Real_Time.Time_Last); end Time_Of_Event; -- ----------------------- -- Set a timer to be called at the given time. -- ----------------------- procedure Set_Timer (List : in out Timer_List; Handler : in Timer_Access; Event : in out Timer_Ref'Class; At_Time : in Ada.Real_Time.Time) is Timer : Timer_Node_Access := Event.Value; begin if Timer = null then Event.Value := new Timer_Node; Timer := Event.Value; end if; Timer.Handler := Handler; -- Cancel the timer if it is part of another timer manager. if Timer.List /= null and Timer.List /= List.Manager'Unchecked_Access then Timer.List.Cancel (Timer); end if; -- Update the timer. Timer.List := List.Manager'Unchecked_Access; List.Manager.Add (Timer, At_Time); end Set_Timer; -- ----------------------- -- Set a timer to be called after the given time span. -- ----------------------- procedure Set_Timer (List : in out Timer_List; Handler : in Timer_Access; Event : in out Timer_Ref'Class; In_Time : in Ada.Real_Time.Time_Span) is begin List.Set_Timer (Handler, Event, Ada.Real_Time.Clock + In_Time); end Set_Timer; -- ----------------------- -- Process the timer handlers that have passed the deadline and return the next -- deadline. The <tt>Max_Count</tt> parameter allows to limit the number of timer handlers -- that are called by operation. The default is not limited. -- ----------------------- procedure Process (List : in out Timer_List; Timeout : out Ada.Real_Time.Time; Max_Count : in Natural := Natural'Last) is Timer : Timer_Ref; Now : constant Ada.Real_Time.Time := Ada.Real_Time.Clock; Count : Natural := 0; begin for Count in 1 .. Max_Count loop List.Manager.Find_Next (Now, Timeout, Timer); exit when Timer.Value = null; begin Timer.Value.Handler.Time_Handler (Timer); exception when E : others => Timer_List'Class (List).Error (Timer.Value.Handler, E); end; Timer.Finalize; end loop; end Process; -- ----------------------- -- Procedure called when a timer handler raises an exception. -- The default operation reports an error in the logs. This procedure can be -- overriden to implement specific error handling. -- ----------------------- procedure Error (List : in out Timer_List; Handler : in Timer_Access; E : in Ada.Exceptions.Exception_Occurrence) is pragma Unreferenced (List, Handler); begin Log.Error ("Timer handler raised an exception", E, True); end Error; overriding procedure Adjust (Object : in out Timer_Ref) is begin if Object.Value /= null then Util.Concurrent.Counters.Increment (Object.Value.Counter); end if; end Adjust; overriding procedure Finalize (Object : in out Timer_Ref) is Is_Zero : Boolean; begin if Object.Value /= null then Util.Concurrent.Counters.Decrement (Object.Value.Counter, Is_Zero); if Is_Zero then Free (Object.Value); else Object.Value := null; end if; end if; end Finalize; protected body Timer_Manager is procedure Remove (Timer : in Timer_Node_Access) is begin if List = Timer then List := Timer.Next; Timer.Prev := null; if List /= null then List.Prev := null; end if; elsif Timer.Prev /= null then Timer.Prev.Next := Timer.Next; Timer.Next.Prev := Timer.Prev; else return; end if; Timer.Next := null; Timer.Prev := null; Timer.List := null; end Remove; -- ----------------------- -- Add a timer. -- ----------------------- procedure Add (Timer : in Timer_Node_Access; Deadline : in Ada.Real_Time.Time) is Current : Timer_Node_Access := List; Prev : Timer_Node_Access; begin Util.Concurrent.Counters.Increment (Timer.Counter); if Timer.List /= null then Remove (Timer); end if; Timer.Deadline := Deadline; while Current /= null loop if Current.Deadline > Deadline then if Prev = null then List := Timer; else Prev.Next := Timer; end if; Timer.Next := Current; Current.Prev := Timer; return; end if; Prev := Current; Current := Current.Next; end loop; if Prev = null then List := Timer; Timer.Prev := null; else Prev.Next := Timer; Timer.Prev := Prev; end if; Timer.Next := null; end Add; -- ----------------------- -- Cancel a timer. -- ----------------------- procedure Cancel (Timer : in out Timer_Node_Access) is Is_Zero : Boolean; begin if Timer.List = null then return; end if; Remove (Timer); Util.Concurrent.Counters.Decrement (Timer.Counter, Is_Zero); if Is_Zero then Free (Timer); end if; end Cancel; -- ----------------------- -- Find the next timer to be executed before the given time or return the next deadline. -- ----------------------- procedure Find_Next (Before : in Ada.Real_Time.Time; Deadline : out Ada.Real_Time.Time; Timer : in out Timer_Ref) is begin if List = null then Deadline := Ada.Real_Time.Time_Last; elsif List.Deadline < Before then Timer.Value := List; List := List.Next; if List /= null then List.Prev := null; Deadline := List.Deadline; else Deadline := Ada.Real_Time.Time_Last; end if; else Deadline := List.Deadline; end if; end Find_Next; end Timer_Manager; overriding procedure Finalize (Object : in out Timer_List) is Timer : Timer_Ref; Timeout : Ada.Real_Time.Time; begin loop Object.Manager.Find_Next (Ada.Real_Time.Time_Last, Timeout, Timer); exit when Timer.Value = null; Timer.Finalize; end loop; end Finalize; end Util.Events.Timers;
----------------------------------------------------------------------- -- util-events-timers -- Timer list management -- Copyright (C) 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Unchecked_Deallocation; with Util.Log.Loggers; package body Util.Events.Timers is use type Ada.Real_Time.Time; Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Util.Events.Timers"); procedure Free is new Ada.Unchecked_Deallocation (Object => Timer_Node, Name => Timer_Node_Access); -- ----------------------- -- Repeat the timer. -- ----------------------- procedure Repeat (Event : in out Timer_Ref; In_Time : in Ada.Real_Time.Time_Span) is Timer : constant Timer_Node_Access := Event.Value; begin if Timer /= null and then Timer.List /= null then Timer.List.Add (Timer, Timer.Deadline + In_Time); end if; end Repeat; -- ----------------------- -- Cancel the timer. -- ----------------------- procedure Cancel (Event : in out Timer_Ref) is begin if Event.Value /= null and then Event.Value.List /= null then Event.Value.List.all.Cancel (Event.Value); Event.Value.List := null; end if; end Cancel; -- ----------------------- -- Check if the timer is ready to be executed. -- ----------------------- function Is_Scheduled (Event : in Timer_Ref) return Boolean is begin return Event.Value /= null and then Event.Value.List /= null; end Is_Scheduled; -- ----------------------- -- Returns the deadline time for the timer execution. -- Returns Time'Last if the timer is not scheduled. -- ----------------------- function Time_Of_Event (Event : in Timer_Ref) return Ada.Real_Time.Time is begin return (if Event.Value /= null then Event.Value.Deadline else Ada.Real_Time.Time_Last); end Time_Of_Event; -- ----------------------- -- Set a timer to be called at the given time. -- ----------------------- procedure Set_Timer (List : in out Timer_List; Handler : in Timer_Access; Event : in out Timer_Ref'Class; At_Time : in Ada.Real_Time.Time) is Timer : Timer_Node_Access := Event.Value; begin if Timer = null then Event.Value := new Timer_Node; Timer := Event.Value; end if; Timer.Handler := Handler; -- Cancel the timer if it is part of another timer manager. if Timer.List /= null and Timer.List /= List.Manager'Unchecked_Access then Timer.List.Cancel (Timer); end if; -- Update the timer. Timer.List := List.Manager'Unchecked_Access; List.Manager.Add (Timer, At_Time); end Set_Timer; -- ----------------------- -- Set a timer to be called after the given time span. -- ----------------------- procedure Set_Timer (List : in out Timer_List; Handler : in Timer_Access; Event : in out Timer_Ref'Class; In_Time : in Ada.Real_Time.Time_Span) is begin List.Set_Timer (Handler, Event, Ada.Real_Time.Clock + In_Time); end Set_Timer; -- ----------------------- -- Process the timer handlers that have passed the deadline and return the next -- deadline. The <tt>Max_Count</tt> parameter allows to limit the number of timer handlers -- that are called by operation. The default is not limited. -- ----------------------- procedure Process (List : in out Timer_List; Timeout : out Ada.Real_Time.Time; Max_Count : in Natural := Natural'Last) is Timer : Timer_Ref; Now : constant Ada.Real_Time.Time := Ada.Real_Time.Clock; begin for Count in 1 .. Max_Count loop List.Manager.Find_Next (Now, Timeout, Timer); exit when Timer.Value = null; begin Timer.Value.Handler.Time_Handler (Timer); exception when E : others => Timer_List'Class (List).Error (Timer.Value.Handler, E); end; Timer.Finalize; end loop; end Process; -- ----------------------- -- Procedure called when a timer handler raises an exception. -- The default operation reports an error in the logs. This procedure can be -- overriden to implement specific error handling. -- ----------------------- procedure Error (List : in out Timer_List; Handler : in Timer_Access; E : in Ada.Exceptions.Exception_Occurrence) is pragma Unreferenced (List, Handler); begin Log.Error ("Timer handler raised an exception", E, True); end Error; overriding procedure Adjust (Object : in out Timer_Ref) is begin if Object.Value /= null then Util.Concurrent.Counters.Increment (Object.Value.Counter); end if; end Adjust; overriding procedure Finalize (Object : in out Timer_Ref) is Is_Zero : Boolean; begin if Object.Value /= null then Util.Concurrent.Counters.Decrement (Object.Value.Counter, Is_Zero); if Is_Zero then Free (Object.Value); else Object.Value := null; end if; end if; end Finalize; protected body Timer_Manager is procedure Remove (Timer : in Timer_Node_Access) is begin if List = Timer then List := Timer.Next; Timer.Prev := null; if List /= null then List.Prev := null; end if; elsif Timer.Prev /= null then Timer.Prev.Next := Timer.Next; Timer.Next.Prev := Timer.Prev; else return; end if; Timer.Next := null; Timer.Prev := null; Timer.List := null; end Remove; -- ----------------------- -- Add a timer. -- ----------------------- procedure Add (Timer : in Timer_Node_Access; Deadline : in Ada.Real_Time.Time) is Current : Timer_Node_Access := List; Prev : Timer_Node_Access; begin Util.Concurrent.Counters.Increment (Timer.Counter); if Timer.List /= null then Remove (Timer); end if; Timer.Deadline := Deadline; while Current /= null loop if Current.Deadline > Deadline then if Prev = null then List := Timer; else Prev.Next := Timer; end if; Timer.Next := Current; Current.Prev := Timer; return; end if; Prev := Current; Current := Current.Next; end loop; if Prev = null then List := Timer; Timer.Prev := null; else Prev.Next := Timer; Timer.Prev := Prev; end if; Timer.Next := null; end Add; -- ----------------------- -- Cancel a timer. -- ----------------------- procedure Cancel (Timer : in out Timer_Node_Access) is Is_Zero : Boolean; begin if Timer.List = null then return; end if; Remove (Timer); Util.Concurrent.Counters.Decrement (Timer.Counter, Is_Zero); if Is_Zero then Free (Timer); end if; end Cancel; -- ----------------------- -- Find the next timer to be executed before the given time or return the next deadline. -- ----------------------- procedure Find_Next (Before : in Ada.Real_Time.Time; Deadline : out Ada.Real_Time.Time; Timer : in out Timer_Ref) is begin if List = null then Deadline := Ada.Real_Time.Time_Last; elsif List.Deadline < Before then Timer.Value := List; List := List.Next; if List /= null then List.Prev := null; Deadline := List.Deadline; else Deadline := Ada.Real_Time.Time_Last; end if; else Deadline := List.Deadline; end if; end Find_Next; end Timer_Manager; overriding procedure Finalize (Object : in out Timer_List) is Timer : Timer_Ref; Timeout : Ada.Real_Time.Time; begin loop Object.Manager.Find_Next (Ada.Real_Time.Time_Last, Timeout, Timer); exit when Timer.Value = null; Timer.Finalize; end loop; end Finalize; end Util.Events.Timers;
Remove unused local variable Count
Remove unused local variable Count
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
bf0d2239dbb94e40fd5674d23bd0abd408e87f00
src/el-expressions.ads
src/el-expressions.ads
----------------------------------------------------------------------- -- EL.Expressions -- Expression Language -- 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. ----------------------------------------------------------------------- -- -- First, create the expression object: -- -- E : constant Expression := EL.Expressions.Create_Expression ("obj.count + 3"); -- -- The expression must be evaluated against an expression context. -- The expression context will resolve variables whose values can change depending -- on the evaluation context. In the example, ''obj'' is the variable name -- and ''count'' is the property associated with that variable. -- -- Value : constant Object := E.Get_Value (Context); -- -- The ''Value'' holds the result which can be a boolean, an integer, a date, -- a float number or a string. The value can be converted as follows: -- -- N : Integer := To_Integer (Value); -- with EL.Objects; with Ada.Finalization; limited with EL.Expressions.Nodes; with EL.Contexts; with EL.Beans; package EL.Expressions is use EL.Objects; use EL.Contexts; -- Exception raised when parsing an invalid expression. Invalid_Expression : exception; -- Exception raised when a variable cannot be resolved. Invalid_Variable : exception; -- ------------------------------ -- Expression -- ------------------------------ type Expression is new Ada.Finalization.Controlled with private; -- Get the value of the expression using the given expression context. -- Returns an object that holds a typed result. function Get_Value (Expr : Expression; Context : ELContext'Class) return Object; -- Parse an expression and return its representation ready for evaluation. -- The context is used to resolve the functions. Variables will be -- resolved during evaluation of the expression. -- Raises <b>Invalid_Expression</b> if the expression is invalid. function Create_Expression (Expr : String; Context : ELContext'Class) return Expression; -- ------------------------------ -- ValueExpression -- ------------------------------ -- type ValueExpression is new Expression with private; type ValueExpression_Access is access all ValueExpression'Class; -- Get the value of the expression using the given expression context. -- Returns an object that holds a typed result. overriding function Get_Value (Expr : in ValueExpression; Context : in ELContext'Class) return Object; procedure Set_Value (Expr : in ValueExpression; Context : in ELContext'Class; Value : in Object); function Is_Readonly (Expr : in ValueExpression) return Boolean; -- Parse an expression and return its representation ready for evaluation. function Create_Expression (Expr : String; Context : ELContext'Class) return ValueExpression; function Create_ValueExpression (Bean : access EL.Beans.Readonly_Bean'Class) return ValueExpression; private procedure Adjust (Object : in out Expression); procedure Finalize (Object : in out Expression); type Expression is new Ada.Finalization.Controlled with record Node : access EL.Expressions.Nodes.ELNode'Class; end record; type ValueExpression is new Expression with record Bean : access EL.Beans.Readonly_Bean'Class; end record; end EL.Expressions;
----------------------------------------------------------------------- -- EL.Expressions -- Expression Language -- 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. ----------------------------------------------------------------------- -- -- First, create the expression object: -- -- E : constant Expression := EL.Expressions.Create_Expression ("obj.count + 3"); -- -- The expression must be evaluated against an expression context. -- The expression context will resolve variables whose values can change depending -- on the evaluation context. In the example, ''obj'' is the variable name -- and ''count'' is the property associated with that variable. -- -- Value : constant Object := E.Get_Value (Context); -- -- The ''Value'' holds the result which can be a boolean, an integer, a date, -- a float number or a string. The value can be converted as follows: -- -- N : Integer := To_Integer (Value); -- with EL.Objects; with Ada.Finalization; limited with EL.Expressions.Nodes; with EL.Contexts; with EL.Beans; package EL.Expressions is use EL.Objects; use EL.Contexts; -- Exception raised when parsing an invalid expression. Invalid_Expression : exception; -- Exception raised when a variable cannot be resolved. Invalid_Variable : exception; -- ------------------------------ -- Expression -- ------------------------------ type Expression is new Ada.Finalization.Controlled with private; type Expression_Access is access all Expression'Class; -- Get the value of the expression using the given expression context. -- Returns an object that holds a typed result. function Get_Value (Expr : Expression; Context : ELContext'Class) return Object; -- Parse an expression and return its representation ready for evaluation. -- The context is used to resolve the functions. Variables will be -- resolved during evaluation of the expression. -- Raises <b>Invalid_Expression</b> if the expression is invalid. function Create_Expression (Expr : String; Context : ELContext'Class) return Expression; -- ------------------------------ -- ValueExpression -- ------------------------------ -- type ValueExpression is new Expression with private; type ValueExpression_Access is access all ValueExpression'Class; -- Get the value of the expression using the given expression context. -- Returns an object that holds a typed result. overriding function Get_Value (Expr : in ValueExpression; Context : in ELContext'Class) return Object; procedure Set_Value (Expr : in ValueExpression; Context : in ELContext'Class; Value : in Object); function Is_Readonly (Expr : in ValueExpression) return Boolean; -- Parse an expression and return its representation ready for evaluation. function Create_Expression (Expr : String; Context : ELContext'Class) return ValueExpression; function Create_ValueExpression (Bean : access EL.Beans.Readonly_Bean'Class) return ValueExpression; private procedure Adjust (Object : in out Expression); procedure Finalize (Object : in out Expression); type Expression is new Ada.Finalization.Controlled with record Node : access EL.Expressions.Nodes.ELNode'Class; end record; type ValueExpression is new Expression with record Bean : access EL.Beans.Readonly_Bean'Class; end record; end EL.Expressions;
Declare Expression_Access
Declare Expression_Access
Ada
apache-2.0
stcarrez/ada-el
fdf4434b3ca23cb643764f5f034676dcb8bb02ae
regtests/asf-routes-tests.ads
regtests/asf-routes-tests.ads
----------------------------------------------------------------------- -- asf-routes-tests - Unit tests for ASF.Routes -- Copyright (C) 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Util.Tests; with Util.Beans.Objects; with ASF.Tests; package ASF.Routes.Tests is -- A test bean to verify the path parameter injection. type Test_Bean is new Util.Beans.Basic.Bean with record Id : Ada.Strings.Unbounded.Unbounded_String; Name : Ada.Strings.Unbounded.Unbounded_String; end record; type Test_Bean_Access is access all Test_Bean; overriding function Get_Value (Bean : in Test_Bean; Name : in String) return Util.Beans.Objects.Object; overriding procedure Set_Value (Bean : in out Test_Bean; Name : in String; Value : in Util.Beans.Objects.Object); MAX_TEST_ROUTES : constant Positive := 100; type Test_Route_Type is new Route_Type with record Index : Natural := 0; end record; type Test_Route_Array is array (1 .. MAX_TEST_ROUTES) of aliased Test_Route_Type; procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite); type Test is new ASF.Tests.EL_Test with record Routes : Test_Route_Array; Bean : Test_Bean_Access; end record; -- Setup the test instance. overriding procedure Set_Up (T : in out Test); -- Verify that the path matches the given route. procedure Verify_Route (T : in out Test; Router : in out Router_Type; Path : in String; Index : in Positive; Bean : in out Test_Bean'Class); -- Add the route associted with the path pattern. procedure Add_Route (T : in out Test; Router : in out Router_Type; Path : in String; Index : in Positive; Bean : in out Test_Bean'Class); -- Test the Add_Route with simple fixed path components. -- Example: /list/index.html procedure Test_Add_Route_With_Path (T : in out Test); -- Test the Add_Route with extension mapping. -- Example: /list/*.html procedure Test_Add_Route_With_Ext (T : in out Test); -- Test the Add_Route with fixed path components and path parameters. -- Example: /users/:id/view.html procedure Test_Add_Route_With_Param (T : in out Test); -- Test the Add_Route with fixed path components and EL path injection. -- Example: /users/#{user.id}/view.html procedure Test_Add_Route_With_EL (T : in out Test); -- Test the Iterate over several paths. procedure Test_Iterate (T : in out Test); end ASF.Routes.Tests;
----------------------------------------------------------------------- -- asf-routes-tests - Unit tests for ASF.Routes -- Copyright (C) 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Util.Tests; with Util.Beans.Objects; with ASF.Tests; package ASF.Routes.Tests is -- A test bean to verify the path parameter injection. type Test_Bean is new Util.Beans.Basic.Bean with record Id : Ada.Strings.Unbounded.Unbounded_String; Name : Ada.Strings.Unbounded.Unbounded_String; end record; type Test_Bean_Access is access all Test_Bean; overriding function Get_Value (Bean : in Test_Bean; Name : in String) return Util.Beans.Objects.Object; overriding procedure Set_Value (Bean : in out Test_Bean; Name : in String; Value : in Util.Beans.Objects.Object); MAX_TEST_ROUTES : constant Positive := 100; type Test_Route_Type is new Route_Type with record Index : Natural := 0; end record; type Test_Route_Type_Access is access Test_Route_Type; type Test_Route_Array is array (1 .. MAX_TEST_ROUTES) of Test_Route_Type_Access; procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite); type Test is new ASF.Tests.EL_Test with record Routes : Test_Route_Array; Bean : Test_Bean_Access; end record; -- Setup the test instance. overriding procedure Set_Up (T : in out Test); -- Verify that the path matches the given route. procedure Verify_Route (T : in out Test; Router : in out Router_Type; Path : in String; Index : in Positive; Bean : in out Test_Bean'Class); -- Add the route associted with the path pattern. procedure Add_Route (T : in out Test; Router : in out Router_Type; Path : in String; Index : in Positive; Bean : in out Test_Bean'Class); -- Test the Add_Route with simple fixed path components. -- Example: /list/index.html procedure Test_Add_Route_With_Path (T : in out Test); -- Test the Add_Route with extension mapping. -- Example: /list/*.html procedure Test_Add_Route_With_Ext (T : in out Test); -- Test the Add_Route with fixed path components and path parameters. -- Example: /users/:id/view.html procedure Test_Add_Route_With_Param (T : in out Test); -- Test the Add_Route with fixed path components and EL path injection. -- Example: /users/#{user.id}/view.html procedure Test_Add_Route_With_EL (T : in out Test); -- Test the Iterate over several paths. procedure Test_Iterate (T : in out Test); end ASF.Routes.Tests;
Change Test_Route_Array to an array of route access types
Change Test_Route_Array to an array of route access types
Ada
apache-2.0
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
610e92d0a5c505692dff7e67400c69f08ed7599a
src/security-permissions.ads
src/security-permissions.ads
----------------------------------------------------------------------- -- security-permissions -- Definition of permissions -- Copyright (C) 2010, 2011, 2012, 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- private with Interfaces; -- == Permission == -- The <b>Security.Permissions</b> package defines the different permissions that can be -- checked by the access control manager. An application should declare each permission -- by instantiating the <tt>Definition</tt> package: -- -- package Perm_Create_Workspace is new Security.Permissions.Definition ("create-workspace"); -- -- This declares a permission that can be represented by "<tt>create-workspace</tt>" in -- configuration files. In Ada, the permission is used as follows: -- -- Perm_Create_Workspace.Permission -- package Security.Permissions is Invalid_Name : exception; -- Max number of permissions supported by the implementation. MAX_PERMISSION : constant Natural := 256; type Permission_Index is new Natural range 0 .. MAX_PERMISSION; -- Get the permission index associated with the name. function Get_Permission_Index (Name : in String) return Permission_Index; -- The permission root class. -- Each permission is represented by a <b>Permission_Index</b> number to provide a fast -- and efficient permission check. type Permission (Id : Permission_Index) is tagged limited null record; generic Name : String; package Definition is function Permission return Permission_Index; pragma Inline_Always (Permission); end Definition; -- Add the permission name and allocate a unique permission index. procedure Add_Permission (Name : in String; Index : out Permission_Index); type Permission_Index_Set is private; -- Check if the permission index set contains the given permission index. function Has_Permission (Set : in Permission_Index_Set; Index : in Permission_Index) return Boolean; -- Add the permission index to the set. procedure Add_Permission (Set : in out Permission_Index_Set; Index : in Permission_Index); private -- Get the last permission index registered in the global permission map. function Get_Last_Permission_Index return Permission_Index; INDEX_SET_SIZE : constant Natural := (MAX_PERMISSION + 7) / 8; type Permission_Index_Set is array (1 .. INDEX_SET_SIZE) of Interfaces.Unsigned_8; end Security.Permissions;
----------------------------------------------------------------------- -- security-permissions -- Definition of permissions -- Copyright (C) 2010, 2011, 2012, 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- private with Interfaces; -- == Permission == -- The <b>Security.Permissions</b> package defines the different permissions that can be -- checked by the access control manager. An application should declare each permission -- by instantiating the <tt>Definition</tt> package: -- -- package Perm_Create_Workspace is new Security.Permissions.Definition ("create-workspace"); -- -- This declares a permission that can be represented by "<tt>create-workspace</tt>" in -- configuration files. In Ada, the permission is used as follows: -- -- Perm_Create_Workspace.Permission -- package Security.Permissions is Invalid_Name : exception; -- Max number of permissions supported by the implementation. MAX_PERMISSION : constant Natural := 255; type Permission_Index is new Natural range 0 .. MAX_PERMISSION; -- Get the permission index associated with the name. function Get_Permission_Index (Name : in String) return Permission_Index; -- The permission root class. -- Each permission is represented by a <b>Permission_Index</b> number to provide a fast -- and efficient permission check. type Permission (Id : Permission_Index) is tagged limited null record; generic Name : String; package Definition is function Permission return Permission_Index; pragma Inline_Always (Permission); end Definition; -- Add the permission name and allocate a unique permission index. procedure Add_Permission (Name : in String; Index : out Permission_Index); type Permission_Index_Set is private; -- Check if the permission index set contains the given permission index. function Has_Permission (Set : in Permission_Index_Set; Index : in Permission_Index) return Boolean; -- Add the permission index to the set. procedure Add_Permission (Set : in out Permission_Index_Set; Index : in Permission_Index); -- The empty set of permission indexes. EMPTY_SET : constant Permission_Index_Set; private -- Get the last permission index registered in the global permission map. function Get_Last_Permission_Index return Permission_Index; INDEX_SET_SIZE : constant Natural := (MAX_PERMISSION + 7) / 8; type Permission_Index_Set is array (0 .. INDEX_SET_SIZE - 1) of Interfaces.Unsigned_8; EMPTY_SET : constant Permission_Index_Set := (others => 0); end Security.Permissions;
Declare the EMPTY_SET constant and fix the MAX_PERMISSION
Declare the EMPTY_SET constant and fix the MAX_PERMISSION
Ada
apache-2.0
stcarrez/ada-security
74f93b0e20943a6807d44d851bbbc0923759b02a
awa/plugins/awa-wikis/src/awa-wikis-modules.ads
awa/plugins/awa-wikis/src/awa-wikis-modules.ads
----------------------------------------------------------------------- -- awa-wikis-modules -- Module wikis -- Copyright (C) 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with ASF.Applications; with ADO; with AWA.Modules; with AWA.Wikis.Models; with Security.Permissions; package AWA.Wikis.Modules is -- The name under which the module is registered. NAME : constant String := "wikis"; package ACL_Create_Wiki_Pages is new Security.Permissions.Definition ("wiki-page-create"); package ACL_Delete_Wiki_Pages is new Security.Permissions.Definition ("wiki-page-delete"); package ACL_Update_Wiki_Pages is new Security.Permissions.Definition ("wiki-page-update"); -- Define the permissions. package ACL_Create_Wiki_Space is new Security.Permissions.Definition ("wiki-space-create"); package ACL_Delete_Wiki_Space is new Security.Permissions.Definition ("wiki-space-delete"); package ACL_Update_Wiki_Space is new Security.Permissions.Definition ("wiki-space-update"); -- ------------------------------ -- Module wikis -- ------------------------------ type Wiki_Module is new AWA.Modules.Module with private; type Wiki_Module_Access is access all Wiki_Module'Class; -- Initialize the wikis module. overriding procedure Initialize (Plugin : in out Wiki_Module; App : in AWA.Modules.Application_Access; Props : in ASF.Applications.Config); -- Get the wikis module. function Get_Wiki_Module return Wiki_Module_Access; -- Create the wiki space. procedure Create_Wiki_Space (Module : in Wiki_Module; Wiki : in out AWA.Wikis.Models.Wiki_Space_Ref'Class); -- Save the wiki space. procedure Save_Wiki_Space (Module : in Wiki_Module; Wiki : in out AWA.Wikis.Models.Wiki_Space_Ref'Class); -- Load the wiki space. procedure Load_Wiki_Space (Module : in Wiki_Module; Wiki : in out AWA.Wikis.Models.Wiki_Space_Ref'Class; Id : in ADO.Identifier); private type Wiki_Module is new AWA.Modules.Module with null record; end AWA.Wikis.Modules;
----------------------------------------------------------------------- -- awa-wikis-modules -- Module wikis -- Copyright (C) 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with ASF.Applications; with ADO; with AWA.Modules; with AWA.Wikis.Models; with Security.Permissions; with Awa.Wikis.Models; package AWA.Wikis.Modules is -- The name under which the module is registered. NAME : constant String := "wikis"; package ACL_Create_Wiki_Pages is new Security.Permissions.Definition ("wiki-page-create"); package ACL_Delete_Wiki_Pages is new Security.Permissions.Definition ("wiki-page-delete"); package ACL_Update_Wiki_Pages is new Security.Permissions.Definition ("wiki-page-update"); -- Define the permissions. package ACL_Create_Wiki_Space is new Security.Permissions.Definition ("wiki-space-create"); package ACL_Delete_Wiki_Space is new Security.Permissions.Definition ("wiki-space-delete"); package ACL_Update_Wiki_Space is new Security.Permissions.Definition ("wiki-space-update"); -- ------------------------------ -- Module wikis -- ------------------------------ type Wiki_Module is new AWA.Modules.Module with private; type Wiki_Module_Access is access all Wiki_Module'Class; -- Initialize the wikis module. overriding procedure Initialize (Plugin : in out Wiki_Module; App : in AWA.Modules.Application_Access; Props : in ASF.Applications.Config); -- Get the wikis module. function Get_Wiki_Module return Wiki_Module_Access; -- Create the wiki space. procedure Create_Wiki_Space (Module : in Wiki_Module; Wiki : in out AWA.Wikis.Models.Wiki_Space_Ref'Class); -- Save the wiki space. procedure Save_Wiki_Space (Module : in Wiki_Module; Wiki : in out AWA.Wikis.Models.Wiki_Space_Ref'Class); -- Load the wiki space. procedure Load_Wiki_Space (Module : in Wiki_Module; Wiki : in out AWA.Wikis.Models.Wiki_Space_Ref'Class; Id : in ADO.Identifier); -- Create the wiki page into the wiki space. procedure Create_Wiki_Page (Model : in Wiki_Module; Into : in AWA.Wikis.Models.Wiki_Space_Ref'Class; Page : in out Awa.Wikis.Models.Wiki_Page_Ref'Class); -- Save the wiki page. procedure Save (Model : in Wiki_Module; Page : in out Awa.Wikis.Models.Wiki_Page_Ref'Class); private type Wiki_Module is new AWA.Modules.Module with null record; end AWA.Wikis.Modules;
Declare the Create_Wiki_Page and Save procedures
Declare the Create_Wiki_Page and Save procedures
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
9af6dad8479cd93cfce048084521afb8f6592078
src/wiki-streams-text_io.adb
src/wiki-streams-text_io.adb
----------------------------------------------------------------------- -- wiki-streams-text_io -- Text_IO input output streams -- Copyright (C) 2016, 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.IO_Exceptions; with Wiki.Helpers; package body Wiki.Streams.Text_IO is -- ------------------------------ -- Open the file and prepare to read the input stream. -- ------------------------------ procedure Open (Stream : in out File_Input_Stream; Path : in String; Form : in String := "") is begin Ada.Wide_Wide_Text_IO.Open (Stream.File, Ada.Wide_Wide_Text_IO.In_File, Path, Form); Stream.Stdin := False; end Open; -- ------------------------------ -- Close the file. -- ------------------------------ procedure Close (Stream : in out File_Input_Stream) is begin if Ada.Wide_Wide_Text_IO.Is_Open (Stream.File) then Ada.Wide_Wide_Text_IO.Close (Stream.File); end if; end Close; -- ------------------------------ -- Close the stream. -- ------------------------------ overriding procedure Finalize (Stream : in out File_Input_Stream) is begin Stream.Close; end Finalize; -- ------------------------------ -- Read the input stream and fill the `Into` buffer until either it is full or -- we reach the end of line. Returns in `Last` the last valid position in the -- `Into` buffer. When there is no character to read, return True in -- the `Eof` indicator. -- ------------------------------ overriding procedure Read (Input : in out File_Input_Stream; Into : in out Wiki.Strings.WString; Last : out Natural; Eof : out Boolean) is Available : Boolean; Pos : Natural := Into'First; Char : Wiki.Strings.WChar; begin Eof := False; while Pos <= Into'Last loop if Input.Stdin then Ada.Wide_Wide_Text_IO.Get_Immediate (Char, Available); else Ada.Wide_Wide_Text_IO.Get_Immediate (Input.File, Char, Available); end if; Into (Pos) := Char; Pos := Pos + 1; exit when Char = Helpers.LF or Char = Helpers.CR; end loop; Last := Pos - 1; exception when Ada.IO_Exceptions.End_Error => Last := Pos - 1; Eof := True; end Read; -- ------------------------------ -- Open the file and prepare to write the output stream. -- ------------------------------ procedure Open (Stream : in out File_Output_Stream; Path : in String; Form : in String := "") is begin if Ada.Wide_Wide_Text_IO.Is_Open (Stream.File) then Ada.Wide_Wide_Text_IO.Close (Stream.File); end if; Ada.Wide_Wide_Text_IO.Open (Stream.File, Ada.Wide_Wide_Text_IO.Out_File, Path, Form); Ada.Wide_Wide_Text_IO.Set_Line_Length (Ada.Wide_Wide_Text_IO.Count'Last); Stream.Stdout := False; end Open; -- ------------------------------ -- Create the file and prepare to write the output stream. -- ------------------------------ procedure Create (Stream : in out File_Output_Stream; Path : in String; Form : in String := "") is begin Ada.Wide_Wide_Text_IO.Create (Stream.File, Ada.Wide_Wide_Text_IO.Out_File, Path, Form); Ada.Wide_Wide_Text_IO.Set_Line_Length (Ada.Wide_Wide_Text_IO.Count'Last); Stream.Stdout := False; end Create; -- ------------------------------ -- Close the file. -- ------------------------------ procedure Close (Stream : in out File_Output_Stream) is begin if Ada.Wide_Wide_Text_IO.Is_Open (Stream.File) then Ada.Wide_Wide_Text_IO.Close (Stream.File); end if; end Close; -- ------------------------------ -- Write the string to the output stream. -- ------------------------------ overriding procedure Write (Stream : in out File_Output_Stream; Content : in Wiki.Strings.WString) is begin if not Stream.Stdout then Ada.Wide_Wide_Text_IO.Put (Stream.File, Content); else Ada.Wide_Wide_Text_IO.Put (Content); end if; end Write; -- ------------------------------ -- Write a single character to the output stream. -- ------------------------------ overriding procedure Write (Stream : in out File_Output_Stream; Char : in Wiki.Strings.WChar) is begin if not Stream.Stdout then Ada.Wide_Wide_Text_IO.Put (Stream.File, Char); else Ada.Wide_Wide_Text_IO.Put (Char); end if; end Write; -- ------------------------------ -- Close the stream. -- ------------------------------ overriding procedure Finalize (Stream : in out File_Output_Stream) is begin Stream.Close; end Finalize; end Wiki.Streams.Text_IO;
----------------------------------------------------------------------- -- wiki-streams-text_io -- Text_IO input output streams -- Copyright (C) 2016, 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.IO_Exceptions; with Wiki.Helpers; package body Wiki.Streams.Text_IO is -- ------------------------------ -- Open the file and prepare to read the input stream. -- ------------------------------ procedure Open (Stream : in out File_Input_Stream; Path : in String; Form : in String := "") is begin Ada.Wide_Wide_Text_IO.Open (Stream.File, Ada.Wide_Wide_Text_IO.In_File, Path, Form); Stream.Stdin := False; end Open; -- ------------------------------ -- Close the file. -- ------------------------------ procedure Close (Stream : in out File_Input_Stream) is begin if Ada.Wide_Wide_Text_IO.Is_Open (Stream.File) then Ada.Wide_Wide_Text_IO.Close (Stream.File); end if; end Close; -- ------------------------------ -- Close the stream. -- ------------------------------ overriding procedure Finalize (Stream : in out File_Input_Stream) is begin Stream.Close; end Finalize; -- ------------------------------ -- Read the input stream and fill the `Into` buffer until either it is full or -- we reach the end of line. Returns in `Last` the last valid position in the -- `Into` buffer. When there is no character to read, return True in -- the `Eof` indicator. -- ------------------------------ overriding procedure Read (Input : in out File_Input_Stream; Into : in out Wiki.Strings.WString; Last : out Natural; Eof : out Boolean) is Available : Boolean; Pos : Natural := Into'First; Char : Wiki.Strings.WChar; begin if Input.Stdin then if not Ada.Wide_Wide_Text_Io.End_Of_File then Ada.Wide_Wide_Text_IO.Get_Line (Into, Last); if Last < Into'Last then Into (Last + 1) := Helpers.Lf; Last := Last + 1; end if; Eof := False; else Last := Into'First - 1; Eof := True; end if; else if not Ada.Wide_Wide_Text_Io.End_Of_File (Input.File) then Ada.Wide_Wide_Text_IO.Get_Line (Input.File, Into, Last); if Last < Into'Last then Into (Last + 1) := Helpers.Lf; Last := Last + 1; end if; Eof := False; else Last := Into'First - 1; Eof := True; end if; end if; -- Eof := False; -- while Pos <= Into'Last loop -- if Input.Stdin then -- Ada.Wide_Wide_Text_IO.Get_Immediate (Char, Available); -- else -- Ada.Wide_Wide_Text_IO.Get_Immediate (Input.File, Char, Available); -- end if; -- Into (Pos) := Char; -- Pos := Pos + 1; -- exit when Char = Helpers.LF or Char = Helpers.CR; -- end loop; -- Last := Pos - 1; exception when Ada.IO_Exceptions.End_Error => Last := Pos - 1; Eof := True; end Read; -- ------------------------------ -- Open the file and prepare to write the output stream. -- ------------------------------ procedure Open (Stream : in out File_Output_Stream; Path : in String; Form : in String := "") is begin if Ada.Wide_Wide_Text_IO.Is_Open (Stream.File) then Ada.Wide_Wide_Text_IO.Close (Stream.File); end if; Ada.Wide_Wide_Text_IO.Open (Stream.File, Ada.Wide_Wide_Text_IO.Out_File, Path, Form); Ada.Wide_Wide_Text_IO.Set_Line_Length (Ada.Wide_Wide_Text_IO.Count'Last); Stream.Stdout := False; end Open; -- ------------------------------ -- Create the file and prepare to write the output stream. -- ------------------------------ procedure Create (Stream : in out File_Output_Stream; Path : in String; Form : in String := "") is begin Ada.Wide_Wide_Text_IO.Create (Stream.File, Ada.Wide_Wide_Text_IO.Out_File, Path, Form); Ada.Wide_Wide_Text_IO.Set_Line_Length (Ada.Wide_Wide_Text_IO.Count'Last); Stream.Stdout := False; end Create; -- ------------------------------ -- Close the file. -- ------------------------------ procedure Close (Stream : in out File_Output_Stream) is begin if Ada.Wide_Wide_Text_IO.Is_Open (Stream.File) then Ada.Wide_Wide_Text_IO.Close (Stream.File); end if; end Close; -- ------------------------------ -- Write the string to the output stream. -- ------------------------------ overriding procedure Write (Stream : in out File_Output_Stream; Content : in Wiki.Strings.WString) is begin if not Stream.Stdout then Ada.Wide_Wide_Text_IO.Put (Stream.File, Content); else Ada.Wide_Wide_Text_IO.Put (Content); end if; end Write; -- ------------------------------ -- Write a single character to the output stream. -- ------------------------------ overriding procedure Write (Stream : in out File_Output_Stream; Char : in Wiki.Strings.WChar) is begin if not Stream.Stdout then Ada.Wide_Wide_Text_IO.Put (Stream.File, Char); else Ada.Wide_Wide_Text_IO.Put (Char); end if; end Write; -- ------------------------------ -- Close the stream. -- ------------------------------ overriding procedure Finalize (Stream : in out File_Output_Stream) is begin Stream.Close; end Finalize; end Wiki.Streams.Text_IO;
Update to use Get_Line
Update to use Get_Line
Ada
apache-2.0
stcarrez/ada-wiki,stcarrez/ada-wiki
f05dfdf3a7d5abf989fe2f3b9dc5383a9fdabe73
awa/plugins/awa-images/src/awa-images-services.adb
awa/plugins/awa-images/src/awa-images-services.adb
----------------------------------------------------------------------- -- awa-images-services -- Image service -- Copyright (C) 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Processes; with Util.Beans.Objects; with Util.Log.Loggers; with Util.Streams.Pipes; with Util.Streams.Texts; with ADO.Sessions; with AWA.Images.Models; with AWA.Services.Contexts; with AWA.Storages.Services; with AWA.Storages.Modules; with Ada.Strings.Unbounded; with EL.Variables.Default; with EL.Contexts.Default; -- == Storage Service == -- The <tt>Storage_Service</tt> provides the operations to access and use the persisent storage. -- It controls the permissions that grant access to the service for users. -- -- Other modules can be notified of storage changes by registering a listener -- on the storage module. package body AWA.Images.Services is package ASC renames Awa.Services.Contexts; -- ------------------------------ -- Image Service -- ------------------------------ Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("AWA.Images.Services"); -- ------------------------------ -- Initializes the storage service. -- ------------------------------ overriding procedure Initialize (Service : in out Image_Service; Module : in AWA.Modules.Module'Class) is begin AWA.Modules.Module_Manager (Service).Initialize (Module); declare Ctx : EL.Contexts.Default.Default_Context; Command : constant String := Module.Get_Config (PARAM_THUMBNAIL_COMMAND); begin Service.Thumbnail_Command := EL.Expressions.Create_Expression (Command, Ctx); exception when E : others => Log.Error ("Invalid thumbnail command: ", E, True); end; end Initialize; procedure Create_Thumbnail (Service : in Image_Service; Source : in String; Into : in String; Width : out Natural; Height : out Natural) is Ctx : EL.Contexts.Default.Default_Context; Variables : aliased EL.Variables.Default.Default_Variable_Mapper; Proc : Util.Processes.Process; Pipe : aliased Util.Streams.Pipes.Pipe_Stream; begin Variables.Bind ("src", Util.Beans.Objects.To_Object (Source)); Variables.Bind ("dst", Util.Beans.Objects.To_Object (Into)); Ctx.Set_Variable_Mapper (Variables'Unchecked_Access); declare Cmd : constant Util.Beans.Objects.Object := Service.Thumbnail_Command.Get_Value (Ctx); Command : constant String := Util.Beans.Objects.To_String (Cmd); Input : Util.Streams.Texts.Reader_Stream; begin Width := 0; Height := 0; Pipe.Open (Command, Util.Processes.READ); Input.Initialize (null, Pipe'Unchecked_Access, 1024); while not Input.Is_Eof loop declare Line : Ada.Strings.Unbounded.Unbounded_String; Pos : Natural; Sep : Natural; Last : Natural; begin Input.Read_Line (Into => Line, Strip => False); exit when Ada.Strings.Unbounded.Length (Line) = 0; Log.Info ("Received: {0}", Line); -- The '-verbose' option of ImageMagick reports information about the original -- image. Extract the picture width and height. -- image.png PNG 120x282 120x282+0+0 8-bit DirectClass 34.4KB 0.000u 0:00.018 Pos := Ada.Strings.Unbounded.Index (Line, " "); if Pos > 0 and Width = 0 then Pos := Ada.Strings.Unbounded.Index (Line, " ", Pos + 1); if Pos > 0 then Sep := Ada.Strings.Unbounded.Index (Line, "x", Pos + 1); Last := Ada.Strings.Unbounded.Index (Line, " ", Pos + 1); if Sep > 0 and Sep < Last then Width := Natural'Value (Ada.Strings.Unbounded.Slice (Line, Pos + 1, Sep - 1)); Height := Natural'Value (Ada.Strings.Unbounded.Slice (Line, Sep + 1, Last - 1)); end if; end if; end if; end; end loop; Pipe.Close; Util.Processes.Wait (Proc); if Pipe.Get_Exit_Status /= 0 then Log.Error ("Command {0} exited with status {1}", Command, Integer'Image (Pipe.Get_Exit_Status)); end if; end; end Create_Thumbnail; -- Save the data object contained in the <b>Data</b> part element into the -- target storage represented by <b>Into</b>. procedure Build_Thumbnail (Service : in Image_Service; Id : in ADO.Identifier; File : in AWA.Storages.Models.Storage_Ref'Class) is Storage_Service : constant AWA.Storages.Services.Storage_Service_Access := AWA.Storages.Modules.Get_Storage_Manager; Ctx : constant ASC.Service_Context_Access := ASC.Current; DB : ADO.Sessions.Master_Session := ASC.Get_Master_Session (Ctx); Img : AWA.Images.Models.Image_Ref; Local_Path : Ada.Strings.Unbounded.Unbounded_String; Target_File : AWA.Storages.Storage_File; Local_File : AWA.Storages.Storage_File; Width : Natural; Height : Natural; begin Img.Load (DB, Id); Storage_Service.Get_Local_File (From => Img.Get_Storage.Get_Id, Into => Local_File); Storage_Service.Create_Local_File (Target_File); Service.Create_Thumbnail (AWA.Storages.Get_Path (Local_File), AWA.Storages.Get_Path (Target_File), Width, Height); Img.Set_Width (Width); Img.Set_Height (Height); Img.Set_Thumb_Width (64); Img.Set_Thumb_Height (64); Ctx.Start; Img.Save (DB); -- Storage_Service.Save (Target_File); Ctx.Commit; end Build_Thumbnail; -- Save the data object contained in the <b>Data</b> part element into the -- target storage represented by <b>Into</b>. procedure Create_Image (Service : in Image_Service; File : in AWA.Storages.Models.Storage_Ref'Class) is Ctx : constant AWA.Services.Contexts.Service_Context_Access := AWA.Services.Contexts.Current; DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx); Img : AWA.Images.Models.Image_Ref; begin Ctx.Start; Img.Set_Width (0); Img.Set_Height (0); Img.Set_Thumb_Height (0); Img.Set_Thumb_Width (0); Img.Set_Storage (File); Img.Save (DB); Ctx.Commit; end Create_Image; -- Deletes the storage instance. procedure Delete_Image (Service : in Image_Service; File : in AWA.Storages.Models.Storage_Ref'Class) is begin null; end Delete_Image; end AWA.Images.Services;
----------------------------------------------------------------------- -- awa-images-services -- Image service -- Copyright (C) 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Processes; with Util.Beans.Objects; with Util.Log.Loggers; with Util.Streams.Pipes; with Util.Streams.Texts; with ADO.Sessions; with AWA.Images.Models; with AWA.Services.Contexts; with AWA.Storages.Services; with AWA.Storages.Modules; with Ada.Strings.Unbounded; with EL.Variables.Default; with EL.Contexts.Default; -- == Storage Service == -- The <tt>Storage_Service</tt> provides the operations to access and use the persisent storage. -- It controls the permissions that grant access to the service for users. -- -- Other modules can be notified of storage changes by registering a listener -- on the storage module. package body AWA.Images.Services is package ASC renames Awa.Services.Contexts; -- ------------------------------ -- Image Service -- ------------------------------ Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("AWA.Images.Services"); -- ------------------------------ -- Initializes the storage service. -- ------------------------------ overriding procedure Initialize (Service : in out Image_Service; Module : in AWA.Modules.Module'Class) is begin AWA.Modules.Module_Manager (Service).Initialize (Module); declare Ctx : EL.Contexts.Default.Default_Context; Command : constant String := Module.Get_Config (PARAM_THUMBNAIL_COMMAND); begin Service.Thumbnail_Command := EL.Expressions.Create_Expression (Command, Ctx); exception when E : others => Log.Error ("Invalid thumbnail command: ", E, True); end; end Initialize; procedure Create_Thumbnail (Service : in Image_Service; Source : in String; Into : in String; Width : out Natural; Height : out Natural) is Ctx : EL.Contexts.Default.Default_Context; Variables : aliased EL.Variables.Default.Default_Variable_Mapper; Proc : Util.Processes.Process; Pipe : aliased Util.Streams.Pipes.Pipe_Stream; begin Variables.Bind ("src", Util.Beans.Objects.To_Object (Source)); Variables.Bind ("dst", Util.Beans.Objects.To_Object (Into)); Ctx.Set_Variable_Mapper (Variables'Unchecked_Access); declare Cmd : constant Util.Beans.Objects.Object := Service.Thumbnail_Command.Get_Value (Ctx); Command : constant String := Util.Beans.Objects.To_String (Cmd); Input : Util.Streams.Texts.Reader_Stream; begin Width := 0; Height := 0; Pipe.Open (Command, Util.Processes.READ); Input.Initialize (null, Pipe'Unchecked_Access, 1024); while not Input.Is_Eof loop declare Line : Ada.Strings.Unbounded.Unbounded_String; Pos : Natural; Sep : Natural; Last : Natural; begin Input.Read_Line (Into => Line, Strip => False); exit when Ada.Strings.Unbounded.Length (Line) = 0; Log.Info ("Received: {0}", Line); -- The '-verbose' option of ImageMagick reports information about the original -- image. Extract the picture width and height. -- image.png PNG 120x282 120x282+0+0 8-bit DirectClass 34.4KB 0.000u 0:00.018 Pos := Ada.Strings.Unbounded.Index (Line, " "); if Pos > 0 and Width = 0 then Pos := Ada.Strings.Unbounded.Index (Line, " ", Pos + 1); if Pos > 0 then Sep := Ada.Strings.Unbounded.Index (Line, "x", Pos + 1); Last := Ada.Strings.Unbounded.Index (Line, "=", Pos + 1); if Sep > 0 and Sep < Last then Log.Info ("Dimension {0} - {1}..{2}", Ada.Strings.Unbounded.Slice (Line, Pos, Last), Natural'Image (Pos), Natural'Image (Last)); Width := Natural'Value (Ada.Strings.Unbounded.Slice (Line, Pos + 1, Sep - 1)); Height := Natural'Value (Ada.Strings.Unbounded.Slice (Line, Sep + 1, Last - 1)); end if; end if; end if; end; end loop; Pipe.Close; Util.Processes.Wait (Proc); if Pipe.Get_Exit_Status /= 0 then Log.Error ("Command {0} exited with status {1}", Command, Integer'Image (Pipe.Get_Exit_Status)); end if; end; end Create_Thumbnail; -- Save the data object contained in the <b>Data</b> part element into the -- target storage represented by <b>Into</b>. procedure Build_Thumbnail (Service : in Image_Service; Id : in ADO.Identifier; File : in AWA.Storages.Models.Storage_Ref'Class) is Storage_Service : constant AWA.Storages.Services.Storage_Service_Access := AWA.Storages.Modules.Get_Storage_Manager; Ctx : constant ASC.Service_Context_Access := ASC.Current; DB : ADO.Sessions.Master_Session := ASC.Get_Master_Session (Ctx); Img : AWA.Images.Models.Image_Ref; Local_Path : Ada.Strings.Unbounded.Unbounded_String; Target_File : AWA.Storages.Storage_File; Local_File : AWA.Storages.Storage_File; Width : Natural; Height : Natural; begin Img.Load (DB, Id); Storage_Service.Get_Local_File (From => Img.Get_Storage.Get_Id, Into => Local_File); Storage_Service.Create_Local_File (Target_File); Service.Create_Thumbnail (AWA.Storages.Get_Path (Local_File), AWA.Storages.Get_Path (Target_File), Width, Height); Img.Set_Width (Width); Img.Set_Height (Height); Img.Set_Thumb_Width (64); Img.Set_Thumb_Height (64); Ctx.Start; Img.Save (DB); -- Storage_Service.Save (Target_File); Ctx.Commit; end Build_Thumbnail; -- Save the data object contained in the <b>Data</b> part element into the -- target storage represented by <b>Into</b>. procedure Create_Image (Service : in Image_Service; File : in AWA.Storages.Models.Storage_Ref'Class) is Ctx : constant AWA.Services.Contexts.Service_Context_Access := AWA.Services.Contexts.Current; DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx); Img : AWA.Images.Models.Image_Ref; begin Ctx.Start; Img.Set_Width (0); Img.Set_Height (0); Img.Set_Thumb_Height (0); Img.Set_Thumb_Width (0); Img.Set_Storage (File); Img.Save (DB); Ctx.Commit; end Create_Image; -- Deletes the storage instance. procedure Delete_Image (Service : in Image_Service; File : in AWA.Storages.Models.Storage_Ref'Class) is begin null; end Delete_Image; end AWA.Images.Services;
Fix extraction of image dimension
Fix extraction of image dimension
Ada
apache-2.0
tectronics/ada-awa,Letractively/ada-awa,tectronics/ada-awa,Letractively/ada-awa,Letractively/ada-awa,tectronics/ada-awa
bba37be8c039f888285b28664593341951263a6d
awa/plugins/awa-wikis/regtests/awa-wikis-tests.adb
awa/plugins/awa-wikis/regtests/awa-wikis-tests.adb
----------------------------------------------------------------------- -- awa-wikis-tests -- Unit tests for wikis module -- Copyright (C) 2018, 2019, 2020 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Test_Caller; with Util.Strings; with ADO; with Servlet.Streams; with ASF.Requests.Mockup; with ASF.Responses.Mockup; with ASF.Tests; with AWA.Tests.Helpers.Users; with AWA.Storages.Beans; with AWA.Storages.Models; with AWA.Storages.Services; with AWA.Storages.Modules; with AWA.Services.Contexts; with Security.Contexts; package body AWA.Wikis.Tests is use Ada.Strings.Unbounded; use AWA.Tests; use type AWA.Storages.Services.Storage_Service_Access; package Caller is new Util.Test_Caller (Test, "Wikis.Beans"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test AWA.Wikis.Beans.Load_List (Anonymous)", Test_Anonymous_Access'Access); Caller.Add_Test (Suite, "Test AWA.Wikis.Beans.Save", Test_Create_Wiki'Access); Caller.Add_Test (Suite, "Test AWA.Wikis.Beans.Load (missing)", Test_Missing_Page'Access); Caller.Add_Test (Suite, "Test AWA.Wikis.Beans.Load (image)", Test_Page_With_Image'Access); end Add_Tests; -- ------------------------------ -- Setup an image for the wiki page. -- ------------------------------ procedure Make_Wiki_Image (T : in out Test) is Sec_Ctx : Security.Contexts.Security_Context; Context : AWA.Services.Contexts.Service_Context; Folder : AWA.Storages.Beans.Folder_Bean; Store : AWA.Storages.Models.Storage_Ref; Mgr : AWA.Storages.Services.Storage_Service_Access; Outcome : Ada.Strings.Unbounded.Unbounded_String; Path : constant String := Util.Tests.Get_Path ("regtests/files/images/Ada-Lovelace.jpg"); Wiki : constant String := To_String (T.Wiki_Ident); begin AWA.Tests.Helpers.Users.Login (Context, Sec_Ctx, "[email protected]"); Mgr := AWA.Storages.Modules.Get_Storage_Manager; T.Assert (Mgr /= null, "Null storage manager"); -- Make a storage folder. Folder.Module := AWA.Storages.Modules.Get_Storage_Module; Folder.Set_Name ("Images"); Folder.Save (Outcome); Store.Set_Folder (Folder); Store.Set_Is_Public (True); Store.Set_Mime_Type ("image/jpg"); Store.Set_Name ("Ada Lovelace"); Mgr.Save (Store, Path, AWA.Storages.Models.FILE); declare Request : ASF.Requests.Mockup.Request; Reply : ASF.Responses.Mockup.Response; Id : constant String := ADO.Identifier'Image (Store.Get_Id); begin T.Image_Ident := To_Unbounded_String (Id (Id'First + 1 .. Id'Last)); AWA.Tests.Helpers.Users.Login ("[email protected]", Request); ASF.Tests.Do_Get (Request, Reply, "/wikis/images/" & Wiki & "/" & Id (Id'First + 1 .. Id'Last) & "/original/Ada-Lovelace.jpg", "wiki-image-get-Ada-Lovelace.jpg"); ASF.Tests.Assert_Header (T, "Content-Type", "image/jpg", Reply); Util.Tests.Assert_Equals (T, Servlet.Responses.SC_OK, Reply.Get_Status, "Invalid response for image"); end; end Make_Wiki_Image; -- ------------------------------ -- Get some access on the wiki as anonymous users. -- ------------------------------ procedure Verify_Anonymous (T : in out Test; Page : in String; Title : in String) is pragma Unreferenced (Title); function Get_Link (Title : in String) return String; Wiki : constant String := To_String (T.Wiki_Ident); Request : ASF.Requests.Mockup.Request; Reply : ASF.Responses.Mockup.Response; function Get_Link (Title : in String) return String is Stream : Servlet.Streams.Print_Stream := Reply.Get_Output_Stream; Content : Ada.Strings.Unbounded.Unbounded_String; begin Reply.Read_Content (Content); Stream.Write (Content); return AWA.Tests.Helpers.Extract_Link (To_String (Content), Title); end Get_Link; begin ASF.Tests.Do_Get (Request, Reply, "/wikis/list/" & Wiki & "/recent", "wiki-list-recent.html"); ASF.Tests.Assert_Contains (T, "List of pages", Reply, "Wiki list recent page is invalid"); ASF.Tests.Do_Get (Request, Reply, "/wikis/tags/" & Wiki, "wiki-list-tagged.html"); ASF.Tests.Assert_Contains (T, "List of pages", Reply, "Wiki tag page is invalid"); if Page'Length > 0 then ASF.Tests.Do_Get (Request, Reply, "/wikis/view/" & Wiki & "/" & Page, "wiki-page-" & Page & ".html"); ASF.Tests.Assert_Contains (T, "The wiki page content", Reply, "Wiki page " & Page & " is invalid"); declare Info : constant String := Get_Link ("Info"); History : constant String := Get_Link ("History"); begin Util.Tests.Assert_Matches (T, "/asfunit/wikis/info/[0-9]+/[0-9]+$", Info, "Invalid wiki info link in the response"); Util.Tests.Assert_Matches (T, "/asfunit/wikis/history/[0-9]+/[0-9]+$", History, "Invalid wiki history link in the response"); -- Get the information page. ASF.Tests.Do_Get (Request, Reply, Info (Info'First + 8 .. Info'Last), "wiki-info-" & Page & ".html"); ASF.Tests.Assert_Contains (T, "wiki-word-list", Reply, "Wiki info page " & Page & " is invalid"); -- Get the history page. ASF.Tests.Do_Get (Request, Reply, History (History'First + 8 .. History'Last), "wiki-history-" & Page & ".html"); ASF.Tests.Assert_Contains (T, "wiki-page-version", Reply, "Wiki history page " & Page & " is invalid"); end; end if; end Verify_Anonymous; -- ------------------------------ -- Verify that the wiki lists contain the given page. -- ------------------------------ procedure Verify_List_Contains (T : in out Test; Page : in String) is Wiki : constant String := To_String (T.Wiki_Ident); Request : ASF.Requests.Mockup.Request; Reply : ASF.Responses.Mockup.Response; begin ASF.Tests.Do_Get (Request, Reply, "/wikis/list/" & Wiki & "/recent", "wiki-list-recent.html"); ASF.Tests.Assert_Contains (T, "List of pages", Reply, "Wiki list recent page is invalid"); ASF.Tests.Assert_Contains (T, "/wikis/view/" & To_String (T.Wiki_Ident) & "/" & Page, Reply, "Wiki list recent page does not reference the page"); ASF.Tests.Do_Get (Request, Reply, "/wikis/list/" & Wiki & "/popular", "wiki-list-popular.html"); ASF.Tests.Assert_Contains (T, "List of pages", Reply, "Wiki list popular page is invalid"); ASF.Tests.Assert_Contains (T, "/wikis/view/" & To_String (T.Wiki_Ident) & "/" & Page, Reply, "Wiki list popular page does not reference the page"); ASF.Tests.Do_Get (Request, Reply, "/wikis/list/" & Wiki & "/name", "wiki-list-name.html"); ASF.Tests.Assert_Contains (T, "List of pages", Reply, "Wiki list name page is invalid"); ASF.Tests.Assert_Contains (T, "/wikis/view/" & To_String (T.Wiki_Ident) & "/" & Page, Reply, "Wiki list name page does not reference the page"); ASF.Tests.Do_Get (Request, Reply, "/wikis/list/" & Wiki & "/name/grid", "wiki-list-name-grid.html"); ASF.Tests.Assert_Contains (T, "List of pages", Reply, "Wiki list name/grid page is invalid"); ASF.Tests.Assert_Contains (T, "/wikis/view/" & To_String (T.Wiki_Ident) & "/" & Page, Reply, "Wiki list name/grid page does not reference the page"); end Verify_List_Contains; -- ------------------------------ -- Test access to the blog as anonymous user. -- ------------------------------ procedure Test_Anonymous_Access (T : in out Test) is begin T.Verify_Anonymous ("", ""); end Test_Anonymous_Access; -- ------------------------------ -- Create a wiki page. -- ------------------------------ procedure Create_Page (T : in out Test; Request : in out ASF.Requests.Mockup.Request; Reply : in out ASF.Responses.Mockup.Response; Name : in String; Title : in String) is begin Request.Set_Parameter ("page-wiki-id", To_String (T.Wiki_Ident)); Request.Set_Parameter ("post", "1"); Request.Set_Parameter ("page-title", Title); Request.Set_Parameter ("text", "# Main title" & ASCII.LF & "* The wiki page content." & ASCII.LF & "* Second item." & ASCII.LF & ASCII.LF & "![Ada Lovelace](Images/Ada-Lovelace.jpg)"); Request.Set_Parameter ("name", Name); Request.Set_Parameter ("comment", "Created wiki page " & Name); Request.Set_Parameter ("save", "1"); Request.Set_Parameter ("page-is-public", "1"); Request.Set_Parameter ("wiki-format", "FORMAT_MARKDOWN"); ASF.Tests.Do_Post (Request, Reply, "/wikis/create.html", "create-wiki.html"); T.Page_Ident := Helpers.Extract_Redirect (Reply, "/asfunit/wikis/view/" & To_String (T.Wiki_Ident) & "/"); Util.Tests.Assert_Equals (T, Name, To_String (T.Page_Ident), "Invalid redirect after wiki page creation"); -- Remove the 'wikiPage' bean from the request so that we get a new instance -- for the next call. Request.Remove_Attribute ("wikiPage"); end Create_Page; -- ------------------------------ -- Test creation of blog by simulating web requests. -- ------------------------------ procedure Test_Create_Wiki (T : in out Test) is Request : ASF.Requests.Mockup.Request; Reply : ASF.Responses.Mockup.Response; begin AWA.Tests.Helpers.Users.Login ("[email protected]", Request); Request.Set_Parameter ("title", "The Wiki Space Title"); Request.Set_Parameter ("post", "1"); Request.Set_Parameter ("create", "1"); ASF.Tests.Do_Post (Request, Reply, "/wikis/setup.html", "setup-wiki.html"); T.Assert (Reply.Get_Status = ASF.Responses.SC_MOVED_TEMPORARILY, "Invalid response after wiki space creation"); declare Ident : constant String := Helpers.Extract_Redirect (Reply, "/asfunit/wikis/list/"); Pos : constant Natural := Util.Strings.Index (Ident, '/'); begin Util.Tests.Assert_Matches (T, "^[0-9]+/recent/grid$", Ident, "Invalid wiki space identifier in the response"); T.Wiki_Ident := To_Unbounded_String (Ident (Ident'First .. Pos - 1)); end; T.Create_Page (Request, Reply, "WikiPageTestName", "Wiki page title1"); T.Verify_List_Contains (To_String (T.Page_Ident)); T.Create_Page (Request, Reply, "WikiSecondPageName", "Wiki page title2"); T.Verify_List_Contains (To_String (T.Page_Ident)); T.Create_Page (Request, Reply, "WikiThirdPageName", "Wiki page title3"); T.Verify_Anonymous ("WikiPageTestName", "Wiki page title1"); T.Verify_Anonymous ("WikiSecondPageName", "Wiki page title2"); T.Verify_Anonymous ("WikiThirdPageName", "Wiki page title3"); end Test_Create_Wiki; -- ------------------------------ -- Test getting a wiki page which does not exist. -- ------------------------------ procedure Test_Missing_Page (T : in out Test) is Wiki : constant String := To_String (T.Wiki_Ident); Request : ASF.Requests.Mockup.Request; Reply : ASF.Responses.Mockup.Response; begin ASF.Tests.Do_Get (Request, Reply, "/wikis/view/" & Wiki & "/MissingPage", "wiki-page-missing.html"); ASF.Tests.Assert_Matches (T, ".title.Wiki page does not exist./title.", Reply, "Wiki page 'MissingPage' is invalid", ASF.Responses.SC_NOT_FOUND); ASF.Tests.Assert_Matches (T, ".h2.MissingPage./h2.", Reply, "Wiki page 'MissingPage' header is invalid", ASF.Responses.SC_NOT_FOUND); end Test_Missing_Page; -- ------------------------------ -- Test creation of wiki page with an image. -- ------------------------------ procedure Test_Page_With_Image (T : in out Test) is Request : ASF.Requests.Mockup.Request; Reply : ASF.Responses.Mockup.Response; Wiki : constant String := To_String (T.Wiki_Ident); begin AWA.Tests.Helpers.Users.Login ("[email protected]", Request); T.Make_Wiki_Image; T.Create_Page (Request, Reply, "WikiImageTest", "Wiki image title3"); ASF.Tests.Do_Get (Request, Reply, "/wikis/view/" & Wiki & "/WikiImageTest", "wiki-image-test.html"); ASF.Tests.Assert_Matches (T, "<img src=./wikis/images/[0-9]*/[0-9]*" & "/default/Ada-Lovelace.jpg. alt=.Ada Lovelace.></img>", Reply, "Wiki page missing image link", ASF.Responses.SC_OK); end Test_Page_With_Image; end AWA.Wikis.Tests;
----------------------------------------------------------------------- -- awa-wikis-tests -- Unit tests for wikis module -- Copyright (C) 2018, 2019, 2020 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Test_Caller; with Util.Strings; with ADO; with Servlet.Streams; with ASF.Tests; with AWA.Tests.Helpers.Users; with AWA.Storages.Beans; with AWA.Storages.Models; with AWA.Storages.Services; with AWA.Storages.Modules; with AWA.Services.Contexts; with Security.Contexts; package body AWA.Wikis.Tests is use Ada.Strings.Unbounded; use AWA.Tests; use type AWA.Storages.Services.Storage_Service_Access; package Caller is new Util.Test_Caller (Test, "Wikis.Beans"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test AWA.Wikis.Beans.Load_List (Anonymous)", Test_Anonymous_Access'Access); Caller.Add_Test (Suite, "Test AWA.Wikis.Beans.Save", Test_Create_Wiki'Access); Caller.Add_Test (Suite, "Test AWA.Wikis.Beans.Load (missing)", Test_Missing_Page'Access); Caller.Add_Test (Suite, "Test AWA.Wikis.Beans.Load (image)", Test_Page_With_Image'Access); end Add_Tests; -- ------------------------------ -- Setup an image for the wiki page. -- ------------------------------ procedure Make_Wiki_Image (T : in out Test) is Sec_Ctx : Security.Contexts.Security_Context; Context : AWA.Services.Contexts.Service_Context; Folder : AWA.Storages.Beans.Folder_Bean; Store : AWA.Storages.Models.Storage_Ref; Mgr : AWA.Storages.Services.Storage_Service_Access; Outcome : Ada.Strings.Unbounded.Unbounded_String; Path : constant String := Util.Tests.Get_Path ("regtests/files/images/Ada-Lovelace.jpg"); Wiki : constant String := To_String (T.Wiki_Ident); begin AWA.Tests.Helpers.Users.Login (Context, Sec_Ctx, "[email protected]"); Mgr := AWA.Storages.Modules.Get_Storage_Manager; T.Assert (Mgr /= null, "Null storage manager"); -- Make a storage folder. Folder.Module := AWA.Storages.Modules.Get_Storage_Module; Folder.Set_Name ("Images"); Folder.Save (Outcome); Store.Set_Folder (Folder); Store.Set_Is_Public (True); Store.Set_Mime_Type ("image/jpg"); Store.Set_Name ("Ada Lovelace"); Mgr.Save (Store, Path, AWA.Storages.Models.FILE); declare Request : ASF.Requests.Mockup.Request; Reply : ASF.Responses.Mockup.Response; Id : constant String := ADO.Identifier'Image (Store.Get_Id); begin T.Image_Ident := To_Unbounded_String (Id (Id'First + 1 .. Id'Last)); AWA.Tests.Helpers.Users.Login ("[email protected]", Request); ASF.Tests.Do_Get (Request, Reply, "/wikis/images/" & Wiki & "/" & Id (Id'First + 1 .. Id'Last) & "/original/Ada-Lovelace.jpg", "wiki-image-get-Ada-Lovelace.jpg"); ASF.Tests.Assert_Header (T, "Content-Type", "image/jpg", Reply); Util.Tests.Assert_Equals (T, Servlet.Responses.SC_OK, Reply.Get_Status, "Invalid response for image"); T.Image_Link := To_Unbounded_String ("/wikis/images/" & Wiki & "/" & Id (Id'First + 1 .. Id'Last) & "/default/Ada-Lovelace.jpg"); end; end Make_Wiki_Image; -- ------------------------------ -- Get some access on the wiki as anonymous users. -- ------------------------------ procedure Verify_Anonymous (T : in out Test; Page : in String; Title : in String) is pragma Unreferenced (Title); function Get_Link (Title : in String) return String; Wiki : constant String := To_String (T.Wiki_Ident); Request : ASF.Requests.Mockup.Request; Reply : ASF.Responses.Mockup.Response; function Get_Link (Title : in String) return String is Stream : Servlet.Streams.Print_Stream := Reply.Get_Output_Stream; Content : Ada.Strings.Unbounded.Unbounded_String; begin Reply.Read_Content (Content); Stream.Write (Content); return AWA.Tests.Helpers.Extract_Link (To_String (Content), Title); end Get_Link; begin ASF.Tests.Do_Get (Request, Reply, "/wikis/list/" & Wiki & "/recent", "wiki-list-recent.html"); ASF.Tests.Assert_Contains (T, "List of pages", Reply, "Wiki list recent page is invalid"); ASF.Tests.Do_Get (Request, Reply, "/wikis/tags/" & Wiki, "wiki-list-tagged.html"); ASF.Tests.Assert_Contains (T, "List of pages", Reply, "Wiki tag page is invalid"); if Page'Length > 0 then ASF.Tests.Do_Get (Request, Reply, "/wikis/view/" & Wiki & "/" & Page, "wiki-page-" & Page & ".html"); ASF.Tests.Assert_Contains (T, "The wiki page content", Reply, "Wiki page " & Page & " is invalid"); declare Info : constant String := Get_Link ("Info"); History : constant String := Get_Link ("History"); begin Util.Tests.Assert_Matches (T, "/asfunit/wikis/info/[0-9]+/[0-9]+$", Info, "Invalid wiki info link in the response"); Util.Tests.Assert_Matches (T, "/asfunit/wikis/history/[0-9]+/[0-9]+$", History, "Invalid wiki history link in the response"); -- Get the information page. ASF.Tests.Do_Get (Request, Reply, Info (Info'First + 8 .. Info'Last), "wiki-info-" & Page & ".html"); ASF.Tests.Assert_Contains (T, "wiki-word-list", Reply, "Wiki info page " & Page & " is invalid"); -- Get the history page. ASF.Tests.Do_Get (Request, Reply, History (History'First + 8 .. History'Last), "wiki-history-" & Page & ".html"); ASF.Tests.Assert_Contains (T, "wiki-page-version", Reply, "Wiki history page " & Page & " is invalid"); end; end if; end Verify_Anonymous; -- ------------------------------ -- Verify that the wiki lists contain the given page. -- ------------------------------ procedure Verify_List_Contains (T : in out Test; Page : in String) is Wiki : constant String := To_String (T.Wiki_Ident); Request : ASF.Requests.Mockup.Request; Reply : ASF.Responses.Mockup.Response; begin ASF.Tests.Do_Get (Request, Reply, "/wikis/list/" & Wiki & "/recent", "wiki-list-recent.html"); ASF.Tests.Assert_Contains (T, "List of pages", Reply, "Wiki list recent page is invalid"); ASF.Tests.Assert_Contains (T, "/wikis/view/" & To_String (T.Wiki_Ident) & "/" & Page, Reply, "Wiki list recent page does not reference the page"); ASF.Tests.Do_Get (Request, Reply, "/wikis/list/" & Wiki & "/popular", "wiki-list-popular.html"); ASF.Tests.Assert_Contains (T, "List of pages", Reply, "Wiki list popular page is invalid"); ASF.Tests.Assert_Contains (T, "/wikis/view/" & To_String (T.Wiki_Ident) & "/" & Page, Reply, "Wiki list popular page does not reference the page"); ASF.Tests.Do_Get (Request, Reply, "/wikis/list/" & Wiki & "/name", "wiki-list-name.html"); ASF.Tests.Assert_Contains (T, "List of pages", Reply, "Wiki list name page is invalid"); ASF.Tests.Assert_Contains (T, "/wikis/view/" & To_String (T.Wiki_Ident) & "/" & Page, Reply, "Wiki list name page does not reference the page"); ASF.Tests.Do_Get (Request, Reply, "/wikis/list/" & Wiki & "/name/grid", "wiki-list-name-grid.html"); ASF.Tests.Assert_Contains (T, "List of pages", Reply, "Wiki list name/grid page is invalid"); ASF.Tests.Assert_Contains (T, "/wikis/view/" & To_String (T.Wiki_Ident) & "/" & Page, Reply, "Wiki list name/grid page does not reference the page"); end Verify_List_Contains; -- ------------------------------ -- Test access to the blog as anonymous user. -- ------------------------------ procedure Test_Anonymous_Access (T : in out Test) is begin T.Verify_Anonymous ("", ""); end Test_Anonymous_Access; -- ------------------------------ -- Create a wiki page. -- ------------------------------ procedure Create_Page (T : in out Test; Request : in out ASF.Requests.Mockup.Request; Reply : in out ASF.Responses.Mockup.Response; Name : in String; Title : in String) is begin Request.Set_Parameter ("page-wiki-id", To_String (T.Wiki_Ident)); Request.Set_Parameter ("post", "1"); Request.Set_Parameter ("page-title", Title); Request.Set_Parameter ("text", "# Main title" & ASCII.LF & "* The wiki page content." & ASCII.LF & "* Second item." & ASCII.LF & ASCII.LF & "![Ada Lovelace](Images/Ada-Lovelace.jpg)"); Request.Set_Parameter ("name", Name); Request.Set_Parameter ("comment", "Created wiki page " & Name); Request.Set_Parameter ("save", "1"); Request.Set_Parameter ("page-is-public", "1"); Request.Set_Parameter ("wiki-format", "FORMAT_MARKDOWN"); ASF.Tests.Do_Post (Request, Reply, "/wikis/create.html", "create-wiki.html"); T.Page_Ident := Helpers.Extract_Redirect (Reply, "/asfunit/wikis/view/" & To_String (T.Wiki_Ident) & "/"); Util.Tests.Assert_Equals (T, Name, To_String (T.Page_Ident), "Invalid redirect after wiki page creation"); -- Remove the 'wikiPage' bean from the request so that we get a new instance -- for the next call. Request.Remove_Attribute ("wikiPage"); end Create_Page; -- ------------------------------ -- Test creation of blog by simulating web requests. -- ------------------------------ procedure Test_Create_Wiki (T : in out Test) is Request : ASF.Requests.Mockup.Request; Reply : ASF.Responses.Mockup.Response; begin AWA.Tests.Helpers.Users.Login ("[email protected]", Request); Request.Set_Parameter ("title", "The Wiki Space Title"); Request.Set_Parameter ("post", "1"); Request.Set_Parameter ("create", "1"); ASF.Tests.Do_Post (Request, Reply, "/wikis/setup.html", "setup-wiki.html"); T.Assert (Reply.Get_Status = ASF.Responses.SC_MOVED_TEMPORARILY, "Invalid response after wiki space creation"); declare Ident : constant String := Helpers.Extract_Redirect (Reply, "/asfunit/wikis/list/"); Pos : constant Natural := Util.Strings.Index (Ident, '/'); begin Util.Tests.Assert_Matches (T, "^[0-9]+/recent/grid$", Ident, "Invalid wiki space identifier in the response"); T.Wiki_Ident := To_Unbounded_String (Ident (Ident'First .. Pos - 1)); end; T.Create_Page (Request, Reply, "WikiPageTestName", "Wiki page title1"); T.Verify_List_Contains (To_String (T.Page_Ident)); T.Create_Page (Request, Reply, "WikiSecondPageName", "Wiki page title2"); T.Verify_List_Contains (To_String (T.Page_Ident)); T.Create_Page (Request, Reply, "WikiThirdPageName", "Wiki page title3"); T.Verify_Anonymous ("WikiPageTestName", "Wiki page title1"); T.Verify_Anonymous ("WikiSecondPageName", "Wiki page title2"); T.Verify_Anonymous ("WikiThirdPageName", "Wiki page title3"); end Test_Create_Wiki; -- ------------------------------ -- Test getting a wiki page which does not exist. -- ------------------------------ procedure Test_Missing_Page (T : in out Test) is Wiki : constant String := To_String (T.Wiki_Ident); Request : ASF.Requests.Mockup.Request; Reply : ASF.Responses.Mockup.Response; begin ASF.Tests.Do_Get (Request, Reply, "/wikis/view/" & Wiki & "/MissingPage", "wiki-page-missing.html"); ASF.Tests.Assert_Matches (T, ".title.Wiki page does not exist./title.", Reply, "Wiki page 'MissingPage' is invalid", ASF.Responses.SC_NOT_FOUND); ASF.Tests.Assert_Matches (T, ".h2.MissingPage./h2.", Reply, "Wiki page 'MissingPage' header is invalid", ASF.Responses.SC_NOT_FOUND); end Test_Missing_Page; -- ------------------------------ -- Test creation of wiki page with an image. -- ------------------------------ procedure Test_Page_With_Image (T : in out Test) is Request : ASF.Requests.Mockup.Request; Reply : ASF.Responses.Mockup.Response; Wiki : constant String := To_String (T.Wiki_Ident); begin AWA.Tests.Helpers.Users.Login ("[email protected]", Request); T.Make_Wiki_Image; T.Create_Page (Request, Reply, "WikiImageTest", "Wiki image title3"); ASF.Tests.Do_Get (Request, Reply, "/wikis/view/" & Wiki & "/WikiImageTest", "wiki-image-test.html"); ASF.Tests.Assert_Matches (T, "<img src=./wikis/images/[0-9]*/[0-9]*" & "/default/Ada-Lovelace.jpg. alt=.Ada Lovelace.></img>", Reply, "Wiki page missing image link", ASF.Responses.SC_OK); ASF.Tests.Do_Get (Request, Reply, To_String (T.Image_Link), "wiki-image-get-Ada-Lovelace.jpg"); ASF.Tests.Assert_Header (T, "Content-Type", "image/jpg", Reply); Util.Tests.Assert_Equals (T, Servlet.Responses.SC_OK, Reply.Get_Status, "Invalid response for image"); end Test_Page_With_Image; end AWA.Wikis.Tests;
Update the Test_Page_With_Image test to get the image included in the page through the wiki image servlet
Update the Test_Page_With_Image test to get the image included in the page through the wiki image servlet
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
84fb2e89df20dbded7b83a0ad910d9d56d1ad16b
mat/src/mat-formats.ads
mat/src/mat-formats.ads
----------------------------------------------------------------------- -- mat-formats - Format various types for the console or GUI interface -- Copyright (C) 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with MAT.Types; with MAT.Events.Targets; package MAT.Formats is -- Format the address into a string. function Addr (Value : in MAT.Types.Target_Addr) return String; -- Format the size into a string. function Size (Value : in MAT.Types.Target_Size) return String; -- Format a file, line, function information into a string. function Location (File : in Ada.Strings.Unbounded.Unbounded_String; Line : in Natural; Func : in Ada.Strings.Unbounded.Unbounded_String) return String; -- Format a short description of the event. function Event (Item : in MAT.Events.Targets.Probe_Event_Type; Related : in MAT.Events.Targets.Target_Event_Vector) return String; end MAT.Formats;
----------------------------------------------------------------------- -- mat-formats - Format various types for the console or GUI interface -- Copyright (C) 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with MAT.Types; with MAT.Events.Targets; package MAT.Formats is -- Format the address into a string. function Addr (Value : in MAT.Types.Target_Addr) return String; -- Format the size into a string. function Size (Value : in MAT.Types.Target_Size) return String; -- Format the time relative to the start time. function Time (Value : in MAT.Types.Target_Tick_Ref; Start : in MAT.Types.Target_Tick_Ref) return String; -- Format a file, line, function information into a string. function Location (File : in Ada.Strings.Unbounded.Unbounded_String; Line : in Natural; Func : in Ada.Strings.Unbounded.Unbounded_String) return String; -- Format a short description of the event. function Event (Item : in MAT.Events.Targets.Probe_Event_Type; Related : in MAT.Events.Targets.Target_Event_Vector) return String; end MAT.Formats;
Declare the Time function to format a time
Declare the Time function to format a time
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
075a39f51d442da0cf8e7ff15a9b742f484f3154
mat/src/mat-targets.adb
mat/src/mat-targets.adb
----------------------------------------------------------------------- -- Clients - Abstract representation of client information -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- package body MAT.Targets is -- ------------------------------ -- Initialize the target object to manage the memory slots, the stack frames -- and setup the reader to analyze the memory and other events. -- ------------------------------ procedure Initialize (Target : in out Target_Type; Reader : in out MAT.Readers.Manager_Base'Class) is begin MAT.Memory.Targets.Initialize (Memory => Target.Memory, Reader => Reader); end Initialize; end MAT.Targets;
----------------------------------------------------------------------- -- Clients - Abstract representation of client information -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- package body MAT.Targets is -- ------------------------------ -- Initialize the target object to manage the memory slots, the stack frames -- and setup the reader to analyze the memory and other events. -- ------------------------------ procedure Initialize (Target : in out Target_Type; Reader : in out MAT.Readers.Manager_Base'Class) is begin MAT.Memory.Targets.Initialize (Memory => Target.Memory, Reader => Reader); end Initialize; -- ------------------------------ -- Create a process instance to hold and keep track of memory and other information about -- the given process ID. -- ------------------------------ procedure Create_Process (Target : in out Target_Type; Pid : in MAT.Types.Target_Process_Ref; Process : out Target_Process_Type_Access) is begin Process := new Target_Process_Type; Process.Pid := Pid; end Create_Process; end MAT.Targets;
Implement the Create_Process procedure
Implement the Create_Process procedure
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
12c969e65215e0a61ec467a1b5b057812bfa56ed
src/asf-contexts-facelets.adb
src/asf-contexts-facelets.adb
----------------------------------------------------------------------- -- contexts-facelets -- Contexts for facelets -- Copyright (C) 2009, 2010, 2011 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Directories; with Util.Files; with Util.Log.Loggers; with EL.Variables; with ASF.Applications.Main; with ASF.Views.Nodes.Facelets; package body ASF.Contexts.Facelets is use Util.Log; -- The logger Log : constant Loggers.Logger := Loggers.Create ("ASF.Contexts.Facelets"); -- ------------------------------ -- Get the EL context for evaluating expressions. -- ------------------------------ function Get_ELContext (Context : in Facelet_Context) return EL.Contexts.ELContext_Access is begin return Context.Context; end Get_ELContext; -- ------------------------------ -- Set the EL context for evaluating expressions. -- ------------------------------ procedure Set_ELContext (Context : in out Facelet_Context; ELContext : in EL.Contexts.ELContext_Access) is begin Context.Context := ELContext; end Set_ELContext; -- ------------------------------ -- Get the function mapper associated with the EL context. -- ------------------------------ function Get_Function_Mapper (Context : in Facelet_Context) return EL.Functions.Function_Mapper_Access is use EL.Contexts; begin if Context.Context = null then return null; else return Context.Context.Get_Function_Mapper; end if; end Get_Function_Mapper; -- ------------------------------ -- Set the attribute having given name with the value. -- ------------------------------ procedure Set_Attribute (Context : in out Facelet_Context; Name : in String; Value : in EL.Objects.Object) is begin null; end Set_Attribute; -- ------------------------------ -- Set the attribute having given name with the value. -- ------------------------------ procedure Set_Attribute (Context : in out Facelet_Context; Name : in Unbounded_String; Value : in EL.Objects.Object) is begin null; end Set_Attribute; -- ------------------------------ -- Set the attribute having given name with the expression. -- ------------------------------ procedure Set_Variable (Context : in out Facelet_Context; Name : in Unbounded_String; Value : in EL.Expressions.Expression) is Mapper : constant access EL.Variables.Variable_Mapper'Class := Context.Context.Get_Variable_Mapper; begin if Mapper /= null then Mapper.Set_Variable (Name, Value); end if; end Set_Variable; -- Set the attribute having given name with the expression. procedure Set_Variable (Context : in out Facelet_Context; Name : in String; Value : in EL.Expressions.Expression) is N : Unbounded_String := To_Unbounded_String (Name); begin Set_Variable (Context, N, Value); end Set_Variable; -- ------------------------------ -- Include the facelet from the given source file. -- The included views appended to the parent component tree. -- ------------------------------ procedure Include_Facelet (Context : in out Facelet_Context; Source : in String; Parent : in Base.UIComponent_Access) is begin null; end Include_Facelet; -- ------------------------------ -- Include the definition having the given name. -- ------------------------------ procedure Include_Definition (Context : in out Facelet_Context; Name : in Unbounded_String; Parent : in Base.UIComponent_Access; Found : out Boolean) is Node : Composition_Tag_Node; Iter : Defines_Vector.Cursor := Context.Defines.Last; The_Name : aliased constant String := To_String (Name); begin if Context.Inserts.Contains (The_Name'Unchecked_Access) then Found := True; return; end if; Context.Inserts.Insert (The_Name'Unchecked_Access); while Defines_Vector.Has_Element (Iter) loop Node := Defines_Vector.Element (Iter); Node.Include_Definition (Parent => Parent, Context => Context, Name => Name, Found => Found); if Found then Context.Inserts.Delete (The_Name'Unchecked_Access); return; end if; Defines_Vector.Previous (Iter); end loop; Found := False; Context.Inserts.Delete (The_Name'Unchecked_Access); end Include_Definition; -- ------------------------------ -- Push into the current facelet context the <ui:define> nodes contained in -- the composition/decorate tag. -- ------------------------------ procedure Push_Defines (Context : in out Facelet_Context; Node : access ASF.Views.Nodes.Facelets.Composition_Tag_Node) is begin Context.Defines.Append (Node.all'Access); end Push_Defines; -- ------------------------------ -- Pop from the current facelet context the <ui:define> nodes. -- ------------------------------ procedure Pop_Defines (Context : in out Facelet_Context) is use Ada.Containers; begin if Context.Defines.Length > 0 then Context.Defines.Delete_Last; end if; end Pop_Defines; -- ------------------------------ -- Set the path to resolve relative facelet paths and get the previous path. -- ------------------------------ procedure Set_Relative_Path (Context : in out Facelet_Context; Path : in String; Previous : out Unbounded_String) is begin Log.Debug ("Set facelet relative path: {0}", Path); Previous := Context.Path; Context.Path := To_Unbounded_String (Ada.Directories.Containing_Directory (Path)); end Set_Relative_Path; -- ------------------------------ -- Set the path to resolve relative facelet paths. -- ------------------------------ procedure Set_Relative_Path (Context : in out Facelet_Context; Path : in Unbounded_String) is begin Log.Debug ("Set facelet relative path: {0}", Path); Context.Path := Path; end Set_Relative_Path; -- ------------------------------ -- Resolve the facelet relative path -- ------------------------------ function Resolve_Path (Context : Facelet_Context; Path : String) return String is begin if Path (Path'First) = '/' then return Path; else Log.Debug ("Resolve {0} with context {1}", Path, To_String (Context.Path)); return Util.Files.Compose (To_String (Context.Path), Path); end if; end Resolve_Path; -- ------------------------------ -- Get a converter from a name. -- Returns the converter object or null if there is no converter. -- ------------------------------ function Get_Converter (Context : in Facelet_Context; Name : in EL.Objects.Object) return ASF.Converters.Converter_Access is begin return Facelet_Context'Class (Context).Get_Application.Find (Name); end Get_Converter; -- ------------------------------ -- Get a validator from a name. -- Returns the validator object or null if there is no validator. -- ------------------------------ function Get_Validator (Context : in Facelet_Context; Name : in EL.Objects.Object) return ASF.Validators.Validator_Access is begin return Facelet_Context'Class (Context).Get_Application.Find_Validator (Name); end Get_Validator; end ASF.Contexts.Facelets;
----------------------------------------------------------------------- -- contexts-facelets -- Contexts for facelets -- Copyright (C) 2009, 2010, 2011, 2013 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Directories; with Util.Files; with Util.Log.Loggers; with EL.Variables; with ASF.Applications.Main; with ASF.Views.Nodes.Facelets; package body ASF.Contexts.Facelets is use Util.Log; -- The logger Log : constant Loggers.Logger := Loggers.Create ("ASF.Contexts.Facelets"); -- ------------------------------ -- Get the EL context for evaluating expressions. -- ------------------------------ function Get_ELContext (Context : in Facelet_Context) return EL.Contexts.ELContext_Access is begin return Context.Context; end Get_ELContext; -- ------------------------------ -- Set the EL context for evaluating expressions. -- ------------------------------ procedure Set_ELContext (Context : in out Facelet_Context; ELContext : in EL.Contexts.ELContext_Access) is begin Context.Context := ELContext; end Set_ELContext; -- ------------------------------ -- Get the function mapper associated with the EL context. -- ------------------------------ function Get_Function_Mapper (Context : in Facelet_Context) return EL.Functions.Function_Mapper_Access is use EL.Contexts; begin if Context.Context = null then return null; else return Context.Context.Get_Function_Mapper; end if; end Get_Function_Mapper; -- ------------------------------ -- Set the attribute having given name with the value. -- ------------------------------ procedure Set_Attribute (Context : in out Facelet_Context; Name : in String; Value : in EL.Objects.Object) is begin null; end Set_Attribute; -- ------------------------------ -- Set the attribute having given name with the value. -- ------------------------------ procedure Set_Attribute (Context : in out Facelet_Context; Name : in Unbounded_String; Value : in EL.Objects.Object) is begin null; end Set_Attribute; -- ------------------------------ -- Set the attribute having given name with the expression. -- ------------------------------ procedure Set_Variable (Context : in out Facelet_Context; Name : in Unbounded_String; Value : in EL.Expressions.Expression) is Mapper : constant access EL.Variables.Variable_Mapper'Class := Context.Context.Get_Variable_Mapper; begin if Mapper /= null then Mapper.Set_Variable (Name, Value); end if; end Set_Variable; -- Set the attribute having given name with the expression. procedure Set_Variable (Context : in out Facelet_Context; Name : in String; Value : in EL.Expressions.Expression) is N : constant Unbounded_String := To_Unbounded_String (Name); begin Set_Variable (Context, N, Value); end Set_Variable; -- ------------------------------ -- Include the facelet from the given source file. -- The included views appended to the parent component tree. -- ------------------------------ procedure Include_Facelet (Context : in out Facelet_Context; Source : in String; Parent : in Base.UIComponent_Access) is begin null; end Include_Facelet; -- ------------------------------ -- Include the definition having the given name. -- ------------------------------ procedure Include_Definition (Context : in out Facelet_Context; Name : in Unbounded_String; Parent : in Base.UIComponent_Access; Found : out Boolean) is Node : Composition_Tag_Node; Iter : Defines_Vector.Cursor := Context.Defines.Last; The_Name : aliased constant String := To_String (Name); begin if Context.Inserts.Contains (The_Name'Unchecked_Access) then Found := True; return; end if; Context.Inserts.Insert (The_Name'Unchecked_Access); while Defines_Vector.Has_Element (Iter) loop Node := Defines_Vector.Element (Iter); Node.Include_Definition (Parent => Parent, Context => Context, Name => Name, Found => Found); if Found then Context.Inserts.Delete (The_Name'Unchecked_Access); return; end if; Defines_Vector.Previous (Iter); end loop; Found := False; Context.Inserts.Delete (The_Name'Unchecked_Access); end Include_Definition; -- ------------------------------ -- Push into the current facelet context the <ui:define> nodes contained in -- the composition/decorate tag. -- ------------------------------ procedure Push_Defines (Context : in out Facelet_Context; Node : access ASF.Views.Nodes.Facelets.Composition_Tag_Node) is begin Context.Defines.Append (Node.all'Access); end Push_Defines; -- ------------------------------ -- Pop from the current facelet context the <ui:define> nodes. -- ------------------------------ procedure Pop_Defines (Context : in out Facelet_Context) is use Ada.Containers; begin if Context.Defines.Length > 0 then Context.Defines.Delete_Last; end if; end Pop_Defines; -- ------------------------------ -- Set the path to resolve relative facelet paths and get the previous path. -- ------------------------------ procedure Set_Relative_Path (Context : in out Facelet_Context; Path : in String; Previous : out Unbounded_String) is begin Log.Debug ("Set facelet relative path: {0}", Path); Previous := Context.Path; Context.Path := To_Unbounded_String (Ada.Directories.Containing_Directory (Path)); end Set_Relative_Path; -- ------------------------------ -- Set the path to resolve relative facelet paths. -- ------------------------------ procedure Set_Relative_Path (Context : in out Facelet_Context; Path : in Unbounded_String) is begin Log.Debug ("Set facelet relative path: {0}", Path); Context.Path := Path; end Set_Relative_Path; -- ------------------------------ -- Resolve the facelet relative path -- ------------------------------ function Resolve_Path (Context : Facelet_Context; Path : String) return String is begin if Path (Path'First) = '/' then return Path; else Log.Debug ("Resolve {0} with context {1}", Path, To_String (Context.Path)); return Util.Files.Compose (To_String (Context.Path), Path); end if; end Resolve_Path; -- ------------------------------ -- Get a converter from a name. -- Returns the converter object or null if there is no converter. -- ------------------------------ function Get_Converter (Context : in Facelet_Context; Name : in EL.Objects.Object) return ASF.Converters.Converter_Access is begin return Facelet_Context'Class (Context).Get_Application.Find (Name); end Get_Converter; -- ------------------------------ -- Get a validator from a name. -- Returns the validator object or null if there is no validator. -- ------------------------------ function Get_Validator (Context : in Facelet_Context; Name : in EL.Objects.Object) return ASF.Validators.Validator_Access is begin return Facelet_Context'Class (Context).Get_Application.Find_Validator (Name); end Get_Validator; end ASF.Contexts.Facelets;
Fix compilation warning
Fix compilation warning
Ada
apache-2.0
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
aadd89478cbe0bb86f7362491ecd5df3b0d6d5d2
mat/src/memory/mat-memory-readers.adb
mat/src/memory/mat-memory-readers.adb
----------------------------------------------------------------------- -- Memory Events - Definition and Analysis of memory events -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Log.Loggers; with MAT.Types; with MAT.Readers.Marshaller; with MAT.Memory; package body MAT.Memory.Readers is -- The logger Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("MAT.Memory.Readers"); MSG_MALLOC : constant MAT.Events.Internal_Reference := 0; MSG_FREE : constant MAT.Events.Internal_Reference := 1; MSG_REALLOC : constant MAT.Events.Internal_Reference := 2; M_SIZE : constant MAT.Events.Internal_Reference := 1; M_FRAME : constant MAT.Events.Internal_Reference := 2; M_ADDR : constant MAT.Events.Internal_Reference := 3; M_OLD_ADDR : constant MAT.Events.Internal_Reference := 4; M_THREAD : constant MAT.Events.Internal_Reference := 5; M_UNKNOWN : constant MAT.Events.Internal_Reference := 6; M_TIME : constant MAT.Events.Internal_Reference := 7; -- Defines the possible data kinds which are recognized by -- the memory unmarshaller. All others are ignored. SIZE_NAME : aliased constant String := "size"; FRAME_NAME : aliased constant String := "frame"; ADDR_NAME : aliased constant String := "pointer"; OLD_NAME : aliased constant String := "old-pointer"; THREAD_NAME : aliased constant String := "thread"; TIME_NAME : aliased constant String := "time"; Memory_Attributes : aliased constant MAT.Events.Attribute_Table := (1 => (Name => SIZE_NAME'Access, Size => 0, Kind => MAT.Events.T_SIZE_T, Ref => M_SIZE), 2 => (Name => FRAME_NAME'Access, Size => 0, Kind => MAT.Events.T_FRAME, Ref => M_FRAME), 3 => (Name => ADDR_NAME'Access, Size => 0, Kind => MAT.Events.T_POINTER, Ref => M_ADDR), 4 => (Name => OLD_NAME'Access, Size => 0, Kind => MAT.Events.T_POINTER, Ref => M_OLD_ADDR), 5 => (Name => THREAD_NAME'Access, Size => 0, Kind => MAT.Events.T_THREAD, Ref => M_THREAD), 6 => (Name => TIME_NAME'Access, Size => 0, Kind => MAT.Events.T_TIME, Ref => M_TIME)); procedure Unmarshall_Allocation (Msg : in out MAT.Readers.Message; Slot : in out Allocation; Addr : in out MAT.Types.Target_Addr; Old_Addr : in out MAT.Types.Target_Addr; Defs : in MAT.Events.Attribute_Table); ---------------------- -- Register the reader to extract and analyze memory events. ---------------------- procedure Register (Into : in out MAT.Readers.Manager_Base'Class; Reader : in Memory_Reader_Access) is begin Into.Register_Reader (Reader.all'Access, "malloc", MSG_MALLOC, Memory_Attributes'Access); Into.Register_Reader (Reader.all'Access, "free", MSG_FREE, Memory_Attributes'Access); Into.Register_Reader (Reader.all'Access, "realloc", MSG_REALLOC, Memory_Attributes'Access); end Register; ---------------------- -- Unmarshall from the message the memory slot information. -- The data is described by the Defs table. ---------------------- procedure Unmarshall_Allocation (Msg : in out MAT.Readers.Message; Slot : in out Allocation; Addr : in out MAT.Types.Target_Addr; Old_Addr : in out MAT.Types.Target_Addr; Defs : in MAT.Events.Attribute_Table) is begin for I in Defs'Range loop declare Def : MAT.Events.Attribute renames Defs (I); begin case Def.Ref is when M_SIZE => Slot.Size := MAT.Readers.Marshaller.Get_Target_Size (Msg.Buffer, Def.Kind); when M_ADDR => Addr := MAT.Readers.Marshaller.Get_Target_Addr (Msg.Buffer, Def.Kind); when M_OLD_ADDR => Old_Addr := MAT.Readers.Marshaller.Get_Target_Addr (Msg.Buffer, Def.Kind); when M_UNKNOWN => MAT.Readers.Marshaller.Skip (Msg.Buffer, Def.Size); when others => MAT.Readers.Marshaller.Skip (Msg.Buffer, Def.Size); end case; end; end loop; end Unmarshall_Allocation; overriding procedure Dispatch (For_Servant : in out Memory_Servant; Id : in MAT.Events.Internal_Reference; Params : in MAT.Events.Const_Attribute_Table_Access; Frame : in MAT.Events.Frame_Info; Msg : in out MAT.Readers.Message) is Slot : Allocation; Addr : MAT.Types.Target_Addr := 0; Old_Addr : MAT.Types.Target_Addr := 0; begin case Id is when MSG_MALLOC => Unmarshall_Allocation (Msg, Slot, Addr, Old_Addr, Params.all); For_Servant.Data.Create_Frame (Pc => Frame.Frame (1 .. Frame.Cur_Depth), Result => Slot.Frame); For_Servant.Data.Probe_Malloc (Addr, Slot); when MSG_FREE => Unmarshall_Allocation (Msg, Slot, Addr, Old_Addr, Params.all); For_Servant.Data.Probe_Free (Addr, Slot); when MSG_REALLOC => Unmarshall_Allocation (Msg, Slot, Addr, Old_Addr, Params.all); For_Servant.Data.Create_Frame (Pc => Frame.Frame (1 .. Frame.Cur_Depth), Result => Slot.Frame); For_Servant.Data.Probe_Realloc (Addr, Old_Addr, Slot); when others => raise Program_Error; end case; end Dispatch; end MAT.Memory.Readers;
----------------------------------------------------------------------- -- Memory Events - Definition and Analysis of memory events -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Log.Loggers; with MAT.Types; with MAT.Readers.Marshaller; with MAT.Memory; package body MAT.Memory.Readers is -- The logger Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("MAT.Memory.Readers"); MSG_MALLOC : constant MAT.Events.Internal_Reference := 0; MSG_FREE : constant MAT.Events.Internal_Reference := 1; MSG_REALLOC : constant MAT.Events.Internal_Reference := 2; M_SIZE : constant MAT.Events.Internal_Reference := 1; M_FRAME : constant MAT.Events.Internal_Reference := 2; M_ADDR : constant MAT.Events.Internal_Reference := 3; M_OLD_ADDR : constant MAT.Events.Internal_Reference := 4; M_THREAD : constant MAT.Events.Internal_Reference := 5; M_UNKNOWN : constant MAT.Events.Internal_Reference := 6; M_TIME : constant MAT.Events.Internal_Reference := 7; -- Defines the possible data kinds which are recognized by -- the memory unmarshaller. All others are ignored. SIZE_NAME : aliased constant String := "size"; FRAME_NAME : aliased constant String := "frame"; ADDR_NAME : aliased constant String := "pointer"; OLD_NAME : aliased constant String := "old-pointer"; THREAD_NAME : aliased constant String := "thread"; TIME_NAME : aliased constant String := "time"; Memory_Attributes : aliased constant MAT.Events.Attribute_Table := (1 => (Name => SIZE_NAME'Access, Size => 0, Kind => MAT.Events.T_SIZE_T, Ref => M_SIZE), 2 => (Name => FRAME_NAME'Access, Size => 0, Kind => MAT.Events.T_FRAME, Ref => M_FRAME), 3 => (Name => ADDR_NAME'Access, Size => 0, Kind => MAT.Events.T_POINTER, Ref => M_ADDR), 4 => (Name => OLD_NAME'Access, Size => 0, Kind => MAT.Events.T_POINTER, Ref => M_OLD_ADDR), 5 => (Name => THREAD_NAME'Access, Size => 0, Kind => MAT.Events.T_THREAD, Ref => M_THREAD), 6 => (Name => TIME_NAME'Access, Size => 0, Kind => MAT.Events.T_TIME, Ref => M_TIME)); procedure Unmarshall_Allocation (Msg : in out MAT.Readers.Message; Slot : in out Allocation; Addr : in out MAT.Types.Target_Addr; Old_Addr : in out MAT.Types.Target_Addr; Defs : in MAT.Events.Attribute_Table); ---------------------- -- Register the reader to extract and analyze memory events. ---------------------- procedure Register (Into : in out MAT.Readers.Manager_Base'Class; Reader : in Memory_Reader_Access) is begin Into.Register_Reader (Reader.all'Access, "malloc", MSG_MALLOC, Memory_Attributes'Access); Into.Register_Reader (Reader.all'Access, "free", MSG_FREE, Memory_Attributes'Access); Into.Register_Reader (Reader.all'Access, "realloc", MSG_REALLOC, Memory_Attributes'Access); end Register; ---------------------- -- Unmarshall from the message the memory slot information. -- The data is described by the Defs table. ---------------------- procedure Unmarshall_Allocation (Msg : in out MAT.Readers.Message; Slot : in out Allocation; Addr : in out MAT.Types.Target_Addr; Old_Addr : in out MAT.Types.Target_Addr; Defs : in MAT.Events.Attribute_Table) is begin for I in Defs'Range loop declare Def : MAT.Events.Attribute renames Defs (I); begin case Def.Ref is when M_SIZE => Slot.Size := MAT.Readers.Marshaller.Get_Target_Size (Msg.Buffer, Def.Kind); when M_ADDR => Addr := MAT.Readers.Marshaller.Get_Target_Addr (Msg.Buffer, Def.Kind); when M_OLD_ADDR => Old_Addr := MAT.Readers.Marshaller.Get_Target_Addr (Msg.Buffer, Def.Kind); when M_UNKNOWN => MAT.Readers.Marshaller.Skip (Msg.Buffer, Def.Size); when others => MAT.Readers.Marshaller.Skip (Msg.Buffer, Def.Size); end case; end; end loop; end Unmarshall_Allocation; overriding procedure Dispatch (For_Servant : in out Memory_Servant; Id : in MAT.Events.Internal_Reference; Params : in MAT.Events.Const_Attribute_Table_Access; Frame : in MAT.Events.Frame_Info; Msg : in out MAT.Readers.Message) is Slot : Allocation; Addr : MAT.Types.Target_Addr := 0; Old_Addr : MAT.Types.Target_Addr := 0; begin Slot.Thread := Frame.Thread; Slot.Time := Frame.Time; case Id is when MSG_MALLOC => Unmarshall_Allocation (Msg, Slot, Addr, Old_Addr, Params.all); For_Servant.Data.Create_Frame (Pc => Frame.Frame (1 .. Frame.Cur_Depth), Result => Slot.Frame); For_Servant.Data.Probe_Malloc (Addr, Slot); when MSG_FREE => Unmarshall_Allocation (Msg, Slot, Addr, Old_Addr, Params.all); For_Servant.Data.Probe_Free (Addr, Slot); when MSG_REALLOC => Unmarshall_Allocation (Msg, Slot, Addr, Old_Addr, Params.all); For_Servant.Data.Create_Frame (Pc => Frame.Frame (1 .. Frame.Cur_Depth), Result => Slot.Frame); For_Servant.Data.Probe_Realloc (Addr, Old_Addr, Slot); when others => raise Program_Error; end case; end Dispatch; end MAT.Memory.Readers;
Save the current thread and time information in the memory slot
Save the current thread and time information in the memory slot
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
4bb4212f4783b33a6674ca2cc11ac515fad78e01
mat/src/memory/mat-memory-targets.adb
mat/src/memory/mat-memory-targets.adb
----------------------------------------------------------------------- -- Memory Events - Definition and Analysis of memory events -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Log.Loggers; with MAT.Memory.Readers; package body MAT.Memory.Targets is -- The logger Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("MAT.Memory.Targets"); -- ------------------------------ -- Initialize the target memory object to manage the memory slots, the stack frames -- and setup the reader to analyze the memory events. -- ------------------------------ procedure Initialize (Memory : in out Target_Memory; Reader : in out MAT.Readers.Manager_Base'Class) is Memory_Reader : constant MAT.Memory.Readers.Memory_Reader_Access := new MAT.Memory.Readers.Memory_Servant; begin Memory.Reader := Memory_Reader.all'Access; Memory_Reader.Data := Memory'Unrestricted_Access; MAT.Memory.Readers.Register (Reader, Memory_Reader); end Initialize; -- ------------------------------ -- Take into account a malloc probe. The memory slot [Addr .. Slot.Size] is inserted -- in the used slots map. The freed slots that intersect the malloc'ed region are -- removed from the freed map. -- ------------------------------ procedure Probe_Malloc (Memory : in out Target_Memory; Addr : in MAT.Types.Target_Addr; Slot : in Allocation) is begin Memory.Memory.Probe_Malloc (Addr, Slot); end Probe_Malloc; -- ------------------------------ -- Take into account a free probe. Add the memory slot in the freed map and remove -- the slot from the used slots map. -- ------------------------------ procedure Probe_Free (Memory : in out Target_Memory; Addr : in MAT.Types.Target_Addr; Slot : in Allocation) is begin Memory.Memory.Probe_Free (Addr, Slot); end Probe_Free; -- ------------------------------ -- Take into account a realloc probe. The old memory slot represented by Old_Addr is -- removed from the used slots maps and the new memory slot [Addr .. Slot.Size] is -- inserted in the used slots map. -- ------------------------------ procedure Probe_Realloc (Memory : in out Target_Memory; Addr : in MAT.Types.Target_Addr; Old_Addr : in MAT.Types.Target_Addr; Slot : in Allocation) is begin Memory.Memory.Probe_Realloc (Addr, Old_Addr, Slot); end Probe_Realloc; -- ------------------------------ -- Insert in the frame tree the new stack frame represented by <tt>Pc</tt>. -- If the frame is already known, the frame reference counter is incremented. -- The frame represented by <tt>Pc</tt> is returned in <tt>Result</tt>. -- ------------------------------ procedure Create_Frame (Memory : in out Target_Memory; Pc : in MAT.Frames.Frame_Table; Result : out MAT.Frames.Frame_Type) is begin Memory.Memory.Create_Frame (Pc, Result); end Create_Frame; -- ------------------------------ -- Collect the information about memory slot sizes allocated by the application. -- ------------------------------ procedure Size_Information (Memory : in out Target_Memory; Sizes : in out MAT.Memory.Tools.Size_Info_Map) is begin Memory.Memory.Size_Information (Sizes); end Size_Information; protected body Memory_Allocator is -- ------------------------------ -- Remove the memory region [Addr .. Addr + Size] from the free list. -- ------------------------------ procedure Remove_Free (Addr : in MAT.Types.Target_Addr; Size : in MAT.Types.Target_Size) is Iter : Allocation_Cursor; Last : constant MAT.Types.Target_Addr := Addr + MAT.Types.Target_Addr (Size); Slot : Allocation; begin -- Walk the list of free blocks and remove all the blocks which intersect the region -- [Addr .. Addr + Slot.Size]. We start walking at the first block below and near -- the address. Slots are then removed when they intersect the malloc'ed region. Iter := Freed_Slots.Floor (Addr); while Allocation_Maps.Has_Element (Iter) loop declare Freed_Addr : constant MAT.Types.Target_Addr := Allocation_Maps.Key (Iter); begin exit when Freed_Addr > Last; Slot := Allocation_Maps.Element (Iter); if Freed_Addr + MAT.Types.Target_Addr (Slot.Size) > Addr then Freed_Slots.Delete (Iter); Iter := Freed_Slots.Floor (Addr); else Allocation_Maps.Next (Iter); end if; end; end loop; end Remove_Free; -- ------------------------------ -- Take into account a malloc probe. The memory slot [Addr .. Slot.Size] is inserted -- in the used slots map. The freed slots that intersect the malloc'ed region are -- removed from the freed map. -- ------------------------------ procedure Probe_Malloc (Addr : in MAT.Types.Target_Addr; Slot : in Allocation) is begin Remove_Free (Addr, Slot.Size); Used_Slots.Insert (Addr, Slot); end Probe_Malloc; -- ------------------------------ -- Take into account a free probe. Add the memory slot in the freed map and remove -- the slot from the used slots map. -- ------------------------------ procedure Probe_Free (Addr : in MAT.Types.Target_Addr; Slot : in Allocation) is Item : Allocation; Iter : Allocation_Cursor; begin Iter := Used_Slots.Find (Addr); if Allocation_Maps.Has_Element (Iter) then Item := Allocation_Maps.Element (Iter); MAT.Frames.Release (Item.Frame); Used_Slots.Delete (Iter); Item.Frame := Slot.Frame; Freed_Slots.Insert (Addr, Item); end if; end Probe_Free; -- ------------------------------ -- Take into account a realloc probe. The old memory slot represented by Old_Addr is -- removed from the used slots maps and the new memory slot [Addr .. Slot.Size] is -- inserted in the used slots map. -- ------------------------------ procedure Probe_Realloc (Addr : in MAT.Types.Target_Addr; Old_Addr : in MAT.Types.Target_Addr; Slot : in Allocation) is Old_Slot : Allocation; Pos : Allocation_Cursor; procedure Update_Size (Key : in MAT.Types.Target_Addr; Element : in out Allocation) is begin Element.Size := Slot.Size; MAT.Frames.Release (Element.Frame); Element.Frame := Slot.Frame; end Update_Size; begin if Old_Addr /= 0 then Pos := Used_Slots.Find (Old_Addr); if Allocation_Maps.Has_Element (Pos) then if Addr = Old_Addr then Used_Slots.Update_Element (Pos, Update_Size'Access); else Used_Slots.Delete (Pos); Used_Slots.Insert (Addr, Slot); end if; else Used_Slots.Insert (Addr, Slot); end if; else Used_Slots.Insert (Addr, Slot); end if; Remove_Free (Addr, Slot.Size); end Probe_Realloc; -- ------------------------------ -- Insert in the frame tree the new stack frame represented by <tt>Pc</tt>. -- If the frame is already known, the frame reference counter is incremented. -- The frame represented by <tt>Pc</tt> is returned in <tt>Result</tt>. -- ------------------------------ procedure Create_Frame (Pc : in MAT.Frames.Frame_Table; Result : out MAT.Frames.Frame_Type) is begin MAT.Frames.Insert (Frames, Pc, Result); end Create_Frame; -- ------------------------------ -- Collect the information about memory slot sizes allocated by the application. -- ------------------------------ procedure Size_Information (Sizes : in out MAT.Memory.Tools.Size_Info_Map) is begin MAT.Memory.Tools.Size_Information (Used_Slots, Sizes); end Size_Information; end Memory_Allocator; end MAT.Memory.Targets;
----------------------------------------------------------------------- -- Memory Events - Definition and Analysis of memory events -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Log.Loggers; with MAT.Memory.Readers; package body MAT.Memory.Targets is -- The logger Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("MAT.Memory.Targets"); -- ------------------------------ -- Initialize the target memory object to manage the memory slots, the stack frames -- and setup the reader to analyze the memory events. -- ------------------------------ procedure Initialize (Memory : in out Target_Memory; Reader : in out MAT.Readers.Manager_Base'Class) is Memory_Reader : constant MAT.Memory.Readers.Memory_Reader_Access := new MAT.Memory.Readers.Memory_Servant; begin Memory.Reader := Memory_Reader.all'Access; Memory_Reader.Data := Memory'Unrestricted_Access; MAT.Memory.Readers.Register (Reader, Memory_Reader); end Initialize; -- ------------------------------ -- Take into account a malloc probe. The memory slot [Addr .. Slot.Size] is inserted -- in the used slots map. The freed slots that intersect the malloc'ed region are -- removed from the freed map. -- ------------------------------ procedure Probe_Malloc (Memory : in out Target_Memory; Addr : in MAT.Types.Target_Addr; Slot : in Allocation) is begin Memory.Memory.Probe_Malloc (Addr, Slot); end Probe_Malloc; -- ------------------------------ -- Take into account a free probe. Add the memory slot in the freed map and remove -- the slot from the used slots map. -- ------------------------------ procedure Probe_Free (Memory : in out Target_Memory; Addr : in MAT.Types.Target_Addr; Slot : in Allocation) is begin Memory.Memory.Probe_Free (Addr, Slot); end Probe_Free; -- ------------------------------ -- Take into account a realloc probe. The old memory slot represented by Old_Addr is -- removed from the used slots maps and the new memory slot [Addr .. Slot.Size] is -- inserted in the used slots map. -- ------------------------------ procedure Probe_Realloc (Memory : in out Target_Memory; Addr : in MAT.Types.Target_Addr; Old_Addr : in MAT.Types.Target_Addr; Slot : in Allocation) is begin Memory.Memory.Probe_Realloc (Addr, Old_Addr, Slot); end Probe_Realloc; -- ------------------------------ -- Insert in the frame tree the new stack frame represented by <tt>Pc</tt>. -- If the frame is already known, the frame reference counter is incremented. -- The frame represented by <tt>Pc</tt> is returned in <tt>Result</tt>. -- ------------------------------ procedure Create_Frame (Memory : in out Target_Memory; Pc : in MAT.Frames.Frame_Table; Result : out MAT.Frames.Frame_Type) is begin Memory.Memory.Create_Frame (Pc, Result); end Create_Frame; -- ------------------------------ -- Collect the information about memory slot sizes allocated by the application. -- ------------------------------ procedure Size_Information (Memory : in out Target_Memory; Sizes : in out MAT.Memory.Tools.Size_Info_Map) is begin Memory.Memory.Size_Information (Sizes); end Size_Information; protected body Memory_Allocator is -- ------------------------------ -- Remove the memory region [Addr .. Addr + Size] from the free list. -- ------------------------------ procedure Remove_Free (Addr : in MAT.Types.Target_Addr; Size : in MAT.Types.Target_Size) is Iter : Allocation_Cursor; Last : constant MAT.Types.Target_Addr := Addr + MAT.Types.Target_Addr (Size); Slot : Allocation; begin -- Walk the list of free blocks and remove all the blocks which intersect the region -- [Addr .. Addr + Slot.Size]. We start walking at the first block below and near -- the address. Slots are then removed when they intersect the malloc'ed region. Iter := Freed_Slots.Floor (Addr); while Allocation_Maps.Has_Element (Iter) loop declare Freed_Addr : constant MAT.Types.Target_Addr := Allocation_Maps.Key (Iter); begin exit when Freed_Addr > Last; Slot := Allocation_Maps.Element (Iter); if Freed_Addr + MAT.Types.Target_Addr (Slot.Size) > Addr then Freed_Slots.Delete (Iter); Iter := Freed_Slots.Floor (Addr); else Allocation_Maps.Next (Iter); end if; end; end loop; end Remove_Free; -- ------------------------------ -- Take into account a malloc probe. The memory slot [Addr .. Slot.Size] is inserted -- in the used slots map. The freed slots that intersect the malloc'ed region are -- removed from the freed map. -- ------------------------------ procedure Probe_Malloc (Addr : in MAT.Types.Target_Addr; Slot : in Allocation) is begin Remove_Free (Addr, Slot.Size); Used_Slots.Insert (Addr, Slot); end Probe_Malloc; -- ------------------------------ -- Take into account a free probe. Add the memory slot in the freed map and remove -- the slot from the used slots map. -- ------------------------------ procedure Probe_Free (Addr : in MAT.Types.Target_Addr; Slot : in Allocation) is Item : Allocation; Iter : Allocation_Cursor; begin Iter := Used_Slots.Find (Addr); if Allocation_Maps.Has_Element (Iter) then Item := Allocation_Maps.Element (Iter); MAT.Frames.Release (Item.Frame); Used_Slots.Delete (Iter); Item.Frame := Slot.Frame; Freed_Slots.Insert (Addr, Item); end if; end Probe_Free; -- ------------------------------ -- Take into account a realloc probe. The old memory slot represented by Old_Addr is -- removed from the used slots maps and the new memory slot [Addr .. Slot.Size] is -- inserted in the used slots map. -- ------------------------------ procedure Probe_Realloc (Addr : in MAT.Types.Target_Addr; Old_Addr : in MAT.Types.Target_Addr; Slot : in Allocation) is Old_Slot : Allocation; Pos : Allocation_Cursor; procedure Update_Size (Key : in MAT.Types.Target_Addr; Element : in out Allocation) is begin Element.Size := Slot.Size; MAT.Frames.Release (Element.Frame); Element.Frame := Slot.Frame; end Update_Size; begin if Old_Addr /= 0 then Pos := Used_Slots.Find (Old_Addr); if Allocation_Maps.Has_Element (Pos) then if Addr = Old_Addr then Used_Slots.Update_Element (Pos, Update_Size'Access); else Used_Slots.Delete (Pos); Used_Slots.Insert (Addr, Slot); end if; else Used_Slots.Insert (Addr, Slot); end if; else Used_Slots.Insert (Addr, Slot); end if; Remove_Free (Addr, Slot.Size); end Probe_Realloc; -- ------------------------------ -- Insert in the frame tree the new stack frame represented by <tt>Pc</tt>. -- If the frame is already known, the frame reference counter is incremented. -- The frame represented by <tt>Pc</tt> is returned in <tt>Result</tt>. -- ------------------------------ procedure Create_Frame (Pc : in MAT.Frames.Frame_Table; Result : out MAT.Frames.Frame_Type) is begin MAT.Frames.Insert (Frames, Pc, Result); end Create_Frame; -- ------------------------------ -- Collect the information about memory slot sizes allocated by the application. -- ------------------------------ procedure Size_Information (Sizes : in out MAT.Memory.Tools.Size_Info_Map) is begin MAT.Memory.Tools.Size_Information (Used_Slots, Sizes); end Size_Information; -- ------------------------------ -- Find from the memory map the memory slots whose address intersects -- the region [From .. To] and add the memory slot in the <tt>Into</tt> list if -- it does not already contains the memory slot. -- ------------------------------ procedure Find (From : in MAT.Types.Target_Addr; To : in MAT.Types.Target_Addr; Into : in out MAT.Memory.Allocation_Map) is begin MAT.Memory.Tools.Find (Used_Slots, From, To, Into); end Find; end Memory_Allocator; end MAT.Memory.Targets;
Implement the protected Find operation
Implement the protected Find operation
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
cbde87c96431d94d96c52442dee7b67a9f3fdde3
matp/src/events/mat-events-probes.ads
matp/src/events/mat-events-probes.ads
----------------------------------------------------------------------- -- mat-events-probes -- Event probes -- Copyright (C) 2014, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Containers; with Ada.Containers.Hashed_Maps; with Ada.Containers.Indefinite_Hashed_Maps; with Ada.Strings.Hash; with Ada.Finalization; with MAT.Types; with MAT.Events; with MAT.Events.Targets; with MAT.Readers; with MAT.Frames.Targets; package MAT.Events.Probes is ----------------- -- Abstract probe definition ----------------- type Probe_Type is abstract tagged limited private; type Probe_Type_Access is access all Probe_Type'Class; -- Extract the probe information from the message. procedure Extract (Probe : in Probe_Type; Params : in MAT.Events.Const_Attribute_Table_Access; Msg : in out MAT.Readers.Message_Type; Event : in out Target_Event_Type) is abstract; procedure Execute (Probe : in Probe_Type; Event : in out Target_Event_Type) is abstract; -- Update the Size and Prev_Id information in the event identified by <tt>Id</tt>. -- Update the event represented by <tt>Prev_Id</tt> so that its Next_Id refers -- to the <tt>Id</tt> event. procedure Update_Event (Probe : in Probe_Type; Id : in MAT.Events.Event_Id_Type; Size : in MAT.Types.Target_Size; Prev_Id : in MAT.Events.Event_Id_Type); ----------------- -- Probe Manager ----------------- type Probe_Manager_Type is abstract new Ada.Finalization.Limited_Controlled with private; type Probe_Manager_Type_Access is access all Probe_Manager_Type'Class; -- Initialize the probe manager instance. overriding procedure Initialize (Manager : in out Probe_Manager_Type); -- Register the probe to handle the event identified by the given name. -- The event is mapped to the given id and the attributes table is used -- to setup the mapping from the data stream attributes. procedure Register_Probe (Into : in out Probe_Manager_Type; Probe : in Probe_Type_Access; Name : in String; Id : in MAT.Events.Probe_Index_Type; Model : in MAT.Events.Const_Attribute_Table_Access); procedure Dispatch_Message (Client : in out Probe_Manager_Type; Msg : in out MAT.Readers.Message_Type); -- Read a list of event definitions from the stream and configure the reader. procedure Read_Event_Definitions (Client : in out Probe_Manager_Type; Msg : in out MAT.Readers.Message_Type); -- Get the target events. function Get_Target_Events (Client : in Probe_Manager_Type) return MAT.Events.Targets.Target_Events_Access; -- Read a message from the stream. procedure Read_Message (Reader : in out Probe_Manager_Type; Msg : in out MAT.Readers.Message_Type) is abstract; -- Get the size of a target address (4 or 8 bytes). function Get_Address_Size (Client : in Probe_Manager_Type) return MAT.Events.Attribute_Type; type Reader_List_Type is limited interface; type Reader_List_Type_Access is access all Reader_List_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 (List : in out Reader_List_Type; Manager : in out Probe_Manager_Type'Class) is abstract; private type Probe_Type is abstract tagged limited record Owner : Probe_Manager_Type_Access := null; end record; -- Record a probe type Probe_Handler is record Probe : Probe_Type_Access; Id : MAT.Events.Probe_Index_Type; Attributes : MAT.Events.Const_Attribute_Table_Access; Mapping : MAT.Events.Attribute_Table_Ptr; end record; function Hash (Key : in MAT.Types.Uint16) return Ada.Containers.Hash_Type; package Probe_Maps is new Ada.Containers.Indefinite_Hashed_Maps (Key_Type => String, Element_Type => Probe_Handler, Hash => Ada.Strings.Hash, Equivalent_Keys => "="); -- Runtime handlers associated with the events. package Handler_Maps is new Ada.Containers.Hashed_Maps (Key_Type => MAT.Types.Uint16, Element_Type => Probe_Handler, Hash => Hash, Equivalent_Keys => "="); type Probe_Manager_Type is abstract new Ada.Finalization.Limited_Controlled with record Probes : Probe_Maps.Map; Handlers : Handler_Maps.Map; Version : MAT.Types.Uint16; Flags : MAT.Types.Uint16; Addr_Size : MAT.Events.Attribute_Type; Probe : MAT.Events.Attribute_Table_Ptr; Frame : access MAT.Events.Frame_Info; Events : MAT.Events.Targets.Target_Events_Access; Event : Target_Event_Type; Frames : MAT.Frames.Targets.Target_Frames; end record; -- Read an event definition from the stream and configure the reader. procedure Read_Definition (Client : in out Probe_Manager_Type; Msg : in out MAT.Readers.Message); end MAT.Events.Probes;
----------------------------------------------------------------------- -- mat-events-probes -- Event probes -- Copyright (C) 2014, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Containers; with Ada.Containers.Hashed_Maps; with Ada.Containers.Indefinite_Hashed_Maps; with Ada.Strings.Hash; with Ada.Finalization; with MAT.Types; with MAT.Events; with MAT.Events.Targets; with MAT.Readers; with MAT.Frames.Targets; package MAT.Events.Probes is ----------------- -- Abstract probe definition ----------------- type Probe_Type is abstract tagged limited private; type Probe_Type_Access is access all Probe_Type'Class; -- Extract the probe information from the message. procedure Extract (Probe : in Probe_Type; Params : in MAT.Events.Const_Attribute_Table_Access; Msg : in out MAT.Readers.Message_Type; Event : in out Target_Event_Type) is abstract; procedure Execute (Probe : in Probe_Type; Event : in out Target_Event_Type) is abstract; -- Update the Size and Prev_Id information in the event identified by <tt>Id</tt>. -- Update the event represented by <tt>Prev_Id</tt> so that its Next_Id refers -- to the <tt>Id</tt> event. procedure Update_Event (Probe : in Probe_Type; Id : in MAT.Events.Event_Id_Type; Size : in MAT.Types.Target_Size; Prev_Id : in MAT.Events.Event_Id_Type); ----------------- -- Probe Manager ----------------- type Probe_Manager_Type is abstract new Ada.Finalization.Limited_Controlled with private; type Probe_Manager_Type_Access is access all Probe_Manager_Type'Class; -- Initialize the probe manager instance. overriding procedure Initialize (Manager : in out Probe_Manager_Type); -- Register the probe to handle the event identified by the given name. -- The event is mapped to the given id and the attributes table is used -- to setup the mapping from the data stream attributes. procedure Register_Probe (Into : in out Probe_Manager_Type; Probe : in Probe_Type_Access; Name : in String; Id : in MAT.Events.Probe_Index_Type; Model : in MAT.Events.Const_Attribute_Table_Access); procedure Dispatch_Message (Client : in out Probe_Manager_Type; Msg : in out MAT.Readers.Message_Type); -- Read a list of event definitions from the stream and configure the reader. procedure Read_Event_Definitions (Client : in out Probe_Manager_Type; Msg : in out MAT.Readers.Message_Type); -- Get the target events. function Get_Target_Events (Client : in Probe_Manager_Type) return MAT.Events.Targets.Target_Events_Access; -- Get the target frames. function Get_Target_Frames (Client : in Probe_Manager_Type) return MAT.Frames.Targets.Target_Frames_Access; -- Read a message from the stream. procedure Read_Message (Reader : in out Probe_Manager_Type; Msg : in out MAT.Readers.Message_Type) is abstract; -- Get the size of a target address (4 or 8 bytes). function Get_Address_Size (Client : in Probe_Manager_Type) return MAT.Events.Attribute_Type; type Reader_List_Type is limited interface; type Reader_List_Type_Access is access all Reader_List_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 (List : in out Reader_List_Type; Manager : in out Probe_Manager_Type'Class) is abstract; private type Probe_Type is abstract tagged limited record Owner : Probe_Manager_Type_Access := null; end record; -- Record a probe type Probe_Handler is record Probe : Probe_Type_Access; Id : MAT.Events.Probe_Index_Type; Attributes : MAT.Events.Const_Attribute_Table_Access; Mapping : MAT.Events.Attribute_Table_Ptr; end record; function Hash (Key : in MAT.Types.Uint16) return Ada.Containers.Hash_Type; package Probe_Maps is new Ada.Containers.Indefinite_Hashed_Maps (Key_Type => String, Element_Type => Probe_Handler, Hash => Ada.Strings.Hash, Equivalent_Keys => "="); -- Runtime handlers associated with the events. package Handler_Maps is new Ada.Containers.Hashed_Maps (Key_Type => MAT.Types.Uint16, Element_Type => Probe_Handler, Hash => Hash, Equivalent_Keys => "="); type Probe_Manager_Type is abstract new Ada.Finalization.Limited_Controlled with record Probes : Probe_Maps.Map; Handlers : Handler_Maps.Map; Version : MAT.Types.Uint16; Flags : MAT.Types.Uint16; Addr_Size : MAT.Events.Attribute_Type; Probe : MAT.Events.Attribute_Table_Ptr; Frame : access MAT.Events.Frame_Info; Events : MAT.Events.Targets.Target_Events_Access; Event : Target_Event_Type; Frames : MAT.Frames.Targets.Target_Frames_Access; end record; -- Read an event definition from the stream and configure the reader. procedure Read_Definition (Client : in out Probe_Manager_Type; Msg : in out MAT.Readers.Message); end MAT.Events.Probes;
Define the Get_Target_Frames function to retrieve the frames target instance
Define the Get_Target_Frames function to retrieve the frames target instance
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
ab7896635e48ff9d120db45c5ad2e3c4d6f88dcc
src/asf-navigations.ads
src/asf-navigations.ads
----------------------------------------------------------------------- -- asf-navigations -- Navigations -- Copyright (C) 2010, 2011, 2012, 2013 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with ASF.Contexts.Faces; with EL.Expressions; with EL.Contexts; with Ada.Finalization; with ASF.Applications.Views; with Ada.Strings.Unbounded; limited with ASF.Applications.Main; private with Ada.Containers.Vectors; private with Ada.Containers.Hashed_Maps; private with Ada.Strings.Unbounded.Hash; -- The <b>ASF.Navigations</b> package is responsible for calculating the view to be -- rendered after an action is processed. The navigation handler contains some rules -- (defined in XML files) and it uses the current view id, the action outcome and -- the faces context to decide which view must be rendered. -- -- See JSR 314 - JavaServer Faces Specification 7.4 NavigationHandler package ASF.Navigations is -- ------------------------------ -- Navigation Handler -- ------------------------------ type Navigation_Handler is new Ada.Finalization.Limited_Controlled with private; type Navigation_Handler_Access is access all Navigation_Handler'Class; -- After executing an action and getting the action outcome, proceed to the navigation -- to the next page. procedure Handle_Navigation (Handler : in Navigation_Handler; Action : in String; Outcome : in String; Context : in out ASF.Contexts.Faces.Faces_Context'Class); -- Provide a default navigation rules for the view and the outcome when no application -- navigation was found. The default looks for an XHTML file in the same directory as -- the view and which has the base name defined by <b>Outcome</b>. procedure Handle_Default_Navigation (Handler : in Navigation_Handler; View : in String; Outcome : in String; Context : in out ASF.Contexts.Faces.Faces_Context'Class); -- Initialize the the lifecycle handler. procedure Initialize (Handler : in out Navigation_Handler; App : access ASF.Applications.Main.Application'Class); -- Free the storage used by the navigation handler. overriding procedure Finalize (Handler : in out Navigation_Handler); -- Add a navigation case to navigate from the view identifier by <b>From</b> -- to the result view identified by <b>To</b>. Some optional conditions are evaluated -- The <b>Outcome</b> must match unless it is empty. -- The <b>Action</b> must match unless it is empty. -- The <b>Condition</b> expression must evaluate to True. procedure Add_Navigation_Case (Handler : in out Navigation_Handler; From : in String; To : in String; Outcome : in String := ""; Action : in String := ""; Condition : in String := ""; Context : in EL.Contexts.ELContext'Class); -- ------------------------------ -- Navigation Case -- ------------------------------ -- The <b>Navigation_Case</b> contains a condition and a navigation action. -- The condition must be matched to execute the navigation action. type Navigation_Case is abstract tagged limited private; type Navigation_Access is access all Navigation_Case'Class; -- Check if the navigator specific condition matches the current execution context. function Matches (Navigator : in Navigation_Case; Action : in String; Outcome : in String; Context : in ASF.Contexts.Faces.Faces_Context'Class) return Boolean; -- Navigate to the next page or action according to the controller's navigator. -- A navigator controller could redirect the user to another page, render a specific -- view or return some raw content. procedure Navigate (Navigator : in Navigation_Case; Context : in out ASF.Contexts.Faces.Faces_Context'Class) is abstract; -- Add a navigation case to navigate from the view identifier by <b>From</b> -- by using the navigation rule defined by <b>Navigator</b>. -- Some optional conditions are evaluated: -- The <b>Outcome</b> must match unless it is empty. -- The <b>Action</b> must match unless it is empty. -- The <b>Condition</b> expression must evaluate to True. procedure Add_Navigation_Case (Handler : in out Navigation_Handler'Class; Navigator : in Navigation_Access; From : in String; Outcome : in String := ""; Action : in String := ""; Condition : in String := ""; Context : in EL.Contexts.ELContext'Class); private use Ada.Strings.Unbounded; type Navigation_Case is abstract tagged limited record -- When not empty, the condition that must be verified to follow this navigator. Condition : EL.Expressions.Expression; View_Handler : access ASF.Applications.Views.View_Handler'Class; Outcome : String_Access; Action : String_Access; end record; package Navigator_Vector is new Ada.Containers.Vectors (Index_Type => Natural, Element_Type => Navigation_Access); -- ------------------------------ -- Navigation Rule -- ------------------------------ type Rule is tagged limited record Navigators : Navigator_Vector.Vector; end record; -- Clear the navigation rules. procedure Clear (Controller : in out Rule); -- Search for the navigator that matches the current action, outcome and context. -- Returns the navigator or null if there was no match. function Find_Navigation (Controller : in Rule; Action : in String; Outcome : in String; Context : in Contexts.Faces.Faces_Context'Class) return Navigation_Access; type Rule_Access is access all Rule'Class; package Rule_Map is new Ada.Containers.Hashed_Maps (Key_Type => Unbounded_String, Element_Type => Rule_Access, Hash => Hash, Equivalent_Keys => "="); type Navigation_Rules is limited record -- Exact match rules Rules : Rule_Map.Map; end record; -- Clear the navigation rules. procedure Clear (Controller : in out Navigation_Rules); type Navigation_Rules_Access is access all Navigation_Rules; type Navigation_Handler is new Ada.Finalization.Limited_Controlled with record Rules : Navigation_Rules_Access; Application : access ASF.Applications.Main.Application'Class; View_Handler : access ASF.Applications.Views.View_Handler'Class; end record; end ASF.Navigations;
----------------------------------------------------------------------- -- asf-navigations -- Navigations -- 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 ASF.Contexts.Faces; with EL.Expressions; with EL.Contexts; with Ada.Finalization; with ASF.Applications.Views; with Ada.Strings.Unbounded; private with Ada.Containers.Vectors; private with Ada.Containers.Hashed_Maps; private with Ada.Strings.Unbounded.Hash; -- The <b>ASF.Navigations</b> package is responsible for calculating the view to be -- rendered after an action is processed. The navigation handler contains some rules -- (defined in XML files) and it uses the current view id, the action outcome and -- the faces context to decide which view must be rendered. -- -- See JSR 314 - JavaServer Faces Specification 7.4 NavigationHandler package ASF.Navigations is -- ------------------------------ -- Navigation Handler -- ------------------------------ type Navigation_Handler is new Ada.Finalization.Limited_Controlled with private; type Navigation_Handler_Access is access all Navigation_Handler'Class; -- After executing an action and getting the action outcome, proceed to the navigation -- to the next page. procedure Handle_Navigation (Handler : in Navigation_Handler; Action : in String; Outcome : in String; Context : in out ASF.Contexts.Faces.Faces_Context'Class); -- Provide a default navigation rules for the view and the outcome when no application -- navigation was found. The default looks for an XHTML file in the same directory as -- the view and which has the base name defined by <b>Outcome</b>. procedure Handle_Default_Navigation (Handler : in Navigation_Handler; View : in String; Outcome : in String; Context : in out ASF.Contexts.Faces.Faces_Context'Class); -- Initialize the the lifecycle handler. procedure Initialize (Handler : in out Navigation_Handler; Views : access ASF.Applications.Views.View_Handler'Class); -- Free the storage used by the navigation handler. overriding procedure Finalize (Handler : in out Navigation_Handler); -- Add a navigation case to navigate from the view identifier by <b>From</b> -- to the result view identified by <b>To</b>. Some optional conditions are evaluated -- The <b>Outcome</b> must match unless it is empty. -- The <b>Action</b> must match unless it is empty. -- The <b>Condition</b> expression must evaluate to True. procedure Add_Navigation_Case (Handler : in out Navigation_Handler; From : in String; To : in String; Outcome : in String := ""; Action : in String := ""; Condition : in String := ""; Context : in EL.Contexts.ELContext'Class); -- ------------------------------ -- Navigation Case -- ------------------------------ -- The <b>Navigation_Case</b> contains a condition and a navigation action. -- The condition must be matched to execute the navigation action. type Navigation_Case is abstract tagged limited private; type Navigation_Access is access all Navigation_Case'Class; -- Check if the navigator specific condition matches the current execution context. function Matches (Navigator : in Navigation_Case; Action : in String; Outcome : in String; Context : in ASF.Contexts.Faces.Faces_Context'Class) return Boolean; -- Navigate to the next page or action according to the controller's navigator. -- A navigator controller could redirect the user to another page, render a specific -- view or return some raw content. procedure Navigate (Navigator : in Navigation_Case; Context : in out ASF.Contexts.Faces.Faces_Context'Class) is abstract; -- Add a navigation case to navigate from the view identifier by <b>From</b> -- by using the navigation rule defined by <b>Navigator</b>. -- Some optional conditions are evaluated: -- The <b>Outcome</b> must match unless it is empty. -- The <b>Action</b> must match unless it is empty. -- The <b>Condition</b> expression must evaluate to True. procedure Add_Navigation_Case (Handler : in out Navigation_Handler'Class; Navigator : in Navigation_Access; From : in String; Outcome : in String := ""; Action : in String := ""; Condition : in String := ""; Context : in EL.Contexts.ELContext'Class); private use Ada.Strings.Unbounded; type Navigation_Case is abstract tagged limited record -- When not empty, the condition that must be verified to follow this navigator. Condition : EL.Expressions.Expression; View_Handler : access ASF.Applications.Views.View_Handler'Class; Outcome : String_Access; Action : String_Access; end record; package Navigator_Vector is new Ada.Containers.Vectors (Index_Type => Natural, Element_Type => Navigation_Access); -- ------------------------------ -- Navigation Rule -- ------------------------------ type Rule is tagged limited record Navigators : Navigator_Vector.Vector; end record; -- Clear the navigation rules. procedure Clear (Controller : in out Rule); -- Search for the navigator that matches the current action, outcome and context. -- Returns the navigator or null if there was no match. function Find_Navigation (Controller : in Rule; Action : in String; Outcome : in String; Context : in Contexts.Faces.Faces_Context'Class) return Navigation_Access; type Rule_Access is access all Rule'Class; package Rule_Map is new Ada.Containers.Hashed_Maps (Key_Type => Unbounded_String, Element_Type => Rule_Access, Hash => Hash, Equivalent_Keys => "="); type Navigation_Rules is limited record -- Exact match rules Rules : Rule_Map.Map; end record; -- Clear the navigation rules. procedure Clear (Controller : in out Navigation_Rules); type Navigation_Rules_Access is access all Navigation_Rules; type Navigation_Handler is new Ada.Finalization.Limited_Controlled with record Rules : Navigation_Rules_Access; View_Handler : access ASF.Applications.Views.View_Handler'Class; end record; end ASF.Navigations;
Use ASF.Applications.Views.View_Handler'Class to avoid using a 'limited with' clause
Use ASF.Applications.Views.View_Handler'Class to avoid using a 'limited with' clause
Ada
apache-2.0
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
0e57206a506075b87096555e1a3a20bd907e8682
testcases/autocommit/autocommit.adb
testcases/autocommit/autocommit.adb
with AdaBase; with Connect; with CommonText; with Ada.Text_IO; with AdaBase.Results.Sets; procedure Autocommit is package CON renames Connect; package TIO renames Ada.Text_IO; package ARS renames AdaBase.Results.Sets; package CT renames CommonText; insX : constant String := "INSERT INTO fruits (id, fruit, color, calories)"; ins1 : constant String := insX & " VALUES (100,'cucumber','green',16)"; ins2 : constant String := insX & " VALUES (101,'kumquat','yellow',71)"; ins3 : constant String := insX & " VALUES (102,'persimmon','orange',127)"; sel : constant String := "SELECT * FROM fruits WHERE id > 99"; del : constant String := "DELETE FROM fruits WHERE id > 99"; procedure clear_table; procedure test_uno (expected : Natural; version2 : Boolean); procedure test_dos (expected : Natural; version2 : Boolean); procedure test_tres (expected : Natural); procedure expect (impacted : AdaBase.AffectedRows; expected : Natural); procedure show_results (expected : Natural); procedure expect (impacted : AdaBase.AffectedRows; expected : Natural) is begin TIO.Put_Line ("Rows expected:" & expected'Img); TIO.Put_Line ("Rows returned:" & impacted'Img); if Natural (impacted) = expected then TIO.Put_Line ("=== PASSED ==="); else TIO.Put_Line ("=== FAILED === <<----------------------------"); end if; TIO.Put_Line (""); end expect; procedure show_results (expected : Natural) is begin CON.connect_database; declare stmt : CON.Stmt_Type := CON.DR.query (sel); begin expect (stmt.rows_returned, expected); end; CON.DR.disconnect; end show_results; procedure test_uno (expected : Natural; version2 : Boolean) is AR : AdaBase.AffectedRows; begin CON.connect_database; AR := CON.DR.execute (ins1); AR := CON.DR.execute (ins2); if version2 then CON.DR.commit; end if; CON.DR.disconnect; show_results (expected); end test_uno; procedure test_dos (expected : Natural; version2 : Boolean) is AR : AdaBase.AffectedRows; begin CON.connect_database; AR := CON.DR.execute (ins1); CON.DR.set_trait_autocommit (True); AR := CON.DR.execute (ins2); CON.DR.set_trait_autocommit (False); AR := CON.DR.execute (ins3); if version2 then CON.DR.commit; end if; CON.DR.disconnect; show_results (expected); end test_dos; procedure test_tres (expected : Natural) is AR : AdaBase.AffectedRows; begin CON.connect_database; AR := CON.DR.execute (ins1); CON.DR.set_trait_autocommit (True); CON.DR.disconnect; show_results (expected); end test_tres; procedure clear_table is AR : AdaBase.AffectedRows; begin CON.connect_database; AR := CON.DR.execute (del); CON.DR.commit; CON.DR.disconnect; end clear_table; begin clear_table; TIO.Put_Line ("=== PRECONNECT AUTOCOMMIT => OFF (DEFAULT) ==="); CON.DR.set_trait_autocommit (False); test_uno (0, False); clear_table; TIO.Put_Line ("=== PRECONNECT AUTOCOMMIT => ON ==="); CON.DR.set_trait_autocommit (True); test_uno (2, False); clear_table; TIO.Put_Line ("=== CONNECT AC=0, INS, AC=1, INS, AC=0, INS ==="); CON.DR.set_trait_autocommit (False); test_dos (2, False); clear_table; TIO.Put_Line ("=== IMPLICIT COMMIT (AC/OFF => ON) ==="); CON.DR.set_trait_autocommit (False); test_tres (1); clear_table; TIO.Put_Line ("=== PRECONNECT AUTOCOMMIT => OFF WITH COMMIT ==="); CON.DR.set_trait_autocommit (False); test_uno (2, True); clear_table; TIO.Put_Line ("=== PRECONNECT AUTOCOMMIT => ON WITH COMMIT (NO-OP) ==="); CON.DR.set_trait_autocommit (True); test_uno (2, True); clear_table; TIO.Put_Line ("=== CONNECT AC=0, INS, AC=1, INS, AC=0, INS COMMIT ==="); CON.DR.set_trait_autocommit (False); test_dos (3, True); end Autocommit;
with AdaBase; with Connect; with CommonText; with Ada.Text_IO; with AdaBase.Results.Sets; procedure Autocommit is package CON renames Connect; package TIO renames Ada.Text_IO; package ARS renames AdaBase.Results.Sets; package CT renames CommonText; insX : constant String := "INSERT INTO fruits (id, fruit, color, calories)"; ins1 : constant String := insX & " VALUES (100,'cucumber','green',16)"; ins2 : constant String := insX & " VALUES (101,'kumquat','yellow',71)"; ins3 : constant String := insX & " VALUES (102,'persimmon','orange',127)"; sel : constant String := "SELECT * FROM fruits WHERE id > 99"; del : constant String := "DELETE FROM fruits WHERE id > 99"; procedure clear_table; procedure test_uno (expected : Natural; version2 : Boolean); procedure test_dos (expected : Natural; version2 : Boolean); procedure test_tres (expected : Natural); procedure expect (impacted, expected : Natural); procedure show_results (expected : Natural); procedure expect (impacted, expected : Natural) is begin TIO.Put_Line ("Rows expected:" & expected'Img); TIO.Put_Line ("Rows returned:" & impacted'Img); if impacted = expected then TIO.Put_Line ("=== PASSED ==="); else TIO.Put_Line ("=== FAILED === <<----------------------------"); end if; TIO.Put_Line (""); end expect; procedure show_results (expected : Natural) is begin CON.connect_database; declare stmt : CON.Stmt_Type := CON.DR.query (sel); row : ARS.DataRow; NR : Natural := 0; begin loop row := stmt.fetch_next; exit when row.data_exhausted; NR := NR + 1; end loop; expect (NR, expected); end; CON.DR.disconnect; end show_results; procedure test_uno (expected : Natural; version2 : Boolean) is AR : AdaBase.AffectedRows; begin CON.connect_database; AR := CON.DR.execute (ins1); AR := CON.DR.execute (ins2); if version2 then CON.DR.commit; end if; CON.DR.disconnect; show_results (expected); end test_uno; procedure test_dos (expected : Natural; version2 : Boolean) is AR : AdaBase.AffectedRows; begin CON.connect_database; AR := CON.DR.execute (ins1); CON.DR.set_trait_autocommit (True); AR := CON.DR.execute (ins2); CON.DR.set_trait_autocommit (False); AR := CON.DR.execute (ins3); if version2 then CON.DR.commit; end if; CON.DR.disconnect; show_results (expected); end test_dos; procedure test_tres (expected : Natural) is AR : AdaBase.AffectedRows; begin CON.connect_database; AR := CON.DR.execute (ins1); CON.DR.set_trait_autocommit (True); CON.DR.disconnect; show_results (expected); end test_tres; procedure clear_table is AR : AdaBase.AffectedRows; begin CON.connect_database; AR := CON.DR.execute (del); if not CON.DR.trait_autocommit then CON.DR.commit; end if; CON.DR.disconnect; end clear_table; begin clear_table; TIO.Put_Line ("=== PRECONNECT AUTOCOMMIT => OFF (DEFAULT) ==="); CON.DR.set_trait_autocommit (False); test_uno (0, False); clear_table; TIO.Put_Line ("=== PRECONNECT AUTOCOMMIT => ON ==="); CON.DR.set_trait_autocommit (True); test_uno (2, False); clear_table; TIO.Put_Line ("=== CONNECT AC=0, INS, AC=1, INS, AC=0, INS ==="); CON.DR.set_trait_autocommit (False); test_dos (2, False); clear_table; TIO.Put_Line ("=== IMPLICIT COMMIT (AC/OFF => ON) ==="); CON.DR.set_trait_autocommit (False); test_tres (1); clear_table; TIO.Put_Line ("=== PRECONNECT AUTOCOMMIT => OFF WITH COMMIT ==="); CON.DR.set_trait_autocommit (False); test_uno (2, True); clear_table; TIO.Put_Line ("=== PRECONNECT AUTOCOMMIT => ON WITH COMMIT (NO-OP) ==="); CON.DR.set_trait_autocommit (True); test_uno (2, True); clear_table; TIO.Put_Line ("=== CONNECT AC=0, INS, AC=1, INS, AC=0, INS COMMIT ==="); CON.DR.set_trait_autocommit (False); test_dos (3, True); end Autocommit;
Fix autocommit testcase for sqlite
Fix autocommit testcase for sqlite On SQLite, "rows returned" is not supported, so change the test to iterate through the rows and count each one instead. Also don't issue "Commit" on the clear table routine if we're in autocommit mode.
Ada
isc
jrmarino/AdaBase
17b30b241c4e565c31758994fcbd802acb9a5a1e
mat/src/memory/mat-memory-targets.adb
mat/src/memory/mat-memory-targets.adb
----------------------------------------------------------------------- -- Memory Events - Definition and Analysis of memory events -- Copyright (C) 2014, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Log.Loggers; with MAT.Memory.Probes; package body MAT.Memory.Targets is -- The logger Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("MAT.Memory.Targets"); -- ------------------------------ -- Initialize the target memory object to manage the memory slots, the stack frames -- and setup the reader to analyze the memory events. -- ------------------------------ procedure Initialize (Memory : in out Target_Memory; Manager : in out MAT.Events.Probes.Probe_Manager_Type'Class) is Memory_Probe : constant MAT.Memory.Probes.Memory_Probe_Type_Access := new MAT.Memory.Probes.Memory_Probe_Type; begin -- Memory.Manager := Memory_Probe.all'Access; Memory_Probe.Data := Memory'Unrestricted_Access; MAT.Memory.Probes.Register (Manager, Memory_Probe); end Initialize; -- ------------------------------ -- Add the memory region from the list of memory region managed by the program. -- ------------------------------ procedure Add_Region (Memory : in out Target_Memory; Region : in Region_Info) is begin Log.Info ("Add region [" & MAT.Types.Hex_Image (Region.Start_Addr) & "-" & MAT.Types.Hex_Image (Region.End_Addr) & "]"); Memory.Memory.Add_Region (Region); end Add_Region; -- ------------------------------ -- Take into account a malloc probe. The memory slot [Addr .. Slot.Size] is inserted -- in the used slots map. The freed slots that intersect the malloc'ed region are -- removed from the freed map. -- ------------------------------ procedure Probe_Malloc (Memory : in out Target_Memory; Addr : in MAT.Types.Target_Addr; Slot : in Allocation) is begin Memory.Memory.Probe_Malloc (Addr, Slot); end Probe_Malloc; -- ------------------------------ -- Take into account a free probe. Add the memory slot in the freed map and remove -- the slot from the used slots map. -- ------------------------------ procedure Probe_Free (Memory : in out Target_Memory; Addr : in MAT.Types.Target_Addr; Slot : in Allocation) is begin Memory.Memory.Probe_Free (Addr, Slot); end Probe_Free; -- ------------------------------ -- Take into account a realloc probe. The old memory slot represented by Old_Addr is -- removed from the used slots maps and the new memory slot [Addr .. Slot.Size] is -- inserted in the used slots map. -- ------------------------------ procedure Probe_Realloc (Memory : in out Target_Memory; Addr : in MAT.Types.Target_Addr; Old_Addr : in MAT.Types.Target_Addr; Slot : in Allocation) is begin Memory.Memory.Probe_Realloc (Addr, Old_Addr, Slot); end Probe_Realloc; -- ------------------------------ -- Insert in the frame tree the new stack frame represented by <tt>Pc</tt>. -- If the frame is already known, the frame reference counter is incremented. -- The frame represented by <tt>Pc</tt> is returned in <tt>Result</tt>. -- ------------------------------ procedure Create_Frame (Memory : in out Target_Memory; Pc : in MAT.Frames.Frame_Table; Result : out MAT.Frames.Frame_Type) is begin Memory.Memory.Create_Frame (Pc, Result); end Create_Frame; -- ------------------------------ -- Collect the information about memory slot sizes allocated by the application. -- ------------------------------ procedure Size_Information (Memory : in out Target_Memory; Sizes : in out MAT.Memory.Tools.Size_Info_Map) is begin Memory.Memory.Size_Information (Sizes); end Size_Information; -- ------------------------------ -- Collect the information about threads and the memory allocations they've made. -- ------------------------------ procedure Thread_Information (Memory : in out Target_Memory; Threads : in out Memory_Info_Map) is begin Memory.Memory.Thread_Information (Threads); end Thread_Information; -- ------------------------------ -- Collect the information about frames and the memory allocations they've made. -- ------------------------------ procedure Frame_Information (Memory : in out Target_Memory; Level : in Natural; Frames : in out Frame_Info_Map) is begin Memory.Memory.Frame_Information (Level, Frames); end Frame_Information; -- ------------------------------ -- Get the global memory and allocation statistics. -- ------------------------------ procedure Stat_Information (Memory : in out Target_Memory; Result : out Memory_Stat) is begin Memory.Memory.Stat_Information (Result); end Stat_Information; -- ------------------------------ -- Find from the <tt>Memory</tt> map the memory slots whose address intersects -- the region [From .. To] and which is selected by the given filter expression. -- Add the memory slot in the <tt>Into</tt> list if it does not already contains -- the memory slot. -- ------------------------------ procedure Find (Memory : in out Target_Memory; From : in MAT.Types.Target_Addr; To : in MAT.Types.Target_Addr; Filter : in MAT.Expressions.Expression_Type; Into : in out MAT.Memory.Allocation_Map) is begin Memory.Memory.Find (From, To, Filter, Into); end Find; protected body Memory_Allocator is -- ------------------------------ -- Add the memory region from the list of memory region managed by the program. -- ------------------------------ procedure Add_Region (Region : in Region_Info) is begin Regions.Insert (Region.Start_Addr, Region); end Add_Region; -- ------------------------------ -- Remove the memory region [Addr .. Addr + Size] from the free list. -- ------------------------------ procedure Remove_Free (Addr : in MAT.Types.Target_Addr; Size : in MAT.Types.Target_Size) is Iter : Allocation_Cursor; Last : constant MAT.Types.Target_Addr := Addr + MAT.Types.Target_Addr (Size); Slot : Allocation; begin -- Walk the list of free blocks and remove all the blocks which intersect the region -- [Addr .. Addr + Slot.Size]. We start walking at the first block below and near -- the address. Slots are then removed when they intersect the malloc'ed region. Iter := Freed_Slots.Floor (Addr); while Allocation_Maps.Has_Element (Iter) loop declare Freed_Addr : constant MAT.Types.Target_Addr := Allocation_Maps.Key (Iter); begin exit when Freed_Addr > Last; Slot := Allocation_Maps.Element (Iter); if Freed_Addr + MAT.Types.Target_Addr (Slot.Size) > Addr then if Stats.Total_Free > Slot.Size then Stats.Total_Free := Stats.Total_Free - Slot.Size; else Stats.Total_Free := 0; end if; Freed_Slots.Delete (Iter); Iter := Freed_Slots.Floor (Addr); else Allocation_Maps.Next (Iter); end if; end; end loop; end Remove_Free; -- ------------------------------ -- Take into account a malloc probe. The memory slot [Addr .. Slot.Size] is inserted -- in the used slots map. The freed slots that intersect the malloc'ed region are -- removed from the freed map. -- ------------------------------ procedure Probe_Malloc (Addr : in MAT.Types.Target_Addr; Slot : in Allocation) is begin if Log.Get_Level = Util.Log.DEBUG_LEVEL then Log.Debug ("Malloc at {0} size {1}", MAT.Types.Hex_Image (Addr), MAT.Types.Target_Size'Image (Slot.Size)); end if; Stats.Malloc_Count := Stats.Malloc_Count + 1; if Addr /= 0 then Stats.Total_Alloc := Stats.Total_Alloc + Slot.Size; Remove_Free (Addr, Slot.Size); Used_Slots.Insert (Addr, Slot); end if; end Probe_Malloc; -- ------------------------------ -- Take into account a free probe. Add the memory slot in the freed map and remove -- the slot from the used slots map. -- ------------------------------ procedure Probe_Free (Addr : in MAT.Types.Target_Addr; Slot : in Allocation) is Item : Allocation; Iter : Allocation_Cursor; begin if Log.Get_Level = Util.Log.DEBUG_LEVEL then Log.Debug ("Free {0}", MAT.Types.Hex_Image (Addr)); end if; Stats.Free_Count := Stats.Free_Count + 1; Iter := Used_Slots.Find (Addr); if Allocation_Maps.Has_Element (Iter) then Item := Allocation_Maps.Element (Iter); if Stats.Total_Alloc >= Item.Size then Stats.Total_Alloc := Stats.Total_Alloc - Item.Size; else Stats.Total_Alloc := 0; end if; Stats.Total_Free := Stats.Total_Free + Item.Size; MAT.Frames.Release (Item.Frame); Used_Slots.Delete (Iter); Item.Frame := Slot.Frame; Freed_Slots.Insert (Addr, Item); end if; end Probe_Free; -- ------------------------------ -- Take into account a realloc probe. The old memory slot represented by Old_Addr is -- removed from the used slots maps and the new memory slot [Addr .. Slot.Size] is -- inserted in the used slots map. -- ------------------------------ procedure Probe_Realloc (Addr : in MAT.Types.Target_Addr; Old_Addr : in MAT.Types.Target_Addr; Slot : in Allocation) is procedure Update_Size (Key : in MAT.Types.Target_Addr; Element : in out Allocation); procedure Update_Size (Key : in MAT.Types.Target_Addr; Element : in out Allocation) is pragma Unreferenced (Key); begin if Stats.Total_Alloc >= Element.Size then Stats.Total_Alloc := Stats.Total_Alloc - Element.Size; else Stats.Total_Alloc := 0; end if; Element.Size := Slot.Size; MAT.Frames.Release (Element.Frame); Element.Frame := Slot.Frame; end Update_Size; Pos : Allocation_Cursor; begin if Log.Get_Level = Util.Log.DEBUG_LEVEL then Log.Debug ("Realloc {0} to {1} size {2}", MAT.Types.Hex_Image (Old_Addr), MAT.Types.Hex_Image (Addr), MAT.Types.Target_Size'Image (Slot.Size)); end if; Stats.Realloc_Count := Stats.Realloc_Count + 1; if Addr /= 0 then Stats.Total_Alloc := Stats.Total_Alloc + Slot.Size; Pos := Used_Slots.Find (Old_Addr); if Allocation_Maps.Has_Element (Pos) then if Addr = Old_Addr then Used_Slots.Update_Element (Pos, Update_Size'Access); else Used_Slots.Delete (Pos); Used_Slots.Insert (Addr, Slot); end if; else Used_Slots.Insert (Addr, Slot); end if; Remove_Free (Addr, Slot.Size); end if; end Probe_Realloc; -- ------------------------------ -- Insert in the frame tree the new stack frame represented by <tt>Pc</tt>. -- If the frame is already known, the frame reference counter is incremented. -- The frame represented by <tt>Pc</tt> is returned in <tt>Result</tt>. -- ------------------------------ procedure Create_Frame (Pc : in MAT.Frames.Frame_Table; Result : out MAT.Frames.Frame_Type) is begin MAT.Frames.Insert (Frames, Pc, Result); end Create_Frame; -- ------------------------------ -- Collect the information about memory slot sizes allocated by the application. -- ------------------------------ procedure Size_Information (Sizes : in out MAT.Memory.Tools.Size_Info_Map) is begin MAT.Memory.Tools.Size_Information (Used_Slots, Sizes); end Size_Information; -- ------------------------------ -- Collect the information about threads and the memory allocations they've made. -- ------------------------------ procedure Thread_Information (Threads : in out Memory_Info_Map) is begin MAT.Memory.Tools.Thread_Information (Used_Slots, Threads); end Thread_Information; -- ------------------------------ -- Collect the information about frames and the memory allocations they've made. -- ------------------------------ procedure Frame_Information (Level : in Natural; Frames : in out Frame_Info_Map) is begin MAT.Memory.Tools.Frame_Information (Used_Slots, Level, Frames); end Frame_Information; -- ------------------------------ -- Find from the <tt>Memory</tt> map the memory slots whose address intersects -- the region [From .. To] and which is selected by the given filter expression. -- Add the memory slot in the <tt>Into</tt> list if it does not already contains -- the memory slot. -- ------------------------------ procedure Find (From : in MAT.Types.Target_Addr; To : in MAT.Types.Target_Addr; Filter : in MAT.Expressions.Expression_Type; Into : in out MAT.Memory.Allocation_Map) is begin MAT.Memory.Tools.Find (Used_Slots, From, To, Filter, Into); end Find; -- ------------------------------ -- Get the global memory and allocation statistics. -- ------------------------------ procedure Stat_Information (Result : out Memory_Stat) is begin Result := Stats; end Stat_Information; end Memory_Allocator; end MAT.Memory.Targets;
----------------------------------------------------------------------- -- Memory Events - Definition and Analysis of memory events -- Copyright (C) 2014, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Log.Loggers; with MAT.Memory.Probes; package body MAT.Memory.Targets is -- The logger Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("MAT.Memory.Targets"); -- ------------------------------ -- Initialize the target memory object to manage the memory slots, the stack frames -- and setup the reader to analyze the memory events. -- ------------------------------ procedure Initialize (Memory : in out Target_Memory; Manager : in out MAT.Events.Probes.Probe_Manager_Type'Class) is Memory_Probe : constant MAT.Memory.Probes.Memory_Probe_Type_Access := new MAT.Memory.Probes.Memory_Probe_Type; begin -- Memory.Manager := Memory_Probe.all'Access; Memory_Probe.Data := Memory'Unrestricted_Access; MAT.Memory.Probes.Register (Manager, Memory_Probe); end Initialize; -- ------------------------------ -- Add the memory region from the list of memory region managed by the program. -- ------------------------------ procedure Add_Region (Memory : in out Target_Memory; Region : in Region_Info) is begin Log.Info ("Add region [" & MAT.Types.Hex_Image (Region.Start_Addr) & "-" & MAT.Types.Hex_Image (Region.End_Addr) & "] - {0}", Region.Path); Memory.Memory.Add_Region (Region); end Add_Region; -- ------------------------------ -- Take into account a malloc probe. The memory slot [Addr .. Slot.Size] is inserted -- in the used slots map. The freed slots that intersect the malloc'ed region are -- removed from the freed map. -- ------------------------------ procedure Probe_Malloc (Memory : in out Target_Memory; Addr : in MAT.Types.Target_Addr; Slot : in Allocation) is begin Memory.Memory.Probe_Malloc (Addr, Slot); end Probe_Malloc; -- ------------------------------ -- Take into account a free probe. Add the memory slot in the freed map and remove -- the slot from the used slots map. -- ------------------------------ procedure Probe_Free (Memory : in out Target_Memory; Addr : in MAT.Types.Target_Addr; Slot : in Allocation) is begin Memory.Memory.Probe_Free (Addr, Slot); end Probe_Free; -- ------------------------------ -- Take into account a realloc probe. The old memory slot represented by Old_Addr is -- removed from the used slots maps and the new memory slot [Addr .. Slot.Size] is -- inserted in the used slots map. -- ------------------------------ procedure Probe_Realloc (Memory : in out Target_Memory; Addr : in MAT.Types.Target_Addr; Old_Addr : in MAT.Types.Target_Addr; Slot : in Allocation) is begin Memory.Memory.Probe_Realloc (Addr, Old_Addr, Slot); end Probe_Realloc; -- ------------------------------ -- Insert in the frame tree the new stack frame represented by <tt>Pc</tt>. -- If the frame is already known, the frame reference counter is incremented. -- The frame represented by <tt>Pc</tt> is returned in <tt>Result</tt>. -- ------------------------------ procedure Create_Frame (Memory : in out Target_Memory; Pc : in MAT.Frames.Frame_Table; Result : out MAT.Frames.Frame_Type) is begin Memory.Memory.Create_Frame (Pc, Result); end Create_Frame; -- ------------------------------ -- Collect the information about memory slot sizes allocated by the application. -- ------------------------------ procedure Size_Information (Memory : in out Target_Memory; Sizes : in out MAT.Memory.Tools.Size_Info_Map) is begin Memory.Memory.Size_Information (Sizes); end Size_Information; -- ------------------------------ -- Collect the information about threads and the memory allocations they've made. -- ------------------------------ procedure Thread_Information (Memory : in out Target_Memory; Threads : in out Memory_Info_Map) is begin Memory.Memory.Thread_Information (Threads); end Thread_Information; -- ------------------------------ -- Collect the information about frames and the memory allocations they've made. -- ------------------------------ procedure Frame_Information (Memory : in out Target_Memory; Level : in Natural; Frames : in out Frame_Info_Map) is begin Memory.Memory.Frame_Information (Level, Frames); end Frame_Information; -- ------------------------------ -- Get the global memory and allocation statistics. -- ------------------------------ procedure Stat_Information (Memory : in out Target_Memory; Result : out Memory_Stat) is begin Memory.Memory.Stat_Information (Result); end Stat_Information; -- ------------------------------ -- Find from the <tt>Memory</tt> map the memory slots whose address intersects -- the region [From .. To] and which is selected by the given filter expression. -- Add the memory slot in the <tt>Into</tt> list if it does not already contains -- the memory slot. -- ------------------------------ procedure Find (Memory : in out Target_Memory; From : in MAT.Types.Target_Addr; To : in MAT.Types.Target_Addr; Filter : in MAT.Expressions.Expression_Type; Into : in out MAT.Memory.Allocation_Map) is begin Memory.Memory.Find (From, To, Filter, Into); end Find; protected body Memory_Allocator is -- ------------------------------ -- Add the memory region from the list of memory region managed by the program. -- ------------------------------ procedure Add_Region (Region : in Region_Info) is begin Regions.Insert (Region.Start_Addr, Region); end Add_Region; -- ------------------------------ -- Remove the memory region [Addr .. Addr + Size] from the free list. -- ------------------------------ procedure Remove_Free (Addr : in MAT.Types.Target_Addr; Size : in MAT.Types.Target_Size) is Iter : Allocation_Cursor; Last : constant MAT.Types.Target_Addr := Addr + MAT.Types.Target_Addr (Size); Slot : Allocation; begin -- Walk the list of free blocks and remove all the blocks which intersect the region -- [Addr .. Addr + Slot.Size]. We start walking at the first block below and near -- the address. Slots are then removed when they intersect the malloc'ed region. Iter := Freed_Slots.Floor (Addr); while Allocation_Maps.Has_Element (Iter) loop declare Freed_Addr : constant MAT.Types.Target_Addr := Allocation_Maps.Key (Iter); begin exit when Freed_Addr > Last; Slot := Allocation_Maps.Element (Iter); if Freed_Addr + MAT.Types.Target_Addr (Slot.Size) > Addr then if Stats.Total_Free > Slot.Size then Stats.Total_Free := Stats.Total_Free - Slot.Size; else Stats.Total_Free := 0; end if; Freed_Slots.Delete (Iter); Iter := Freed_Slots.Floor (Addr); else Allocation_Maps.Next (Iter); end if; end; end loop; end Remove_Free; -- ------------------------------ -- Take into account a malloc probe. The memory slot [Addr .. Slot.Size] is inserted -- in the used slots map. The freed slots that intersect the malloc'ed region are -- removed from the freed map. -- ------------------------------ procedure Probe_Malloc (Addr : in MAT.Types.Target_Addr; Slot : in Allocation) is begin if Log.Get_Level = Util.Log.DEBUG_LEVEL then Log.Debug ("Malloc at {0} size {1}", MAT.Types.Hex_Image (Addr), MAT.Types.Target_Size'Image (Slot.Size)); end if; Stats.Malloc_Count := Stats.Malloc_Count + 1; if Addr /= 0 then Stats.Total_Alloc := Stats.Total_Alloc + Slot.Size; Remove_Free (Addr, Slot.Size); Used_Slots.Insert (Addr, Slot); end if; end Probe_Malloc; -- ------------------------------ -- Take into account a free probe. Add the memory slot in the freed map and remove -- the slot from the used slots map. -- ------------------------------ procedure Probe_Free (Addr : in MAT.Types.Target_Addr; Slot : in Allocation) is Item : Allocation; Iter : Allocation_Cursor; begin if Log.Get_Level = Util.Log.DEBUG_LEVEL then Log.Debug ("Free {0}", MAT.Types.Hex_Image (Addr)); end if; Stats.Free_Count := Stats.Free_Count + 1; Iter := Used_Slots.Find (Addr); if Allocation_Maps.Has_Element (Iter) then Item := Allocation_Maps.Element (Iter); if Stats.Total_Alloc >= Item.Size then Stats.Total_Alloc := Stats.Total_Alloc - Item.Size; else Stats.Total_Alloc := 0; end if; Stats.Total_Free := Stats.Total_Free + Item.Size; MAT.Frames.Release (Item.Frame); Used_Slots.Delete (Iter); Item.Frame := Slot.Frame; Freed_Slots.Insert (Addr, Item); end if; end Probe_Free; -- ------------------------------ -- Take into account a realloc probe. The old memory slot represented by Old_Addr is -- removed from the used slots maps and the new memory slot [Addr .. Slot.Size] is -- inserted in the used slots map. -- ------------------------------ procedure Probe_Realloc (Addr : in MAT.Types.Target_Addr; Old_Addr : in MAT.Types.Target_Addr; Slot : in Allocation) is procedure Update_Size (Key : in MAT.Types.Target_Addr; Element : in out Allocation); procedure Update_Size (Key : in MAT.Types.Target_Addr; Element : in out Allocation) is pragma Unreferenced (Key); begin if Stats.Total_Alloc >= Element.Size then Stats.Total_Alloc := Stats.Total_Alloc - Element.Size; else Stats.Total_Alloc := 0; end if; Element.Size := Slot.Size; MAT.Frames.Release (Element.Frame); Element.Frame := Slot.Frame; end Update_Size; Pos : Allocation_Cursor; begin if Log.Get_Level = Util.Log.DEBUG_LEVEL then Log.Debug ("Realloc {0} to {1} size {2}", MAT.Types.Hex_Image (Old_Addr), MAT.Types.Hex_Image (Addr), MAT.Types.Target_Size'Image (Slot.Size)); end if; Stats.Realloc_Count := Stats.Realloc_Count + 1; if Addr /= 0 then Stats.Total_Alloc := Stats.Total_Alloc + Slot.Size; Pos := Used_Slots.Find (Old_Addr); if Allocation_Maps.Has_Element (Pos) then if Addr = Old_Addr then Used_Slots.Update_Element (Pos, Update_Size'Access); else Used_Slots.Delete (Pos); Used_Slots.Insert (Addr, Slot); end if; else Used_Slots.Insert (Addr, Slot); end if; Remove_Free (Addr, Slot.Size); end if; end Probe_Realloc; -- ------------------------------ -- Insert in the frame tree the new stack frame represented by <tt>Pc</tt>. -- If the frame is already known, the frame reference counter is incremented. -- The frame represented by <tt>Pc</tt> is returned in <tt>Result</tt>. -- ------------------------------ procedure Create_Frame (Pc : in MAT.Frames.Frame_Table; Result : out MAT.Frames.Frame_Type) is begin MAT.Frames.Insert (Frames, Pc, Result); end Create_Frame; -- ------------------------------ -- Collect the information about memory slot sizes allocated by the application. -- ------------------------------ procedure Size_Information (Sizes : in out MAT.Memory.Tools.Size_Info_Map) is begin MAT.Memory.Tools.Size_Information (Used_Slots, Sizes); end Size_Information; -- ------------------------------ -- Collect the information about threads and the memory allocations they've made. -- ------------------------------ procedure Thread_Information (Threads : in out Memory_Info_Map) is begin MAT.Memory.Tools.Thread_Information (Used_Slots, Threads); end Thread_Information; -- ------------------------------ -- Collect the information about frames and the memory allocations they've made. -- ------------------------------ procedure Frame_Information (Level : in Natural; Frames : in out Frame_Info_Map) is begin MAT.Memory.Tools.Frame_Information (Used_Slots, Level, Frames); end Frame_Information; -- ------------------------------ -- Find from the <tt>Memory</tt> map the memory slots whose address intersects -- the region [From .. To] and which is selected by the given filter expression. -- Add the memory slot in the <tt>Into</tt> list if it does not already contains -- the memory slot. -- ------------------------------ procedure Find (From : in MAT.Types.Target_Addr; To : in MAT.Types.Target_Addr; Filter : in MAT.Expressions.Expression_Type; Into : in out MAT.Memory.Allocation_Map) is begin MAT.Memory.Tools.Find (Used_Slots, From, To, Filter, Into); end Find; -- ------------------------------ -- Get the global memory and allocation statistics. -- ------------------------------ procedure Stat_Information (Result : out Memory_Stat) is begin Result := Stats; end Stat_Information; end Memory_Allocator; end MAT.Memory.Targets;
Print the region name in the log message
Print the region name in the log message
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
fb7de944e10f2310a214ee4a463987993c70b17d
src/util-properties.ads
src/util-properties.ads
----------------------------------------------------------------------- -- properties -- Generic name/value property management -- Copyright (C) 2001, 2002, 2003, 2006, 2008, 2009, 2010, 2014, 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; with Ada.Text_IO; with Util.Beans.Objects; with Util.Beans.Basic; with Util.Strings.Vectors; private with Util.Concurrent.Counters; -- = Property Files = -- The `Util.Properties` package and children implements support to read, write and use -- property files either in the Java property file format or the Windows INI configuration file. -- Each property is assigned a key and a value. The list of properties are stored in the -- `Util.Properties.Manager` tagged record and they are indexed by the key name. A property -- is therefore unique in the list. Properties can be grouped together in sub-properties so -- that a key can represent another list of properties. -- -- == File formats == -- The property file consists of a simple name and value pair separated by the `=` sign. -- Thanks to the Windows INI file format, list of properties can be grouped together -- in sections by using the `[section-name`] notation. -- -- test.count=20 -- test.repeat=5 -- [FileTest] -- test.count=5 -- test.repeat=2 -- -- == Using property files == -- An instance of the `Util.Properties.Manager` tagged record must be declared and it provides -- various operations that can be used. When created, the property manager is empty. One way -- to fill it is by using the `Load_Properties` procedure to read the property file. Another -- way is by using the `Set` procedure to insert or change a property by giving its name -- and its value. -- -- In this example, the property file `test.properties` is loaded and assuming that it contains -- the above configuration example, the `Get ("test.count")` will return the string `"20"`. -- -- with Util.Properties; -- ... -- Props : Util.Properties.Manager; -- ... -- Props.Load_Properties (Path => "test.properties"); -- Ada.Text_IO.Put_Line ("Count: " & Props.Get ("test.count"); -- Props.Set ("test.repeat", "23"); -- Props.Save_Properties (Path => "test.properties"); -- -- To be able to access a section from the property manager, it is necessary to retrieve it -- by using the `Get` function and giving the section name. For example, to retrieve the -- `test.count` property of the `FileTest` section, the following code is used: -- -- FileTest : Util.Properties.Manager := Props.Get ("FileTest"); -- ... -- Ada.Text_IO.Put_Line ("[FileTest] Count: " & FileTest.Get ("test.count"); -- -- @include util-properties-json.ads -- @include util-properties-bundles.ads package Util.Properties is NO_PROPERTY : exception; use Ada.Strings.Unbounded; subtype Value is Util.Beans.Objects.Object; function "+" (S : String) return Unbounded_String renames To_Unbounded_String; function "-" (S : Unbounded_String) return String renames To_String; function To_String (V : in Value) return String renames Util.Beans.Objects.To_String; -- The manager holding the name/value pairs and providing the operations -- to get and set the properties. type Manager is new Ada.Finalization.Controlled and Util.Beans.Basic.Bean with private; type Manager_Access is access all Manager'Class; -- Get the value identified by the name. -- If the name cannot be found, the method should return the Null object. overriding function Get_Value (From : in Manager; Name : in String) return Util.Beans.Objects.Object; -- Set the value identified by the name. -- If the map contains the given name, the value changed. -- Otherwise name is added to the map and the value associated with it. overriding procedure Set_Value (From : in out Manager; Name : in String; Value : in Util.Beans.Objects.Object); -- Returns TRUE if the property exists. function Exists (Self : in Manager'Class; Name : in Unbounded_String) return Boolean; -- Returns TRUE if the property exists. function Exists (Self : in Manager'Class; Name : in String) return Boolean; -- Returns the property value. Raises an exception if not found. function Get (Self : in Manager'Class; Name : in String) return String; -- Returns the property value. Raises an exception if not found. function Get (Self : in Manager'Class; Name : in String) return Unbounded_String; -- Returns the property value. Raises an exception if not found. function Get (Self : in Manager'Class; Name : in Unbounded_String) return Unbounded_String; -- Returns the property value. Raises an exception if not found. function Get (Self : in Manager'Class; Name : in Unbounded_String) return String; -- Returns the property value or Default if it does not exist. function Get (Self : in Manager'Class; Name : in String; Default : in String) return String; -- Returns a property manager that is associated with the given name. -- Raises NO_PROPERTY if there is no such property manager or if a property exists -- but is not a property manager. function Get (Self : in Manager'Class; Name : in String) return Manager; -- Create a property manager and associated it with the given name. function Create (Self : in out Manager'Class; Name : in String) return Manager; -- Set the value of the property. The property is created if it -- does not exists. procedure Set (Self : in out Manager'Class; Name : in String; Item : in String); -- Set the value of the property. The property is created if it -- does not exists. procedure Set (Self : in out Manager'Class; Name : in String; Item : in Unbounded_String); -- Set the value of the property. The property is created if it -- does not exists. procedure Set (Self : in out Manager'Class; Name : in Unbounded_String; Item : in Unbounded_String); -- Remove the property given its name. If the property does not -- exist, raises NO_PROPERTY exception. procedure Remove (Self : in out Manager'Class; Name : in String); -- Remove the property given its name. If the property does not -- exist, raises NO_PROPERTY exception. procedure Remove (Self : in out Manager'Class; Name : in Unbounded_String); -- Iterate over the properties and execute the given procedure passing the -- property name and its value. procedure Iterate (Self : in Manager'Class; Process : access procedure (Name : in String; Item : in Value)); -- Collect the name of the properties defined in the manager. -- When a prefix is specified, only the properties starting with the prefix are -- returned. procedure Get_Names (Self : in Manager; Into : in out Util.Strings.Vectors.Vector; Prefix : in String := ""); -- Load the properties from the file input stream. The file must follow -- the definition of Java property files. When a prefix is specified, keep -- only the properties that starts with the prefix. When <b>Strip</b> is True, -- the prefix part is removed from the property name. procedure Load_Properties (Self : in out Manager'Class; File : in Ada.Text_IO.File_Type; Prefix : in String := ""; Strip : in Boolean := False); -- Load the properties from the file. The file must follow the -- definition of Java property files. When a prefix is specified, keep -- only the properties that starts with the prefix. When <b>Strip</b> is True, -- the prefix part is removed from the property name. -- Raises NAME_ERROR if the file does not exist. procedure Load_Properties (Self : in out Manager'Class; Path : in String; Prefix : in String := ""; Strip : in Boolean := False); -- Save the properties in the given file path. procedure Save_Properties (Self : in out Manager'Class; Path : in String; Prefix : in String := ""); -- Copy the properties from FROM which start with a given prefix. -- If the prefix is empty, all properties are copied. When <b>Strip</b> is True, -- the prefix part is removed from the property name. procedure Copy (Self : in out Manager'Class; From : in Manager'Class; Prefix : in String := ""; Strip : in Boolean := False); -- Get the property manager represented by the item value. -- Raise the Conversion_Error exception if the value is not a property manager. function To_Manager (Item : in Value) return Manager; -- Returns True if the item value represents a property manager. function Is_Manager (Item : in Value) return Boolean; private -- Abstract interface for the implementation of Properties -- (this allows to decouples the implementation from the API) package Interface_P is type Manager is abstract limited new Util.Beans.Basic.Bean with record Count : Util.Concurrent.Counters.Counter; Shared : Boolean := False; end record; type Manager_Access is access all Manager'Class; -- Returns TRUE if the property exists. function Exists (Self : in Manager; Name : in String) return Boolean is abstract; -- Remove the property given its name. procedure Remove (Self : in out Manager; Name : in String) is abstract; -- Iterate over the properties and execute the given procedure passing the -- property name and its value. procedure Iterate (Self : in Manager; Process : access procedure (Name : in String; Item : in Value)) is abstract; -- Deep copy of properties stored in 'From' to 'To'. function Create_Copy (Self : in Manager) return Manager_Access is abstract; end Interface_P; -- Create a property implementation if there is none yet. procedure Check_And_Create_Impl (Self : in out Manager); type Manager is new Ada.Finalization.Controlled and Util.Beans.Basic.Bean with record Impl : Interface_P.Manager_Access := null; end record; overriding procedure Adjust (Object : in out Manager); overriding procedure Finalize (Object : in out Manager); end Util.Properties;
----------------------------------------------------------------------- -- util-properties -- Generic name/value property management -- Copyright (C) 2001, 2002, 2003, 2006, 2008, 2009, 2010, 2014, 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; with Ada.Text_IO; with Util.Beans.Objects; with Util.Beans.Basic; with Util.Strings.Vectors; private with Util.Concurrent.Counters; -- = Property Files = -- The `Util.Properties` package and children implements support to read, write and use -- property files either in the Java property file format or the Windows INI configuration file. -- Each property is assigned a key and a value. The list of properties are stored in the -- `Util.Properties.Manager` tagged record and they are indexed by the key name. A property -- is therefore unique in the list. Properties can be grouped together in sub-properties so -- that a key can represent another list of properties. -- -- == File formats == -- The property file consists of a simple name and value pair separated by the `=` sign. -- Thanks to the Windows INI file format, list of properties can be grouped together -- in sections by using the `[section-name`] notation. -- -- test.count=20 -- test.repeat=5 -- [FileTest] -- test.count=5 -- test.repeat=2 -- -- == Using property files == -- An instance of the `Util.Properties.Manager` tagged record must be declared and it provides -- various operations that can be used. When created, the property manager is empty. One way -- to fill it is by using the `Load_Properties` procedure to read the property file. Another -- way is by using the `Set` procedure to insert or change a property by giving its name -- and its value. -- -- In this example, the property file `test.properties` is loaded and assuming that it contains -- the above configuration example, the `Get ("test.count")` will return the string `"20"`. -- -- with Util.Properties; -- ... -- Props : Util.Properties.Manager; -- ... -- Props.Load_Properties (Path => "test.properties"); -- Ada.Text_IO.Put_Line ("Count: " & Props.Get ("test.count"); -- Props.Set ("test.repeat", "23"); -- Props.Save_Properties (Path => "test.properties"); -- -- To be able to access a section from the property manager, it is necessary to retrieve it -- by using the `Get` function and giving the section name. For example, to retrieve the -- `test.count` property of the `FileTest` section, the following code is used: -- -- FileTest : Util.Properties.Manager := Props.Get ("FileTest"); -- ... -- Ada.Text_IO.Put_Line ("[FileTest] Count: " & FileTest.Get ("test.count"); -- -- @include util-properties-json.ads -- @include util-properties-bundles.ads package Util.Properties is NO_PROPERTY : exception; use Ada.Strings.Unbounded; subtype Value is Util.Beans.Objects.Object; function "+" (S : String) return Unbounded_String renames To_Unbounded_String; function "-" (S : Unbounded_String) return String renames To_String; function To_String (V : in Value) return String renames Util.Beans.Objects.To_String; -- The manager holding the name/value pairs and providing the operations -- to get and set the properties. type Manager is new Ada.Finalization.Controlled and Util.Beans.Basic.Bean with private; type Manager_Access is access all Manager'Class; -- Get the value identified by the name. -- If the name cannot be found, the method should return the Null object. overriding function Get_Value (From : in Manager; Name : in String) return Util.Beans.Objects.Object; -- Set the value identified by the name. -- If the map contains the given name, the value changed. -- Otherwise name is added to the map and the value associated with it. overriding procedure Set_Value (From : in out Manager; Name : in String; Value : in Util.Beans.Objects.Object); -- Returns TRUE if the property exists. function Exists (Self : in Manager'Class; Name : in Unbounded_String) return Boolean; -- Returns TRUE if the property exists. function Exists (Self : in Manager'Class; Name : in String) return Boolean; -- Returns the property value. Raises an exception if not found. function Get (Self : in Manager'Class; Name : in String) return String; -- Returns the property value. Raises an exception if not found. function Get (Self : in Manager'Class; Name : in String) return Unbounded_String; -- Returns the property value. Raises an exception if not found. function Get (Self : in Manager'Class; Name : in Unbounded_String) return Unbounded_String; -- Returns the property value. Raises an exception if not found. function Get (Self : in Manager'Class; Name : in Unbounded_String) return String; -- Returns the property value or Default if it does not exist. function Get (Self : in Manager'Class; Name : in String; Default : in String) return String; -- Returns a property manager that is associated with the given name. -- Raises NO_PROPERTY if there is no such property manager or if a property exists -- but is not a property manager. function Get (Self : in Manager'Class; Name : in String) return Manager; -- Create a property manager and associated it with the given name. function Create (Self : in out Manager'Class; Name : in String) return Manager; -- Set the value of the property. The property is created if it -- does not exists. procedure Set (Self : in out Manager'Class; Name : in String; Item : in String); -- Set the value of the property. The property is created if it -- does not exists. procedure Set (Self : in out Manager'Class; Name : in String; Item : in Unbounded_String); -- Set the value of the property. The property is created if it -- does not exists. procedure Set (Self : in out Manager'Class; Name : in Unbounded_String; Item : in Unbounded_String); -- Remove the property given its name. If the property does not -- exist, raises NO_PROPERTY exception. procedure Remove (Self : in out Manager'Class; Name : in String); -- Remove the property given its name. If the property does not -- exist, raises NO_PROPERTY exception. procedure Remove (Self : in out Manager'Class; Name : in Unbounded_String); -- Iterate over the properties and execute the given procedure passing the -- property name and its value. procedure Iterate (Self : in Manager'Class; Process : access procedure (Name : in String; Item : in Value)); -- Collect the name of the properties defined in the manager. -- When a prefix is specified, only the properties starting with the prefix are -- returned. procedure Get_Names (Self : in Manager; Into : in out Util.Strings.Vectors.Vector; Prefix : in String := ""); -- Load the properties from the file input stream. The file must follow -- the definition of Java property files. When a prefix is specified, keep -- only the properties that starts with the prefix. When <b>Strip</b> is True, -- the prefix part is removed from the property name. procedure Load_Properties (Self : in out Manager'Class; File : in Ada.Text_IO.File_Type; Prefix : in String := ""; Strip : in Boolean := False); -- Load the properties from the file. The file must follow the -- definition of Java property files. When a prefix is specified, keep -- only the properties that starts with the prefix. When <b>Strip</b> is True, -- the prefix part is removed from the property name. -- Raises NAME_ERROR if the file does not exist. procedure Load_Properties (Self : in out Manager'Class; Path : in String; Prefix : in String := ""; Strip : in Boolean := False); -- Save the properties in the given file path. procedure Save_Properties (Self : in out Manager'Class; Path : in String; Prefix : in String := ""); -- Copy the properties from FROM which start with a given prefix. -- If the prefix is empty, all properties are copied. When <b>Strip</b> is True, -- the prefix part is removed from the property name. procedure Copy (Self : in out Manager'Class; From : in Manager'Class; Prefix : in String := ""; Strip : in Boolean := False); -- Get the property manager represented by the item value. -- Raise the Conversion_Error exception if the value is not a property manager. function To_Manager (Item : in Value) return Manager; -- Returns True if the item value represents a property manager. function Is_Manager (Item : in Value) return Boolean; private -- Abstract interface for the implementation of Properties -- (this allows to decouples the implementation from the API) package Interface_P is type Manager is abstract limited new Util.Beans.Basic.Bean with record Count : Util.Concurrent.Counters.Counter; Shared : Boolean := False; end record; type Manager_Access is access all Manager'Class; -- Returns TRUE if the property exists. function Exists (Self : in Manager; Name : in String) return Boolean is abstract; -- Remove the property given its name. procedure Remove (Self : in out Manager; Name : in String) is abstract; -- Iterate over the properties and execute the given procedure passing the -- property name and its value. procedure Iterate (Self : in Manager; Process : access procedure (Name : in String; Item : in Value)) is abstract; -- Deep copy of properties stored in 'From' to 'To'. function Create_Copy (Self : in Manager) return Manager_Access is abstract; end Interface_P; -- Create a property implementation if there is none yet. procedure Check_And_Create_Impl (Self : in out Manager); type Manager is new Ada.Finalization.Controlled and Util.Beans.Basic.Bean with record Impl : Interface_P.Manager_Access := null; end record; overriding procedure Adjust (Object : in out Manager); overriding procedure Finalize (Object : in out Manager); end Util.Properties;
Fix header style
Fix header style
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
85cef578447ab30016982da9a2a79dfb209b5b06
src/wiki-attributes.ads
src/wiki-attributes.ads
----------------------------------------------------------------------- -- wiki-attributes -- Wiki document attributes -- 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; private with Ada.Containers.Vectors; private with Ada.Finalization; -- == Attributes == -- The <tt>Attributes</tt> package defines a simple management of attributes for -- the wiki document parser. Attribute lists are described by the <tt>Attribute_List_Type</tt> -- with some operations to append or query for an attribute. package Wiki.Attributes is pragma Preelaborate; use Ada.Strings.Wide_Wide_Unbounded; type Cursor is private; -- Get the attribute name. function Get_Name (Position : in Cursor) return String; -- Get the attribute value. function Get_Value (Position : in Cursor) return String; -- Get the attribute wide value. function Get_Wide_Value (Position : in Cursor) return Wide_Wide_String; -- Get the attribute wide value. function Get_Unbounded_Wide_Value (Position : in Cursor) return Unbounded_Wide_Wide_String; -- Returns True if the cursor has a valid attribute. function Has_Element (Position : in Cursor) return Boolean; -- Move the cursor to the next attribute. procedure Next (Position : in out Cursor); -- A list of attributes. type Attribute_List_Type is private; -- Find the attribute with the given name. function Find (List : in Attribute_List_Type; Name : in String) return Cursor; -- Find the attribute with the given name and return its value. function Get_Attribute (List : in Attribute_List_Type; Name : in String) return Unbounded_Wide_Wide_String; -- Append the attribute to the attribute list. procedure Append (List : in out Attribute_List_Type; Name : in Wide_Wide_String; Value : in Wide_Wide_String); -- Append the attribute to the attribute list. procedure Append (List : in out Attribute_List_Type; Name : in Ada.Strings.Wide_Wide_Unbounded.Unbounded_Wide_Wide_String; Value : in Ada.Strings.Wide_Wide_Unbounded.Unbounded_Wide_Wide_String); -- Get the cursor to get access to the first attribute. function First (List : in Attribute_List_Type) return Cursor; -- Get the number of attributes in the list. function Length (List : in Attribute_List_Type) return Natural; -- Clear the list and remove all existing attributes. procedure Clear (List : in out Attribute_List_Type); -- Iterate over the list attributes and call the <tt>Process</tt> procedure. procedure Iterate (List : in Attribute_List_Type; Process : not null access procedure (Name : in String; Value : in Wide_Wide_String)); private type Attribute (Name_Length, Value_Length : Natural) is limited record Name : String (1 .. Name_Length); Value : Wide_Wide_String (1 .. Value_Length); end record; type Attribute_Access is access all Attribute; package Attribute_Vectors is new Ada.Containers.Vectors (Index_Type => Positive, Element_Type => Attribute_Access); subtype Attribute_Vector is Attribute_Vectors.Vector; type Cursor is record Pos : Attribute_Vectors.Cursor; end record; type Attribute_List_Type is new Ada.Finalization.Controlled with record List : Attribute_Vector; end record; -- Finalize the attribute list releasing any storage. overriding procedure Finalize (List : in out Attribute_List_Type); end Wiki.Attributes;
----------------------------------------------------------------------- -- wiki-attributes -- Wiki document attributes -- 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; private with Ada.Containers.Vectors; private with Ada.Finalization; -- == Attributes == -- The <tt>Attributes</tt> package defines a simple management of attributes for -- the wiki document parser. Attribute lists are described by the <tt>Attribute_List_Type</tt> -- with some operations to append or query for an attribute. package Wiki.Attributes is pragma Preelaborate; use Ada.Strings.Wide_Wide_Unbounded; type Cursor is private; -- Get the attribute name. function Get_Name (Position : in Cursor) return String; -- Get the attribute value. function Get_Value (Position : in Cursor) return String; -- Get the attribute wide value. function Get_Wide_Value (Position : in Cursor) return Wide_Wide_String; -- Get the attribute wide value. function Get_Unbounded_Wide_Value (Position : in Cursor) return Unbounded_Wide_Wide_String; -- Returns True if the cursor has a valid attribute. function Has_Element (Position : in Cursor) return Boolean; -- Move the cursor to the next attribute. procedure Next (Position : in out Cursor); -- A list of attributes. type Attribute_List_Type is private; -- Find the attribute with the given name. function Find (List : in Attribute_List_Type; Name : in String) return Cursor; -- Find the attribute with the given name and return its value. function Get_Attribute (List : in Attribute_List_Type; Name : in String) return Unbounded_Wide_Wide_String; -- Append the attribute to the attribute list. procedure Append (List : in out Attribute_List_Type; Name : in Wide_Wide_String; Value : in Wide_Wide_String); -- Append the attribute to the attribute list. procedure Append (List : in out Attribute_List_Type; Name : in Ada.Strings.Wide_Wide_Unbounded.Unbounded_Wide_Wide_String; Value : in Ada.Strings.Wide_Wide_Unbounded.Unbounded_Wide_Wide_String); -- Append the attribute to the attribute list. procedure Append (List : in out Attribute_List_Type; Name : in String; Value : in Ada.Strings.Wide_Wide_Unbounded.Unbounded_Wide_Wide_String); -- Get the cursor to get access to the first attribute. function First (List : in Attribute_List_Type) return Cursor; -- Get the number of attributes in the list. function Length (List : in Attribute_List_Type) return Natural; -- Clear the list and remove all existing attributes. procedure Clear (List : in out Attribute_List_Type); -- Iterate over the list attributes and call the <tt>Process</tt> procedure. procedure Iterate (List : in Attribute_List_Type; Process : not null access procedure (Name : in String; Value : in Wide_Wide_String)); private type Attribute (Name_Length, Value_Length : Natural) is limited record Name : String (1 .. Name_Length); Value : Wide_Wide_String (1 .. Value_Length); end record; type Attribute_Access is access all Attribute; package Attribute_Vectors is new Ada.Containers.Vectors (Index_Type => Positive, Element_Type => Attribute_Access); subtype Attribute_Vector is Attribute_Vectors.Vector; type Cursor is record Pos : Attribute_Vectors.Cursor; end record; type Attribute_List_Type is new Ada.Finalization.Controlled with record List : Attribute_Vector; end record; -- Finalize the attribute list releasing any storage. overriding procedure Finalize (List : in out Attribute_List_Type); end Wiki.Attributes;
Declare new Append procedure with a String type as the attribute name
Declare new Append procedure with a String type as the attribute name
Ada
apache-2.0
stcarrez/ada-wiki,stcarrez/ada-wiki
dd1ec23689a3d32f689db2ab507cffe87a181f55
awa/src/awa-users-filters.adb
awa/src/awa-users-filters.adb
----------------------------------------------------------------------- -- awa-users-filters -- Specific filters for authentication and key verification -- Copyright (C) 2011, 2012, 2013, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Log.Loggers; with ASF.Cookies; with AWA.Users.Services; with AWA.Users.Modules; package body AWA.Users.Filters is -- The logger Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("AWA.Users.Filters"); -- ------------------------------ -- Set the user principal on the session associated with the ASF request. -- ------------------------------ procedure Set_Session_Principal (Request : in out ASF.Requests.Request'Class; Principal : in Principals.Principal_Access) is Session : ASF.Sessions.Session := Request.Get_Session (Create => True); begin Session.Set_Principal (Principal.all'Access); end Set_Session_Principal; -- ------------------------------ -- Initialize the filter and configure the redirection URIs. -- ------------------------------ procedure Initialize (Filter : in out Auth_Filter; Config : in ASF.Servlets.Filter_Config) is URI : constant String := ASF.Servlets.Get_Init_Parameter (Config, AUTH_FILTER_REDIRECT_PARAM); begin Log.Info ("Using login URI: {0}", URI); if URI = "" then Log.Error ("The login URI is empty. Redirection to the login page will not work."); end if; Filter.Login_URI := To_Unbounded_String (URI); ASF.Security.Filters.Auth_Filter (Filter).Initialize (Config); end Initialize; procedure Authenticate (F : in Auth_Filter; Request : in out ASF.Requests.Request'Class; Response : in out ASF.Responses.Response'Class; Session : in ASF.Sessions.Session; Auth_Id : in String; Principal : out ASF.Principals.Principal_Access) is pragma Unreferenced (F, Session); use AWA.Users.Modules; use AWA.Users.Services; Manager : constant User_Service_Access := AWA.Users.Modules.Get_User_Manager; P : AWA.Users.Principals.Principal_Access; begin Manager.Authenticate (Cookie => Auth_Id, Ip_Addr => "", Principal => P); Principal := P.all'Access; -- Setup a new AID cookie with the new connection session. declare Cookie : constant String := Manager.Get_Authenticate_Cookie (P.Get_Session_Identifier); C : ASF.Cookies.Cookie := ASF.Cookies.Create (ASF.Security.Filters.AID_COOKIE, Cookie); begin ASF.Cookies.Set_Path (C, Request.Get_Context_Path); ASF.Cookies.Set_Max_Age (C, 15 * 86400); Response.Add_Cookie (Cookie => C); end; exception when Not_Found => Principal := null; end Authenticate; -- ------------------------------ -- Display or redirects the user to the login page. This procedure is called when -- the user is not authenticated. -- ------------------------------ overriding procedure Do_Login (Filter : in Auth_Filter; Request : in out ASF.Requests.Request'Class; Response : in out ASF.Responses.Response'Class) is Login_URI : constant String := To_String (Filter.Login_URI); Context : constant String := Request.Get_Context_Path; Servlet : constant String := Request.Get_Servlet_Path; URL : constant String := Context & Servlet & Request.Get_Path_Info; C : ASF.Cookies.Cookie := ASF.Cookies.Create (REDIRECT_COOKIE, URL); begin Log.Info ("User is not logged, redirecting to {0}", Login_URI); ASF.Cookies.Set_Path (C, Request.Get_Context_Path); ASF.Cookies.Set_Max_Age (C, 86400); Response.Add_Cookie (Cookie => C); if Request.Get_Header ("X-Requested-With") = "" then Response.Send_Redirect (Location => Login_URI); else Response.Send_Error (ASF.Responses.SC_UNAUTHORIZED); end if; end Do_Login; -- ------------------------------ -- Initialize the filter and configure the redirection URIs. -- ------------------------------ overriding procedure Initialize (Filter : in out Verify_Filter; Config : in ASF.Servlets.Filter_Config) is URI : constant String := ASF.Servlets.Get_Init_Parameter (Config, VERIFY_FILTER_REDIRECT_PARAM); begin Filter.Invalid_Key_URI := To_Unbounded_String (URI); end Initialize; -- ------------------------------ -- Filter a request which contains an access key and verify that the -- key is valid and identifies a user. Once the user is known, create -- a session and setup the user principal. -- -- If the access key is missing or invalid, redirect to the -- <b>Invalid_Key_URI</b> associated with the filter. -- ------------------------------ overriding procedure Do_Filter (Filter : in Verify_Filter; Request : in out ASF.Requests.Request'Class; Response : in out ASF.Responses.Response'Class; Chain : in out ASF.Servlets.Filter_Chain) is Key : constant String := Request.Get_Parameter (PARAM_ACCESS_KEY); Manager : constant Users.Services.User_Service_Access := Users.Modules.Get_User_Manager; Principal : AWA.Users.Principals.Principal_Access; begin Log.Info ("Verify access key {0}", Key); Manager.Verify_User (Key => Key, IpAddr => "", Principal => Principal); Set_Session_Principal (Request, Principal); -- Request is authorized, proceed to the next filter. ASF.Servlets.Do_Filter (Chain => Chain, Request => Request, Response => Response); exception when AWA.Users.Services.Not_Found => declare URI : constant String := To_String (Filter.Invalid_Key_URI); begin Log.Info ("Invalid access key {0}, redirecting to {1}", Key, URI); Response.Send_Redirect (Location => URI); end; end Do_Filter; end AWA.Users.Filters;
----------------------------------------------------------------------- -- awa-users-filters -- Specific filters for authentication and key verification -- Copyright (C) 2011, 2012, 2013, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Log.Loggers; with ASF.Cookies; with AWA.Users.Services; with AWA.Users.Modules; package body AWA.Users.Filters is -- The logger Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("AWA.Users.Filters"); -- ------------------------------ -- Set the user principal on the session associated with the ASF request. -- ------------------------------ procedure Set_Session_Principal (Request : in out ASF.Requests.Request'Class; Principal : in Principals.Principal_Access) is Session : ASF.Sessions.Session := Request.Get_Session (Create => True); begin Session.Set_Principal (Principal.all'Access); end Set_Session_Principal; -- ------------------------------ -- Initialize the filter and configure the redirection URIs. -- ------------------------------ procedure Initialize (Filter : in out Auth_Filter; Config : in ASF.Servlets.Filter_Config) is URI : constant String := ASF.Servlets.Get_Init_Parameter (Config, AUTH_FILTER_REDIRECT_PARAM); begin Log.Info ("Using login URI: {0}", URI); if URI = "" then Log.Error ("The login URI is empty. Redirection to the login page will not work."); end if; Filter.Login_URI := To_Unbounded_String (URI); ASF.Security.Filters.Auth_Filter (Filter).Initialize (Config); end Initialize; procedure Authenticate (F : in Auth_Filter; Request : in out ASF.Requests.Request'Class; Response : in out ASF.Responses.Response'Class; Session : in ASF.Sessions.Session; Auth_Id : in String; Principal : out ASF.Principals.Principal_Access) is pragma Unreferenced (F, Session); use AWA.Users.Modules; use AWA.Users.Services; Manager : constant User_Service_Access := AWA.Users.Modules.Get_User_Manager; P : AWA.Users.Principals.Principal_Access; begin Manager.Authenticate (Cookie => Auth_Id, Ip_Addr => "", Principal => P); Principal := P.all'Access; -- Setup a new AID cookie with the new connection session. declare Cookie : constant String := Manager.Get_Authenticate_Cookie (P.Get_Session_Identifier); C : ASF.Cookies.Cookie := ASF.Cookies.Create (ASF.Security.Filters.AID_COOKIE, Cookie); begin ASF.Cookies.Set_Path (C, Request.Get_Context_Path); ASF.Cookies.Set_Max_Age (C, 15 * 86400); Response.Add_Cookie (Cookie => C); end; exception when Not_Found => Principal := null; end Authenticate; -- ------------------------------ -- Display or redirects the user to the login page. This procedure is called when -- the user is not authenticated. -- ------------------------------ overriding procedure Do_Login (Filter : in Auth_Filter; Request : in out ASF.Requests.Request'Class; Response : in out ASF.Responses.Response'Class) is Login_URI : constant String := To_String (Filter.Login_URI); Context : constant String := Request.Get_Context_Path; Servlet : constant String := Request.Get_Servlet_Path; URL : constant String := Context & Servlet & Request.Get_Path_Info; C : ASF.Cookies.Cookie := ASF.Cookies.Create (REDIRECT_COOKIE, URL); begin Log.Info ("User is not logged, redirecting to {0}", Login_URI); ASF.Cookies.Set_Path (C, Request.Get_Context_Path); ASF.Cookies.Set_Max_Age (C, 86400); Response.Add_Cookie (Cookie => C); if Request.Get_Header ("X-Requested-With") = "" then Response.Send_Redirect (Location => Login_URI); else Response.Send_Error (ASF.Responses.SC_UNAUTHORIZED); end if; end Do_Login; -- ------------------------------ -- Initialize the filter and configure the redirection URIs. -- ------------------------------ overriding procedure Initialize (Filter : in out Verify_Filter; Config : in ASF.Servlets.Filter_Config) is URI : constant String := ASF.Servlets.Get_Init_Parameter (Config, VERIFY_FILTER_REDIRECT_PARAM); begin Filter.Invalid_Key_URI := To_Unbounded_String (URI); end Initialize; -- ------------------------------ -- Filter a request which contains an access key and verify that the -- key is valid and identifies a user. Once the user is known, create -- a session and setup the user principal. -- -- If the access key is missing or invalid, redirect to the -- <b>Invalid_Key_URI</b> associated with the filter. -- ------------------------------ overriding procedure Do_Filter (Filter : in Verify_Filter; Request : in out ASF.Requests.Request'Class; Response : in out ASF.Responses.Response'Class; Chain : in out ASF.Servlets.Filter_Chain) is Key : constant String := Request.Get_Parameter (PARAM_ACCESS_KEY); Manager : constant Users.Services.User_Service_Access := Users.Modules.Get_User_Manager; Principal : AWA.Users.Principals.Principal_Access; begin Log.Info ("Verify access key {0}", Key); Manager.Verify_User (Key => Key, IpAddr => "", Principal => Principal); Set_Session_Principal (Request, Principal); -- Request is authorized, proceed to the next filter. ASF.Servlets.Do_Filter (Chain => Chain, Request => Request, Response => Response); exception when AWA.Users.Services.Not_Found => declare URI : constant String := To_String (Filter.Invalid_Key_URI); begin Log.Info ("Invalid access key {0}, redirecting to {1}", Key, URI); Response.Send_Redirect (Location => URI); end; end Do_Filter; end AWA.Users.Filters;
Fix compilation warnings
Fix compilation warnings
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
375cf49e8cb99bd2206ac945b93afe36d6fcf8e3
src/gen-model-enums.adb
src/gen-model-enums.adb
----------------------------------------------------------------------- -- gen-model-enums -- Enum definitions -- 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. ----------------------------------------------------------------------- package body Gen.Model.Enums 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 : Value_Definition; Name : String) return Util.Beans.Objects.Object is begin if Name = "value" then return Util.Beans.Objects.To_Object (From.Number); 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 : Enum_Definition; Name : String) return Util.Beans.Objects.Object is begin if Name = "values" then return From.Values_Bean; elsif Name = "name" then return Util.Beans.Objects.To_Object (From.Type_Name); elsif Name = "isEnum" then return Util.Beans.Objects.To_Object (True); elsif Name = "sqlType" then return Util.Beans.Objects.To_Object (From.Sql_Type); else return Mappings.Mapping_Definition (From).Get_Value (Name); end if; end Get_Value; -- ------------------------------ -- Compare two enum literals. -- ------------------------------ function "<" (Left, Right : in Value_Definition_Access) return Boolean is begin return Left.Number < Right.Number; end "<"; -- ------------------------------ -- Prepare the generation of the model. -- ------------------------------ overriding procedure Prepare (O : in out Enum_Definition) is begin O.Target := O.Type_Name; O.Values.Sort; end Prepare; -- ------------------------------ -- Initialize the table definition instance. -- ------------------------------ overriding procedure Initialize (O : in out Enum_Definition) is begin O.Values_Bean := Util.Beans.Objects.To_Object (O.Values'Unchecked_Access, Util.Beans.Objects.STATIC); end Initialize; -- ------------------------------ -- Add an enum value to this enum definition and return the new value. -- ------------------------------ procedure Add_Value (Enum : in out Enum_Definition; Name : in String; Value : out Value_Definition_Access) is begin Value := new Value_Definition; Value.Name := To_Unbounded_String (Name); Value.Number := Enum.Values.Get_Count; Enum.Values.Append (Value); end Add_Value; -- ------------------------------ -- Create an enum with the given name. -- ------------------------------ function Create_Enum (Name : in Unbounded_String) return Enum_Definition_Access is Enum : constant Enum_Definition_Access := new Enum_Definition; begin Enum.Name := Name; declare Pos : constant Natural := Index (Enum.Name, ".", Ada.Strings.Backward); begin if Pos > 0 then Enum.Pkg_Name := Unbounded_Slice (Enum.Name, 1, Pos - 1); Enum.Type_Name := Unbounded_Slice (Enum.Name, Pos + 1, Length (Enum.Name)); else Enum.Pkg_Name := To_Unbounded_String ("ADO"); Enum.Type_Name := Enum.Name; end if; end; return Enum; end Create_Enum; end Gen.Model.Enums;
----------------------------------------------------------------------- -- gen-model-enums -- Enum definitions -- 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. ----------------------------------------------------------------------- package body Gen.Model.Enums 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 : Value_Definition; Name : String) return Util.Beans.Objects.Object is begin if Name = "value" then return Util.Beans.Objects.To_Object (From.Number); 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 : Enum_Definition; Name : String) return Util.Beans.Objects.Object is begin if Name = "values" then return From.Values_Bean; elsif Name = "name" then return Util.Beans.Objects.To_Object (From.Type_Name); elsif Name = "isEnum" then return Util.Beans.Objects.To_Object (True); elsif Name = "sqlType" then return Util.Beans.Objects.To_Object (From.Sql_Type); else return Mappings.Mapping_Definition (From).Get_Value (Name); end if; end Get_Value; -- ------------------------------ -- Compare two enum literals. -- ------------------------------ function "<" (Left, Right : in Value_Definition_Access) return Boolean is begin return Left.Number < Right.Number; end "<"; -- ------------------------------ -- Prepare the generation of the model. -- ------------------------------ overriding procedure Prepare (O : in out Enum_Definition) is procedure Sort is new Value_List.Sort_On ("<"); begin O.Target := O.Type_Name; Sort (O.Values); end Prepare; -- ------------------------------ -- Initialize the table definition instance. -- ------------------------------ overriding procedure Initialize (O : in out Enum_Definition) is begin O.Values_Bean := Util.Beans.Objects.To_Object (O.Values'Unchecked_Access, Util.Beans.Objects.STATIC); end Initialize; -- ------------------------------ -- Add an enum value to this enum definition and return the new value. -- ------------------------------ procedure Add_Value (Enum : in out Enum_Definition; Name : in String; Value : out Value_Definition_Access) is begin Value := new Value_Definition; Value.Name := To_Unbounded_String (Name); Value.Number := Enum.Values.Get_Count; Enum.Values.Append (Value); end Add_Value; -- ------------------------------ -- Create an enum with the given name. -- ------------------------------ function Create_Enum (Name : in Unbounded_String) return Enum_Definition_Access is Enum : constant Enum_Definition_Access := new Enum_Definition; begin Enum.Name := Name; declare Pos : constant Natural := Index (Enum.Name, ".", Ada.Strings.Backward); begin if Pos > 0 then Enum.Pkg_Name := Unbounded_Slice (Enum.Name, 1, Pos - 1); Enum.Type_Name := Unbounded_Slice (Enum.Name, Pos + 1, Length (Enum.Name)); else Enum.Pkg_Name := To_Unbounded_String ("ADO"); Enum.Type_Name := Enum.Name; end if; end; return Enum; end Create_Enum; end Gen.Model.Enums;
Fix sorting of enum values
Fix sorting of enum values
Ada
apache-2.0
Letractively/ada-gen,Letractively/ada-gen,Letractively/ada-gen,Letractively/ada-gen
8978005367d86d0752b7d831dcd6721a3a6a78a9
samples/volume_servlet.adb
samples/volume_servlet.adb
----------------------------------------------------------------------- -- volume_servlet -- Servlet example to compute some volumes -- Copyright (C) 2010 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Numerics; with ASF.Streams; package body Volume_Servlet is -- ------------------------------ -- Write the volume form page with an optional response message. -- ------------------------------ procedure Write (Response : in out Responses.Response'Class; Message : in String; Height : in String; Radius : in String) is Output : ASF.Streams.Print_Stream := Response.Get_Output_Stream; begin Output.Write ("<html><head><title>Volume servlet example</title></head>" & "<style></style>" & "<body>" & "<h1>Compute the volume of a cylinder</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'>" & "<table>" & "<tr><td>Height</td>" & "<td><input type='text' size='10' name='height'"); if Height /= "" then Output.Write (" value='" & Height & "'"); end if; Output.Write ("></input></td></tr>" & "<tr><td>Radius</td>" & "<td><input type='text' size='10' name='radius'"); if Radius /= "" then Output.Write (" value='" & Radius & "'"); end if; Output.Write ("></input></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; -- ------------------------------ -- Called by the servlet container when a POST request is received. -- Computes the cylinder volume and display the result page. -- ------------------------------ procedure Do_Post (Server : in Servlet; Request : in out Requests.Request'Class; Response : in out Responses.Response'Class) is pragma Unreferenced (Server); Height : constant String := Request.Get_Parameter ("height"); Radius : constant String := Request.Get_Parameter ("radius"); begin declare H : constant Float := Float'Value (Height); R : constant Float := Float'Value (Radius); V : constant Float := Ada.Numerics.Pi * R * R * H; begin Write (Response, "The cylinder volume is: " & Float'Image (V), Height, Radius); end; exception when others => Write (Response, "Invalid height or radius. Please, enter a number", Height, Radius); end Do_Post; end Volume_Servlet;
----------------------------------------------------------------------- -- volume_servlet -- Servlet example to compute some volumes -- 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 Ada.Numerics; with ASF.Streams; package body Volume_Servlet is procedure Write (Response : in out Responses.Response'Class; Message : in String; Height : in String; Radius : in String); -- ------------------------------ -- Write the volume form page with an optional response message. -- ------------------------------ procedure Write (Response : in out Responses.Response'Class; Message : in String; Height : in String; Radius : in String) is Output : ASF.Streams.Print_Stream := Response.Get_Output_Stream; begin Output.Write ("<html><head><title>Volume servlet example</title></head>" & "<style></style>" & "<body>" & "<h1>Compute the volume of a cylinder</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'>" & "<table>" & "<tr><td>Height</td>" & "<td><input type='text' size='10' name='height'"); if Height /= "" then Output.Write (" value='" & Height & "'"); end if; Output.Write ("></input></td></tr>" & "<tr><td>Radius</td>" & "<td><input type='text' size='10' name='radius'"); if Radius /= "" then Output.Write (" value='" & Radius & "'"); end if; Output.Write ("></input></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; -- ------------------------------ -- Called by the servlet container when a POST request is received. -- Computes the cylinder volume and display the result page. -- ------------------------------ procedure Do_Post (Server : in Servlet; Request : in out Requests.Request'Class; Response : in out Responses.Response'Class) is pragma Unreferenced (Server); Height : constant String := Request.Get_Parameter ("height"); Radius : constant String := Request.Get_Parameter ("radius"); begin declare H : constant Float := Float'Value (Height); R : constant Float := Float'Value (Radius); V : constant Float := Ada.Numerics.Pi * R * R * H; begin Write (Response, "The cylinder volume is: " & Float'Image (V), Height, Radius); end; exception when others => Write (Response, "Invalid height or radius. Please, enter a number", Height, Radius); end Do_Post; end Volume_Servlet;
Fix compilation warnings
Fix compilation warnings
Ada
apache-2.0
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
43f3297b7df31989e65f1cb9c77219d1a41f23ee
awa/plugins/awa-comments/src/awa-comments-beans.adb
awa/plugins/awa-comments/src/awa-comments-beans.adb
----------------------------------------------------------------------- -- awa-comments-beans -- Beans for the comments module -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with ADO.Sessions.Entities; with ADO.Queries; with ADO.Utils; with AWA.Helpers.Requests; package body AWA.Comments.Beans is use Ada.Strings.Unbounded; -- ------------------------------ -- Get the value identified by the name. -- ------------------------------ overriding function Get_Value (From : in Comment_Bean; Name : in String) return Util.Beans.Objects.Object is begin if From.Is_Null then return Util.Beans.Objects.Null_Object; else return AWA.Comments.Models.Comment_Bean (From).Get_Value (Name); end if; end Get_Value; -- ------------------------------ -- Set the value identified by the name. -- ------------------------------ overriding procedure Set_Value (From : in out Comment_Bean; Name : in String; Value : in Util.Beans.Objects.Object) is begin if Name = "message" then From.Set_Message (Util.Beans.Objects.To_String (Value)); elsif Name = "entity_type" then From.Entity_Type := Util.Beans.Objects.To_Unbounded_String (Value); elsif Name = "entity_id" then declare use type ADO.Identifier; Id : constant ADO.Identifier := ADO.Utils.To_Identifier (Value); begin if Id /= ADO.NO_IDENTIFIER then From.Set_Entity_Id (ADO.Utils.To_Identifier (Value)); end if; end; elsif Name = "permission" then From.Permission := Util.Beans.Objects.To_Unbounded_String (Value); elsif Name = "status" then From.Set_Status (AWA.Comments.Models.Status_Type_Objects.To_Value (Value)); elsif Name = "id" and not Util.Beans.Objects.Is_Empty (Value) then declare Id : constant ADO.Identifier := ADO.Utils.To_Identifier (Value); begin From.Module.Load_Comment (From, Id); end; end if; end Set_Value; -- ------------------------------ -- Create the comment. -- ------------------------------ overriding procedure Create (Bean : in out Comment_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is pragma Unreferenced (Outcome); begin Bean.Module.Create_Comment (Permission => To_String (Bean.Permission), Entity_Type => To_String (Bean.Entity_Type), Comment => Bean); end Create; -- ------------------------------ -- Save the comment. -- ------------------------------ overriding procedure Save (Bean : in out Comment_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is pragma Unreferenced (Outcome); begin Bean.Module.Update_Comment (Permission => To_String (Bean.Permission), Comment => Bean); end Save; -- ------------------------------ -- Publish or not the comment. -- ------------------------------ overriding procedure Publish (Bean : in out Comment_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is pragma Unreferenced (Outcome); Id : constant ADO.Identifier := Helpers.Requests.Get_Parameter ("id"); Value : constant Util.Beans.Objects.Object := Helpers.Requests.Get_Parameter ("status"); begin Bean.Module.Publish_Comment (Permission => To_String (Bean.Permission), Id => Id, Status => Models.Status_Type_Objects.To_Value (Value), Comment => Bean); end Publish; -- ------------------------------ -- Delete the comment. -- ------------------------------ overriding procedure Delete (Bean : in out Comment_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is pragma Unreferenced (Outcome); begin Bean.Module.Delete_Comment (Ada.Strings.Unbounded.To_String (Bean.Permission), Bean); end Delete; -- ------------------------------ -- Create a new comment bean instance. -- ------------------------------ function Create_Comment_Bean (Module : in AWA.Comments.Modules.Comment_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is Result : constant Comment_Bean_Access := new Comment_Bean; begin Result.Module := Module; return Result.all'Access; end Create_Comment_Bean; -- ------------------------------ -- Set the value identified by the name. -- If the name cannot be found, the method should raise the No_Value -- exception. -- ------------------------------ overriding procedure Set_Value (From : in out Comment_List_Bean; Name : in String; Value : in Util.Beans.Objects.Object) is begin if Name = "entity_type" then From.Entity_Type := Util.Beans.Objects.To_Unbounded_String (Value); elsif Name = "permission" then From.Permission := Util.Beans.Objects.To_Unbounded_String (Value); elsif Name = "entity_id" then From.Load_Comments (ADO.Utils.To_Identifier (Value)); end if; end Set_Value; -- ------------------------------ -- Set the entity type (database table) with which the comments are associated. -- ------------------------------ procedure Set_Entity_Type (Into : in out Comment_List_Bean; Table : in ADO.Schemas.Class_Mapping_Access) is begin Into.Entity_Type := Ada.Strings.Unbounded.To_Unbounded_String (Table.Table.all); end Set_Entity_Type; -- ------------------------------ -- Set the permission to check before removing or adding a comment on the entity. -- ------------------------------ procedure Set_Permission (Into : in out Comment_List_Bean; Permission : in String) is begin Into.Permission := Ada.Strings.Unbounded.To_Unbounded_String (Permission); end Set_Permission; -- ------------------------------ -- Load the comments associated with the given database identifier. -- ------------------------------ procedure Load_Comments (Into : in out Comment_List_Bean; For_Entity_Id : in ADO.Identifier) is Session : ADO.Sessions.Session := Into.Module.Get_Session; begin Into.Load_Comments (Session, For_Entity_Id); end Load_Comments; -- ------------------------------ -- Load the comments associated with the given database identifier. -- ------------------------------ procedure Load_Comments (Into : in out Comment_List_Bean; Session : in out ADO.Sessions.Session; For_Entity_Id : in ADO.Identifier) is use ADO.Sessions.Entities; Entity_Type : constant String := Ada.Strings.Unbounded.To_String (Into.Entity_Type); Kind : constant ADO.Entity_Type := Find_Entity_Type (Session, Entity_Type); Query : ADO.Queries.Context; begin Into.Entity_Id := For_Entity_Id; Query.Set_Query (AWA.Comments.Models.Query_Comment_List); Query.Bind_Param ("entity_type", Kind); Query.Bind_Param ("entity_id", For_Entity_Id); Query.Bind_Param ("status", Integer (Models.Status_Type'Pos (Models.COMMENT_PUBLISHED))); AWA.Comments.Models.List (Into, Session, Query); end Load_Comments; -- ------------------------------ -- Create the comment list bean instance. -- ------------------------------ function Create_Comment_List_Bean (Module : in AWA.Comments.Modules.Comment_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is Result : constant Comment_List_Bean_Access := new Comment_List_Bean; begin Result.Module := Module; return Result.all'Access; end Create_Comment_List_Bean; end AWA.Comments.Beans;
----------------------------------------------------------------------- -- awa-comments-beans -- Beans for the comments module -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with ADO.Sessions.Entities; with ADO.Queries; with ADO.Utils; with AWA.Helpers.Requests; package body AWA.Comments.Beans is use Ada.Strings.Unbounded; -- ------------------------------ -- Get the value identified by the name. -- ------------------------------ overriding function Get_Value (From : in Comment_Bean; Name : in String) return Util.Beans.Objects.Object is begin if From.Is_Null then return Util.Beans.Objects.Null_Object; else return AWA.Comments.Models.Comment_Bean (From).Get_Value (Name); end if; end Get_Value; -- ------------------------------ -- Set the value identified by the name. -- ------------------------------ overriding procedure Set_Value (From : in out Comment_Bean; Name : in String; Value : in Util.Beans.Objects.Object) is begin if Name = "message" then From.Set_Message (Util.Beans.Objects.To_String (Value)); elsif Name = "entity_type" then From.Entity_Type := Util.Beans.Objects.To_Unbounded_String (Value); elsif Name = "entity_id" then declare use type ADO.Identifier; Id : constant ADO.Identifier := ADO.Utils.To_Identifier (Value); begin if Id /= ADO.NO_IDENTIFIER then From.Set_Entity_Id (ADO.Utils.To_Identifier (Value)); end if; end; elsif Name = "permission" then From.Permission := Util.Beans.Objects.To_Unbounded_String (Value); elsif Name = "status" then From.Set_Status (AWA.Comments.Models.Status_Type_Objects.To_Value (Value)); elsif Name = "format" then From.Set_Format (AWA.Comments.Models.Format_Type_Objects.To_Value (Value)); elsif Name = "id" and not Util.Beans.Objects.Is_Empty (Value) then declare Id : constant ADO.Identifier := ADO.Utils.To_Identifier (Value); begin From.Module.Load_Comment (From, Id); end; end if; end Set_Value; -- ------------------------------ -- Create the comment. -- ------------------------------ overriding procedure Create (Bean : in out Comment_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is pragma Unreferenced (Outcome); begin Bean.Module.Create_Comment (Permission => To_String (Bean.Permission), Entity_Type => To_String (Bean.Entity_Type), Comment => Bean); end Create; -- ------------------------------ -- Save the comment. -- ------------------------------ overriding procedure Save (Bean : in out Comment_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is pragma Unreferenced (Outcome); begin Bean.Module.Update_Comment (Permission => To_String (Bean.Permission), Comment => Bean); end Save; -- ------------------------------ -- Publish or not the comment. -- ------------------------------ overriding procedure Publish (Bean : in out Comment_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is pragma Unreferenced (Outcome); Id : constant ADO.Identifier := Helpers.Requests.Get_Parameter ("id"); Value : constant Util.Beans.Objects.Object := Helpers.Requests.Get_Parameter ("status"); begin Bean.Module.Publish_Comment (Permission => To_String (Bean.Permission), Id => Id, Status => Models.Status_Type_Objects.To_Value (Value), Comment => Bean); end Publish; -- ------------------------------ -- Delete the comment. -- ------------------------------ overriding procedure Delete (Bean : in out Comment_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is pragma Unreferenced (Outcome); begin Bean.Module.Delete_Comment (Ada.Strings.Unbounded.To_String (Bean.Permission), Bean); end Delete; -- ------------------------------ -- Create a new comment bean instance. -- ------------------------------ function Create_Comment_Bean (Module : in AWA.Comments.Modules.Comment_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is Result : constant Comment_Bean_Access := new Comment_Bean; begin Result.Module := Module; return Result.all'Access; end Create_Comment_Bean; -- ------------------------------ -- Set the value identified by the name. -- If the name cannot be found, the method should raise the No_Value -- exception. -- ------------------------------ overriding procedure Set_Value (From : in out Comment_List_Bean; Name : in String; Value : in Util.Beans.Objects.Object) is begin if Name = "entity_type" then From.Entity_Type := Util.Beans.Objects.To_Unbounded_String (Value); elsif Name = "permission" then From.Permission := Util.Beans.Objects.To_Unbounded_String (Value); elsif Name = "entity_id" then From.Load_Comments (ADO.Utils.To_Identifier (Value)); end if; end Set_Value; -- ------------------------------ -- Set the entity type (database table) with which the comments are associated. -- ------------------------------ procedure Set_Entity_Type (Into : in out Comment_List_Bean; Table : in ADO.Schemas.Class_Mapping_Access) is begin Into.Entity_Type := Ada.Strings.Unbounded.To_Unbounded_String (Table.Table.all); end Set_Entity_Type; -- ------------------------------ -- Set the permission to check before removing or adding a comment on the entity. -- ------------------------------ procedure Set_Permission (Into : in out Comment_List_Bean; Permission : in String) is begin Into.Permission := Ada.Strings.Unbounded.To_Unbounded_String (Permission); end Set_Permission; -- ------------------------------ -- Load the comments associated with the given database identifier. -- ------------------------------ procedure Load_Comments (Into : in out Comment_List_Bean; For_Entity_Id : in ADO.Identifier) is Session : ADO.Sessions.Session := Into.Module.Get_Session; begin Into.Load_Comments (Session, For_Entity_Id); end Load_Comments; -- ------------------------------ -- Load the comments associated with the given database identifier. -- ------------------------------ procedure Load_Comments (Into : in out Comment_List_Bean; Session : in out ADO.Sessions.Session; For_Entity_Id : in ADO.Identifier) is use ADO.Sessions.Entities; Entity_Type : constant String := Ada.Strings.Unbounded.To_String (Into.Entity_Type); Kind : constant ADO.Entity_Type := Find_Entity_Type (Session, Entity_Type); Query : ADO.Queries.Context; begin Into.Entity_Id := For_Entity_Id; Query.Set_Query (AWA.Comments.Models.Query_Comment_List); Query.Bind_Param ("entity_type", Kind); Query.Bind_Param ("entity_id", For_Entity_Id); Query.Bind_Param ("status", Integer (Models.Status_Type'Pos (Models.COMMENT_PUBLISHED))); AWA.Comments.Models.List (Into, Session, Query); end Load_Comments; -- ------------------------------ -- Create the comment list bean instance. -- ------------------------------ function Create_Comment_List_Bean (Module : in AWA.Comments.Modules.Comment_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is Result : constant Comment_List_Bean_Access := new Comment_List_Bean; begin Result.Module := Module; return Result.all'Access; end Create_Comment_List_Bean; end AWA.Comments.Beans;
Update Set_Value to allow the setting of comment format
Update Set_Value to allow the setting of comment format
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
b3efd16a1db642c59e828a9c90cc13f0a3a953d3
awa/plugins/awa-comments/src/awa-comments-beans.adb
awa/plugins/awa-comments/src/awa-comments-beans.adb
----------------------------------------------------------------------- -- awa-comments-beans -- Beans for the comments module -- Copyright (C) 2014, 2015, 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with ADO.Sessions.Entities; with ADO.Queries; with ADO.Utils; with ADO.Parameters; with AWA.Helpers.Requests; package body AWA.Comments.Beans is use Ada.Strings.Unbounded; -- ------------------------------ -- Get the value identified by the name. -- ------------------------------ overriding function Get_Value (From : in Comment_Bean; Name : in String) return Util.Beans.Objects.Object is begin if From.Is_Null then return Util.Beans.Objects.Null_Object; else return AWA.Comments.Models.Comment_Bean (From).Get_Value (Name); end if; end Get_Value; -- ------------------------------ -- Set the value identified by the name. -- ------------------------------ overriding procedure Set_Value (From : in out Comment_Bean; Name : in String; Value : in Util.Beans.Objects.Object) is begin if Name = "entity_type" then From.Entity_Type := Util.Beans.Objects.To_Unbounded_String (Value); elsif Name = "entity_id" then declare use type ADO.Identifier; Id : constant ADO.Identifier := ADO.Utils.To_Identifier (Value); begin if Id /= ADO.NO_IDENTIFIER then From.Set_Entity_Id (ADO.Utils.To_Identifier (Value)); end if; end; elsif Name = "permission" then From.Permission := Util.Beans.Objects.To_Unbounded_String (Value); elsif Name = "id" and not Util.Beans.Objects.Is_Empty (Value) then declare Id : constant ADO.Identifier := ADO.Utils.To_Identifier (Value); begin From.Module.Load_Comment (From, Id); end; else AWA.Comments.Models.Comment_Bean (From).Set_Value (Name, Value); end if; end Set_Value; -- ------------------------------ -- Create the comment. -- ------------------------------ overriding procedure Create (Bean : in out Comment_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is pragma Unreferenced (Outcome); begin Bean.Module.Create_Comment (Permission => To_String (Bean.Permission), Entity_Type => To_String (Bean.Entity_Type), Comment => Bean); end Create; -- ------------------------------ -- Save the comment. -- ------------------------------ overriding procedure Save (Bean : in out Comment_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is pragma Unreferenced (Outcome); begin Bean.Module.Update_Comment (Permission => To_String (Bean.Permission), Comment => Bean); end Save; -- ------------------------------ -- Publish or not the comment. -- ------------------------------ overriding procedure Publish (Bean : in out Comment_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is pragma Unreferenced (Outcome); Id : constant ADO.Identifier := Helpers.Requests.Get_Parameter ("id"); Value : constant Util.Beans.Objects.Object := Helpers.Requests.Get_Parameter ("status"); begin Bean.Module.Publish_Comment (Permission => To_String (Bean.Permission), Id => Id, Status => Models.Status_Type_Objects.To_Value (Value), Comment => Bean); end Publish; -- ------------------------------ -- Delete the comment. -- ------------------------------ overriding procedure Delete (Bean : in out Comment_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is pragma Unreferenced (Outcome); begin Bean.Module.Delete_Comment (Ada.Strings.Unbounded.To_String (Bean.Permission), Bean); end Delete; -- ------------------------------ -- Create a new comment bean instance. -- ------------------------------ function Create_Comment_Bean (Module : in AWA.Comments.Modules.Comment_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is Result : constant Comment_Bean_Access := new Comment_Bean; begin Result.Module := Module; return Result.all'Access; end Create_Comment_Bean; -- ------------------------------ -- Set the value identified by the name. -- If the name cannot be found, the method should raise the No_Value -- exception. -- ------------------------------ overriding procedure Set_Value (From : in out Comment_List_Bean; Name : in String; Value : in Util.Beans.Objects.Object) is begin if Name = "entity_type" then From.Entity_Type := Util.Beans.Objects.To_Unbounded_String (Value); elsif Name = "permission" then From.Permission := Util.Beans.Objects.To_Unbounded_String (Value); elsif Name = "entity_id" then From.Load_Comments (ADO.Utils.To_Identifier (Value)); elsif Name = "sort" then if Util.Beans.Objects.To_String (Value) = "oldest" then From.Oldest_First := True; else From.Oldest_First := False; end if; end if; end Set_Value; -- ------------------------------ -- Set the entity type (database table) with which the comments are associated. -- ------------------------------ procedure Set_Entity_Type (Into : in out Comment_List_Bean; Table : in ADO.Schemas.Class_Mapping_Access) is begin Into.Entity_Type := Ada.Strings.Unbounded.To_Unbounded_String (Table.Table.all); end Set_Entity_Type; -- ------------------------------ -- Set the permission to check before removing or adding a comment on the entity. -- ------------------------------ procedure Set_Permission (Into : in out Comment_List_Bean; Permission : in String) is begin Into.Permission := Ada.Strings.Unbounded.To_Unbounded_String (Permission); end Set_Permission; -- ------------------------------ -- Load the comments associated with the given database identifier. -- ------------------------------ procedure Load_Comments (Into : in out Comment_List_Bean; For_Entity_Id : in ADO.Identifier) is Session : ADO.Sessions.Session := Into.Module.Get_Session; begin Into.Load_Comments (Session, For_Entity_Id); end Load_Comments; -- ------------------------------ -- Load the comments associated with the given database identifier. -- ------------------------------ procedure Load_Comments (Into : in out Comment_List_Bean; Session : in out ADO.Sessions.Session; For_Entity_Id : in ADO.Identifier) is use ADO.Sessions.Entities; Entity_Type : constant String := Ada.Strings.Unbounded.To_String (Into.Entity_Type); Kind : constant ADO.Entity_Type := Find_Entity_Type (Session, Entity_Type); Query : ADO.Queries.Context; begin Into.Entity_Id := For_Entity_Id; Query.Set_Query (AWA.Comments.Models.Query_Comment_List); Query.Bind_Param ("entity_type", Kind); Query.Bind_Param ("entity_id", For_Entity_Id); Query.Bind_Param ("status", Integer (Models.Status_Type'Pos (Models.COMMENT_PUBLISHED))); if Into.Oldest_First then Query.Bind_Param ("sort", ADO.Parameters.Token '("ASC")); else Query.Bind_Param ("sort", ADO.Parameters.Token '("DESC")); end if; AWA.Comments.Models.List (Into, Session, Query); end Load_Comments; -- ------------------------------ -- Create the comment list bean instance. -- ------------------------------ function Create_Comment_List_Bean (Module : in AWA.Comments.Modules.Comment_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is Result : constant Comment_List_Bean_Access := new Comment_List_Bean; begin Result.Module := Module; return Result.all'Access; end Create_Comment_List_Bean; end AWA.Comments.Beans;
----------------------------------------------------------------------- -- awa-comments-beans -- Beans for the comments module -- Copyright (C) 2014, 2015, 2016, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with ADO.Sessions.Entities; with ADO.Queries; with ADO.Utils; with ADO.Parameters; with AWA.Helpers.Requests; package body AWA.Comments.Beans is use Ada.Strings.Unbounded; -- ------------------------------ -- Get the value identified by the name. -- ------------------------------ overriding function Get_Value (From : in Comment_Bean; Name : in String) return Util.Beans.Objects.Object is begin if From.Is_Null then return Util.Beans.Objects.Null_Object; else return AWA.Comments.Models.Comment_Bean (From).Get_Value (Name); end if; end Get_Value; -- ------------------------------ -- Set the value identified by the name. -- ------------------------------ overriding procedure Set_Value (From : in out Comment_Bean; Name : in String; Value : in Util.Beans.Objects.Object) is begin if Name = "entity_type" then From.Entity_Type := Util.Beans.Objects.To_Unbounded_String (Value); elsif Name = "entity_id" then declare use type ADO.Identifier; Id : constant ADO.Identifier := ADO.Utils.To_Identifier (Value); begin if Id /= ADO.NO_IDENTIFIER then From.Set_Entity_Id (ADO.Utils.To_Identifier (Value)); end if; end; elsif Name = "permission" then From.Permission := Util.Beans.Objects.To_Unbounded_String (Value); elsif Name = "id" and not Util.Beans.Objects.Is_Empty (Value) then declare Id : constant ADO.Identifier := ADO.Utils.To_Identifier (Value); begin From.Module.Load_Comment (From, Id); end; else AWA.Comments.Models.Comment_Bean (From).Set_Value (Name, Value); end if; end Set_Value; -- ------------------------------ -- Create the comment. -- ------------------------------ overriding procedure Create (Bean : in out Comment_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is pragma Unreferenced (Outcome); begin Bean.Module.Create_Comment (Permission => To_String (Bean.Permission), Entity_Type => To_String (Bean.Entity_Type), Comment => Bean); end Create; -- ------------------------------ -- Save the comment. -- ------------------------------ overriding procedure Save (Bean : in out Comment_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is pragma Unreferenced (Outcome); begin Bean.Module.Update_Comment (Permission => To_String (Bean.Permission), Comment => Bean); end Save; -- ------------------------------ -- Publish or not the comment. -- ------------------------------ overriding procedure Publish (Bean : in out Comment_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is pragma Unreferenced (Outcome); Id : constant ADO.Identifier := Helpers.Requests.Get_Parameter ("id"); Value : constant Util.Beans.Objects.Object := Helpers.Requests.Get_Parameter ("status"); begin Bean.Module.Publish_Comment (Permission => To_String (Bean.Permission), Id => Id, Status => Models.Status_Type_Objects.To_Value (Value), Comment => Bean); end Publish; -- ------------------------------ -- Delete the comment. -- ------------------------------ overriding procedure Delete (Bean : in out Comment_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is pragma Unreferenced (Outcome); begin Bean.Module.Delete_Comment (Ada.Strings.Unbounded.To_String (Bean.Permission), Bean); end Delete; -- ------------------------------ -- Create a new comment bean instance. -- ------------------------------ function Create_Comment_Bean (Module : in AWA.Comments.Modules.Comment_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is Result : constant Comment_Bean_Access := new Comment_Bean; begin Result.Module := Module; return Result.all'Access; end Create_Comment_Bean; -- ------------------------------ -- Set the value identified by the name. -- If the name cannot be found, the method should raise the No_Value -- exception. -- ------------------------------ overriding procedure Set_Value (From : in out Comment_List_Bean; Name : in String; Value : in Util.Beans.Objects.Object) is begin if Name = "entity_type" then From.Entity_Type := Util.Beans.Objects.To_Unbounded_String (Value); elsif Name = "permission" then From.Permission := Util.Beans.Objects.To_Unbounded_String (Value); elsif Name = "entity_id" then From.Load_Comments (ADO.Utils.To_Identifier (Value)); elsif Name = "sort" then if Util.Beans.Objects.To_String (Value) = "oldest" then From.Oldest_First := True; else From.Oldest_First := False; end if; elsif Name = "status" then if Util.Beans.Objects.To_String (Value) = "published" then From.Publish_Only := True; else From.Publish_Only := False; end if; end if; end Set_Value; -- ------------------------------ -- Set the entity type (database table) with which the comments are associated. -- ------------------------------ procedure Set_Entity_Type (Into : in out Comment_List_Bean; Table : in ADO.Schemas.Class_Mapping_Access) is begin Into.Entity_Type := Ada.Strings.Unbounded.To_Unbounded_String (Table.Table.all); end Set_Entity_Type; -- ------------------------------ -- Set the permission to check before removing or adding a comment on the entity. -- ------------------------------ procedure Set_Permission (Into : in out Comment_List_Bean; Permission : in String) is begin Into.Permission := Ada.Strings.Unbounded.To_Unbounded_String (Permission); end Set_Permission; -- ------------------------------ -- Load the comments associated with the given database identifier. -- ------------------------------ procedure Load_Comments (Into : in out Comment_List_Bean; For_Entity_Id : in ADO.Identifier) is Session : ADO.Sessions.Session := Into.Module.Get_Session; begin Into.Load_Comments (Session, For_Entity_Id); end Load_Comments; -- ------------------------------ -- Load the comments associated with the given database identifier. -- ------------------------------ procedure Load_Comments (Into : in out Comment_List_Bean; Session : in out ADO.Sessions.Session; For_Entity_Id : in ADO.Identifier) is use ADO.Sessions.Entities; Entity_Type : constant String := Ada.Strings.Unbounded.To_String (Into.Entity_Type); Kind : constant ADO.Entity_Type := Find_Entity_Type (Session, Entity_Type); Query : ADO.Queries.Context; begin Into.Entity_Id := For_Entity_Id; if Into.Publish_Only then Query.Set_Query (AWA.Comments.Models.Query_Comment_List); Query.Bind_Param ("status", Integer (Models.Status_Type'Pos (Models.COMMENT_PUBLISHED))); else Query.Set_Query (AWA.Comments.Models.Query_All_Comment_List); end if; Query.Bind_Param ("entity_type", Kind); Query.Bind_Param ("entity_id", For_Entity_Id); if Into.Oldest_First then Query.Bind_Param ("sort", ADO.Parameters.Token '("ASC")); else Query.Bind_Param ("sort", ADO.Parameters.Token '("DESC")); end if; AWA.Comments.Models.List (Into, Session, Query); end Load_Comments; -- ------------------------------ -- Create the comment list bean instance. -- ------------------------------ function Create_Comment_List_Bean (Module : in AWA.Comments.Modules.Comment_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is Result : constant Comment_List_Bean_Access := new Comment_List_Bean; begin Result.Module := Module; return Result.all'Access; end Create_Comment_List_Bean; end AWA.Comments.Beans;
Update Get_Value for Comment_List_Bean to take into account the 'status' bean and setup the publish_only flag When loading the list of comments, load all the comments (Publish_Only = False) or only those that are published (Publish_Only = True)
Update Get_Value for Comment_List_Bean to take into account the 'status' bean and setup the publish_only flag When loading the list of comments, load all the comments (Publish_Only = False) or only those that are published (Publish_Only = True)
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
bfb23be38fd9582b3a9c4c8d0ddf6e0ca8471300
awa/plugins/awa-counters/src/awa-counters-beans.ads
awa/plugins/awa-counters/src/awa-counters-beans.ads
----------------------------------------------------------------------- -- awa-counters-beans -- Counter bean definition -- 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 ADO.Objects; with ADO.Schemas; with Util.Beans.Objects; with Util.Beans.Basic; -- == Counter Bean == -- The <b>Counter_Bean</b> allows to represent a counter associated with some database -- entity and allows its control by the <awa:counter> component. -- package AWA.Counters.Beans is type Counter_Bean (Of_Type : ADO.Objects.Object_Key_Type; Of_Class : ADO.Schemas.Class_Mapping_Access) is new Util.Beans.Basic.Readonly_Bean with record Counter : Counter_Index_Type; Value : Integer := -1; Object : ADO.Objects.Object_Key (Of_Type, Of_Class); end record; type Counter_Bean_Access is access all Counter_Bean'Class; -- Get the value identified by the name. overriding function Get_Value (From : in Counter_Bean; Name : in String) return Util.Beans.Objects.Object; end AWA.Counters.Beans;
----------------------------------------------------------------------- -- awa-counters-beans -- Counter bean definition -- 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 ADO.Objects; with ADO.Schemas; with Util.Beans.Objects; with Util.Beans.Basic; with AWA.Counters.Modules; with AWA.Counters.Models; -- == Counter Bean == -- The <b>Counter_Bean</b> allows to represent a counter associated with some database -- entity and allows its control by the <awa:counter> component. -- package AWA.Counters.Beans is type Counter_Bean (Of_Type : ADO.Objects.Object_Key_Type; Of_Class : ADO.Schemas.Class_Mapping_Access) is new Util.Beans.Basic.Readonly_Bean with record Counter : Counter_Index_Type; Value : Integer := -1; Object : ADO.Objects.Object_Key (Of_Type, Of_Class); end record; type Counter_Bean_Access is access all Counter_Bean'Class; -- Get the value identified by the name. overriding function Get_Value (From : in Counter_Bean; Name : in String) return Util.Beans.Objects.Object; type Counter_Stat_Bean is new AWA.Counters.Models.Stat_List_Bean with record Module : AWA.Counters.Modules.Counter_Module_Access; Stats : aliased AWA.Counters.Models.Stat_Info_List_Bean; Stats_Bean : AWA.Counters.Models.Stat_Info_List_Bean_Access; end record; type Counter_Stat_Bean_Access is access all Counter_Stat_Bean'Class; overriding function Get_Value (List : in Counter_Stat_Bean; Name : in String) return Util.Beans.Objects.Object; -- Set the value identified by the name. overriding procedure Set_Value (From : in out Counter_Stat_Bean; Name : in String; Value : in Util.Beans.Objects.Object); -- Load the statistics information. overriding procedure Load (List : in out Counter_Stat_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- Create the Blog_Stat_Bean bean instance. function Create_Counter_Stat_Bean (Module : in AWA.Counters.Modules.Counter_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access; end AWA.Counters.Beans;
Declare the Counter_Stat_Bean type with Get_Value, Set_Value, Load operations
Declare the Counter_Stat_Bean type with Get_Value, Set_Value, Load operations
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa