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
146319da0bec84c37fd7c49bd49bd7f13aca3e28
orka_egl/src/egl-objects-surfaces.adb
orka_egl/src/egl-objects-surfaces.adb
-- SPDX-License-Identifier: Apache-2.0 -- -- Copyright (c) 2021 onox <[email protected]> -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. with Ada.Unchecked_Conversion; with EGL.API; with EGL.Errors; package body EGL.Objects.Surfaces is Color_Space : constant Int := 16#309D#; Color_Space_sRGB : constant Int := 16#3089#; Color_Space_Linear : constant Int := 16#308A#; function Create_Surface (Display : Displays.Display; Config : Configs.Config; Window : Native_Window_Ptr; sRGB : Boolean) return Surface is No_Surface : constant ID_Type := ID_Type (System.Null_Address); Attributes : constant Int_Array := (Color_Space, (if sRGB then Color_Space_sRGB else Color_Space_Linear), None); ID : constant ID_Type := API.Create_Platform_Window_Surface.Ref (Display.ID, Config.ID, Window, Attributes); begin if ID = No_Surface then Errors.Raise_Exception_On_EGL_Error; end if; return Result : Surface (Display.Platform) do Result.Reference.ID := ID; Result.Display := Display; end return; end Create_Surface; function Width (Object : Surface) return Natural is Result : Int; begin if not Boolean (API.Query_Surface (Object.Display.ID, Object.ID, Width, Result)) then Errors.Raise_Exception_On_EGL_Error; end if; return Natural (Result); end Width; function Height (Object : Surface) return Natural is Result : Int; begin if not Boolean (API.Query_Surface (Object.Display.ID, Object.ID, Height, Result)) then Errors.Raise_Exception_On_EGL_Error; end if; return Natural (Result); end Height; function Behavior (Object : Surface) return Swap_Behavior is Result : Int; function Convert is new Ada.Unchecked_Conversion (Source => Int, Target => Swap_Behavior); begin if not Boolean (API.Query_Surface (Object.Display.ID, Object.ID, EGL.Swap_Behavior, Result)) then Errors.Raise_Exception_On_EGL_Error; end if; return Convert (Result); end Behavior; procedure Swap_Buffers (Object : Surface) is begin if not Boolean (API.Swap_Buffers (Object.Display.ID, Object.ID)) then Errors.Raise_Exception_On_EGL_Error; end if; end Swap_Buffers; overriding procedure Pre_Finalize (Object : in out Surface) is No_Surface : constant ID_Type := ID_Type (System.Null_Address); begin pragma Assert (Object.ID /= No_Surface); if not Boolean (API.Destroy_Surface (Object.Display.ID, Object.ID)) then Errors.Raise_Exception_On_EGL_Error; end if; Object.Reference.ID := No_Surface; end Pre_Finalize; end EGL.Objects.Surfaces;
-- SPDX-License-Identifier: Apache-2.0 -- -- Copyright (c) 2021 onox <[email protected]> -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. with Ada.Unchecked_Conversion; with EGL.API; with EGL.Errors; package body EGL.Objects.Surfaces is Color_Space : constant Int := 16#309D#; Color_Space_sRGB : constant Int := 16#3089#; Color_Space_Linear : constant Int := 16#308A#; function Create_Surface (Display : Displays.Display; Config : Configs.Config; Window : Native_Window_Ptr; sRGB : Boolean) return Surface is No_Surface : constant ID_Type := ID_Type (System.Null_Address); Attributes : constant Int_Array := (Color_Space, (if sRGB then Color_Space_sRGB else Color_Space_Linear), None); ID : constant ID_Type := API.Create_Platform_Window_Surface.Ref (Display.ID, Config.ID, Window, Attributes); -- TODO Support EGL_EXT_present_opaque -- (so that background will be opaque; alpha of FB gets ignored) begin if ID = No_Surface then Errors.Raise_Exception_On_EGL_Error; end if; return Result : Surface (Display.Platform) do Result.Reference.ID := ID; Result.Display := Display; end return; end Create_Surface; function Width (Object : Surface) return Natural is Result : Int; begin if not Boolean (API.Query_Surface (Object.Display.ID, Object.ID, Width, Result)) then Errors.Raise_Exception_On_EGL_Error; end if; return Natural (Result); end Width; function Height (Object : Surface) return Natural is Result : Int; begin if not Boolean (API.Query_Surface (Object.Display.ID, Object.ID, Height, Result)) then Errors.Raise_Exception_On_EGL_Error; end if; return Natural (Result); end Height; function Behavior (Object : Surface) return Swap_Behavior is Result : Int; function Convert is new Ada.Unchecked_Conversion (Source => Int, Target => Swap_Behavior); begin if not Boolean (API.Query_Surface (Object.Display.ID, Object.ID, EGL.Swap_Behavior, Result)) then Errors.Raise_Exception_On_EGL_Error; end if; return Convert (Result); end Behavior; procedure Swap_Buffers (Object : Surface) is begin if not Boolean (API.Swap_Buffers (Object.Display.ID, Object.ID)) then Errors.Raise_Exception_On_EGL_Error; end if; end Swap_Buffers; overriding procedure Pre_Finalize (Object : in out Surface) is No_Surface : constant ID_Type := ID_Type (System.Null_Address); begin pragma Assert (Object.ID /= No_Surface); if not Boolean (API.Destroy_Surface (Object.Display.ID, Object.ID)) then Errors.Raise_Exception_On_EGL_Error; end if; Object.Reference.ID := No_Surface; end Pre_Finalize; end EGL.Objects.Surfaces;
Add TODO to support EGL_EXT_present_opaque
egl: Add TODO to support EGL_EXT_present_opaque Signed-off-by: onox <[email protected]>
Ada
apache-2.0
onox/orka
79746007619984cb2db861a49aa2ff815f1d3dba
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
Letractively/ada-awa,tectronics/ada-awa,Letractively/ada-awa,Letractively/ada-awa,tectronics/ada-awa,tectronics/ada-awa
53caa2ad6ee1b02172acaad39f930136ed4fbf4f
awa/plugins/awa-blogs/regtests/awa-blogs-tests.adb
awa/plugins/awa-blogs/regtests/awa-blogs-tests.adb
----------------------------------------------------------------------- -- awa-blogs-tests -- Unit tests for blogs module -- 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.Test_Caller; with ASF.Requests.Mockup; with ASF.Responses.Mockup; with ASF.Tests; with AWA.Tests.Helpers.Users; package body AWA.Blogs.Tests is use Ada.Strings.Unbounded; use AWA.Tests; package Caller is new Util.Test_Caller (Test, "Blogs.Beans"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test AWA.Blogs.Beans.List_Post (Anonymous)", Test_Anonymous_Access'Access); Caller.Add_Test (Suite, "Test AWA.Blogs.Beans.Create_Blog", Test_Create_Blog'Access); Caller.Add_Test (Suite, "Test AWA.Blogs.Beans.Update_Post", Test_Update_Post'Access); Caller.Add_Test (Suite, "Test AWA.Blogs.Beans.List_Post (Admin)", Test_Admin_List_Posts'Access); Caller.Add_Test (Suite, "Test AWA.Blogs.Beans.List_Comments (Admin)", Test_Admin_List_Comments'Access); Caller.Add_Test (Suite, "Test AWA.Blogs.Beans.Stats (Admin)", Test_Admin_Blog_Stats'Access); end Add_Tests; -- ------------------------------ -- Get some access on the blog as anonymous users. -- ------------------------------ procedure Verify_Anonymous (T : in out Test; Post : in String) is Request : ASF.Requests.Mockup.Request; Reply : ASF.Responses.Mockup.Response; begin ASF.Tests.Do_Get (Request, Reply, "/blogs/view.html", "blog-view.html"); ASF.Tests.Assert_Contains (T, "Blog posts", Reply, "Blog view page is invalid"); ASF.Tests.Do_Get (Request, Reply, "/blogs/tagged.html?tag=test", "blog-tagged.html"); ASF.Tests.Assert_Contains (T, "Tag - test", Reply, "Blog tag page is invalid"); ASF.Tests.Do_Get (Request, Reply, "/blogs/post.html?post=missing", "blog-missing.html"); ASF.Tests.Assert_Contains (T, "The post you are looking for does not exist", Reply, "Blog post missing page is invalid"); if Post = "" then return; end if; ASF.Tests.Do_Get (Request, Reply, "/blogs/post.html?post=" & Post, "blog-post.html"); ASF.Tests.Assert_Contains (T, "post-title", Reply, "Blog post page is invalid"); end Verify_Anonymous; -- ------------------------------ -- 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; -- ------------------------------ -- Test creation of blog by simulating web requests. -- ------------------------------ procedure Test_Create_Blog (T : in out Test) is Request : ASF.Requests.Mockup.Request; Reply : ASF.Responses.Mockup.Response; Uuid : constant String := Util.Tests.Get_Uuid; begin AWA.Tests.Helpers.Users.Login ("[email protected]", Request); Request.Set_Parameter ("title", "The Blog Title"); Request.Set_Parameter ("create-blog", "1"); Request.Set_Parameter ("create", "1"); ASF.Tests.Do_Post (Request, Reply, "/blogs/admin/create-blog.html", "create-blog.html"); T.Assert (Reply.Get_Status = ASF.Responses.SC_MOVED_TEMPORARILY, "Invalid response after blog creation"); declare Ident : constant String := Helpers.Extract_Redirect (Reply, "/asfunit/blogs/admin/create.html?id="); begin Util.Tests.Assert_Matches (T, "^[0-9]+$", Ident, "Invalid blog identifier in the response"); T.Blog_Ident := To_Unbounded_String (Ident); Request.Set_Parameter ("post-blog-id", Ident); Request.Set_Parameter ("post", "1"); Request.Set_Parameter ("post-title", "Post title"); Request.Set_Parameter ("text", "The blog post content."); Request.Set_Parameter ("uri", Uuid); Request.Set_Parameter ("save", "1"); Request.Set_Parameter ("post-status", "1"); Request.Set_Parameter ("allow-comment", "0"); ASF.Tests.Do_Post (Request, Reply, "/blogs/admin/create.html", "create-post.html"); T.Post_Ident := Helpers.Extract_Redirect (Reply, "/asfunit/blogs/admin/" & Ident & "/preview/"); Util.Tests.Assert_Matches (T, "^[0-9]+$", To_String (T.Post_Ident), "Invalid post identifier in the response"); end; -- Check public access to the post. T.Post_Uri := To_Unbounded_String (Uuid); T.Verify_Anonymous (Uuid); end Test_Create_Blog; -- ------------------------------ -- Test updating a post by simulating web requests. -- ------------------------------ procedure Test_Update_Post (T : in out Test) is Request : ASF.Requests.Mockup.Request; Reply : ASF.Responses.Mockup.Response; Uuid : constant String := Util.Tests.Get_Uuid; Ident : constant String := To_String (T.Blog_Ident); Post_Ident : Unbounded_String; begin AWA.Tests.Helpers.Users.Login ("[email protected]", Request); Request.Set_Parameter ("post-blog-id", Ident); Request.Set_Parameter ("post-id", To_String (T.Post_Ident)); Request.Set_Parameter ("post", "1"); Request.Set_Parameter ("post-title", "New post title"); Request.Set_Parameter ("text", "The blog post new content."); Request.Set_Parameter ("uri", Uuid); Request.Set_Parameter ("save", "1"); Request.Set_Parameter ("post-status", "1"); Request.Set_Parameter ("allow-comment", "0"); ASF.Tests.Do_Post (Request, Reply, "/blogs/admin/edit.html", "edit-post.html"); Post_Ident := Helpers.Extract_Redirect (Reply, "/asfunit/blogs/admin/" & Ident & "/preview/"); Util.Tests.Assert_Equals (T, To_String (T.Post_Ident), To_String (Post_Ident), "Invalid post identifier returned after post update"); T.Verify_Anonymous (Uuid); end Test_Update_Post; -- ------------------------------ -- Test listing the blog posts. -- ------------------------------ procedure Test_Admin_List_Posts (T : in out Test) is Request : ASF.Requests.Mockup.Request; Reply : ASF.Responses.Mockup.Response; Ident : constant String := To_String (T.Blog_Ident); begin AWA.Tests.Helpers.Users.Login ("[email protected]", Request); ASF.Tests.Do_Get (Request, Reply, "/blogs/admin/list.html?id=" & Ident, "blog-list.html"); ASF.Tests.Assert_Contains (T, "blog-post-list-header", Reply, "Blog admin page is invalid"); end Test_Admin_List_Posts; -- ------------------------------ -- Test listing the blog comments. -- ------------------------------ procedure Test_Admin_List_Comments (T : in out Test) is Request : ASF.Requests.Mockup.Request; Reply : ASF.Responses.Mockup.Response; Ident : constant String := To_String (T.Blog_Ident); begin AWA.Tests.Helpers.Users.Login ("[email protected]", Request); ASF.Tests.Do_Get (Request, Reply, "/blogs/admin/list-comments.html?id=" & Ident, "blog-list-comments.html"); ASF.Tests.Assert_Contains (T, "blog-comment-list-header", Reply, "Blog admin comments page is invalid"); end Test_Admin_List_Comments; -- ------------------------------ -- Test getting the JSON blog stats (for graphs). -- ------------------------------ procedure Test_Admin_Blog_Stats (T : in out Test) is Request : ASF.Requests.Mockup.Request; Reply : ASF.Responses.Mockup.Response; Ident : constant String := To_String (T.Blog_Ident); begin AWA.Tests.Helpers.Users.Login ("[email protected]", Request); ASF.Tests.Do_Get (Request, Reply, "/blogs/admin/" & Ident & "/stats", "blog-stats.html"); ASF.Tests.Assert_Contains (T, "data", Reply, "Blog admin stats page is invalid"); end Test_Admin_Blog_Stats; end AWA.Blogs.Tests;
----------------------------------------------------------------------- -- awa-blogs-tests -- Unit tests for blogs module -- Copyright (C) 2017, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Test_Caller; with ASF.Requests.Mockup; with ASF.Responses.Mockup; with ASF.Tests; with AWA.Tests.Helpers.Users; package body AWA.Blogs.Tests is use Ada.Strings.Unbounded; use AWA.Tests; package Caller is new Util.Test_Caller (Test, "Blogs.Beans"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test AWA.Blogs.Beans.List_Post (Anonymous)", Test_Anonymous_Access'Access); Caller.Add_Test (Suite, "Test AWA.Blogs.Beans.Create_Blog", Test_Create_Blog'Access); Caller.Add_Test (Suite, "Test AWA.Blogs.Beans.Update_Post", Test_Update_Post'Access); Caller.Add_Test (Suite, "Test AWA.Blogs.Beans.List_Post (Admin)", Test_Admin_List_Posts'Access); Caller.Add_Test (Suite, "Test AWA.Blogs.Beans.List_Comments (Admin)", Test_Admin_List_Comments'Access); Caller.Add_Test (Suite, "Test AWA.Blogs.Beans.Stats (Admin)", Test_Admin_Blog_Stats'Access); Caller.Add_Test (Suite, "Test AWA.Blogs.Beans.Update_Post (Publish_Date)", Test_Update_Publish_Date'Access); end Add_Tests; -- ------------------------------ -- Get some access on the blog as anonymous users. -- ------------------------------ procedure Verify_Anonymous (T : in out Test; Post : in String) is Request : ASF.Requests.Mockup.Request; Reply : ASF.Responses.Mockup.Response; begin ASF.Tests.Do_Get (Request, Reply, "/blogs/view.html", "blog-view.html"); ASF.Tests.Assert_Contains (T, "Blog posts", Reply, "Blog view page is invalid"); ASF.Tests.Do_Get (Request, Reply, "/blogs/tagged.html?tag=test", "blog-tagged.html"); ASF.Tests.Assert_Contains (T, "Tag - test", Reply, "Blog tag page is invalid"); ASF.Tests.Do_Get (Request, Reply, "/blogs/post.html?post=missing", "blog-missing.html"); ASF.Tests.Assert_Matches (T, "The post you are looking for does not exist", Reply, "Blog post missing page is invalid", ASF.Responses.SC_NOT_FOUND); if Post = "" then return; end if; ASF.Tests.Do_Get (Request, Reply, "/blogs/post.html?post=" & Post, "blog-post.html"); ASF.Tests.Assert_Matches (T, ".*The blog post.*content.*", Reply, "Blog post page is invalid" ); end Verify_Anonymous; -- ------------------------------ -- 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; -- ------------------------------ -- Test creation of blog by simulating web requests. -- ------------------------------ procedure Test_Create_Blog (T : in out Test) is Request : ASF.Requests.Mockup.Request; Reply : ASF.Responses.Mockup.Response; Uuid : constant String := Util.Tests.Get_Uuid; begin AWA.Tests.Helpers.Users.Login ("[email protected]", Request); Request.Set_Parameter ("title", "The Blog Title"); Request.Set_Parameter ("create-blog", "1"); Request.Set_Parameter ("create", "1"); ASF.Tests.Do_Post (Request, Reply, "/blogs/admin/create-blog.html", "create-blog.html"); T.Assert (Reply.Get_Status = ASF.Responses.SC_MOVED_TEMPORARILY, "Invalid response after blog creation"); declare Ident : constant String := Helpers.Extract_Redirect (Reply, "/asfunit/blogs/admin/create.html?id="); begin Util.Tests.Assert_Matches (T, "^[0-9]+$", Ident, "Invalid blog identifier in the response"); T.Blog_Ident := To_Unbounded_String (Ident); Request.Set_Parameter ("post-blog-id", Ident); Request.Set_Parameter ("post", "1"); Request.Set_Parameter ("post-title", "Post title"); Request.Set_Parameter ("text", "The blog post content."); Request.Set_Parameter ("uri", Uuid); Request.Set_Parameter ("save", "1"); Request.Set_Parameter ("post-status", "1"); Request.Set_Parameter ("allow-comment", "0"); ASF.Tests.Do_Post (Request, Reply, "/blogs/admin/create.html", "create-post.html"); T.Post_Ident := Helpers.Extract_Redirect (Reply, "/asfunit/blogs/admin/" & Ident & "/preview/"); Util.Tests.Assert_Matches (T, "^[0-9]+$", To_String (T.Post_Ident), "Invalid post identifier in the response"); end; -- Check public access to the post. T.Post_Uri := To_Unbounded_String (Uuid); T.Verify_Anonymous (Uuid); end Test_Create_Blog; -- ------------------------------ -- Test updating a post by simulating web requests. -- ------------------------------ procedure Test_Update_Post (T : in out Test) is Request : ASF.Requests.Mockup.Request; Reply : ASF.Responses.Mockup.Response; Uuid : constant String := Util.Tests.Get_Uuid; Ident : constant String := To_String (T.Blog_Ident); Post_Ident : Unbounded_String; begin AWA.Tests.Helpers.Users.Login ("[email protected]", Request); Request.Set_Parameter ("post-blog-id", Ident); Request.Set_Parameter ("post-id", To_String (T.Post_Ident)); Request.Set_Parameter ("post", "1"); Request.Set_Parameter ("post-title", "New post title"); Request.Set_Parameter ("text", "The blog post new content."); Request.Set_Parameter ("uri", Uuid); Request.Set_Parameter ("save", "1"); Request.Set_Parameter ("post-status", "POST_PUBLISHED"); Request.Set_Parameter ("allow-comment", "0"); ASF.Tests.Do_Post (Request, Reply, "/blogs/admin/edit.html", "edit-post.html"); Post_Ident := Helpers.Extract_Redirect (Reply, "/asfunit/blogs/admin/" & Ident & "/preview/"); Util.Tests.Assert_Equals (T, To_String (T.Post_Ident), To_String (Post_Ident), "Invalid post identifier returned after post update"); T.Verify_Anonymous (Uuid); end Test_Update_Post; -- ------------------------------ -- Test updating the publication date by simulating web requests. -- ------------------------------ procedure Test_Update_Publish_Date (T : in out Test) is Request : ASF.Requests.Mockup.Request; Reply : ASF.Responses.Mockup.Response; Uuid : constant String := Util.Tests.Get_Uuid; Ident : constant String := To_String (T.Blog_Ident); Post_Ident : Unbounded_String; begin AWA.Tests.Helpers.Users.Login ("[email protected]", Request); Request.Set_Parameter ("post_id", To_String (T.Post_Ident)); Request.Set_Parameter ("blog_id", Ident); ASF.Tests.Do_Get (Request, Reply, "/blogs/admin/edit.html", "edit-post-form.html"); Request.Set_Parameter ("post-blog-id", Ident); Request.Set_Parameter ("post-id", To_String (T.Post_Ident)); Request.Set_Parameter ("post", "1"); Request.Set_Parameter ("post-title", "New post title"); Request.Set_Parameter ("text", "The blog post new content."); Request.Set_Parameter ("uri", Uuid); Request.Set_Parameter ("save", "POST_PUBLISHED"); Request.Set_Parameter ("post-status", "1"); Request.Set_Parameter ("allow-comment", "0"); Request.Set_Parameter ("publish-date", ""); ASF.Tests.Do_Post (Request, Reply, "/blogs/admin/edit.html", "edit-post.html"); Post_Ident := Helpers.Extract_Redirect (Reply, "/asfunit/blogs/admin/" & Ident & "/preview/"); Util.Tests.Assert_Equals (T, To_String (T.Post_Ident), To_String (Post_Ident), "Invalid post identifier returned after post update"); T.Verify_Anonymous (Uuid); end Test_Update_Publish_Date; -- ------------------------------ -- Test listing the blog posts. -- ------------------------------ procedure Test_Admin_List_Posts (T : in out Test) is Request : ASF.Requests.Mockup.Request; Reply : ASF.Responses.Mockup.Response; Ident : constant String := To_String (T.Blog_Ident); begin AWA.Tests.Helpers.Users.Login ("[email protected]", Request); ASF.Tests.Do_Get (Request, Reply, "/blogs/admin/list.html?id=" & Ident, "blog-list.html"); ASF.Tests.Assert_Contains (T, "blog-post-list-header", Reply, "Blog admin page is invalid"); end Test_Admin_List_Posts; -- ------------------------------ -- Test listing the blog comments. -- ------------------------------ procedure Test_Admin_List_Comments (T : in out Test) is Request : ASF.Requests.Mockup.Request; Reply : ASF.Responses.Mockup.Response; Ident : constant String := To_String (T.Blog_Ident); begin AWA.Tests.Helpers.Users.Login ("[email protected]", Request); ASF.Tests.Do_Get (Request, Reply, "/blogs/admin/list-comments.html?id=" & Ident, "blog-list-comments.html"); ASF.Tests.Assert_Contains (T, "blog-comment-list-header", Reply, "Blog admin comments page is invalid"); end Test_Admin_List_Comments; -- ------------------------------ -- Test getting the JSON blog stats (for graphs). -- ------------------------------ procedure Test_Admin_Blog_Stats (T : in out Test) is Request : ASF.Requests.Mockup.Request; Reply : ASF.Responses.Mockup.Response; Ident : constant String := To_String (T.Blog_Ident); begin AWA.Tests.Helpers.Users.Login ("[email protected]", Request); ASF.Tests.Do_Get (Request, Reply, "/blogs/admin/" & Ident & "/stats", "blog-stats.html"); ASF.Tests.Assert_Contains (T, "data", Reply, "Blog admin stats page is invalid"); end Test_Admin_Blog_Stats; end AWA.Blogs.Tests;
Implement the Test_Update_Publish_Date procedure and register the new test for execution
Implement the Test_Update_Publish_Date procedure and register the new test for execution
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
c4e8299a9aab2c427158680273261aba4c40d4c2
awa/plugins/awa-tags/src/awa-tags.ads
awa/plugins/awa-tags/src/awa-tags.ads
----------------------------------------------------------------------- -- awa-tags -- Tags management -- Copyright (C) 2013 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- -- == Introduction == -- The <b>Tags</b> module allows to associate general purpose tags to any database entity. -- It provides a JSF component that allows to insert easily a list of tags in a page and -- in a form. An application can use the bean types defined in <tt>AWA.Tags.Beans</tt> -- to define the tags and it will use the <tt>awa:tagList</tt> component to display them. -- -- == Model == -- [http://ada-awa.googlecode.com/svn/wiki/awa_tags_model.png] -- -- @include awa-tags-modules.ads -- @include awa-tags-beans.ads -- @include awa-tags-components.ads -- package AWA.Tags is pragma Pure; end AWA.Tags;
----------------------------------------------------------------------- -- awa-tags -- Tags management -- Copyright (C) 2013 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- -- == Introduction == -- The <b>Tags</b> module allows to associate general purpose tags to any database entity. -- It provides a JSF component that allows to insert easily a list of tags in a page and -- in a form. An application can use the bean types defined in <tt>AWA.Tags.Beans</tt> -- to define the tags and it will use the <tt>awa:tagList</tt> component to display them. -- A tag cloud is also provided by the <tt>awa:tagCloud</tt> component. -- -- == Model == -- The database model is generic and it uses the <tt>Entity_Type</tt> provided by -- [http://ada-ado.googlecode.com ADO] to associate a tag to entities stored in different -- tables. The <tt>Entity_Type</tt> identifies the database table and the stored identifier -- in <tt>for_entity_id</tt> defines the entity in that table. -- -- [http://ada-awa.googlecode.com/svn/wiki/awa_tags_model.png] -- -- @include awa-tags-modules.ads -- @include awa-tags-beans.ads -- @include awa-tags-components.ads -- package AWA.Tags is pragma Pure; end AWA.Tags;
Document the tag model
Document the tag model
Ada
apache-2.0
Letractively/ada-awa,Letractively/ada-awa,tectronics/ada-awa,tectronics/ada-awa,tectronics/ada-awa,Letractively/ada-awa
1733ba370627a262ce2f97cd59599232b64f1e66
src/gen-commands-plugins.adb
src/gen-commands-plugins.adb
----------------------------------------------------------------------- -- gen-commands-plugins -- Plugin creation and management commands for dynamo -- Copyright (C) 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Directories; with Ada.Text_IO; with Gen.Artifacts; with Gen.Model.Projects; with GNAT.Command_Line; with Util.Files; with Util.Log.Loggers; with Util.Strings.Transforms; package body Gen.Commands.Plugins is Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Gen.Commands.Project"); -- ------------------------------ -- Generator Command -- ------------------------------ -- Execute the command with the arguments. procedure Execute (Cmd : in Command; Generator : in out Gen.Generator.Handler) is pragma Unreferenced (Cmd); use GNAT.Command_Line; Result_Dir : constant String := Generator.Get_Result_Directory; begin -- If a dynamo.xml file exists, read it. if Ada.Directories.Exists ("dynamo.xml") then Generator.Read_Project ("dynamo.xml"); else Generator.Set_Project_Property ("license", "apache"); Generator.Set_Project_Property ("author", "unknown"); Generator.Set_Project_Property ("author_email", "[email protected]"); end if; -- Parse the command line loop case Getopt ("l:") is when ASCII.NUL => exit; when 'l' => declare L : constant String := Util.Strings.Transforms.To_Lower_Case (Parameter); begin Log.Info ("License {0}", L); if L = "apache" then Generator.Set_Project_Property ("license", "apache"); elsif L = "gpl" then Generator.Set_Project_Property ("license", "gpl"); elsif L = "proprietary" then Generator.Set_Project_Property ("license", "proprietary"); else Generator.Error ("Invalid license: {0}", L); Generator.Error ("Valid licenses: apache, gpl, proprietary"); return; end if; end; when others => null; end case; end loop; declare Name : constant String := Get_Argument; Arg2 : constant String := Get_Argument; Arg3 : constant String := Get_Argument; Dir : constant String := Generator.Get_Plugin_Directory; Path : constant String := Util.Files.Compose (Dir, Name); begin if Name'Length = 0 then Generator.Error ("Missing plugin name"); Gen.Commands.Usage; return; end if; if Ada.Directories.Exists (Path) then Generator.Error ("Plugin {0} exists already", Name); return; end if; if not Ada.Directories.Exists (Dir) then Ada.Directories.Create_Directory (Dir); end if; Ada.Directories.Create_Directory (Path); Generator.Set_Result_Directory (Path); -- Create the plugin project instance and generate its dynamo.xml file. -- The new plugin is added to the current project so that it will be referenced. declare procedure Create_Plugin (Project : in out Model.Projects.Root_Project_Definition); procedure Create_Plugin (Project : in out Model.Projects.Root_Project_Definition) is Plugin : Gen.Model.Projects.Project_Definition_Access; File : constant String := Util.Files.Compose (Path, "dynamo.xml"); begin Project.Create_Project (Name => Name, Path => File, Project => Plugin); Project.Add_Module (Plugin); Plugin.Props.Set ("license", Project.Props.Get ("license", "none")); Plugin.Props.Set ("author", Project.Props.Get ("author", "")); Plugin.Props.Set ("author_email", Project.Props.Get ("author_email", "")); Plugin.Save (File); end Create_Plugin; begin Generator.Update_Project (Create_Plugin'Access); end; -- Generate the new plugin content. Generator.Set_Force_Save (False); Gen.Generator.Generate_All (Generator, Gen.Artifacts.ITERATION_TABLE, "create-plugin"); -- And save the project dynamo.xml file which now refers to the new plugin. Generator.Set_Result_Directory (Result_Dir); Generator.Save_Project; end; end Execute; -- ------------------------------ -- Write the help associated with the command. -- ------------------------------ procedure Help (Cmd : in Command; Generator : in out Gen.Generator.Handler) is pragma Unreferenced (Cmd, Generator); use Ada.Text_IO; begin Put_Line ("create-plugin: Create a new plugin for the current project"); Put_Line ("Usage: create-plugin NAME"); New_Line; Put_Line (" Creates a new AWA plugin for the application with the name passed in NAME."); end Help; end Gen.Commands.Plugins;
----------------------------------------------------------------------- -- gen-commands-plugins -- Plugin creation and management commands for dynamo -- Copyright (C) 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Directories; with Ada.Text_IO; with Gen.Artifacts; with Gen.Model.Projects; with GNAT.Command_Line; with Util.Files; with Util.Log.Loggers; with Util.Strings.Transforms; package body Gen.Commands.Plugins is Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Gen.Commands.Project"); -- ------------------------------ -- Generator Command -- ------------------------------ -- Execute the command with the arguments. procedure Execute (Cmd : in Command; Generator : in out Gen.Generator.Handler) is pragma Unreferenced (Cmd); use GNAT.Command_Line; Result_Dir : constant String := Generator.Get_Result_Directory; begin -- If a dynamo.xml file exists, read it. if Ada.Directories.Exists ("dynamo.xml") then Generator.Read_Project ("dynamo.xml"); else Generator.Set_Project_Property ("license", "apache"); Generator.Set_Project_Property ("author", "unknown"); Generator.Set_Project_Property ("author_email", "[email protected]"); end if; -- Parse the command line loop case Getopt ("l:") is when ASCII.NUL => exit; when 'l' => declare L : constant String := Util.Strings.Transforms.To_Lower_Case (Parameter); begin Log.Info ("License {0}", L); if L = "apache" then Generator.Set_Project_Property ("license", "apache"); elsif L = "gpl" then Generator.Set_Project_Property ("license", "gpl"); elsif L = "proprietary" then Generator.Set_Project_Property ("license", "proprietary"); else Generator.Error ("Invalid license: {0}", L); Generator.Error ("Valid licenses: apache, gpl, proprietary"); return; end if; end; when others => null; end case; end loop; declare Name : constant String := Get_Argument; Kind : constant String := Get_Argument; Dir : constant String := Generator.Get_Plugin_Directory; Path : constant String := Util.Files.Compose (Dir, Name); begin if Name'Length = 0 then Generator.Error ("Missing plugin name"); Gen.Commands.Usage; return; end if; if Kind /= "ada" and Kind /= "web" and Kind /= "" then Generator.Error ("Invalid plugin type (must be 'ada' or 'web')"); return; end if; if Ada.Directories.Exists (Path) then Generator.Error ("Plugin {0} exists already", Name); return; end if; if not Ada.Directories.Exists (Dir) then Ada.Directories.Create_Directory (Dir); end if; Ada.Directories.Create_Directory (Path); Generator.Set_Result_Directory (Path); -- Create the plugin project instance and generate its dynamo.xml file. -- The new plugin is added to the current project so that it will be referenced. declare procedure Create_Plugin (Project : in out Model.Projects.Root_Project_Definition); procedure Create_Plugin (Project : in out Model.Projects.Root_Project_Definition) is Plugin : Gen.Model.Projects.Project_Definition_Access; File : constant String := Util.Files.Compose (Path, "dynamo.xml"); begin Project.Create_Project (Name => Name, Path => File, Project => Plugin); Project.Add_Module (Plugin); Plugin.Props.Set ("license", Project.Props.Get ("license", "none")); Plugin.Props.Set ("author", Project.Props.Get ("author", "")); Plugin.Props.Set ("author_email", Project.Props.Get ("author_email", "")); Plugin.Save (File); end Create_Plugin; begin Generator.Update_Project (Create_Plugin'Access); end; -- Generate the new plugin content. Generator.Set_Force_Save (False); Generator.Set_Global ("pluginName", Name); Gen.Generator.Generate_All (Generator, Gen.Artifacts.ITERATION_TABLE, "create-plugin"); if Kind /= "" then Gen.Generator.Generate_All (Generator, Gen.Artifacts.ITERATION_TABLE, "create-plugin-" & Kind); end if; -- And save the project dynamo.xml file which now refers to the new plugin. Generator.Set_Result_Directory (Result_Dir); Generator.Save_Project; end; end Execute; -- ------------------------------ -- Write the help associated with the command. -- ------------------------------ procedure Help (Cmd : in Command; Generator : in out Gen.Generator.Handler) is pragma Unreferenced (Cmd, Generator); use Ada.Text_IO; begin Put_Line ("create-plugin: Create a new plugin for the current project"); Put_Line ("Usage: create-plugin NAME"); New_Line; Put_Line (" Creates a new AWA plugin for the application with the name passed in NAME."); end Help; end Gen.Commands.Plugins;
Add an option to create-plugin to generate an Ada or a Web plugin
Add an option to create-plugin to generate an Ada or a Web plugin
Ada
apache-2.0
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
24231f5a239c66abe5410a5c129b444b557eb207
src/security-openid.ads
src/security-openid.ads
----------------------------------------------------------------------- -- security-openid -- Open ID 2.0 Support -- Copyright (C) 2009, 2010, 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Ada.Calendar; with Ada.Finalization; with Security.Permissions; -- == OpenID == -- The <b>Security.Openid</b> package implements an authentication framework based -- on OpenID 2.0. -- -- See OpenID Authentication 2.0 - Final -- http://openid.net/specs/openid-authentication-2_0.html -- -- The authentication process is the following: -- -- * The <b>Initialize</b> procedure is called to configure the OpenID realm and set the -- OpenID return callback CB. -- * 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. -- * 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. -- * The <b>Get_Authentication_URL</b> builds the provider OpenID authentication -- URL for the association. -- * The application should redirected 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. -- -- There are basically two steps that an application must implement. -- -- == Step 1: 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>. -- -- Mgr : Openid.Manager; -- OP : Openid.End_Point; -- Assoc : constant Association_Access := new Association; -- -- The -- -- Server.Initialize (Mgr); -- 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); -- -- == Step 2: verify 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. -- -- Mgr : Openid.Manager; -- Assoc : Association_Access := ...; -- Get the association saved in the session. -- Auth : Openid.Authentication; -- Params : Auth_Params; -- -- The OpenID 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. -- -- Server.Initialize (Mgr); -- Mgr.Verify (Assoc.all, Params, Auth); -- if Openid.Get_Status (Auth) /= Openid.AUTHENTICATED then ... -- Failure. -- -- -- package Security.Openid is 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; -- ------------------------------ -- OpenID provider -- ------------------------------ -- The <b>End_Point</b> represents the OpenID provider that will authenticate -- the user. type End_Point is private; function To_String (OP : End_Point) return String; -- ------------------------------ -- Association -- ------------------------------ -- The OpenID association contains the shared secret between the relying party -- and the OpenID provider. The association can be cached and reused to authenticate -- different users using the same OpenID provider. The association also has an -- expiration date. type Association is private; -- 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); -- ------------------------------ -- OpenID provider -- ------------------------------ -- 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; -- ------------------------------ -- OpenID Default principal -- ------------------------------ type Principal is new Security.Permissions.Principal with private; type Principal_Access is access all Principal'Class; -- Returns true if the given role is stored in the user principal. function Has_Role (User : in Principal; Role : in Permissions.Role_Type) return Boolean; -- 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; -- ------------------------------ -- OpenID Manager -- ------------------------------ -- The <b>Manager</b> provides the core operations for the OpenID process. type Manager is tagged limited private; -- Initialize the OpenID realm. procedure Initialize (Realm : in out Manager; Name : in String; Return_To : in String); -- Discover the OpenID 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. -- (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 OpenID 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); 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); -- Verify the authentication result procedure Verify_Discovered (Realm : in out Manager; Assoc : in Association; Request : in Parameters'Class; Result : out Authentication); -- Verify the signature part of the result procedure Verify_Signature (Realm : in Manager; Assoc : in Association; Request : in Parameters'Class; Result : in out Authentication); -- Read the XRDS document from the URI and initialize the OpenID provider end point. procedure Discover_XRDS (Realm : in out Manager; URI : in String; Result : out End_Point); -- Extract from the XRDS content the OpenID provider URI. -- The default implementation is very basic as it returns the first <URI> -- available in the stream without validating the XRDS document. -- Raises the <b>Invalid_End_Point</b> exception if the URI cannot be found. procedure Extract_XRDS (Realm : in out Manager; Content : in String; Result : out End_Point); private use Ada.Strings.Unbounded; type Association is record 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 is new Ada.Finalization.Limited_Controlled with record Realm : Unbounded_String; Return_To : Unbounded_String; end record; type Principal is new Security.Permissions.Principal with record Auth : Authentication; end record; end Security.Openid;
----------------------------------------------------------------------- -- security-openid -- Open ID 2.0 Support -- Copyright (C) 2009, 2010, 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Ada.Calendar; with Ada.Finalization; with Security.Permissions; -- == OpenID == -- The <b>Security.Openid</b> package implements an authentication framework based -- on OpenID 2.0. -- -- See OpenID Authentication 2.0 - Final -- http://openid.net/specs/openid-authentication-2_0.html -- -- The authentication process is the following: -- -- * The <b>Initialize</b> procedure is called to configure the OpenID realm and set the -- OpenID return callback CB. -- * 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. -- * 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. -- * The <b>Get_Authentication_URL</b> builds the provider OpenID authentication -- URL for the association. -- * The application should redirected 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. -- -- There are basically two steps that an application must implement. -- -- [http://ada-security.googlecode.com/svn/wiki/OpenID.png] -- -- == Step 1: 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>. -- -- Mgr : Openid.Manager; -- OP : Openid.End_Point; -- Assoc : constant Association_Access := new Association; -- -- The -- -- Server.Initialize (Mgr); -- 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); -- -- == Step 2: verify 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. -- -- Mgr : Openid.Manager; -- Assoc : Association_Access := ...; -- Get the association saved in the session. -- Auth : Openid.Authentication; -- Params : Auth_Params; -- -- The OpenID 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. -- -- Server.Initialize (Mgr); -- Mgr.Verify (Assoc.all, Params, Auth); -- if Openid.Get_Status (Auth) /= Openid.AUTHENTICATED then ... -- Failure. -- -- -- package Security.Openid is 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; -- ------------------------------ -- OpenID provider -- ------------------------------ -- The <b>End_Point</b> represents the OpenID provider that will authenticate -- the user. type End_Point is private; function To_String (OP : End_Point) return String; -- ------------------------------ -- Association -- ------------------------------ -- The OpenID association contains the shared secret between the relying party -- and the OpenID provider. The association can be cached and reused to authenticate -- different users using the same OpenID provider. The association also has an -- expiration date. type Association is private; -- 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); -- ------------------------------ -- OpenID provider -- ------------------------------ -- 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; -- ------------------------------ -- OpenID Default principal -- ------------------------------ type Principal is new Security.Permissions.Principal with private; type Principal_Access is access all Principal'Class; -- Returns true if the given role is stored in the user principal. function Has_Role (User : in Principal; Role : in Permissions.Role_Type) return Boolean; -- 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; -- ------------------------------ -- OpenID Manager -- ------------------------------ -- The <b>Manager</b> provides the core operations for the OpenID process. type Manager is tagged limited private; -- Initialize the OpenID realm. procedure Initialize (Realm : in out Manager; Name : in String; Return_To : in String); -- Discover the OpenID 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. -- (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 OpenID 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); 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); -- Verify the authentication result procedure Verify_Discovered (Realm : in out Manager; Assoc : in Association; Request : in Parameters'Class; Result : out Authentication); -- Verify the signature part of the result procedure Verify_Signature (Realm : in Manager; Assoc : in Association; Request : in Parameters'Class; Result : in out Authentication); -- Read the XRDS document from the URI and initialize the OpenID provider end point. procedure Discover_XRDS (Realm : in out Manager; URI : in String; Result : out End_Point); -- Extract from the XRDS content the OpenID provider URI. -- The default implementation is very basic as it returns the first <URI> -- available in the stream without validating the XRDS document. -- Raises the <b>Invalid_End_Point</b> exception if the URI cannot be found. procedure Extract_XRDS (Realm : in out Manager; Content : in String; Result : out End_Point); private use Ada.Strings.Unbounded; type Association is record 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 is new Ada.Finalization.Limited_Controlled with record Realm : Unbounded_String; Return_To : Unbounded_String; end record; type Principal is new Security.Permissions.Principal with record Auth : Authentication; end record; end Security.Openid;
Add picture
Add picture
Ada
apache-2.0
Letractively/ada-security
421773d1fe86bfed90a300662bb0dabf6dee33f8
regtests/util-processes-tests.adb
regtests/util-processes-tests.adb
----------------------------------------------------------------------- -- util-processes-tests - Test for processes -- Copyright (C) 2011, 2012, 2016, 2018, 2019, 2021 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Log.Loggers; with Util.Test_Caller; with Util.Files; with Util.Strings.Vectors; with Util.Streams.Pipes; with Util.Streams.Buffered; with Util.Streams.Texts; with Util.Processes.Tools; package body Util.Processes.Tests is -- The logger Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Util.Processes.Tests"); package Caller is new Util.Test_Caller (Test, "Processes"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test Util.Processes.Is_Running", Test_No_Process'Access); Caller.Add_Test (Suite, "Test Util.Processes.Spawn/Wait/Get_Exit_Status", Test_Spawn'Access); Caller.Add_Test (Suite, "Test Util.Processes.Spawn(READ pipe)", Test_Output_Pipe'Access); Caller.Add_Test (Suite, "Test Util.Processes.Spawn(WRITE pipe)", Test_Input_Pipe'Access); Caller.Add_Test (Suite, "Test Util.Processes.Spawn/Shell(WRITE pipe)", Test_Shell_Splitting_Pipe'Access); Caller.Add_Test (Suite, "Test Util.Processes.Spawn(OUTPUT redirect)", Test_Output_Redirect'Access); Caller.Add_Test (Suite, "Test Util.Processes.Spawn(INPUT redirect)", Test_Input_Redirect'Access); Caller.Add_Test (Suite, "Test Util.Processes.Spawn(CHDIR)", Test_Set_Working_Directory'Access); Caller.Add_Test (Suite, "Test Util.Streams.Pipes.Open/Read/Close (Multi spawn)", Test_Multi_Spawn'Access); Caller.Add_Test (Suite, "Test Util.Processes.Tools.Execute", Test_Tools_Execute'Access); end Add_Tests; -- ------------------------------ -- Tests when the process is not launched -- ------------------------------ procedure Test_No_Process (T : in out Test) is P : Process; begin T.Assert (not P.Is_Running, "Process should not be running"); T.Assert (P.Get_Pid < 0, "Invalid process id"); end Test_No_Process; -- ------------------------------ -- Test executing a process -- ------------------------------ procedure Test_Spawn (T : in out Test) is P : Process; begin -- Launch the test process => exit code 2 P.Spawn ("bin/util_test_process"); T.Assert (P.Is_Running, "Process is running"); P.Wait; T.Assert (not P.Is_Running, "Process has stopped"); T.Assert (P.Get_Pid > 0, "Invalid process id"); Util.Tests.Assert_Equals (T, 2, P.Get_Exit_Status, "Invalid exit status"); -- Launch the test process => exit code 0 P.Spawn ("bin/util_test_process 0 write b c d e f"); T.Assert (P.Is_Running, "Process is running"); P.Wait; T.Assert (not P.Is_Running, "Process has stopped"); T.Assert (P.Get_Pid > 0, "Invalid process id"); Util.Tests.Assert_Equals (T, 0, P.Get_Exit_Status, "Invalid exit status"); end Test_Spawn; -- ------------------------------ -- Test output pipe redirection: read the process standard output -- ------------------------------ procedure Test_Output_Pipe (T : in out Test) is P : aliased Util.Streams.Pipes.Pipe_Stream; begin P.Open ("bin/util_test_process 0 write b c d e f test_marker"); declare Buffer : Util.Streams.Buffered.Input_Buffer_Stream; Content : Ada.Strings.Unbounded.Unbounded_String; begin Buffer.Initialize (P'Unchecked_Access, 19); Buffer.Read (Content); P.Close; Util.Tests.Assert_Matches (T, "b\s+c\s+d\s+e\s+f\s+test_marker\s+", Content, "Invalid content"); end; T.Assert (not P.Is_Running, "Process has stopped"); Util.Tests.Assert_Equals (T, 0, P.Get_Exit_Status, "Invalid exit status"); end Test_Output_Pipe; -- ------------------------------ -- Test shell splitting. -- ------------------------------ procedure Test_Shell_Splitting_Pipe (T : in out Test) is P : aliased Util.Streams.Pipes.Pipe_Stream; begin P.Open ("bin/util_test_process 0 write ""b c d e f"" test_marker"); declare Buffer : Util.Streams.Buffered.Input_Buffer_Stream; Content : Ada.Strings.Unbounded.Unbounded_String; begin Buffer.Initialize (P'Unchecked_Access, 19); Buffer.Read (Content); P.Close; Util.Tests.Assert_Matches (T, "b c d e f\s+test_marker\s+", Content, "Invalid content"); end; T.Assert (not P.Is_Running, "Process has stopped"); Util.Tests.Assert_Equals (T, 0, P.Get_Exit_Status, "Invalid exit status"); end Test_Shell_Splitting_Pipe; -- ------------------------------ -- Test input pipe redirection: write the process standard input -- At the same time, read the process standard output. -- ------------------------------ procedure Test_Input_Pipe (T : in out Test) is P : aliased Util.Streams.Pipes.Pipe_Stream; begin P.Open ("bin/util_test_process 0 read -", READ_WRITE); declare Buffer : Util.Streams.Buffered.Input_Buffer_Stream; Content : Ada.Strings.Unbounded.Unbounded_String; Print : Util.Streams.Texts.Print_Stream; begin -- Write on the process input stream. Print.Initialize (P'Unchecked_Access); Print.Write ("Write test on the input pipe"); Print.Close; -- Read the output. Buffer.Initialize (P'Unchecked_Access, 19); Buffer.Read (Content); -- Wait for the process to finish. P.Close; Util.Tests.Assert_Matches (T, "Write test on the input pipe-\s", Content, "Invalid content"); end; T.Assert (not P.Is_Running, "Process has stopped"); Util.Tests.Assert_Equals (T, 0, P.Get_Exit_Status, "Invalid exit status"); end Test_Input_Pipe; -- ------------------------------ -- Test launching several processes through pipes in several threads. -- ------------------------------ procedure Test_Multi_Spawn (T : in out Test) is Task_Count : constant Natural := 8; Count_By_Task : constant Natural := 10; type State_Array is array (1 .. Task_Count) of Boolean; States : State_Array; begin declare task type Worker is entry Start (Count : in Natural); entry Result (Status : out Boolean); end Worker; task body Worker is Cnt : Natural; State : Boolean := True; begin accept Start (Count : in Natural) do Cnt := Count; end Start; declare type Pipe_Array is array (1 .. Cnt) of aliased Util.Streams.Pipes.Pipe_Stream; Pipes : Pipe_Array; begin -- Launch the processes. -- They will print their arguments on stdout, one by one on each line. -- The expected exit status is the first argument. for I in 1 .. Cnt loop Pipes (I).Open ("bin/util_test_process 0 write b c d e f test_marker"); end loop; -- Read their output for I in 1 .. Cnt loop declare Buffer : Util.Streams.Buffered.Input_Buffer_Stream; Content : Ada.Strings.Unbounded.Unbounded_String; begin Buffer.Initialize (Pipes (I)'Unchecked_Access, 19); Buffer.Read (Content); Pipes (I).Close; -- Check status and output. State := State and Pipes (I).Get_Exit_Status = 0; State := State and Ada.Strings.Unbounded.Index (Content, "test_marker") > 0; end; end loop; exception when E : others => Log.Error ("Exception raised", E); State := False; end; accept Result (Status : out Boolean) do Status := State; end Result; end Worker; type Worker_Array is array (1 .. Task_Count) of Worker; Tasks : Worker_Array; begin for I in Tasks'Range loop Tasks (I).Start (Count_By_Task); end loop; -- Get the results (do not raise any assertion here because we have to call -- 'Result' to ensure the thread terminates. for I in Tasks'Range loop Tasks (I).Result (States (I)); end loop; -- Leaving the Worker task scope means we are waiting for our tasks to finish. end; for I in States'Range loop T.Assert (States (I), "Task " & Natural'Image (I) & " failed"); end loop; end Test_Multi_Spawn; -- ------------------------------ -- Test output file redirection. -- ------------------------------ procedure Test_Output_Redirect (T : in out Test) is P : Process; Path : constant String := Util.Tests.Get_Test_Path ("proc-output.txt"); Content : Ada.Strings.Unbounded.Unbounded_String; begin Util.Processes.Set_Output_Stream (P, Path); Util.Processes.Spawn (P, "bin/util_test_process 0 write b c d e f test_marker"); Util.Processes.Wait (P); T.Assert (not P.Is_Running, "Process has stopped"); Util.Tests.Assert_Equals (T, 0, P.Get_Exit_Status, "Process failed"); Util.Files.Read_File (Path, Content); Util.Tests.Assert_Matches (T, ".*test_marker", Content, "Invalid content"); Util.Processes.Set_Output_Stream (P, Path, True); Util.Processes.Spawn (P, "bin/util_test_process 0 write appended_text"); Util.Processes.Wait (P); Content := Ada.Strings.Unbounded.Null_Unbounded_String; Util.Files.Read_File (Path, Content); Util.Tests.Assert_Matches (T, ".*appended_text", Content, "Invalid content"); Util.Tests.Assert_Matches (T, ".*test_marker.*", Content, "Invalid content"); end Test_Output_Redirect; -- ------------------------------ -- Test input file redirection. -- ------------------------------ procedure Test_Input_Redirect (T : in out Test) is P : Process; In_Path : constant String := Util.Tests.Get_Path ("regtests/files/proc-input.txt"); Exp_Path : constant String := Util.Tests.Get_Path ("regtests/expect/proc-inres.txt"); Out_Path : constant String := Util.Tests.Get_Test_Path ("proc-inres.txt"); Err_Path : constant String := Util.Tests.Get_Test_Path ("proc-errres.txt"); begin Util.Processes.Set_Input_Stream (P, In_Path); Util.Processes.Set_Output_Stream (P, Out_Path); Util.Processes.Set_Error_Stream (P, Err_Path); Util.Processes.Spawn (P, "bin/util_test_process 0 read -"); Util.Processes.Wait (P); T.Assert (not P.Is_Running, "Process has stopped"); Util.Tests.Assert_Equals (T, 0, P.Get_Exit_Status, "Process failed"); Util.Tests.Assert_Equal_Files (T => T, Expect => Exp_Path, Test => Out_Path, Message => "Process input/output redirection"); end Test_Input_Redirect; -- ------------------------------ -- Test chaning working directory. -- ------------------------------ procedure Test_Set_Working_Directory (T : in out Test) is P : Process; Dir_Path : constant String := Util.Tests.Get_Path ("regtests/files"); In_Path : constant String := Util.Tests.Get_Path ("regtests/files/proc-empty.txt"); Exp_Path : constant String := Util.Tests.Get_Path ("regtests/files/proc-input.txt"); Out_Path : constant String := Util.Tests.Get_Test_Path ("proc-cat.txt"); Err_Path : constant String := Util.Tests.Get_Test_Path ("proc-errres.txt"); begin Util.Processes.Set_Working_Directory (P, Dir_Path); Util.Processes.Set_Input_Stream (P, In_Path); Util.Processes.Set_Output_Stream (P, Out_Path); Util.Processes.Set_Error_Stream (P, Err_Path); Util.Processes.Spawn (P, "cat proc-input.txt"); Util.Processes.Wait (P); T.Assert (not P.Is_Running, "Process has stopped"); Util.Tests.Assert_Equals (T, 0, P.Get_Exit_Status, "Process failed"); Util.Tests.Assert_Equal_Files (T => T, Expect => Exp_Path, Test => Out_Path, Message => "Process input/output redirection"); end Test_Set_Working_Directory; -- ------------------------------ -- Test the Tools.Execute operation. -- ------------------------------ procedure Test_Tools_Execute (T : in out Test) is List : Util.Strings.Vectors.Vector; Status : Integer; begin Tools.Execute (Command => "bin/util_test_process 23 write ""b c d e f"" test_marker", Output => List, Status => Status); Util.Tests.Assert_Equals (T, 23, Status, "Invalid exit status"); Util.Tests.Assert_Equals (T, 2, Integer (List.Length), "Invalid output collected by Execute"); Util.Tests.Assert_Equals (T, "b c d e f", List.Element (1), ""); Util.Tests.Assert_Equals (T, "test_marker", List.Element (2), ""); end Test_Tools_Execute; end Util.Processes.Tests;
----------------------------------------------------------------------- -- util-processes-tests - Test for processes -- Copyright (C) 2011, 2012, 2016, 2018, 2019, 2021 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Log.Loggers; with Util.Test_Caller; with Util.Files; with Util.Strings.Vectors; with Util.Streams.Pipes; with Util.Streams.Buffered; with Util.Streams.Texts; with Util.Processes.Tools; package body Util.Processes.Tests is -- The logger Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Util.Processes.Tests"); package Caller is new Util.Test_Caller (Test, "Processes"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test Util.Processes.Is_Running", Test_No_Process'Access); Caller.Add_Test (Suite, "Test Util.Processes.Spawn/Wait/Get_Exit_Status", Test_Spawn'Access); Caller.Add_Test (Suite, "Test Util.Processes.Spawn(READ pipe)", Test_Output_Pipe'Access); Caller.Add_Test (Suite, "Test Util.Processes.Spawn(WRITE pipe)", Test_Input_Pipe'Access); Caller.Add_Test (Suite, "Test Util.Processes.Spawn/Shell(WRITE pipe)", Test_Shell_Splitting_Pipe'Access); Caller.Add_Test (Suite, "Test Util.Processes.Spawn(OUTPUT redirect)", Test_Output_Redirect'Access); Caller.Add_Test (Suite, "Test Util.Processes.Spawn(INPUT redirect)", Test_Input_Redirect'Access); Caller.Add_Test (Suite, "Test Util.Processes.Spawn(CHDIR)", Test_Set_Working_Directory'Access); Caller.Add_Test (Suite, "Test Util.Processes.Spawn(errors)", Test_Errors'Access); Caller.Add_Test (Suite, "Test Util.Streams.Pipes.Open/Read/Close (Multi spawn)", Test_Multi_Spawn'Access); Caller.Add_Test (Suite, "Test Util.Processes.Tools.Execute", Test_Tools_Execute'Access); end Add_Tests; -- ------------------------------ -- Tests when the process is not launched -- ------------------------------ procedure Test_No_Process (T : in out Test) is P : Process; begin T.Assert (not P.Is_Running, "Process should not be running"); T.Assert (P.Get_Pid < 0, "Invalid process id"); end Test_No_Process; -- ------------------------------ -- Test executing a process -- ------------------------------ procedure Test_Spawn (T : in out Test) is P : Process; begin -- Launch the test process => exit code 2 P.Spawn ("bin/util_test_process"); T.Assert (P.Is_Running, "Process is running"); P.Wait; T.Assert (not P.Is_Running, "Process has stopped"); T.Assert (P.Get_Pid > 0, "Invalid process id"); Util.Tests.Assert_Equals (T, 2, P.Get_Exit_Status, "Invalid exit status"); -- Launch the test process => exit code 0 P.Spawn ("bin/util_test_process 0 write b c d e f"); T.Assert (P.Is_Running, "Process is running"); P.Wait; T.Assert (not P.Is_Running, "Process has stopped"); T.Assert (P.Get_Pid > 0, "Invalid process id"); Util.Tests.Assert_Equals (T, 0, P.Get_Exit_Status, "Invalid exit status"); end Test_Spawn; -- ------------------------------ -- Test output pipe redirection: read the process standard output -- ------------------------------ procedure Test_Output_Pipe (T : in out Test) is P : aliased Util.Streams.Pipes.Pipe_Stream; begin P.Open ("bin/util_test_process 0 write b c d e f test_marker"); declare Buffer : Util.Streams.Buffered.Input_Buffer_Stream; Content : Ada.Strings.Unbounded.Unbounded_String; begin Buffer.Initialize (P'Unchecked_Access, 19); Buffer.Read (Content); P.Close; Util.Tests.Assert_Matches (T, "b\s+c\s+d\s+e\s+f\s+test_marker\s+", Content, "Invalid content"); end; T.Assert (not P.Is_Running, "Process has stopped"); Util.Tests.Assert_Equals (T, 0, P.Get_Exit_Status, "Invalid exit status"); end Test_Output_Pipe; -- ------------------------------ -- Test shell splitting. -- ------------------------------ procedure Test_Shell_Splitting_Pipe (T : in out Test) is P : aliased Util.Streams.Pipes.Pipe_Stream; begin P.Open ("bin/util_test_process 0 write ""b c d e f"" test_marker"); declare Buffer : Util.Streams.Buffered.Input_Buffer_Stream; Content : Ada.Strings.Unbounded.Unbounded_String; begin Buffer.Initialize (P'Unchecked_Access, 19); Buffer.Read (Content); P.Close; Util.Tests.Assert_Matches (T, "b c d e f\s+test_marker\s+", Content, "Invalid content"); end; T.Assert (not P.Is_Running, "Process has stopped"); Util.Tests.Assert_Equals (T, 0, P.Get_Exit_Status, "Invalid exit status"); end Test_Shell_Splitting_Pipe; -- ------------------------------ -- Test input pipe redirection: write the process standard input -- At the same time, read the process standard output. -- ------------------------------ procedure Test_Input_Pipe (T : in out Test) is P : aliased Util.Streams.Pipes.Pipe_Stream; begin P.Open ("bin/util_test_process 0 read -", READ_WRITE); declare Buffer : Util.Streams.Buffered.Input_Buffer_Stream; Content : Ada.Strings.Unbounded.Unbounded_String; Print : Util.Streams.Texts.Print_Stream; begin -- Write on the process input stream. Print.Initialize (P'Unchecked_Access); Print.Write ("Write test on the input pipe"); Print.Close; -- Read the output. Buffer.Initialize (P'Unchecked_Access, 19); Buffer.Read (Content); -- Wait for the process to finish. P.Close; Util.Tests.Assert_Matches (T, "Write test on the input pipe-\s", Content, "Invalid content"); end; T.Assert (not P.Is_Running, "Process has stopped"); Util.Tests.Assert_Equals (T, 0, P.Get_Exit_Status, "Invalid exit status"); end Test_Input_Pipe; -- ------------------------------ -- Test launching several processes through pipes in several threads. -- ------------------------------ procedure Test_Multi_Spawn (T : in out Test) is Task_Count : constant Natural := 8; Count_By_Task : constant Natural := 10; type State_Array is array (1 .. Task_Count) of Boolean; States : State_Array; begin declare task type Worker is entry Start (Count : in Natural); entry Result (Status : out Boolean); end Worker; task body Worker is Cnt : Natural; State : Boolean := True; begin accept Start (Count : in Natural) do Cnt := Count; end Start; declare type Pipe_Array is array (1 .. Cnt) of aliased Util.Streams.Pipes.Pipe_Stream; Pipes : Pipe_Array; begin -- Launch the processes. -- They will print their arguments on stdout, one by one on each line. -- The expected exit status is the first argument. for I in 1 .. Cnt loop Pipes (I).Open ("bin/util_test_process 0 write b c d e f test_marker"); end loop; -- Read their output for I in 1 .. Cnt loop declare Buffer : Util.Streams.Buffered.Input_Buffer_Stream; Content : Ada.Strings.Unbounded.Unbounded_String; begin Buffer.Initialize (Pipes (I)'Unchecked_Access, 19); Buffer.Read (Content); Pipes (I).Close; -- Check status and output. State := State and Pipes (I).Get_Exit_Status = 0; State := State and Ada.Strings.Unbounded.Index (Content, "test_marker") > 0; end; end loop; exception when E : others => Log.Error ("Exception raised", E); State := False; end; accept Result (Status : out Boolean) do Status := State; end Result; end Worker; type Worker_Array is array (1 .. Task_Count) of Worker; Tasks : Worker_Array; begin for I in Tasks'Range loop Tasks (I).Start (Count_By_Task); end loop; -- Get the results (do not raise any assertion here because we have to call -- 'Result' to ensure the thread terminates. for I in Tasks'Range loop Tasks (I).Result (States (I)); end loop; -- Leaving the Worker task scope means we are waiting for our tasks to finish. end; for I in States'Range loop T.Assert (States (I), "Task " & Natural'Image (I) & " failed"); end loop; end Test_Multi_Spawn; -- ------------------------------ -- Test output file redirection. -- ------------------------------ procedure Test_Output_Redirect (T : in out Test) is P : Process; Path : constant String := Util.Tests.Get_Test_Path ("proc-output.txt"); Content : Ada.Strings.Unbounded.Unbounded_String; begin Util.Processes.Set_Output_Stream (P, Path); Util.Processes.Spawn (P, "bin/util_test_process 0 write b c d e f test_marker"); Util.Processes.Wait (P); T.Assert (not P.Is_Running, "Process has stopped"); Util.Tests.Assert_Equals (T, 0, P.Get_Exit_Status, "Process failed"); Util.Files.Read_File (Path, Content); Util.Tests.Assert_Matches (T, ".*test_marker", Content, "Invalid content"); Util.Processes.Set_Output_Stream (P, Path, True); Util.Processes.Spawn (P, "bin/util_test_process 0 write appended_text"); Util.Processes.Wait (P); Content := Ada.Strings.Unbounded.Null_Unbounded_String; Util.Files.Read_File (Path, Content); Util.Tests.Assert_Matches (T, ".*appended_text", Content, "Invalid content"); Util.Tests.Assert_Matches (T, ".*test_marker.*", Content, "Invalid content"); end Test_Output_Redirect; -- ------------------------------ -- Test input file redirection. -- ------------------------------ procedure Test_Input_Redirect (T : in out Test) is P : Process; In_Path : constant String := Util.Tests.Get_Path ("regtests/files/proc-input.txt"); Exp_Path : constant String := Util.Tests.Get_Path ("regtests/expect/proc-inres.txt"); Out_Path : constant String := Util.Tests.Get_Test_Path ("proc-inres.txt"); Err_Path : constant String := Util.Tests.Get_Test_Path ("proc-errres.txt"); begin Util.Processes.Set_Input_Stream (P, In_Path); Util.Processes.Set_Output_Stream (P, Out_Path); Util.Processes.Set_Error_Stream (P, Err_Path); Util.Processes.Spawn (P, "bin/util_test_process 0 read -"); Util.Processes.Wait (P); T.Assert (not P.Is_Running, "Process has stopped"); Util.Tests.Assert_Equals (T, 0, P.Get_Exit_Status, "Process failed"); Util.Tests.Assert_Equal_Files (T => T, Expect => Exp_Path, Test => Out_Path, Message => "Process input/output redirection"); end Test_Input_Redirect; -- ------------------------------ -- Test changing working directory. -- ------------------------------ procedure Test_Set_Working_Directory (T : in out Test) is P : Process; Dir_Path : constant String := Util.Tests.Get_Path ("regtests/files"); In_Path : constant String := Util.Tests.Get_Path ("regtests/files/proc-empty.txt"); Exp_Path : constant String := Util.Tests.Get_Path ("regtests/files/proc-input.txt"); Out_Path : constant String := Util.Tests.Get_Test_Path ("proc-cat.txt"); Err_Path : constant String := Util.Tests.Get_Test_Path ("proc-errres.txt"); begin Util.Processes.Set_Working_Directory (P, Dir_Path); Util.Processes.Set_Input_Stream (P, In_Path); Util.Processes.Set_Output_Stream (P, Out_Path); Util.Processes.Set_Error_Stream (P, Err_Path); Util.Processes.Spawn (P, "cat proc-input.txt"); Util.Processes.Wait (P); T.Assert (not P.Is_Running, "Process has stopped"); Util.Tests.Assert_Equals (T, 0, P.Get_Exit_Status, "Process failed"); Util.Tests.Assert_Equal_Files (T => T, Expect => Exp_Path, Test => Out_Path, Message => "Process input/output redirection"); end Test_Set_Working_Directory; -- ------------------------------ -- Test various errors. -- ------------------------------ procedure Test_Errors (T : in out Test) is P : Process; begin Util.Processes.Spawn (P, "sleep 1"); begin Util.Processes.Set_Working_Directory (P, "/"); T.Fail ("Set_Working_Directory: no exception raised"); exception when Invalid_State => null; end; begin Util.Processes.Set_Input_Stream (P, "/"); T.Fail ("Set_Input_Stream: no exception raised"); exception when Invalid_State => null; end; begin Util.Processes.Set_Output_Stream (P, "/"); T.Fail ("Set_Output_Stream: no exception raised"); exception when Invalid_State => null; end; begin Util.Processes.Set_Error_Stream (P, "."); T.Fail ("Set_Error_Stream: no exception raised"); exception when Invalid_State => null; end; Util.Processes.Wait (P); T.Assert (not P.Is_Running, "Process has stopped"); Util.Tests.Assert_Equals (T, 0, P.Get_Exit_Status, "Process failed"); end Test_Errors; -- ------------------------------ -- Test the Tools.Execute operation. -- ------------------------------ procedure Test_Tools_Execute (T : in out Test) is List : Util.Strings.Vectors.Vector; Status : Integer; begin Tools.Execute (Command => "bin/util_test_process 23 write ""b c d e f"" test_marker", Output => List, Status => Status); Util.Tests.Assert_Equals (T, 23, Status, "Invalid exit status"); Util.Tests.Assert_Equals (T, 2, Integer (List.Length), "Invalid output collected by Execute"); Util.Tests.Assert_Equals (T, "b c d e f", List.Element (1), ""); Util.Tests.Assert_Equals (T, "test_marker", List.Element (2), ""); end Test_Tools_Execute; end Util.Processes.Tests;
Implement Test_Errors and register the new test for execution
Implement Test_Errors and register the new test for execution
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
04372dc77c9a81628f8339e99f22bbbb69fa86fd
src/security-permissions.ads
src/security-permissions.ads
----------------------------------------------------------------------- -- security-permissions -- Definition of permissions -- Copyright (C) 2010, 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Finalization; with Ada.Strings.Unbounded; with Ada.Containers.Hashed_Maps; with Ada.Containers.Vectors; with Util.Strings; with Util.Refs; with Util.Beans.Objects; with Util.Beans.Objects.Vectors; with Util.Serialize.IO.XML; with GNAT.Regexp; limited with Security.Controllers; limited with Security.Contexts; -- == Permissions == -- The <b>Security.Permissions</b> package defines the different permissions that can be -- checked by the access control manager. -- -- === Principal === -- The <tt>Principal</tt> is the entity that can be authenticated. A principal is obtained -- after successful authentication of a user or of a system through an authorization process. -- The OpenID or OAuth authentication processes generate such security principal. -- -- === Permission === -- The <tt>Permission</tt> represents an access to a system or application resource. -- A permission is checked by using the security manager. The security manager uses a -- security controller to enforce the permission. -- package Security.Permissions is Invalid_Name : exception; type Security_Context_Access is access all Contexts.Security_Context'Class; type Permission_Index is new Natural; type Controller_Access is access all Security.Controllers.Controller'Class; type Controller_Access_Array is array (Permission_Index range <>) of Controller_Access; -- Get the permission index associated with the name. function Get_Permission_Index (Name : in String) return Permission_Index; -- Get the last permission index registered in the global permission map. function Get_Last_Permission_Index return Permission_Index; -- Add the permission name and allocate a unique permission index. procedure Add_Permission (Name : in String; Index : out Permission_Index); -- The permission root class. type Permission is abstract tagged limited null record; -- Each permission is represented by a <b>Permission_Type</b> number to provide a fast -- and efficient permission check. type Permission_Type is new Natural range 0 .. 63; -- The <b>Permission_Map</b> represents a set of permissions which are granted to a user. -- Each permission is represented by a boolean in the map. The implementation is limited -- to 64 permissions. type Permission_Map is array (Permission_Type'Range) of Boolean; pragma Pack (Permission_Map); generic Name : String; package Permission_ACL is function Permission return Permission_Index; pragma Inline_Always (Permission); end Permission_ACL; private use Util.Strings; type Permission_Type_Array is array (1 .. 10) of Permission_Type; type Permission_Index_Array is array (Positive range <>) of Permission_Index; type Controller_Access_Array_Access is access all Controller_Access_Array; end Security.Permissions;
----------------------------------------------------------------------- -- security-permissions -- Definition of permissions -- Copyright (C) 2010, 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- -- == Permissions == -- The <b>Security.Permissions</b> package defines the different permissions that can be -- checked by the access control manager. -- -- === Principal === -- The <tt>Principal</tt> is the entity that can be authenticated. A principal is obtained -- after successful authentication of a user or of a system through an authorization process. -- The OpenID or OAuth authentication processes generate such security principal. -- -- === Permission === -- The <tt>Permission</tt> represents an access to a system or application resource. -- A permission is checked by using the security manager. The security manager uses a -- security controller to enforce the permission. -- package Security.Permissions is Invalid_Name : exception; type Permission_Index is new Natural; -- Get the permission index associated with the name. function Get_Permission_Index (Name : in String) return Permission_Index; -- Get the last permission index registered in the global permission map. function Get_Last_Permission_Index return Permission_Index; -- Add the permission name and allocate a unique permission index. procedure Add_Permission (Name : in String; Index : out Permission_Index); -- The permission root class. type Permission is abstract tagged limited null record; -- Each permission is represented by a <b>Permission_Type</b> number to provide a fast -- and efficient permission check. type Permission_Type is new Natural range 0 .. 63; -- The <b>Permission_Map</b> represents a set of permissions which are granted to a user. -- Each permission is represented by a boolean in the map. The implementation is limited -- to 64 permissions. type Permission_Map is array (Permission_Type'Range) of Boolean; pragma Pack (Permission_Map); generic Name : String; package Permission_ACL is function Permission return Permission_Index; pragma Inline_Always (Permission); end Permission_ACL; end Security.Permissions;
Remove the with clauses which are no longer necessary
Remove the with clauses which are no longer necessary
Ada
apache-2.0
stcarrez/ada-security
42668c88da89b31c8d8bac6966df8881ce2755be
src/natools-smaz_implementations-base_256.adb
src/natools-smaz_implementations-base_256.adb
------------------------------------------------------------------------------ -- Copyright (c) 2016, Natacha Porté -- -- -- -- Permission to use, copy, modify, and distribute this software for any -- -- purpose with or without fee is hereby granted, provided that the above -- -- copyright notice and this permission notice appear in all copies. -- -- -- -- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES -- -- WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -- -- MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR -- -- ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -- -- WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -- -- ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF -- -- OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -- ------------------------------------------------------------------------------ package body Natools.Smaz_Implementations.Base_256 is use type Ada.Streams.Stream_Element; use type Ada.Streams.Stream_Element_Offset; procedure Read_Code (Input : in Ada.Streams.Stream_Element_Array; Offset : in out Ada.Streams.Stream_Element_Offset; Code : out Ada.Streams.Stream_Element; Verbatim_Length : out Natural; Last_Code : in Ada.Streams.Stream_Element; Variable_Length_Verbatim : in Boolean) is Input_Byte : constant Ada.Streams.Stream_Element := Input (Offset); begin if Input_Byte <= Last_Code then Code := Input_Byte; Verbatim_Length := 0; else Code := 0; if not Variable_Length_Verbatim then Verbatim_Length := Positive (Ada.Streams.Stream_Element'Last - Input_Byte) + 1; elsif Input_Byte < Ada.Streams.Stream_Element'Last then Verbatim_Length := Positive (Ada.Streams.Stream_Element'Last - Input_Byte); else Offset := Offset + 1; Verbatim_Length := Positive (Input (Offset)) + Natural (Ada.Streams.Stream_Element'Last - Last_Code) - 1; end if; end if; Offset := Offset + 1; end Read_Code; procedure Read_Verbatim (Input : in Ada.Streams.Stream_Element_Array; Offset : in out Ada.Streams.Stream_Element_Offset; Output : out String) is begin for I in Output'Range loop Output (I) := Character'Val (Input (Offset)); Offset := Offset + 1; end loop; end Read_Verbatim; procedure Skip_Verbatim (Input : in Ada.Streams.Stream_Element_Array; Offset : in out Ada.Streams.Stream_Element_Offset; Verbatim_Length : in Positive) is pragma Unreferenced (Input); begin Offset := Offset + Ada.Streams.Stream_Element_Offset (Verbatim_Length); end Skip_Verbatim; function Verbatim_Size (Input_Length : in Positive; Last_Code : in Ada.Streams.Stream_Element; Variable_Length_Verbatim : in Boolean) return Ada.Streams.Stream_Element_Count is Verbatim1_Max_Size : constant Ada.Streams.Stream_Element_Count := Ada.Streams.Stream_Element_Count (Ada.Streams.Stream_Element'Last - Last_Code) - Boolean'Pos (Variable_Length_Verbatim); Verbatim2_Max_Size : constant Ada.Streams.Stream_Element_Count := Ada.Streams.Stream_Element_Count (Ada.Streams.Stream_Element'Last) + Verbatim1_Max_Size; Remaining : Ada.Streams.Stream_Element_Count := Ada.Streams.Stream_Element_Count (Input_Length); Overhead : Ada.Streams.Stream_Element_Count := 0; begin if Variable_Length_Verbatim then if Remaining >= Verbatim2_Max_Size then declare Full_Blocks : constant Ada.Streams.Stream_Element_Count := Remaining / Verbatim2_Max_Size; begin Overhead := Overhead + 2 * Full_Blocks; Remaining := Remaining - Verbatim2_Max_Size * Full_Blocks; end; end if; if Remaining > Verbatim1_Max_Size then Overhead := Overhead + 2; Remaining := 0; end if; end if; declare Full_Blocks : constant Ada.Streams.Stream_Element_Count := Remaining / Verbatim1_Max_Size; begin Overhead := Overhead + Full_Blocks; end; return Overhead + Ada.Streams.Stream_Element_Count (Input_Length); end Verbatim_Size; procedure Write_Code (Output : in out Ada.Streams.Stream_Element_Array; Offset : in out Ada.Streams.Stream_Element_Offset; Code : in Ada.Streams.Stream_Element) is begin Output (Offset) := Code; Offset := Offset + 1; end Write_Code; procedure Write_Verbatim (Output : in out Ada.Streams.Stream_Element_Array; Offset : in out Ada.Streams.Stream_Element_Offset; Input : in String; Last_Code : in Ada.Streams.Stream_Element; Variable_Length_Verbatim : in Boolean) is Verbatim1_Max_Size : constant Natural := Natural (Ada.Streams.Stream_Element'Last - Last_Code) - Boolean'Pos (Variable_Length_Verbatim); Verbatim2_Max_Size : constant Natural := Natural (Ada.Streams.Stream_Element'Last) + Verbatim1_Max_Size; Input_Index : Positive := Input'First; Remaining_Length, Block_Length : Positive; begin while Input_Index in Input'Range loop Remaining_Length := Input'Last - Input_Index + 1; if Variable_Length_Verbatim and then Remaining_Length > Verbatim1_Max_Size then Block_Length := Positive'Min (Remaining_Length, Verbatim2_Max_Size); Output (Offset) := Ada.Streams.Stream_Element'Last; Output (Offset + 1) := Ada.Streams.Stream_Element (Block_Length - Verbatim1_Max_Size); Offset := Offset + 2; else Block_Length := Positive'Min (Remaining_Length, Verbatim1_Max_Size); Output (Offset) := Ada.Streams.Stream_Element'Last - Ada.Streams.Stream_Element (Block_Length - 1 + Boolean'Pos (Variable_Length_Verbatim)); Offset := Offset + 1; end if; Verbatim_Copy : for I in 1 .. Block_Length loop Output (Offset) := Character'Pos (Input (Input_Index)); Offset := Offset + 1; Input_Index := Input_Index + 1; end loop Verbatim_Copy; end loop; end Write_Verbatim; end Natools.Smaz_Implementations.Base_256;
------------------------------------------------------------------------------ -- Copyright (c) 2016-2017, Natacha Porté -- -- -- -- Permission to use, copy, modify, and distribute this software for any -- -- purpose with or without fee is hereby granted, provided that the above -- -- copyright notice and this permission notice appear in all copies. -- -- -- -- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES -- -- WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -- -- MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR -- -- ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -- -- WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -- -- ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF -- -- OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -- ------------------------------------------------------------------------------ package body Natools.Smaz_Implementations.Base_256 is use type Ada.Streams.Stream_Element; use type Ada.Streams.Stream_Element_Offset; procedure Read_Code (Input : in Ada.Streams.Stream_Element_Array; Offset : in out Ada.Streams.Stream_Element_Offset; Code : out Ada.Streams.Stream_Element; Verbatim_Length : out Natural; Last_Code : in Ada.Streams.Stream_Element; Variable_Length_Verbatim : in Boolean) is Input_Byte : constant Ada.Streams.Stream_Element := Input (Offset); begin if Input_Byte <= Last_Code then Code := Input_Byte; Verbatim_Length := 0; else Code := 0; if not Variable_Length_Verbatim then Verbatim_Length := Positive (Ada.Streams.Stream_Element'Last - Input_Byte) + 1; elsif Input_Byte < Ada.Streams.Stream_Element'Last then Verbatim_Length := Positive (Ada.Streams.Stream_Element'Last - Input_Byte); else Offset := Offset + 1; Verbatim_Length := Positive (Input (Offset)) + Natural (Ada.Streams.Stream_Element'Last - Last_Code) - 1; end if; end if; Offset := Offset + 1; end Read_Code; procedure Read_Verbatim (Input : in Ada.Streams.Stream_Element_Array; Offset : in out Ada.Streams.Stream_Element_Offset; Output : out String) is begin for I in Output'Range loop Output (I) := Character'Val (Input (Offset)); Offset := Offset + 1; end loop; end Read_Verbatim; procedure Skip_Verbatim (Input : in Ada.Streams.Stream_Element_Array; Offset : in out Ada.Streams.Stream_Element_Offset; Verbatim_Length : in Positive) is pragma Unreferenced (Input); begin Offset := Offset + Ada.Streams.Stream_Element_Offset (Verbatim_Length); end Skip_Verbatim; function Verbatim_Size (Input_Length : in Positive; Last_Code : in Ada.Streams.Stream_Element; Variable_Length_Verbatim : in Boolean) return Ada.Streams.Stream_Element_Count is Verbatim1_Max_Size : constant Ada.Streams.Stream_Element_Count := Ada.Streams.Stream_Element_Count (Ada.Streams.Stream_Element'Last - Last_Code) - Boolean'Pos (Variable_Length_Verbatim); Verbatim2_Max_Size : constant Ada.Streams.Stream_Element_Count := Ada.Streams.Stream_Element_Count (Ada.Streams.Stream_Element'Last) + Verbatim1_Max_Size; Remaining : Ada.Streams.Stream_Element_Count := Ada.Streams.Stream_Element_Count (Input_Length); Overhead : Ada.Streams.Stream_Element_Count := 0; begin if Variable_Length_Verbatim then if Remaining >= Verbatim2_Max_Size then declare Full_Blocks : constant Ada.Streams.Stream_Element_Count := Remaining / Verbatim2_Max_Size; begin Overhead := Overhead + 2 * Full_Blocks; Remaining := Remaining - Verbatim2_Max_Size * Full_Blocks; end; end if; if Remaining > Verbatim1_Max_Size then Overhead := Overhead + 2; Remaining := 0; end if; end if; declare Block_Count : constant Ada.Streams.Stream_Element_Count := (Remaining + Verbatim1_Max_Size - 1) / Verbatim1_Max_Size; begin Overhead := Overhead + Block_Count; end; return Overhead + Ada.Streams.Stream_Element_Count (Input_Length); end Verbatim_Size; procedure Write_Code (Output : in out Ada.Streams.Stream_Element_Array; Offset : in out Ada.Streams.Stream_Element_Offset; Code : in Ada.Streams.Stream_Element) is begin Output (Offset) := Code; Offset := Offset + 1; end Write_Code; procedure Write_Verbatim (Output : in out Ada.Streams.Stream_Element_Array; Offset : in out Ada.Streams.Stream_Element_Offset; Input : in String; Last_Code : in Ada.Streams.Stream_Element; Variable_Length_Verbatim : in Boolean) is Verbatim1_Max_Size : constant Natural := Natural (Ada.Streams.Stream_Element'Last - Last_Code) - Boolean'Pos (Variable_Length_Verbatim); Verbatim2_Max_Size : constant Natural := Natural (Ada.Streams.Stream_Element'Last) + Verbatim1_Max_Size; Input_Index : Positive := Input'First; Remaining_Length, Block_Length : Positive; begin while Input_Index in Input'Range loop Remaining_Length := Input'Last - Input_Index + 1; if Variable_Length_Verbatim and then Remaining_Length > Verbatim1_Max_Size then Block_Length := Positive'Min (Remaining_Length, Verbatim2_Max_Size); Output (Offset) := Ada.Streams.Stream_Element'Last; Output (Offset + 1) := Ada.Streams.Stream_Element (Block_Length - Verbatim1_Max_Size); Offset := Offset + 2; else Block_Length := Positive'Min (Remaining_Length, Verbatim1_Max_Size); Output (Offset) := Ada.Streams.Stream_Element'Last - Ada.Streams.Stream_Element (Block_Length - 1 + Boolean'Pos (Variable_Length_Verbatim)); Offset := Offset + 1; end if; Verbatim_Copy : for I in 1 .. Block_Length loop Output (Offset) := Character'Pos (Input (Input_Index)); Offset := Offset + 1; Input_Index := Input_Index + 1; end loop Verbatim_Copy; end loop; end Write_Verbatim; end Natools.Smaz_Implementations.Base_256;
fix off-by-one error in Verbatim_Size
smaz_implementations-base_256: fix off-by-one error in Verbatim_Size
Ada
isc
faelys/natools
d6b4353f67d45ab45a14f806d611ddb7dd76741a
testutil/ahven/ahven-xml_runner.adb
testutil/ahven/ahven-xml_runner.adb
-- -- Copyright (c) 2007-2009 Tero Koskinen <[email protected]> -- -- Permission to use, copy, modify, and distribute this software for any -- purpose with or without fee is hereby granted, provided that the above -- copyright notice and this permission notice appear in all copies. -- -- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES -- WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -- MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR -- ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -- WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -- ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF -- OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -- with Ada.Text_IO; with Ada.Strings; with Ada.Strings.Fixed; with Ada.Strings.Maps; with Ahven.Runner; with Ahven_Compat; with Ahven.AStrings; package body Ahven.XML_Runner is use Ada.Text_IO; use Ada.Strings.Fixed; use Ada.Strings.Maps; use Ahven.Results; use Ahven.Framework; use Ahven.AStrings; function Filter_String (Str : String) return String; function Filter_String (Str : String; Map : Character_Mapping) return String; procedure Print_Test_Pass (File : File_Type; Parent_Test : String; Info : Result_Info); procedure Print_Test_Failure (File : File_Type; Parent_Test : String; Info : Result_Info); procedure Print_Test_Error (File : File_Type; Parent_Test : String; Info : Result_Info); procedure Print_Test_Case (Collection : Result_Collection; Dir : String); procedure Print_Log_File (File : File_Type; Filename : String); procedure Print_Attribute (File : File_Type; Attr : String; Value : String); procedure Start_Testcase_Tag (File : File_Type; Parent : String; Name : String; Execution_Time : String); procedure End_Testcase_Tag (File : File_Type); function Create_Name (Dir : String; Name : String) return String; function Filter_String (Str : String) return String is Result : String (Str'First .. Str'First + 6 * Str'Length); Pos : Natural := Str'First; begin for I in Str'Range loop if Str (I) = ''' then Result (Pos .. Pos + 6 - 1) := "&apos;"; Pos := Pos + 6; elsif Str (I) = '<' then Result (Pos .. Pos + 4 - 1) := "&lt;"; Pos := Pos + 4; elsif Str (I) = '>' then Result (Pos .. Pos + 4 - 1) := "&gt;"; Pos := Pos + 4; elsif Str (I) = '&' then Result (Pos .. Pos + 5 - 1) := "&amp;"; Pos := Pos + 5; elsif Str (I) = '"' then Result (Pos) := '''; Pos := Pos + 1; else Result (Pos) := Str (I); Pos := Pos + 1; end if; end loop; return Result (Result'First .. Pos - 1); end Filter_String; function Filter_String (Str : String; Map : Character_Mapping) return String is begin return Translate (Source => Str, Mapping => Map); end Filter_String; procedure Print_Attribute (File : File_Type; Attr : String; Value : String) is begin Put (File, Attr & "=" & '"' & Value & '"'); end Print_Attribute; procedure Start_Testcase_Tag (File : File_Type; Parent : String; Name : String; Execution_Time : String) is begin Put (File, "<testcase "); Print_Attribute (File, "classname", Filter_String (Parent)); Put (File, " "); Print_Attribute (File, "name", Filter_String (Name)); Put (File, " "); Print_Attribute (File, "time", Filter_String (Execution_Time)); Put_Line (File, ">"); end Start_Testcase_Tag; procedure End_Testcase_Tag (File : File_Type) is begin Put_Line (File, "</testcase>"); end End_Testcase_Tag; function Create_Name (Dir : String; Name : String) return String is function Filename (Test : String) return String is Map : Ada.Strings.Maps.Character_Mapping; begin Map := To_Mapping (From => " '/\<>:|?*()" & '"', To => "-___________" & '_'); return "TEST-" & Filter_String (Test, Map) & ".xml"; end Filename; begin if Dir'Length > 0 then return Dir & Ahven_Compat.Directory_Separator & Filename (Name); else return Filename (Name); end if; end Create_Name; procedure Print_Test_Pass (File : File_Type; Parent_Test : String; Info : Result_Info) is Exec_Time : constant String := Trim (Duration'Image (Get_Execution_Time (Info)), Ada.Strings.Both); begin Start_Testcase_Tag (File => File, Parent => Parent_Test, Name => Get_Routine_Name (Info), Execution_Time => Exec_Time); if Length (Get_Output_File (Info)) > 0 then Put (File, "<system-out>"); Print_Log_File (File, To_String (Get_Output_File (Info))); Put_Line (File, "</system-out>"); end if; End_Testcase_Tag (File); end Print_Test_Pass; procedure Print_Test_Skipped (File : File_Type; Parent_Test : String; Info : Result_Info) is Exec_Time : constant String := Trim (Duration'Image (Get_Execution_Time (Info)), Ada.Strings.Both); begin Start_Testcase_Tag (File => File, Parent => Parent_Test, Name => Get_Routine_Name (Info), Execution_Time => Exec_Time); Put (File, "<skipped "); Print_Attribute (File, "message", Filter_String (Trim (Get_Message (Info), Ada.Strings.Both))); Put (File, ">"); Put_Line (File, Filter_String (Get_Message (Info))); Put_Line (File, "</skipped>"); End_Testcase_Tag (File); end Print_Test_Skipped; procedure Print_Test_Failure (File : File_Type; Parent_Test : String; Info : Result_Info) is Exec_Time : constant String := Trim (Duration'Image (Get_Execution_Time (Info)), Ada.Strings.Both); begin Start_Testcase_Tag (File => File, Parent => Parent_Test, Name => Get_Routine_Name (Info), Execution_Time => Exec_Time); Put (File, "<failure "); Print_Attribute (File, "type", Filter_String (Trim (Get_Message (Info), Ada.Strings.Both))); Put (File, ">"); Put_Line (File, Filter_String (Get_Message (Info))); Put_Line (File, "</failure>"); if Length (Get_Output_File (Info)) > 0 then Put (File, "<system-out>"); Print_Log_File (File, To_String (Get_Output_File (Info))); Put_Line (File, "</system-out>"); end if; End_Testcase_Tag (File); end Print_Test_Failure; procedure Print_Test_Error (File : File_Type; Parent_Test : String; Info : Result_Info) is Exec_Time : constant String := Trim (Duration'Image (Get_Execution_Time (Info)), Ada.Strings.Both); begin Start_Testcase_Tag (File => File, Parent => Parent_Test, Name => Get_Routine_Name (Info), Execution_Time => Exec_Time); Put (File, "<error "); Print_Attribute (File, "type", Filter_String (Trim (Get_Message (Info), Ada.Strings.Both))); Put (File, ">"); Put_Line (File, Filter_String (Get_Message (Info))); Put_Line (File, "</error>"); if Length (Get_Output_File (Info)) > 0 then Put (File, "<system-out>"); Print_Log_File (File, To_String (Get_Output_File (Info))); Put_Line (File, "</system-out>"); end if; End_Testcase_Tag (File); end Print_Test_Error; procedure Print_Test_Case (Collection : Result_Collection; Dir : String) is procedure Print (Output : File_Type; Result : Result_Collection); -- Internal procedure to print the testcase into given file. function Img (Value : Natural) return String is begin return Trim (Natural'Image (Value), Ada.Strings.Both); end Img; procedure Print (Output : File_Type; Result : Result_Collection) is Position : Result_Info_Cursor; begin Put_Line (Output, "<?xml version=" & '"' & "1.0" & '"' & " encoding=" & '"' & "iso-8859-1" & '"' & "?>"); Put (Output, "<testsuite "); Print_Attribute (Output, "errors", Img (Error_Count (Result))); Put (Output, " "); Print_Attribute (Output, "failures", Img (Failure_Count (Result))); Put (Output, " "); Print_Attribute (Output, "skips", Img (Skipped_Count (Result))); Put (Output, " "); Print_Attribute (Output, "tests", Img (Test_Count (Result))); Put (Output, " "); Print_Attribute (Output, "time", Trim (Duration'Image (Get_Execution_Time (Result)), Ada.Strings.Both)); Put (Output, " "); Print_Attribute (Output, "name", To_String (Get_Test_Name (Result))); Put_Line (Output, ">"); Position := First_Error (Result); Error_Loop: loop exit Error_Loop when not Is_Valid (Position); Print_Test_Error (Output, To_String (Get_Test_Name (Result)), Data (Position)); Position := Next (Position); end loop Error_Loop; Position := First_Failure (Result); Failure_Loop: loop exit Failure_Loop when not Is_Valid (Position); Print_Test_Failure (Output, To_String (Get_Test_Name (Result)), Data (Position)); Position := Next (Position); end loop Failure_Loop; Position := First_Pass (Result); Pass_Loop: loop exit Pass_Loop when not Is_Valid (Position); Print_Test_Pass (Output, To_String (Get_Test_Name (Result)), Data (Position)); Position := Next (Position); end loop Pass_Loop; Position := First_Skipped (Result); Skip_Loop: loop exit Skip_Loop when not Is_Valid (Position); Print_Test_Skipped (Output, To_String (Get_Test_Name (Result)), Data (Position)); Position := Next (Position); end loop Skip_Loop; Put_Line (Output, "</testsuite>"); end Print; File : File_Type; begin if Dir = "-" then Print (Standard_Output, Collection); else Create (File => File, Mode => Ada.Text_IO.Out_File, Name => Create_Name (Dir, To_String (Get_Test_Name (Collection)))); Print (File, Collection); Ada.Text_IO.Close (File); end if; end Print_Test_Case; procedure Report_Results (Result : Result_Collection; Dir : String) is Position : Result_Collection_Cursor; begin Position := First_Child (Result); loop exit when not Is_Valid (Position); if Child_Depth (Data (Position).all) = 0 then Print_Test_Case (Data (Position).all, Dir); else Report_Results (Data (Position).all, Dir); -- Handle the test cases in this collection if Direct_Test_Count (Result) > 0 then Print_Test_Case (Result, Dir); end if; end if; Position := Next (Position); end loop; end Report_Results; -- Print the log by placing the data inside CDATA block. procedure Print_Log_File (File : File_Type; Filename : String) is type CData_End_State is (NONE, FIRST_BRACKET, SECOND_BRACKET); function State_Change (Old_State : CData_End_State) return CData_End_State; Handle : File_Type; Char : Character := ' '; First : Boolean := True; -- We need to escape ]]>, this variable tracks -- the characters, so we know when to do the escaping. CData_Ending : CData_End_State := NONE; function State_Change (Old_State : CData_End_State) return CData_End_State is New_State : CData_End_State := NONE; -- By default New_State will be NONE, so there is -- no need to set it inside when blocks. begin case Old_State is when NONE => if Char = ']' then New_State := FIRST_BRACKET; end if; when FIRST_BRACKET => if Char = ']' then New_State := SECOND_BRACKET; end if; when SECOND_BRACKET => if Char = '>' then Put (File, " "); end if; end case; return New_State; end State_Change; begin Open (Handle, In_File, Filename); loop exit when End_Of_File (Handle); Get (Handle, Char); if First then Put (File, "<![CDATA["); First := False; end if; CData_Ending := State_Change (CData_Ending); Put (File, Char); if End_Of_Line (Handle) then New_Line (File); end if; end loop; Close (Handle); if not First then Put_Line (File, "]]>"); end if; end Print_Log_File; procedure Do_Report (Test_Results : Results.Result_Collection; Args : Parameters.Parameter_Info) is begin Report_Results (Test_Results, Parameters.Result_Dir (Args)); end Do_Report; procedure Run (Suite : in out Framework.Test_Suite'Class) is begin Runner.Run_Suite (Suite, Do_Report'Access); end Run; procedure Run (Suite : Framework.Test_Suite_Access) is begin Run (Suite.all); end Run; end Ahven.XML_Runner;
-- -- Copyright (c) 2007-2009 Tero Koskinen <[email protected]> -- -- Permission to use, copy, modify, and distribute this software for any -- purpose with or without fee is hereby granted, provided that the above -- copyright notice and this permission notice appear in all copies. -- -- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES -- WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -- MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR -- ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -- WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -- ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF -- OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -- with Ada.Text_IO; with Ada.Strings; with Ada.Strings.Fixed; with Ada.Strings.Maps; with Ada.IO_Exceptions; with Ahven.Runner; with Ahven_Compat; with Ahven.AStrings; package body Ahven.XML_Runner is use Ada.Text_IO; use Ada.Strings.Fixed; use Ada.Strings.Maps; use Ahven.Results; use Ahven.Framework; use Ahven.AStrings; function Filter_String (Str : String) return String; function Filter_String (Str : String; Map : Character_Mapping) return String; procedure Print_Test_Pass (File : File_Type; Parent_Test : String; Info : Result_Info); procedure Print_Test_Failure (File : File_Type; Parent_Test : String; Info : Result_Info); procedure Print_Test_Error (File : File_Type; Parent_Test : String; Info : Result_Info); procedure Print_Test_Case (Collection : Result_Collection; Dir : String); procedure Print_Log_File (File : File_Type; Filename : String); procedure Print_Attribute (File : File_Type; Attr : String; Value : String); procedure Start_Testcase_Tag (File : File_Type; Parent : String; Name : String; Execution_Time : String); procedure End_Testcase_Tag (File : File_Type); function Create_Name (Dir : String; Name : String) return String; function Filter_String (Str : String) return String is Result : String (Str'First .. Str'First + 6 * Str'Length); Pos : Natural := Str'First; begin for I in Str'Range loop if Str (I) = ''' then Result (Pos .. Pos + 6 - 1) := "&apos;"; Pos := Pos + 6; elsif Str (I) = '<' then Result (Pos .. Pos + 4 - 1) := "&lt;"; Pos := Pos + 4; elsif Str (I) = '>' then Result (Pos .. Pos + 4 - 1) := "&gt;"; Pos := Pos + 4; elsif Str (I) = '&' then Result (Pos .. Pos + 5 - 1) := "&amp;"; Pos := Pos + 5; elsif Str (I) = '"' then Result (Pos) := '''; Pos := Pos + 1; else Result (Pos) := Str (I); Pos := Pos + 1; end if; end loop; return Result (Result'First .. Pos - 1); end Filter_String; function Filter_String (Str : String; Map : Character_Mapping) return String is begin return Translate (Source => Str, Mapping => Map); end Filter_String; procedure Print_Attribute (File : File_Type; Attr : String; Value : String) is begin Put (File, Attr & "=" & '"' & Value & '"'); end Print_Attribute; procedure Start_Testcase_Tag (File : File_Type; Parent : String; Name : String; Execution_Time : String) is begin Put (File, "<testcase "); Print_Attribute (File, "classname", Filter_String (Parent)); Put (File, " "); Print_Attribute (File, "name", Filter_String (Name)); Put (File, " "); Print_Attribute (File, "time", Filter_String (Execution_Time)); Put_Line (File, ">"); end Start_Testcase_Tag; procedure End_Testcase_Tag (File : File_Type) is begin Put_Line (File, "</testcase>"); end End_Testcase_Tag; function Create_Name (Dir : String; Name : String) return String is function Filename (Test : String) return String is Map : Ada.Strings.Maps.Character_Mapping; begin Map := To_Mapping (From => " '/\<>:|?*()" & '"', To => "-___________" & '_'); return "TEST-" & Filter_String (Test, Map) & ".xml"; end Filename; begin if Dir'Length > 0 then return Dir & Ahven_Compat.Directory_Separator & Filename (Name); else return Filename (Name); end if; end Create_Name; procedure Print_Test_Pass (File : File_Type; Parent_Test : String; Info : Result_Info) is Exec_Time : constant String := Trim (Duration'Image (Get_Execution_Time (Info)), Ada.Strings.Both); begin Start_Testcase_Tag (File => File, Parent => Parent_Test, Name => Get_Routine_Name (Info), Execution_Time => Exec_Time); if Length (Get_Output_File (Info)) > 0 then Put (File, "<system-out>"); Print_Log_File (File, To_String (Get_Output_File (Info))); Put_Line (File, "</system-out>"); end if; End_Testcase_Tag (File); end Print_Test_Pass; procedure Print_Test_Skipped (File : File_Type; Parent_Test : String; Info : Result_Info) is Exec_Time : constant String := Trim (Duration'Image (Get_Execution_Time (Info)), Ada.Strings.Both); begin Start_Testcase_Tag (File => File, Parent => Parent_Test, Name => Get_Routine_Name (Info), Execution_Time => Exec_Time); Put (File, "<skipped "); Print_Attribute (File, "message", Filter_String (Trim (Get_Message (Info), Ada.Strings.Both))); Put (File, ">"); Put_Line (File, Filter_String (Get_Message (Info))); Put_Line (File, "</skipped>"); End_Testcase_Tag (File); end Print_Test_Skipped; procedure Print_Test_Failure (File : File_Type; Parent_Test : String; Info : Result_Info) is Exec_Time : constant String := Trim (Duration'Image (Get_Execution_Time (Info)), Ada.Strings.Both); begin Start_Testcase_Tag (File => File, Parent => Parent_Test, Name => Get_Routine_Name (Info), Execution_Time => Exec_Time); Put (File, "<failure "); Print_Attribute (File, "type", Filter_String (Trim (Get_Message (Info), Ada.Strings.Both))); Put (File, ">"); Put_Line (File, Filter_String (Get_Message (Info))); Put_Line (File, "</failure>"); if Length (Get_Output_File (Info)) > 0 then Put (File, "<system-out>"); Print_Log_File (File, To_String (Get_Output_File (Info))); Put_Line (File, "</system-out>"); end if; End_Testcase_Tag (File); end Print_Test_Failure; procedure Print_Test_Error (File : File_Type; Parent_Test : String; Info : Result_Info) is Exec_Time : constant String := Trim (Duration'Image (Get_Execution_Time (Info)), Ada.Strings.Both); begin Start_Testcase_Tag (File => File, Parent => Parent_Test, Name => Get_Routine_Name (Info), Execution_Time => Exec_Time); Put (File, "<error "); Print_Attribute (File, "type", Filter_String (Trim (Get_Message (Info), Ada.Strings.Both))); Put (File, ">"); Put_Line (File, Filter_String (Get_Message (Info))); Put_Line (File, "</error>"); if Length (Get_Output_File (Info)) > 0 then Put (File, "<system-out>"); Print_Log_File (File, To_String (Get_Output_File (Info))); Put_Line (File, "</system-out>"); end if; End_Testcase_Tag (File); end Print_Test_Error; procedure Print_Test_Case (Collection : Result_Collection; Dir : String) is procedure Print (Output : File_Type; Result : Result_Collection); -- Internal procedure to print the testcase into given file. function Img (Value : Natural) return String is begin return Trim (Natural'Image (Value), Ada.Strings.Both); end Img; procedure Print (Output : File_Type; Result : Result_Collection) is Position : Result_Info_Cursor; begin Put_Line (Output, "<?xml version=" & '"' & "1.0" & '"' & " encoding=" & '"' & "iso-8859-1" & '"' & "?>"); Put (Output, "<testsuite "); Print_Attribute (Output, "errors", Img (Error_Count (Result))); Put (Output, " "); Print_Attribute (Output, "failures", Img (Failure_Count (Result))); Put (Output, " "); Print_Attribute (Output, "skips", Img (Skipped_Count (Result))); Put (Output, " "); Print_Attribute (Output, "tests", Img (Test_Count (Result))); Put (Output, " "); Print_Attribute (Output, "time", Trim (Duration'Image (Get_Execution_Time (Result)), Ada.Strings.Both)); Put (Output, " "); Print_Attribute (Output, "name", To_String (Get_Test_Name (Result))); Put_Line (Output, ">"); Position := First_Error (Result); Error_Loop: loop exit Error_Loop when not Is_Valid (Position); Print_Test_Error (Output, To_String (Get_Test_Name (Result)), Data (Position)); Position := Next (Position); end loop Error_Loop; Position := First_Failure (Result); Failure_Loop: loop exit Failure_Loop when not Is_Valid (Position); Print_Test_Failure (Output, To_String (Get_Test_Name (Result)), Data (Position)); Position := Next (Position); end loop Failure_Loop; Position := First_Pass (Result); Pass_Loop: loop exit Pass_Loop when not Is_Valid (Position); Print_Test_Pass (Output, To_String (Get_Test_Name (Result)), Data (Position)); Position := Next (Position); end loop Pass_Loop; Position := First_Skipped (Result); Skip_Loop: loop exit Skip_Loop when not Is_Valid (Position); Print_Test_Skipped (Output, To_String (Get_Test_Name (Result)), Data (Position)); Position := Next (Position); end loop Skip_Loop; Put_Line (Output, "</testsuite>"); end Print; File : File_Type; begin if Dir = "-" then Print (Standard_Output, Collection); else Create (File => File, Mode => Ada.Text_IO.Out_File, Name => Create_Name (Dir, To_String (Get_Test_Name (Collection)))); Print (File, Collection); Ada.Text_IO.Close (File); end if; end Print_Test_Case; procedure Report_Results (Result : Result_Collection; Dir : String) is Position : Result_Collection_Cursor; begin Position := First_Child (Result); loop exit when not Is_Valid (Position); if Child_Depth (Data (Position).all) = 0 then Print_Test_Case (Data (Position).all, Dir); else Report_Results (Data (Position).all, Dir); -- Handle the test cases in this collection if Direct_Test_Count (Result) > 0 then Print_Test_Case (Result, Dir); end if; end if; Position := Next (Position); end loop; end Report_Results; -- Print the log by placing the data inside CDATA block. procedure Print_Log_File (File : File_Type; Filename : String) is type CData_End_State is (NONE, FIRST_BRACKET, SECOND_BRACKET); function State_Change (Old_State : CData_End_State) return CData_End_State; Handle : File_Type; Char : Character := ' '; First : Boolean := True; -- We need to escape ]]>, this variable tracks -- the characters, so we know when to do the escaping. CData_Ending : CData_End_State := NONE; function State_Change (Old_State : CData_End_State) return CData_End_State is New_State : CData_End_State := NONE; -- By default New_State will be NONE, so there is -- no need to set it inside when blocks. begin case Old_State is when NONE => if Char = ']' then New_State := FIRST_BRACKET; end if; when FIRST_BRACKET => if Char = ']' then New_State := SECOND_BRACKET; end if; when SECOND_BRACKET => if Char = '>' then Put (File, " "); end if; end case; return New_State; end State_Change; begin Open (Handle, In_File, Filename); begin loop exit when End_Of_File (Handle); Get (Handle, Char); if First then Put (File, "<![CDATA["); First := False; end if; CData_Ending := State_Change (CData_Ending); Put (File, Char); if End_Of_Line (Handle) then New_Line (File); end if; end loop; -- The End_Error exception is sometimes raised. exception when Ada.IO_Exceptions.End_Error => null; end; Close (Handle); if not First then Put_Line (File, "]]>"); end if; end Print_Log_File; procedure Do_Report (Test_Results : Results.Result_Collection; Args : Parameters.Parameter_Info) is begin Report_Results (Test_Results, Parameters.Result_Dir (Args)); end Do_Report; procedure Run (Suite : in out Framework.Test_Suite'Class) is begin Runner.Run_Suite (Suite, Do_Report'Access); end Run; procedure Run (Suite : Framework.Test_Suite_Access) is begin Run (Suite.all); end Run; end Ahven.XML_Runner;
Handle the End_Error exception which can be raised while reading a file
Handle the End_Error exception which can be raised while reading a file
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
0d7e288f46bd95f336fe2b0a97d4e321910769fd
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 out 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 out 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; -- ------------------------------ -- 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 -- Block : Node_List_Block_Access := Doc.Nodes.Value.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; 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 out 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 out 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; end Wiki.Nodes;
Remove unused Iterate procedure
Remove unused Iterate procedure
Ada
apache-2.0
stcarrez/ada-wiki,stcarrez/ada-wiki
fbc232ecc6bcb49c488ea00547b830290c59ad71
regtests/ado-drivers-tests.ads
regtests/ado-drivers-tests.ads
----------------------------------------------------------------------- -- ado-drivers-tests -- Unit tests for database drivers -- Copyright (C) 2014, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Tests; package ADO.Drivers.Tests is procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite); type Test is new Util.Tests.Test with null record; -- Test the Initialize operation. procedure Test_Initialize (T : in out Test); -- Test the Get_Config operation. procedure Test_Get_Config (T : in out Test); -- Test the Get_Driver operation. procedure Test_Get_Driver (T : in out Test); -- Test loading some invalid database driver. procedure Test_Load_Invalid_Driver (T : in out Test); -- Test the Get_Driver_Index operation. procedure Test_Get_Driver_Index (T : in out Test); -- Test the Set_Connection procedure. procedure Test_Set_Connection (T : in out Test); -- Test the Set_Connection procedure with several error cases. procedure Test_Set_Connection_Error (T : in out Test); end ADO.Drivers.Tests;
----------------------------------------------------------------------- -- ado-drivers-tests -- Unit tests for database drivers -- Copyright (C) 2014, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Tests; package ADO.Drivers.Tests is procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite); type Test is new Util.Tests.Test with null record; -- Test the Initialize operation. procedure Test_Initialize (T : in out Test); -- Test the Get_Config operation. procedure Test_Get_Config (T : in out Test); -- Test the Get_Driver operation. procedure Test_Get_Driver (T : in out Test); -- Test loading some invalid database driver. procedure Test_Load_Invalid_Driver (T : in out Test); -- Test the Get_Driver_Index operation. procedure Test_Get_Driver_Index (T : in out Test); -- Test the Set_Connection procedure. procedure Test_Set_Connection (T : in out Test); -- Test the Set_Connection procedure with several error cases. procedure Test_Set_Connection_Error (T : in out Test); -- Test the connection operations on an empty connection. procedure Test_Empty_Connection (T : in out Test); end ADO.Drivers.Tests;
Declare Test_Empty_Connection test procedure
Declare Test_Empty_Connection test procedure
Ada
apache-2.0
stcarrez/ada-ado
e25f93a1e3e7acc592e0aaee830284c07bf840a5
src/asf-lifecycles-restore.adb
src/asf-lifecycles-restore.adb
----------------------------------------------------------------------- -- asf-lifecycles-restore -- Restore view phase -- Copyright (C) 2010, 2011, 2015, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Exceptions; with ASF.Applications.Main; with ASF.Components.Root; with ASF.Requests; with Util.Log.Loggers; package body ASF.Lifecycles.Restore is use Ada.Exceptions; use ASF.Applications; -- The logger Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("ASF.Lifecycles.Restore"); -- ------------------------------ -- Initialize the phase controller. -- ------------------------------ overriding procedure Initialize (Controller : in out Restore_Controller; Views : access ASF.Applications.Views.View_Handler'Class) is begin Controller.View_Handler := Views; end Initialize; -- ------------------------------ -- Execute the restore view phase. -- ------------------------------ overriding procedure Execute (Controller : in Restore_Controller; Context : in out ASF.Contexts.Faces.Faces_Context'Class) is use ASF.Components; Req : constant ASF.Requests.Request_Access := Context.Get_Request; Page : constant String := Context.Get_View_Name; View : Components.Root.UIViewRoot; begin Controller.View_Handler.Restore_View (Page, Context, View); Context.Set_View_Root (View); -- If the view was not found, render the response immediately. -- The missing page will be handled by the lifecycle response handler. if Components.Root.Get_Root (View) = null then Context.Render_Response; -- If this is not a postback, check for view parameters. elsif Req.Get_Method = "GET" then -- We need to process the ASF lifecycle towards the meta data component tree. -- This allows some Ada beans to be initialized from the request parameters -- and have some component actions called on the http GET (See <f:viewActions)). Components.Root.Set_Meta (View); -- If the view has no meta data, render the response immediately. if not Components.Root.Has_Meta (View) then Context.Render_Response; end if; end if; exception when E : others => Log.Error ("Error when restoring view {0}: {1}: {2}", Page, Exception_Name (E), Exception_Message (E)); raise; end Execute; end ASF.Lifecycles.Restore;
----------------------------------------------------------------------- -- asf-lifecycles-restore -- Restore view phase -- Copyright (C) 2010, 2011, 2015, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Exceptions; with ASF.Components.Root; with ASF.Requests; with Util.Log.Loggers; package body ASF.Lifecycles.Restore is use Ada.Exceptions; -- The logger Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("ASF.Lifecycles.Restore"); -- ------------------------------ -- Initialize the phase controller. -- ------------------------------ overriding procedure Initialize (Controller : in out Restore_Controller; Views : access ASF.Applications.Views.View_Handler'Class) is begin Controller.View_Handler := Views; end Initialize; -- ------------------------------ -- Execute the restore view phase. -- ------------------------------ overriding procedure Execute (Controller : in Restore_Controller; Context : in out ASF.Contexts.Faces.Faces_Context'Class) is use ASF.Components; Req : constant ASF.Requests.Request_Access := Context.Get_Request; Page : constant String := Context.Get_View_Name; View : Components.Root.UIViewRoot; begin Controller.View_Handler.Restore_View (Page, Context, View); Context.Set_View_Root (View); -- If the view was not found, render the response immediately. -- The missing page will be handled by the lifecycle response handler. if Components.Root.Get_Root (View) = null then Context.Render_Response; -- If this is not a postback, check for view parameters. elsif Req.Get_Method = "GET" then -- We need to process the ASF lifecycle towards the meta data component tree. -- This allows some Ada beans to be initialized from the request parameters -- and have some component actions called on the http GET (See <f:viewActions)). Components.Root.Set_Meta (View); -- If the view has no meta data, render the response immediately. if not Components.Root.Has_Meta (View) then Context.Render_Response; end if; end if; exception when E : others => Log.Error ("Error when restoring view {0}: {1}: {2}", Page, Exception_Name (E), Exception_Message (E)); raise; end Execute; end ASF.Lifecycles.Restore;
Remove unused with clauses
Remove unused with clauses
Ada
apache-2.0
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
613d5580e529137c5b718101edcc6061f68fcd11
src/util-serialize-mappers.adb
src/util-serialize-mappers.adb
----------------------------------------------------------------------- -- util-serialize-mappers -- Serialize objects in various formats -- 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.Strings; with Ada.Unchecked_Deallocation; package body Util.Serialize.Mappers is use Util.Log; -- The logger Log : constant Loggers.Logger := Loggers.Create ("Util.Serialize.Mappers", Util.Log.WARN_LEVEL); -- ----------------------- -- Execute the mapping operation on the object associated with the current context. -- The object is extracted from the context and the <b>Execute</b> operation is called. -- ----------------------- procedure Execute (Handler : in Mapper; Map : in Mapping'Class; Ctx : in out Util.Serialize.Contexts.Context'Class; Value : in Util.Beans.Objects.Object) is begin if Handler.Mapper /= null then Handler.Mapper.all.Execute (Map, Ctx, Value); end if; end Execute; function Is_Proxy (Controller : in Mapper) return Boolean is begin return Controller.Is_Proxy_Mapper; end Is_Proxy; -- ----------------------- -- Returns true if the mapper is a wildcard node (matches any element). -- ----------------------- function Is_Wildcard (Controller : in Mapper) return Boolean is begin return Controller.Is_Wildcard; end Is_Wildcard; -- ----------------------- -- Returns the mapping name. -- ----------------------- function Get_Name (Controller : in Mapper) return String is begin return Ada.Strings.Unbounded.To_String (Controller.Name); end Get_Name; -- ----------------------- -- Find the mapper associated with the given name. -- Returns null if there is no mapper. -- ----------------------- function Find_Mapper (Controller : in Mapper; Name : in String; Attribute : in Boolean := False) return Mapper_Access is use type Ada.Strings.Unbounded.Unbounded_String; Node : Mapper_Access := Controller.First_Child; begin if Node = null and Controller.Mapper /= null then return Controller.Mapper.Find_Mapper (Name, Attribute); end if; while Node /= null loop if Node.Is_Wildcard then declare Result : constant Mapper_Access := Node.Find_Mapper (Name, Attribute); begin if Result /= null then return Result; else return Node; end if; end; end if; if Node.Name = Name then if (Attribute = False and Node.Mapping = null) or else not Node.Mapping.Is_Attribute then return Node; end if; if Attribute and Node.Mapping.Is_Attribute then return Node; end if; end if; Node := Node.Next_Mapping; end loop; return null; end Find_Mapper; -- ----------------------- -- Find a path component representing a child mapper under <b>From</b> and -- identified by the given <b>Name</b>. If the mapper is not found, a new -- Mapper_Node is created. -- ----------------------- procedure Find_Path_Component (From : in out Mapper'Class; Name : in String; Result : out Mapper_Access) is use Ada.Strings.Unbounded; Node : Mapper_Access := From.First_Child; Previous : Mapper_Access := null; Wildcard : constant Boolean := Name = "*"; begin if Node = null then Result := new Mapper; Result.Name := To_Unbounded_String (Name); Result.Is_Wildcard := Wildcard; From.First_Child := Result; return; end if; loop if Node.Name = Name then Result := Node; return; end if; if Node.Next_Mapping = null then Result := new Mapper; Result.Name := To_Unbounded_String (Name); Result.Is_Wildcard := Wildcard; if Node.Is_Wildcard then Result.Next_Mapping := Node; if Previous = null then From.First_Child := Result; else Previous.Next_Mapping := Result; end if; else Node.Next_Mapping := Result; end if; return; end if; Previous := Node; Node := Node.Next_Mapping; end loop; end Find_Path_Component; -- ----------------------- -- Build the mapping tree that corresponds to the given <b>Path</b>. -- Each path component is represented by a <b>Mapper_Node</b> element. -- The node is created if it does not exists. -- ----------------------- procedure Build_Path (Into : in out Mapper'Class; Path : in String; Last_Pos : out Natural; Node : out Mapper_Access) is Pos : Natural; begin Node := Into'Unchecked_Access; Last_Pos := Path'First; loop Pos := Util.Strings.Index (Source => Path, Char => '/', From => Last_Pos); if Pos = 0 then Node.Find_Path_Component (Name => Path (Last_Pos .. Path'Last), Result => Node); Last_Pos := Path'Last + 1; else Node.Find_Path_Component (Name => Path (Last_Pos .. Pos - 1), Result => Node); Last_Pos := Pos + 1; end if; exit when Last_Pos > Path'Last; end loop; end Build_Path; -- ----------------------- -- Add a mapping to associate the given <b>Path</b> to the mapper defined in <b>Map</b>. -- The <b>Path</b> string describes the matching node using a simplified XPath notation. -- Example: -- info/first_name matches: <info><first_name>...</first_name></info> -- info/a/b/name matches: <info><a><b><name>...</name></b></a></info> -- */a/b/name matches: <i><i><j><a><b><name>...</name></b></a></j></i></i> -- ----------------------- procedure Add_Mapping (Into : in out Mapper; Path : in String; Map : in Mapper_Access) is procedure Copy (To : in Mapper_Access; From : in Mapper_Access); Node : Mapper_Access; Last_Pos : Natural; procedure Copy (To : in Mapper_Access; From : in Mapper_Access) is N : Mapper_Access; Src : Mapper_Access := From; begin while Src /= null loop N := Src.Clone; N.Is_Clone := True; N.Next_Mapping := To.First_Child; To.First_Child := N; if Src.First_Child /= null then Copy (N, Src.First_Child); end if; Src := Src.Next_Mapping; end loop; end Copy; begin Log.Info ("Mapping '{0}' for mapper X", Path); -- Find or build the mapping tree. Into.Build_Path (Path, Last_Pos, Node); if Last_Pos < Path'Last then Log.Warn ("Ignoring the end of mapping path {0}", Path); end if; if Node.Mapper /= null then Log.Warn ("Overriding the mapping {0} for mapper X", Path); end if; if Map.First_Child /= null then Copy (Node, Map.First_Child); else Node.Mapper := Map; end if; end Add_Mapping; procedure Add_Mapping (Into : in out Mapper; Path : in String; Map : in Mapping_Access) is use Ada.Strings.Unbounded; Node : Mapper_Access; Last_Pos : Natural; begin Log.Info ("Mapping {0}", Path); -- Find or build the mapping tree. Into.Build_Path (Path, Last_Pos, Node); if Last_Pos < Path'Last then Log.Warn ("Ignoring the end of mapping path {0}", Path); end if; if Node.Mapping /= null then Log.Warn ("Overriding the mapping {0} for mapper X", Path); end if; if Length (Node.Name) = 0 then Log.Warn ("Mapped name is empty in mapping path {0}", Path); elsif Element (Node.Name, 1) = '@' then Delete (Node.Name, 1, 1); Map.Is_Attribute := True; else Map.Is_Attribute := False; end if; Node.Mapping := Map; Node.Mapper := Into'Unchecked_Access; end Add_Mapping; -- ----------------------- -- Clone the <b>Handler</b> instance and get a copy of that single object. -- ----------------------- function Clone (Handler : in Mapper) return Mapper_Access is Result : constant Mapper_Access := new Mapper; begin Result.Name := Handler.Name; Result.Mapper := Handler.Mapper; Result.Mapping := Handler.Mapping; Result.Is_Proxy_Mapper := Handler.Is_Proxy_Mapper; Result.Is_Clone := True; Result.Is_Wildcard := Handler.Is_Wildcard; return Result; end Clone; -- ----------------------- -- Set the name/value pair on the current object. For each active mapping, -- find whether a rule matches our name and execute it. -- ----------------------- procedure Set_Member (Handler : in Mapper; Name : in String; Value : in Util.Beans.Objects.Object; Attribute : in Boolean := False; Context : in out Util.Serialize.Contexts.Context'Class) is Map : constant Mapper_Access := Mapper'Class (Handler).Find_Mapper (Name, Attribute); begin if Map /= null and then Map.Mapping /= null and then Map.Mapper /= null then Map.Mapper.all.Execute (Map.Mapping.all, Context, Value); end if; end Set_Member; procedure Start_Object (Handler : in Mapper; Context : in out Util.Serialize.Contexts.Context'Class; Name : in String) is begin if Handler.Mapper /= null then Handler.Mapper.Start_Object (Context, Name); end if; end Start_Object; procedure Finish_Object (Handler : in Mapper; Context : in out Util.Serialize.Contexts.Context'Class; Name : in String) is begin if Handler.Mapper /= null then Handler.Mapper.Finish_Object (Context, Name); end if; end Finish_Object; -- ----------------------- -- Dump the mapping tree on the logger using the INFO log level. -- ----------------------- procedure Dump (Handler : in Mapper'Class; Log : in Util.Log.Loggers.Logger'Class; Prefix : in String := "") is procedure Dump (Map : in Mapper'Class); -- ----------------------- -- Dump the mapping description -- ----------------------- procedure Dump (Map : in Mapper'Class) is begin if Map.Mapping /= null and then Map.Mapping.Is_Attribute then Log.Info (" {0}@{1}", Prefix, Ada.Strings.Unbounded.To_String (Map.Mapping.Name)); else Log.Info (" {0}/{1}", Prefix, Ada.Strings.Unbounded.To_String (Map.Name)); Dump (Map, Log, Prefix & "/" & Ada.Strings.Unbounded.To_String (Map.Name)); end if; end Dump; begin Iterate (Handler, Dump'Access); end Dump; procedure Iterate (Controller : in Mapper; Process : not null access procedure (Map : in Mapper'Class)) is Node : Mapper_Access := Controller.First_Child; begin -- Pass 1: process the attributes first while Node /= null loop if Node.Mapping /= null and then Node.Mapping.Is_Attribute then Process.all (Node.all); end if; Node := Node.Next_Mapping; end loop; -- Pass 2: process the elements Node := Controller.First_Child; while Node /= null loop if Node.Mapping = null or else not Node.Mapping.Is_Attribute then Process.all (Node.all); end if; Node := Node.Next_Mapping; end loop; end Iterate; -- ----------------------- -- Finalize the object and release any mapping. -- ----------------------- overriding procedure Finalize (Controller : in out Mapper) is procedure Free is new Ada.Unchecked_Deallocation (Mapper'Class, Mapper_Access); procedure Free is new Ada.Unchecked_Deallocation (Mapping'Class, Mapping_Access); Node : Mapper_Access := Controller.First_Child; Next : Mapper_Access; begin Controller.First_Child := null; while Node /= null loop Next := Node.Next_Mapping; Free (Node); Node := Next; end loop; if not Controller.Is_Clone then Free (Controller.Mapping); else Controller.Mapping := null; end if; end Finalize; end Util.Serialize.Mappers;
----------------------------------------------------------------------- -- util-serialize-mappers -- Serialize objects in various formats -- 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.Strings; with Ada.Unchecked_Deallocation; package body Util.Serialize.Mappers is use Util.Log; -- The logger Log : constant Loggers.Logger := Loggers.Create ("Util.Serialize.Mappers", Util.Log.WARN_LEVEL); -- ----------------------- -- Execute the mapping operation on the object associated with the current context. -- The object is extracted from the context and the <b>Execute</b> operation is called. -- ----------------------- procedure Execute (Handler : in Mapper; Map : in Mapping'Class; Ctx : in out Util.Serialize.Contexts.Context'Class; Value : in Util.Beans.Objects.Object) is begin if Handler.Mapper /= null then Handler.Mapper.all.Execute (Map, Ctx, Value); end if; end Execute; function Is_Proxy (Controller : in Mapper) return Boolean is begin return Controller.Is_Proxy_Mapper; end Is_Proxy; -- ----------------------- -- Returns true if the mapper is a wildcard node (matches any element). -- ----------------------- function Is_Wildcard (Controller : in Mapper) return Boolean is begin return Controller.Is_Wildcard; end Is_Wildcard; -- ----------------------- -- Returns the mapping name. -- ----------------------- function Get_Name (Controller : in Mapper) return String is begin return Ada.Strings.Unbounded.To_String (Controller.Name); end Get_Name; -- ----------------------- -- Find the mapper associated with the given name. -- Returns null if there is no mapper. -- ----------------------- function Find_Mapper (Controller : in Mapper; Name : in String; Attribute : in Boolean := False) return Mapper_Access is use type Ada.Strings.Unbounded.Unbounded_String; Node : Mapper_Access := Controller.First_Child; begin if Node = null and Controller.Mapper /= null then return Controller.Mapper.Find_Mapper (Name, Attribute); end if; while Node /= null loop if not Attribute and Node.Is_Wildcard then declare Result : constant Mapper_Access := Node.Find_Mapper (Name, Attribute); begin if Result /= null then return Result; else return Node; end if; end; end if; if Node.Name = Name then if (Attribute = False and Node.Mapping = null) or else not Node.Mapping.Is_Attribute then return Node; end if; if Attribute and Node.Mapping.Is_Attribute then return Node; end if; end if; Node := Node.Next_Mapping; end loop; return null; end Find_Mapper; -- ----------------------- -- Find a path component representing a child mapper under <b>From</b> and -- identified by the given <b>Name</b>. If the mapper is not found, a new -- Mapper_Node is created. -- ----------------------- procedure Find_Path_Component (From : in out Mapper'Class; Name : in String; Result : out Mapper_Access) is use Ada.Strings.Unbounded; Node : Mapper_Access := From.First_Child; Previous : Mapper_Access := null; Wildcard : constant Boolean := Name = "*"; begin if Node = null then Result := new Mapper; Result.Name := To_Unbounded_String (Name); Result.Is_Wildcard := Wildcard; From.First_Child := Result; return; end if; loop if Node.Name = Name then Result := Node; return; end if; if Node.Next_Mapping = null then Result := new Mapper; Result.Name := To_Unbounded_String (Name); Result.Is_Wildcard := Wildcard; if Node.Is_Wildcard then Result.Next_Mapping := Node; if Previous = null then From.First_Child := Result; else Previous.Next_Mapping := Result; end if; else Node.Next_Mapping := Result; end if; return; end if; Previous := Node; Node := Node.Next_Mapping; end loop; end Find_Path_Component; -- ----------------------- -- Build the mapping tree that corresponds to the given <b>Path</b>. -- Each path component is represented by a <b>Mapper_Node</b> element. -- The node is created if it does not exists. -- ----------------------- procedure Build_Path (Into : in out Mapper'Class; Path : in String; Last_Pos : out Natural; Node : out Mapper_Access) is Pos : Natural; begin Node := Into'Unchecked_Access; Last_Pos := Path'First; loop Pos := Util.Strings.Index (Source => Path, Char => '/', From => Last_Pos); if Pos = 0 then Node.Find_Path_Component (Name => Path (Last_Pos .. Path'Last), Result => Node); Last_Pos := Path'Last + 1; else Node.Find_Path_Component (Name => Path (Last_Pos .. Pos - 1), Result => Node); Last_Pos := Pos + 1; end if; exit when Last_Pos > Path'Last; end loop; end Build_Path; -- ----------------------- -- Add a mapping to associate the given <b>Path</b> to the mapper defined in <b>Map</b>. -- The <b>Path</b> string describes the matching node using a simplified XPath notation. -- Example: -- info/first_name matches: <info><first_name>...</first_name></info> -- info/a/b/name matches: <info><a><b><name>...</name></b></a></info> -- */a/b/name matches: <i><i><j><a><b><name>...</name></b></a></j></i></i> -- ----------------------- procedure Add_Mapping (Into : in out Mapper; Path : in String; Map : in Mapper_Access) is procedure Copy (To : in Mapper_Access; From : in Mapper_Access); Node : Mapper_Access; Last_Pos : Natural; procedure Copy (To : in Mapper_Access; From : in Mapper_Access) is N : Mapper_Access; Src : Mapper_Access := From; begin while Src /= null loop N := Src.Clone; N.Is_Clone := True; N.Next_Mapping := To.First_Child; To.First_Child := N; if Src.First_Child /= null then Copy (N, Src.First_Child); end if; Src := Src.Next_Mapping; end loop; end Copy; begin Log.Info ("Mapping '{0}' for mapper X", Path); -- Find or build the mapping tree. Into.Build_Path (Path, Last_Pos, Node); if Last_Pos < Path'Last then Log.Warn ("Ignoring the end of mapping path {0}", Path); end if; if Node.Mapper /= null then Log.Warn ("Overriding the mapping {0} for mapper X", Path); end if; if Map.First_Child /= null then Copy (Node, Map.First_Child); else Node.Mapper := Map; end if; end Add_Mapping; procedure Add_Mapping (Into : in out Mapper; Path : in String; Map : in Mapping_Access) is use Ada.Strings.Unbounded; Node : Mapper_Access; Last_Pos : Natural; begin Log.Info ("Mapping {0}", Path); -- Find or build the mapping tree. Into.Build_Path (Path, Last_Pos, Node); if Last_Pos < Path'Last then Log.Warn ("Ignoring the end of mapping path {0}", Path); end if; if Node.Mapping /= null then Log.Warn ("Overriding the mapping {0} for mapper X", Path); end if; if Length (Node.Name) = 0 then Log.Warn ("Mapped name is empty in mapping path {0}", Path); elsif Element (Node.Name, 1) = '@' then Delete (Node.Name, 1, 1); Map.Is_Attribute := True; else Map.Is_Attribute := False; end if; Node.Mapping := Map; Node.Mapper := Into'Unchecked_Access; end Add_Mapping; -- ----------------------- -- Clone the <b>Handler</b> instance and get a copy of that single object. -- ----------------------- function Clone (Handler : in Mapper) return Mapper_Access is Result : constant Mapper_Access := new Mapper; begin Result.Name := Handler.Name; Result.Mapper := Handler.Mapper; Result.Mapping := Handler.Mapping; Result.Is_Proxy_Mapper := Handler.Is_Proxy_Mapper; Result.Is_Clone := True; Result.Is_Wildcard := Handler.Is_Wildcard; return Result; end Clone; -- ----------------------- -- Set the name/value pair on the current object. For each active mapping, -- find whether a rule matches our name and execute it. -- ----------------------- procedure Set_Member (Handler : in Mapper; Name : in String; Value : in Util.Beans.Objects.Object; Attribute : in Boolean := False; Context : in out Util.Serialize.Contexts.Context'Class) is Map : constant Mapper_Access := Mapper'Class (Handler).Find_Mapper (Name, Attribute); begin if Map /= null and then Map.Mapping /= null and then Map.Mapper /= null then Map.Mapper.all.Execute (Map.Mapping.all, Context, Value); end if; end Set_Member; procedure Start_Object (Handler : in Mapper; Context : in out Util.Serialize.Contexts.Context'Class; Name : in String) is begin if Handler.Mapper /= null then Handler.Mapper.Start_Object (Context, Name); end if; end Start_Object; procedure Finish_Object (Handler : in Mapper; Context : in out Util.Serialize.Contexts.Context'Class; Name : in String) is begin if Handler.Mapper /= null then Handler.Mapper.Finish_Object (Context, Name); end if; end Finish_Object; -- ----------------------- -- Dump the mapping tree on the logger using the INFO log level. -- ----------------------- procedure Dump (Handler : in Mapper'Class; Log : in Util.Log.Loggers.Logger'Class; Prefix : in String := "") is procedure Dump (Map : in Mapper'Class); -- ----------------------- -- Dump the mapping description -- ----------------------- procedure Dump (Map : in Mapper'Class) is begin if Map.Mapping /= null and then Map.Mapping.Is_Attribute then Log.Info (" {0}@{1}", Prefix, Ada.Strings.Unbounded.To_String (Map.Mapping.Name)); else Log.Info (" {0}/{1}", Prefix, Ada.Strings.Unbounded.To_String (Map.Name)); Dump (Map, Log, Prefix & "/" & Ada.Strings.Unbounded.To_String (Map.Name)); end if; end Dump; begin Iterate (Handler, Dump'Access); end Dump; procedure Iterate (Controller : in Mapper; Process : not null access procedure (Map : in Mapper'Class)) is Node : Mapper_Access := Controller.First_Child; begin -- Pass 1: process the attributes first while Node /= null loop if Node.Mapping /= null and then Node.Mapping.Is_Attribute then Process.all (Node.all); end if; Node := Node.Next_Mapping; end loop; -- Pass 2: process the elements Node := Controller.First_Child; while Node /= null loop if Node.Mapping = null or else not Node.Mapping.Is_Attribute then Process.all (Node.all); end if; Node := Node.Next_Mapping; end loop; end Iterate; -- ----------------------- -- Finalize the object and release any mapping. -- ----------------------- overriding procedure Finalize (Controller : in out Mapper) is procedure Free is new Ada.Unchecked_Deallocation (Mapper'Class, Mapper_Access); procedure Free is new Ada.Unchecked_Deallocation (Mapping'Class, Mapping_Access); Node : Mapper_Access := Controller.First_Child; Next : Mapper_Access; begin Controller.First_Child := null; while Node /= null loop Next := Node.Next_Mapping; Free (Node); Node := Next; end loop; if not Controller.Is_Clone then Free (Controller.Mapping); else Controller.Mapping := null; end if; end Finalize; end Util.Serialize.Mappers;
Fix mapping of attribute when wildcard mapping is also used
Fix mapping of attribute when wildcard mapping is also used
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
aae21f2ae6347d5562a58e10be001d79ed165b9d
src/asf-applications.adb
src/asf-applications.adb
----------------------------------------------------------------------- -- applications -- Ada Web Application -- Copyright (C) 2009, 2010 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Properties.Basic; package body ASF.Applications is -- ------------------------------ -- Get the configuration parameter; -- ------------------------------ function Get (Self : Config; Param : Config_Param) return String is begin return Self.Get (Param.Name.all, Param.Default.all); end Get; -- ------------------------------ -- Get the configuration parameter; -- ------------------------------ function Get (Self : Config; Param : Config_Param) return Boolean is use Util.Properties.Basic.Boolean_Property; begin return Get (Self, Param.Name.all, Boolean'Value (Param.Default.all)); end Get; end ASF.Applications;
----------------------------------------------------------------------- -- applications -- Ada Web Application -- Copyright (C) 2009, 2010, 2013 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Properties.Basic; package body ASF.Applications is -- ------------------------------ -- Get the configuration parameter; -- ------------------------------ function Get (Self : Config; Param : Config_Param) return String is begin return Self.Get (Param.Name.all, Param.Default.all); end Get; -- ------------------------------ -- Get the configuration parameter; -- ------------------------------ function Get (Self : Config; Param : Config_Param) return Boolean is use Util.Properties.Basic.Boolean_Property; begin return Get (Self, Param.Name.all, Boolean'Value (Param.Default.all)); end Get; -- ------------------------------ -- Create the configuration parameter definition instance. -- ------------------------------ package body Parameter is Param : constant Config_Param := ASF.Applications.P '(Name => PARAM_NAME'Access, Default => PARAM_VALUE'Access); -- ------------------------------ -- Returns the configuration parameter. -- ------------------------------ function P return Config_Param is begin return Param; end P; end Parameter; end ASF.Applications;
Implement the Parameter generic package
Implement the Parameter generic package
Ada
apache-2.0
Letractively/ada-asf,Letractively/ada-asf,Letractively/ada-asf
c90ea2fd686bf821cadd30695e76fece7679e182
src/ado-sessions-sources.adb
src/ado-sessions-sources.adb
----------------------------------------------------------------------- -- ADO Databases -- Database Connections -- Copyright (C) 2010, 2011, 2012, 2013, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Log; with Util.Log.Loggers; package body ADO.Sessions.Sources is use ADO.Drivers; use type ADO.Drivers.Connections.Database_Connection_Access; Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("ADO.Databases"); -- ------------------------------ -- Set the master data source -- ------------------------------ procedure Set_Master (Controller : in out Replicated_DataSource; Master : in Data_Source_Access) is begin Controller.Master := Master; end Set_Master; -- ------------------------------ -- Get the master data source -- ------------------------------ function Get_Master (Controller : in Replicated_DataSource) return Data_Source_Access is begin return Controller.Master; end Get_Master; -- ------------------------------ -- Set the slave data source -- ------------------------------ procedure Set_Slave (Controller : in out Replicated_DataSource; Slave : in Data_Source_Access) is begin Controller.Slave := Slave; end Set_Slave; -- ------------------------------ -- Get the slave data source -- ------------------------------ function Get_Slave (Controller : in Replicated_DataSource) return Data_Source_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.Sessions.Sources;
----------------------------------------------------------------------- -- ADO Databases -- Database Connections -- Copyright (C) 2010, 2011, 2012, 2013, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- package body ADO.Sessions.Sources is use ADO.Drivers; use type ADO.Drivers.Connections.Database_Connection_Access; -- ------------------------------ -- Set the master data source -- ------------------------------ procedure Set_Master (Controller : in out Replicated_DataSource; Master : in Data_Source_Access) is begin Controller.Master := Master; end Set_Master; -- ------------------------------ -- Get the master data source -- ------------------------------ function Get_Master (Controller : in Replicated_DataSource) return Data_Source_Access is begin return Controller.Master; end Get_Master; -- ------------------------------ -- Set the slave data source -- ------------------------------ procedure Set_Slave (Controller : in out Replicated_DataSource; Slave : in Data_Source_Access) is begin Controller.Slave := Slave; end Set_Slave; -- ------------------------------ -- Get the slave data source -- ------------------------------ function Get_Slave (Controller : in Replicated_DataSource) return Data_Source_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.Sessions.Sources;
Fix compilation warning detected by GNAT 2017
Fix compilation warning detected by GNAT 2017
Ada
apache-2.0
stcarrez/ada-ado
fb0435a114cd726aa6207025e957ee0fcc8d9dd8
src/el-expressions-nodes.ads
src/el-expressions-nodes.ads
----------------------------------------------------------------------- -- EL.Expressions -- Expression Nodes -- Copyright (C) 2009, 2010 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- -- The 'ELNode' describes an expression that can later be evaluated -- on an expression context. Expressions are parsed and translated -- to a read-only tree. with EL.Functions; with Ada.Strings.Wide_Wide_Unbounded; with Ada.Strings.Unbounded; with Util.Concurrent.Counters; private package EL.Expressions.Nodes is use EL.Functions; use Ada.Strings.Wide_Wide_Unbounded; use Ada.Strings.Unbounded; type Reduction; type ELNode is abstract tagged limited record Ref_Counter : Util.Concurrent.Counters.Counter; end record; type ELNode_Access is access all ELNode'Class; type Reduction is record Node : ELNode_Access; Value : EL.Objects.Object; end record; -- Evaluate a node on a given context. function Get_Value (Expr : ELNode; Context : ELContext'Class) return Object is abstract; -- Reduce the expression by eliminating variables which are known -- and computing constant expressions. Returns either a new expression -- tree or a constant value. function Reduce (Expr : ELNode; Context : ELContext'Class) return Reduction is abstract; -- Delete the expression tree (calls Delete (ELNode_Access) recursively). procedure Delete (Node : in out ELNode) is abstract; -- Delete the expression tree. Free the memory allocated by nodes -- of the expression tree. Clears the node pointer. procedure Delete (Node : in out ELNode_Access); -- ------------------------------ -- Unary expression node -- ------------------------------ type ELUnary is new ELNode with private; type Unary_Node is (EL_VOID, EL_NOT, EL_MINUS, EL_EMPTY); -- Evaluate a node on a given context. overriding function Get_Value (Expr : ELUnary; Context : ELContext'Class) return Object; -- Reduce the expression by eliminating variables which are known -- and computing constant expressions. Returns either a new expression -- tree or a constant value. overriding function Reduce (Expr : ELUnary; Context : ELContext'Class) return Reduction; overriding procedure Delete (Node : in out ELUnary); -- ------------------------------ -- Binary expression node -- ------------------------------ type ELBinary is new ELNode with private; type Binary_Node is (EL_EQ, EL_NE, EL_LE, EL_LT, EL_GE, EL_GT, EL_ADD, EL_SUB, EL_MUL, EL_DIV, EL_MOD, EL_AND, EL_OR, EL_LAND, EL_LOR, EL_CONCAT); -- Evaluate a node on a given context. overriding function Get_Value (Expr : ELBinary; Context : ELContext'Class) return Object; -- Reduce the expression by eliminating variables which are known -- and computing constant expressions. Returns either a new expression -- tree or a constant value. overriding function Reduce (Expr : ELBinary; Context : ELContext'Class) return Reduction; overriding procedure Delete (Node : in out ELBinary); -- ------------------------------ -- Ternary expression node -- ------------------------------ type ELTernary is new ELNode with private; -- Evaluate a node on a given context. overriding function Get_Value (Expr : ELTernary; Context : ELContext'Class) return Object; -- Reduce the expression by eliminating variables which are known -- and computing constant expressions. Returns either a new expression -- tree or a constant value. overriding function Reduce (Expr : ELTernary; Context : ELContext'Class) return Reduction; overriding procedure Delete (Node : in out ELTernary); -- ------------------------------ -- Variable to be looked at in the expression context -- ------------------------------ type ELVariable is new ELNode with private; -- Evaluate a node on a given context. overriding function Get_Value (Expr : ELVariable; Context : ELContext'Class) return Object; -- Reduce the expression by eliminating variables which are known -- and computing constant expressions. Returns either a new expression -- tree or a constant value. overriding function Reduce (Expr : ELVariable; Context : ELContext'Class) return Reduction; overriding procedure Delete (Node : in out ELVariable); -- ------------------------------ -- Value property referring to a variable -- ------------------------------ type ELValue is new ELNode with private; type ELValue_Access is access all ELValue'Class; -- Evaluate the node and return a method info with -- the bean object and the method binding. function Get_Method_Info (Node : in ELValue; Context : in ELContext'Class) return Method_Info; -- Evaluate a node on a given context. overriding function Get_Value (Expr : ELValue; Context : ELContext'Class) return Object; -- Reduce the expression by eliminating variables which are known -- and computing constant expressions. Returns either a new expression -- tree or a constant value. overriding function Reduce (Expr : ELValue; Context : ELContext'Class) return Reduction; overriding procedure Delete (Node : in out ELValue); -- ------------------------------ -- Literal object (integer, boolean, float, string) -- ------------------------------ type ELObject is new ELNode with private; -- Evaluate a node on a given context. overriding function Get_Value (Expr : ELObject; Context : ELContext'Class) return Object; -- Reduce the expression by eliminating variables which are known -- and computing constant expressions. Returns either a new expression -- tree or a constant value. overriding function Reduce (Expr : ELObject; Context : ELContext'Class) return Reduction; overriding procedure Delete (Node : in out ELObject); -- ------------------------------ -- Function call with up to 4 arguments -- ------------------------------ type ELFunction is new ELNode with private; -- Evaluate a node on a given context. overriding function Get_Value (Expr : ELFunction; Context : ELContext'Class) return Object; -- Reduce the expression by eliminating variables which are known -- and computing constant expressions. Returns either a new expression -- tree or a constant value. overriding function Reduce (Expr : ELFunction; Context : ELContext'Class) return Reduction; overriding procedure Delete (Node : in out ELFunction); -- Create constant nodes function Create_Node (Value : Boolean) return ELNode_Access; function Create_Node (Value : Long_Long_Integer) return ELNode_Access; function Create_Node (Value : String) return ELNode_Access; function Create_Node (Value : Wide_Wide_String) return ELNode_Access; function Create_Node (Value : Long_Float) return ELNode_Access; function Create_Node (Value : Unbounded_Wide_Wide_String) return ELNode_Access; function Create_Variable (Name : Unbounded_String) return ELNode_Access; function Create_Value (Variable : ELNode_Access; Name : Unbounded_String) return ELNode_Access; -- Create unary expressions function Create_Node (Of_Type : Unary_Node; Expr : ELNode_Access) return ELNode_Access; -- Create binary expressions function Create_Node (Of_Type : Binary_Node; Left : ELNode_Access; Right : ELNode_Access) return ELNode_Access; -- Create a ternary expression. function Create_Node (Cond : ELNode_Access; Left : ELNode_Access; Right : ELNode_Access) return ELNode_Access; -- Create a function call function Create_Node (Func : EL.Functions.Function_Access; Arg1 : ELNode_Access) return ELNode_Access; -- Create a function call function Create_Node (Func : EL.Functions.Function_Access; Arg1 : ELNode_Access; Arg2 : ELNode_Access) return ELNode_Access; -- Create a function call function Create_Node (Func : EL.Functions.Function_Access; Arg1 : ELNode_Access; Arg2 : ELNode_Access; Arg3 : ELNode_Access) return ELNode_Access; -- Create a function call function Create_Node (Func : EL.Functions.Function_Access; Arg1 : ELNode_Access; Arg2 : ELNode_Access; Arg3 : ELNode_Access; Arg4 : ELNode_Access) return ELNode_Access; private type ELUnary is new ELNode with record Kind : Unary_Node; Node : ELNode_Access; end record; -- ------------------------------ -- Binary nodes -- ------------------------------ type ELBinary is new ELNode with record Kind : Binary_Node; Left : ELNode_Access; Right : ELNode_Access; end record; -- ------------------------------ -- Ternary expression -- ------------------------------ type ELTernary is new ELNode with record Cond : ELNode_Access; Left : ELNode_Access; Right : ELNode_Access; end record; -- #{bean.name} - Bean name, Bean property -- #{bean[12]} - Bean name, -- Variable to be looked at in the expression context type ELVariable is new ELNode with record Name : Unbounded_String; end record; type ELValue is new ELNode with record Name : Unbounded_String; Variable : ELNode_Access; end record; -- A literal object (integer, boolean, float, String) type ELObject is new ELNode with record Value : Object; end record; -- A function call with up to 4 arguments. type ELFunction is new ELNode with record Func : EL.Functions.Function_Access; Arg1 : ELNode_Access; Arg2 : ELNode_Access; Arg3 : ELNode_Access; Arg4 : ELNode_Access; end record; end EL.Expressions.Nodes;
----------------------------------------------------------------------- -- EL.Expressions -- Expression Nodes -- Copyright (C) 2009, 2010 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- -- The 'ELNode' describes an expression that can later be evaluated -- on an expression context. Expressions are parsed and translated -- to a read-only tree. with EL.Functions; with Ada.Strings.Wide_Wide_Unbounded; with Ada.Strings.Unbounded; with Util.Concurrent.Counters; private package EL.Expressions.Nodes is use EL.Functions; use Ada.Strings.Wide_Wide_Unbounded; use Ada.Strings.Unbounded; type Reduction; type ELNode is abstract tagged limited record Ref_Counter : Util.Concurrent.Counters.Counter; end record; type ELNode_Access is access all ELNode'Class; type Reduction is record Node : ELNode_Access; Value : EL.Objects.Object; end record; -- Evaluate a node on a given context. function Get_Value (Expr : ELNode; Context : ELContext'Class) return Object is abstract; -- Reduce the expression by eliminating variables which are known -- and computing constant expressions. Returns either a new expression -- tree or a constant value. function Reduce (Expr : ELNode; Context : ELContext'Class) return Reduction is abstract; -- Delete the expression tree (calls Delete (ELNode_Access) recursively). procedure Delete (Node : in out ELNode) is abstract; -- Delete the expression tree. Free the memory allocated by nodes -- of the expression tree. Clears the node pointer. procedure Delete (Node : in out ELNode_Access); -- ------------------------------ -- Unary expression node -- ------------------------------ type ELUnary is new ELNode with private; type Unary_Node is (EL_VOID, EL_NOT, EL_MINUS, EL_EMPTY); -- Evaluate a node on a given context. overriding function Get_Value (Expr : ELUnary; Context : ELContext'Class) return Object; -- Reduce the expression by eliminating variables which are known -- and computing constant expressions. Returns either a new expression -- tree or a constant value. overriding function Reduce (Expr : ELUnary; Context : ELContext'Class) return Reduction; overriding procedure Delete (Node : in out ELUnary); -- ------------------------------ -- Binary expression node -- ------------------------------ type ELBinary is new ELNode with private; type Binary_Node is (EL_EQ, EL_NE, EL_LE, EL_LT, EL_GE, EL_GT, EL_ADD, EL_SUB, EL_MUL, EL_DIV, EL_MOD, EL_AND, EL_OR, EL_LAND, EL_LOR, EL_CONCAT); -- Evaluate a node on a given context. overriding function Get_Value (Expr : ELBinary; Context : ELContext'Class) return Object; -- Reduce the expression by eliminating variables which are known -- and computing constant expressions. Returns either a new expression -- tree or a constant value. overriding function Reduce (Expr : ELBinary; Context : ELContext'Class) return Reduction; overriding procedure Delete (Node : in out ELBinary); -- ------------------------------ -- Ternary expression node -- ------------------------------ type ELTernary is new ELNode with private; -- Evaluate a node on a given context. overriding function Get_Value (Expr : ELTernary; Context : ELContext'Class) return Object; -- Reduce the expression by eliminating variables which are known -- and computing constant expressions. Returns either a new expression -- tree or a constant value. overriding function Reduce (Expr : ELTernary; Context : ELContext'Class) return Reduction; overriding procedure Delete (Node : in out ELTernary); -- ------------------------------ -- Variable to be looked at in the expression context -- ------------------------------ type ELVariable is new ELNode with private; -- Evaluate a node on a given context. overriding function Get_Value (Expr : ELVariable; Context : ELContext'Class) return Object; -- Reduce the expression by eliminating variables which are known -- and computing constant expressions. Returns either a new expression -- tree or a constant value. overriding function Reduce (Expr : ELVariable; Context : ELContext'Class) return Reduction; overriding procedure Delete (Node : in out ELVariable); -- ------------------------------ -- Value property referring to a variable -- ------------------------------ type ELValue is new ELNode with private; type ELValue_Access is access all ELValue'Class; -- Evaluate the node and return a method info with -- the bean object and the method binding. function Get_Method_Info (Node : in ELValue; Context : in ELContext'Class) return Method_Info; -- Evaluate a node on a given context. overriding function Get_Value (Expr : ELValue; Context : ELContext'Class) return Object; -- Reduce the expression by eliminating variables which are known -- and computing constant expressions. Returns either a new expression -- tree or a constant value. overriding function Reduce (Expr : ELValue; Context : ELContext'Class) return Reduction; overriding procedure Delete (Node : in out ELValue); -- ------------------------------ -- Literal object (integer, boolean, float, string) -- ------------------------------ type ELObject is new ELNode with private; -- Evaluate a node on a given context. overriding function Get_Value (Expr : ELObject; Context : ELContext'Class) return Object; -- Reduce the expression by eliminating variables which are known -- and computing constant expressions. Returns either a new expression -- tree or a constant value. overriding function Reduce (Expr : ELObject; Context : ELContext'Class) return Reduction; overriding procedure Delete (Node : in out ELObject); -- ------------------------------ -- Function call with up to 4 arguments -- ------------------------------ type ELFunction is new ELNode with private; -- Evaluate a node on a given context. overriding function Get_Value (Expr : ELFunction; Context : ELContext'Class) return Object; -- Reduce the expression by eliminating variables which are known -- and computing constant expressions. Returns either a new expression -- tree or a constant value. overriding function Reduce (Expr : ELFunction; Context : ELContext'Class) return Reduction; overriding procedure Delete (Node : in out ELFunction); -- Create constant nodes function Create_Node (Value : Boolean) return ELNode_Access; function Create_Node (Value : Long_Long_Integer) return ELNode_Access; function Create_Node (Value : String) return ELNode_Access; function Create_Node (Value : Wide_Wide_String) return ELNode_Access; function Create_Node (Value : Long_Float) return ELNode_Access; function Create_Node (Value : Unbounded_Wide_Wide_String) return ELNode_Access; function Create_Variable (Name : Unbounded_String) return ELNode_Access; function Create_Value (Variable : ELNode_Access; Name : Unbounded_String) return ELNode_Access; -- Create unary expressions function Create_Node (Of_Type : Unary_Node; Expr : ELNode_Access) return ELNode_Access; -- Create binary expressions function Create_Node (Of_Type : Binary_Node; Left : ELNode_Access; Right : ELNode_Access) return ELNode_Access; -- Create a ternary expression. function Create_Node (Cond : ELNode_Access; Left : ELNode_Access; Right : ELNode_Access) return ELNode_Access; -- Create a function call function Create_Node (Func : EL.Functions.Function_Access; Arg1 : ELNode_Access) return ELNode_Access; -- Create a function call function Create_Node (Func : EL.Functions.Function_Access; Arg1 : ELNode_Access; Arg2 : ELNode_Access) return ELNode_Access; -- Create a function call function Create_Node (Func : EL.Functions.Function_Access; Arg1 : ELNode_Access; Arg2 : ELNode_Access; Arg3 : ELNode_Access) return ELNode_Access; -- Create a function call function Create_Node (Func : EL.Functions.Function_Access; Arg1 : ELNode_Access; Arg2 : ELNode_Access; Arg3 : ELNode_Access; Arg4 : ELNode_Access) return ELNode_Access; private type ELUnary is new ELNode with record Kind : Unary_Node; Node : ELNode_Access; end record; -- ------------------------------ -- Binary nodes -- ------------------------------ type ELBinary is new ELNode with record Kind : Binary_Node; Left : ELNode_Access; Right : ELNode_Access; end record; -- ------------------------------ -- Ternary expression -- ------------------------------ type ELTernary is new ELNode with record Cond : ELNode_Access; Left : ELNode_Access; Right : ELNode_Access; end record; -- #{bean.name} - Bean name, Bean property -- #{bean[12]} - Bean name, -- Variable to be looked at in the expression context type ELVariable is new ELNode with record Name : Unbounded_String; end record; type ELValue is new ELNode with record Name : Unbounded_String; Variable : ELNode_Access; end record; -- A literal object (integer, boolean, float, String) type ELObject is new ELNode with record Value : Object; end record; -- A function call with up to 4 arguments. type ELFunction is new ELNode with record Func : EL.Functions.Function_Access; Arg1 : ELNode_Access; Arg2 : ELNode_Access; Arg3 : ELNode_Access; Arg4 : ELNode_Access; end record; end EL.Expressions.Nodes;
Fix indentation
Fix indentation
Ada
apache-2.0
Letractively/ada-el
e97730b03d320d3a3cac0b49a75b767c430ca202
src/security-controllers.ads
src/security-controllers.ads
----------------------------------------------------------------------- -- security-controllers -- Controllers to verify a security permission -- Copyright (C) 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Security.Contexts; -- == Security Controller == -- The <b>Security.Controllers</b> package defines the security controller used to -- verify that a given permission is granted. A security controller uses the security -- context and other controller specific and internal data to verify that the permission -- is granted. -- -- To implement a new security controller, one must: -- -- * Define a type that implements the <b>Controller</b> interface with the -- <b>Has_Permission</b> operation -- * Write a function to allocate instances of the given <b>Controller</b> type -- * Register the function under a unique name by using <b>Register_Controller</b> -- -- Security controller instances are created when the security policy rules are parsed. -- These instances are shared across possibly several concurrent requests. package Security.Controllers is Invalid_Controller : exception; -- ------------------------------ -- Security Controller interface -- ------------------------------ type Controller is limited interface; type Controller_Access is access all Controller'Class; -- Checks whether the permission defined by the <b>Handler</b> controller data is granted -- by the security context passed in <b>Context</b>. -- Returns true if such permission is granted. function Has_Permission (Handler : in Controller; Context : in Security.Contexts.Security_Context'Class) return Boolean is abstract; type Controller_Factory is not null access function return Controller_Access; -- To keep this implementation simple, a maximum of 32 security controller factory -- can be registered. ASF provides one based on roles. AWA provides another one -- based on entity ACLs. MAX_CONTROLLER_FACTORY : constant Positive := 32; -- Register in a global table the controller factory under the name <b>Name</b>. -- When this factory is used, the <b>Factory</b> operation will be called to -- create new instances of the controller. procedure Register_Controller (Name : in String; Factory : in Controller_Factory); -- Create a security controller by using the controller factory registered under -- the name <b>Name</b>. -- Raises <b>Invalid_Controller</b> if the name is not recognized. function Create_Controller (Name : in String) return Controller_Access; end Security.Controllers;
----------------------------------------------------------------------- -- security-controllers -- Controllers to verify a security permission -- Copyright (C) 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Security.Contexts; -- == Security Controller == -- The <b>Security.Controllers</b> package defines the security controller used to -- verify that a given permission is granted. A security controller uses the security -- context and other controller specific and internal data to verify that the permission -- is granted. -- -- To implement a new security controller, one must: -- -- * Define a type that implements the <b>Controller</b> interface with the -- <b>Has_Permission</b> operation -- * Write a function to allocate instances of the given <b>Controller</b> type -- * Register the function under a unique name by using <b>Register_Controller</b> -- -- Security controller instances are created when the security policy rules are parsed. -- These instances are shared across possibly several concurrent requests. package Security.Controllers is Invalid_Controller : exception; -- ------------------------------ -- Security Controller interface -- ------------------------------ type Controller is limited interface; type Controller_Access is access all Controller'Class; -- Checks whether the permission defined by the <b>Handler</b> controller data is granted -- by the security context passed in <b>Context</b>. -- Returns true if such permission is granted. function Has_Permission (Handler : in Controller; Context : in Security.Contexts.Security_Context'Class; Permission : in Security.Permissions.Permission'Class) return Boolean is abstract; type Controller_Factory is not null access function return Controller_Access; -- To keep this implementation simple, a maximum of 32 security controller factory -- can be registered. ASF provides one based on roles. AWA provides another one -- based on entity ACLs. MAX_CONTROLLER_FACTORY : constant Positive := 32; -- Register in a global table the controller factory under the name <b>Name</b>. -- When this factory is used, the <b>Factory</b> operation will be called to -- create new instances of the controller. procedure Register_Controller (Name : in String; Factory : in Controller_Factory); -- Create a security controller by using the controller factory registered under -- the name <b>Name</b>. -- Raises <b>Invalid_Controller</b> if the name is not recognized. function Create_Controller (Name : in String) return Controller_Access; end Security.Controllers;
Add the permission to the Has_Permission function so that some permissions could specify a resource (ie, File_Permission, URL_Permission, ...)
Add the permission to the Has_Permission function so that some permissions could specify a resource (ie, File_Permission, URL_Permission, ...)
Ada
apache-2.0
stcarrez/ada-security
03fb8477bcd925a9de2328836d352bd13a1b7d5d
src/security-permissions.ads
src/security-permissions.ads
----------------------------------------------------------------------- -- security-permissions -- Definition of permissions -- Copyright (C) 2010, 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- -- == Permissions == -- The <b>Security.Permissions</b> package defines the different permissions that can be -- checked by the access control manager. -- -- === Principal === -- The <tt>Principal</tt> is the entity that can be authenticated. A principal is obtained -- after successful authentication of a user or of a system through an authorization process. -- The OpenID or OAuth authentication processes generate such security principal. -- -- === Permission === -- The <tt>Permission</tt> represents an access to a system or application resource. -- A permission is checked by using the security manager. The security manager uses a -- security controller to enforce the permission. -- package Security.Permissions is Invalid_Name : exception; type Permission_Index is new Natural; -- Get the permission index associated with the name. function Get_Permission_Index (Name : in String) return Permission_Index; -- Get the last permission index registered in the global permission map. function Get_Last_Permission_Index return Permission_Index; -- Add the permission name and allocate a unique permission index. procedure Add_Permission (Name : in String; Index : out Permission_Index); -- The permission root class. type Permission is abstract tagged limited null record; -- Each permission is represented by a <b>Permission_Type</b> number to provide a fast -- and efficient permission check. type Permission_Type is new Natural range 0 .. 63; -- The <b>Permission_Map</b> represents a set of permissions which are granted to a user. -- Each permission is represented by a boolean in the map. The implementation is limited -- to 64 permissions. type Permission_Map is array (Permission_Type'Range) of Boolean; pragma Pack (Permission_Map); generic Name : String; package Permission_ACL is function Permission return Permission_Index; pragma Inline_Always (Permission); end Permission_ACL; end Security.Permissions;
----------------------------------------------------------------------- -- security-permissions -- Definition of permissions -- Copyright (C) 2010, 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- -- == Permissions == -- The <b>Security.Permissions</b> package defines the different permissions that can be -- checked by the access control manager. -- -- package Security.Permissions is Invalid_Name : exception; type Permission_Index is new Natural; -- Get the permission index associated with the name. function Get_Permission_Index (Name : in String) return Permission_Index; -- Get the last permission index registered in the global permission map. function Get_Last_Permission_Index return Permission_Index; -- Add the permission name and allocate a unique permission index. procedure Add_Permission (Name : in String; Index : out Permission_Index); -- The permission root class. type Permission is abstract tagged limited null record; -- Each permission is represented by a <b>Permission_Type</b> number to provide a fast -- and efficient permission check. type Permission_Type is new Natural range 0 .. 63; -- The <b>Permission_Map</b> represents a set of permissions which are granted to a user. -- Each permission is represented by a boolean in the map. The implementation is limited -- to 64 permissions. type Permission_Map is array (Permission_Type'Range) of Boolean; pragma Pack (Permission_Map); generic Name : String; package Permission_ACL is function Permission return Permission_Index; pragma Inline_Always (Permission); end Permission_ACL; end Security.Permissions;
Move the documentation in Security package
Move the documentation in Security package
Ada
apache-2.0
Letractively/ada-security
aa351a892646b8f9ceb33925d2a742698e82fde2
src/security-permissions.ads
src/security-permissions.ads
----------------------------------------------------------------------- -- security-permissions -- Definition of permissions -- Copyright (C) 2010, 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- -- The <b>Security.Permissions</b> package defines the different permissions that can be -- checked by the access control manager. package Security.Permissions is Invalid_Name : exception; type Permission_Index is new Natural; -- Get the permission index associated with the name. function Get_Permission_Index (Name : in String) return Permission_Index; -- Get the last permission index registered in the global permission map. function Get_Last_Permission_Index return Permission_Index; -- Add the permission name and allocate a unique permission index. procedure Add_Permission (Name : in String; Index : out Permission_Index); -- The permission root class. type Permission (Id : Permission_Index) is abstract tagged limited null record; -- Each permission is represented by a <b>Permission_Type</b> number to provide a fast -- and efficient permission check. type Permission_Type is new Natural range 0 .. 63; -- The <b>Permission_Map</b> represents a set of permissions which are granted to a user. -- Each permission is represented by a boolean in the map. The implementation is limited -- to 64 permissions. type Permission_Map is array (Permission_Type'Range) of Boolean; pragma Pack (Permission_Map); generic Name : String; package Permission_ACL is function Permission return Permission_Index; pragma Inline_Always (Permission); end Permission_ACL; end Security.Permissions;
----------------------------------------------------------------------- -- security-permissions -- Definition of permissions -- Copyright (C) 2010, 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- -- The <b>Security.Permissions</b> package defines the different permissions that can be -- checked by the access control manager. package Security.Permissions is Invalid_Name : exception; type Permission_Index is new Natural; -- Get the permission index associated with the name. function Get_Permission_Index (Name : in String) return Permission_Index; -- Get the last permission index registered in the global permission map. function Get_Last_Permission_Index return Permission_Index; -- Add the permission name and allocate a unique permission index. procedure Add_Permission (Name : in String; Index : out Permission_Index); -- The permission root class. type Permission (Id : Permission_Index) is tagged limited null record; -- Each permission is represented by a <b>Permission_Type</b> number to provide a fast -- and efficient permission check. type Permission_Type is new Natural range 0 .. 63; -- The <b>Permission_Map</b> represents a set of permissions which are granted to a user. -- Each permission is represented by a boolean in the map. The implementation is limited -- to 64 permissions. type Permission_Map is array (Permission_Type'Range) of Boolean; pragma Pack (Permission_Map); generic Name : String; package Permission_ACL is function Permission return Permission_Index; pragma Inline_Always (Permission); end Permission_ACL; end Security.Permissions;
Make the Permission type not abstract
Make the Permission type not abstract
Ada
apache-2.0
Letractively/ada-security
ac01fc4ff360e7529dac64126da1c76713b825a9
src/wiki-render-text.adb
src/wiki-render-text.adb
----------------------------------------------------------------------- -- wiki-render-text -- Wiki Text renderer -- Copyright (C) 2011, 2012, 2013, 2015, 2016, 2018, 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 Wiki.Helpers; with Util.Strings; package body Wiki.Render.Text is -- ------------------------------ -- Set the output writer. -- ------------------------------ procedure Set_Output_Stream (Engine : in out Text_Renderer; Stream : in Streams.Output_Stream_Access) is begin Engine.Output := Stream; end Set_Output_Stream; -- ------------------------------ -- Set the no-newline mode to produce a single line text (disabled by default). -- ------------------------------ procedure Set_No_Newline (Engine : in out Text_Renderer; Enable : in Boolean) is begin Engine.No_Newline := Enable; end Set_No_Newline; -- ------------------------------ -- Emit a new line. -- ------------------------------ procedure New_Line (Document : in out Text_Renderer) is begin if not Document.No_Newline then Document.Output.Write (Wiki.Helpers.LF); end if; Document.Empty_Line := True; end New_Line; -- ------------------------------ -- Add a line break (<br>). -- ------------------------------ procedure Add_Line_Break (Document : in out Text_Renderer) is begin if not Document.No_Newline then Document.Output.Write (Wiki.Helpers.LF); end if; Document.Empty_Line := True; Document.Current_Indent := 0; end Add_Line_Break; -- ------------------------------ -- Render a blockquote (<blockquote>). The level indicates the blockquote nested level. -- The blockquote must be closed at the next header. -- ------------------------------ procedure Render_Blockquote (Engine : in out Text_Renderer; Level : in Natural) is begin Engine.Close_Paragraph; for I in 1 .. Level loop Engine.Output.Write (" "); end loop; end Render_Blockquote; procedure Render_List_Start (Engine : in out Text_Renderer; Tag : in String; Level : in Natural) is begin if not Engine.Empty_Line then Engine.Add_Line_Break; end if; Engine.Need_Paragraph := False; Engine.Open_Paragraph; if not Engine.No_Newline then Engine.Output.Write (Wiki.Helpers.LF); end if; Engine.List_Index := Engine.List_Index + 1; Engine.List_Levels (Engine.List_Index) := Level; Engine.Indent_Level := Engine.Indent_Level + 2; end Render_List_Start; procedure Render_List_End (Engine : in out Text_Renderer; Tag : in String) is begin if not Engine.Empty_Line then Engine.Add_Line_Break; end if; Engine.Need_Paragraph := False; Engine.Open_Paragraph; Engine.List_Index := Engine.List_Index - 1; Engine.Indent_Level := Engine.Indent_Level - 2; end Render_List_End; -- ------------------------------ -- Render a list item (<li>). Close the previous paragraph and list item if any. -- The list item will be closed at the next list item, next paragraph or next header. -- ------------------------------ procedure Render_List_Item_Start (Engine : in out Text_Renderer) is begin if not Engine.Empty_Line then Engine.Add_Line_Break; end if; Engine.Need_Paragraph := False; Engine.Open_Paragraph; if Engine.List_Levels (Engine.List_Index) > 0 then Engine.Render_Paragraph (Strings.To_Wstring (Util.Strings.Image (Engine.List_Levels (Engine.List_Index)))); Engine.List_Levels (Engine.List_Index) := Engine.List_Levels (Engine.List_index) + 1; Engine.Render_Paragraph (") "); Engine.Indent_Level := Engine.Indent_Level + 4; else Engine.Render_Paragraph ("- "); Engine.Indent_Level := Engine.Indent_Level + 2; end if; end Render_List_Item_Start; procedure Render_List_Item_End (Engine : in out Text_Renderer) is begin if not Engine.Empty_Line then Engine.Add_Line_Break; end if; Engine.Need_Paragraph := False; Engine.Open_Paragraph; if Engine.List_Levels (Engine.List_Index) > 0 then Engine.Indent_Level := Engine.Indent_Level - 4; else Engine.Indent_Level := Engine.Indent_Level - 2; end if; end Render_List_Item_End; procedure Close_Paragraph (Document : in out Text_Renderer) is begin if Document.Has_Paragraph then Document.Add_Line_Break; end if; Document.Has_Paragraph := False; end Close_Paragraph; procedure Open_Paragraph (Document : in out Text_Renderer) is begin if Document.Need_Paragraph then Document.Has_Paragraph := True; Document.Need_Paragraph := False; end if; end Open_Paragraph; -- ------------------------------ -- Render a link. -- ------------------------------ procedure Render_Link (Engine : in out Text_Renderer; Title : in Wiki.Strings.WString; Attr : in Wiki.Attributes.Attribute_List) is Href : constant Wiki.Strings.WString := Wiki.Attributes.Get_Attribute (Attr, "href"); begin Engine.Open_Paragraph; if Title'Length /= 0 then Engine.Output.Write (Title); end if; if Title /= Href and Href'Length /= 0 then if Title'Length /= 0 then Engine.Output.Write (" ("); end if; Engine.Output.Write (Href); if Title'Length /= 0 then Engine.Output.Write (")"); end if; end if; Engine.Empty_Line := False; end Render_Link; -- ------------------------------ -- Render an image. -- ------------------------------ procedure Render_Image (Engine : in out Text_Renderer; Title : in Wiki.Strings.WString; Attr : in Wiki.Attributes.Attribute_List) is Desc : constant Wiki.Strings.WString := Wiki.Attributes.Get_Attribute (Attr, "longdesc"); begin Engine.Open_Paragraph; if Title'Length > 0 then Engine.Output.Write (Title); end if; if Title'Length > 0 and Desc'Length > 0 then Engine.Output.Write (' '); end if; if Desc'Length > 0 then Engine.Output.Write (Desc); end if; Engine.Empty_Line := False; end Render_Image; -- ------------------------------ -- Render a text block that is pre-formatted. -- ------------------------------ procedure Render_Preformatted (Engine : in out Text_Renderer; Text : in Wiki.Strings.WString; Format : in Wiki.Strings.WString) is pragma Unreferenced (Format); begin Engine.Close_Paragraph; Engine.Output.Write (Text); Engine.Empty_Line := False; end Render_Preformatted; -- ------------------------------ -- Render a text block indenting the text if necessary. -- ------------------------------ procedure Render_Paragraph (Engine : in out Text_Renderer; Text : in Wiki.Strings.WString) is begin for C of Text loop if C = Helpers.LF then Engine.Empty_Line := True; Engine.Current_Indent := 0; Engine.Output.Write (C); else while Engine.Current_Indent < Engine.Indent_Level loop Engine.Output.Write (' '); Engine.Current_Indent := Engine.Current_Indent + 1; end loop; Engine.Output.Write (C); Engine.Empty_Line := False; Engine.Current_Indent := Engine.Current_Indent + 1; Engine.Has_Paragraph := True; end if; end loop; end Render_Paragraph; -- Render the node instance from the document. overriding procedure Render (Engine : in out Text_Renderer; Doc : in Wiki.Documents.Document; Node : in Wiki.Nodes.Node_Type) is use type Wiki.Nodes.Node_List_Access; begin case Node.Kind is when Wiki.Nodes.N_HEADER => Engine.Close_Paragraph; if not Engine.Empty_Line then Engine.Add_Line_Break; end if; Engine.Output.Write (Node.Header); Engine.Add_Line_Break; when Wiki.Nodes.N_LINE_BREAK => Engine.Add_Line_Break; when Wiki.Nodes.N_HORIZONTAL_RULE => Engine.Close_Paragraph; Engine.Output.Write ("---------------------------------------------------------"); Engine.Add_Line_Break; when Wiki.Nodes.N_PARAGRAPH => Engine.Close_Paragraph; Engine.Need_Paragraph := True; Engine.Add_Line_Break; when Wiki.Nodes.N_NEWLINE => if not Engine.No_Newline then Engine.Output.Write (Wiki.Helpers.LF); else Engine.Output.Write (' '); end if; when Wiki.Nodes.N_INDENT => Engine.Indent_Level := Node.Level; when Wiki.Nodes.N_BLOCKQUOTE => Engine.Render_Blockquote (Node.Level); when Wiki.Nodes.N_LIST_START => Engine.Render_List_Start ("o", 0); when Wiki.Nodes.N_NUM_LIST_START => Engine.Render_List_Start (".", Node.Level); when Wiki.Nodes.N_LIST_END => Engine.Render_List_End (""); when Wiki.Nodes.N_NUM_LIST_END => Engine.Render_List_End (""); when Wiki.Nodes.N_LIST_ITEM => Engine.Render_List_Item_Start; when Wiki.Nodes.N_LIST_ITEM_END => Engine.Render_List_Item_End; when Wiki.Nodes.N_TEXT => Engine.Render_Paragraph (Node.Text); when Wiki.Nodes.N_QUOTE => Engine.Open_Paragraph; Engine.Output.Write (Node.Title); Engine.Empty_Line := False; when Wiki.Nodes.N_LINK => Engine.Render_Link (Node.Title, Node.Link_Attr); when Wiki.Nodes.N_IMAGE => Engine.Render_Image (Node.Title, Node.Link_Attr); when Wiki.Nodes.N_PREFORMAT => Engine.Render_Preformatted (Node.Preformatted, ""); when Wiki.Nodes.N_TAG_START => if Node.Children /= null then if Node.Tag_Start = Wiki.DT_TAG then Engine.Close_Paragraph; Engine.Indent_Level := 0; Engine.Render (Doc, Node.Children); Engine.Close_Paragraph; Engine.Indent_Level := 0; elsif Node.Tag_Start = Wiki.DD_TAG then Engine.Close_Paragraph; Engine.Empty_Line := True; Engine.Indent_Level := 4; Engine.Render (Doc, Node.Children); Engine.Close_Paragraph; Engine.Indent_Level := 0; else Engine.Render (Doc, Node.Children); if Node.Tag_Start = Wiki.DL_TAG then Engine.Close_Paragraph; Engine.New_Line; end if; end if; end if; when others => null; end case; end Render; -- ------------------------------ -- Finish the document after complete wiki text has been parsed. -- ------------------------------ overriding procedure Finish (Engine : in out Text_Renderer; Doc : in Wiki.Documents.Document) is pragma Unreferenced (Doc); begin Engine.Close_Paragraph; end Finish; end Wiki.Render.Text;
----------------------------------------------------------------------- -- wiki-render-text -- Wiki Text renderer -- Copyright (C) 2011, 2012, 2013, 2015, 2016, 2018, 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 Wiki.Helpers; with Util.Strings; package body Wiki.Render.Text is -- ------------------------------ -- Set the output writer. -- ------------------------------ procedure Set_Output_Stream (Engine : in out Text_Renderer; Stream : in Streams.Output_Stream_Access) is begin Engine.Output := Stream; end Set_Output_Stream; -- ------------------------------ -- Set the no-newline mode to produce a single line text (disabled by default). -- ------------------------------ procedure Set_No_Newline (Engine : in out Text_Renderer; Enable : in Boolean) is begin Engine.No_Newline := Enable; end Set_No_Newline; -- ------------------------------ -- Emit a new line. -- ------------------------------ procedure New_Line (Document : in out Text_Renderer) is begin if not Document.No_Newline then Document.Output.Write (Wiki.Helpers.LF); end if; Document.Empty_Line := True; end New_Line; -- ------------------------------ -- Add a line break (<br>). -- ------------------------------ procedure Add_Line_Break (Document : in out Text_Renderer) is begin if not Document.No_Newline then Document.Output.Write (Wiki.Helpers.LF); end if; Document.Empty_Line := True; Document.Current_Indent := 0; end Add_Line_Break; -- ------------------------------ -- Render a blockquote (<blockquote>). The level indicates the blockquote nested level. -- The blockquote must be closed at the next header. -- ------------------------------ procedure Render_Blockquote (Engine : in out Text_Renderer; Level : in Natural) is begin Engine.Close_Paragraph; for I in 1 .. Level loop Engine.Output.Write (" "); end loop; end Render_Blockquote; procedure Render_List_Start (Engine : in out Text_Renderer; Tag : in String; Level : in Natural) is begin if not Engine.Empty_Line then Engine.Add_Line_Break; end if; Engine.Need_Paragraph := False; Engine.Open_Paragraph; if not Engine.No_Newline then Engine.Output.Write (Wiki.Helpers.LF); end if; Engine.List_Index := Engine.List_Index + 1; Engine.List_Levels (Engine.List_Index) := Level; Engine.Indent_Level := Engine.Indent_Level + 2; end Render_List_Start; procedure Render_List_End (Engine : in out Text_Renderer; Tag : in String) is begin if not Engine.Empty_Line then Engine.Add_Line_Break; end if; Engine.Need_Paragraph := False; Engine.Open_Paragraph; Engine.List_Index := Engine.List_Index - 1; Engine.Indent_Level := Engine.Indent_Level - 2; end Render_List_End; -- ------------------------------ -- Render a list item (<li>). Close the previous paragraph and list item if any. -- The list item will be closed at the next list item, next paragraph or next header. -- ------------------------------ procedure Render_List_Item_Start (Engine : in out Text_Renderer) is begin if not Engine.Empty_Line then Engine.Add_Line_Break; end if; Engine.Need_Paragraph := False; Engine.Open_Paragraph; if Engine.List_Levels (Engine.List_Index) > 0 then Engine.Render_Paragraph (Strings.To_Wstring (Util.Strings.Image (Engine.List_Levels (Engine.List_Index)))); Engine.List_Levels (Engine.List_Index) := Engine.List_Levels (Engine.List_index) + 1; Engine.Render_Paragraph (") "); Engine.Indent_Level := Engine.Indent_Level + 4; else Engine.Render_Paragraph ("- "); Engine.Indent_Level := Engine.Indent_Level + 2; end if; end Render_List_Item_Start; procedure Render_List_Item_End (Engine : in out Text_Renderer) is begin if not Engine.Empty_Line then Engine.Add_Line_Break; end if; Engine.Need_Paragraph := False; Engine.Open_Paragraph; if Engine.List_Levels (Engine.List_Index) > 0 then Engine.Indent_Level := Engine.Indent_Level - 4; else Engine.Indent_Level := Engine.Indent_Level - 2; end if; end Render_List_Item_End; procedure Close_Paragraph (Document : in out Text_Renderer) is begin if Document.Has_Paragraph then Document.Add_Line_Break; end if; Document.Has_Paragraph := False; end Close_Paragraph; procedure Open_Paragraph (Document : in out Text_Renderer) is begin if Document.Need_Paragraph then Document.Has_Paragraph := True; Document.Need_Paragraph := False; end if; end Open_Paragraph; -- ------------------------------ -- Render a link. -- ------------------------------ procedure Render_Link (Engine : in out Text_Renderer; Title : in Wiki.Strings.WString; Attr : in Wiki.Attributes.Attribute_List) is Href : constant Wiki.Strings.WString := Wiki.Attributes.Get_Attribute (Attr, "href"); begin Engine.Open_Paragraph; if Title'Length /= 0 then Engine.Output.Write (Title); end if; if Title /= Href and Href'Length /= 0 then if Title'Length /= 0 then Engine.Output.Write (" ("); end if; Engine.Output.Write (Href); if Title'Length /= 0 then Engine.Output.Write (")"); end if; end if; Engine.Empty_Line := False; end Render_Link; -- ------------------------------ -- Render an image. -- ------------------------------ procedure Render_Image (Engine : in out Text_Renderer; Title : in Wiki.Strings.WString; Attr : in Wiki.Attributes.Attribute_List) is Desc : constant Wiki.Strings.WString := Wiki.Attributes.Get_Attribute (Attr, "longdesc"); begin Engine.Open_Paragraph; if Title'Length > 0 then Engine.Output.Write (Title); end if; if Title'Length > 0 and Desc'Length > 0 then Engine.Output.Write (' '); end if; if Desc'Length > 0 then Engine.Output.Write (Desc); end if; Engine.Empty_Line := False; end Render_Image; -- ------------------------------ -- Render a text block that is pre-formatted. -- ------------------------------ procedure Render_Preformatted (Engine : in out Text_Renderer; Text : in Wiki.Strings.WString; Format : in Wiki.Strings.WString) is pragma Unreferenced (Format); begin Engine.Close_Paragraph; Engine.Output.Write (Text); Engine.Empty_Line := False; end Render_Preformatted; -- ------------------------------ -- Render a text block indenting the text if necessary. -- ------------------------------ procedure Render_Paragraph (Engine : in out Text_Renderer; Text : in Wiki.Strings.WString) is begin for C of Text loop if C = Helpers.LF then Engine.Empty_Line := True; Engine.Current_Indent := 0; Engine.Output.Write (C); else while Engine.Current_Indent < Engine.Indent_Level loop Engine.Output.Write (' '); Engine.Current_Indent := Engine.Current_Indent + 1; end loop; Engine.Output.Write (C); Engine.Empty_Line := False; Engine.Current_Indent := Engine.Current_Indent + 1; Engine.Has_Paragraph := True; end if; end loop; end Render_Paragraph; -- Render the node instance from the document. overriding procedure Render (Engine : in out Text_Renderer; Doc : in Wiki.Documents.Document; Node : in Wiki.Nodes.Node_Type) is use type Wiki.Nodes.Node_List_Access; begin case Node.Kind is when Wiki.Nodes.N_HEADER => Engine.Close_Paragraph; if not Engine.Empty_Line then Engine.Add_Line_Break; end if; Engine.Render (Doc, Node.Content); Engine.Add_Line_Break; when Wiki.Nodes.N_LINE_BREAK => Engine.Add_Line_Break; when Wiki.Nodes.N_HORIZONTAL_RULE => Engine.Close_Paragraph; Engine.Output.Write ("---------------------------------------------------------"); Engine.Add_Line_Break; when Wiki.Nodes.N_PARAGRAPH => Engine.Close_Paragraph; Engine.Need_Paragraph := True; Engine.Add_Line_Break; when Wiki.Nodes.N_NEWLINE => if not Engine.No_Newline then Engine.Output.Write (Wiki.Helpers.LF); else Engine.Output.Write (' '); end if; when Wiki.Nodes.N_INDENT => Engine.Indent_Level := Node.Level; when Wiki.Nodes.N_BLOCKQUOTE => Engine.Render_Blockquote (Node.Level); when Wiki.Nodes.N_LIST_START => Engine.Render_List_Start ("o", 0); when Wiki.Nodes.N_NUM_LIST_START => Engine.Render_List_Start (".", Node.Level); when Wiki.Nodes.N_LIST_END => Engine.Render_List_End (""); when Wiki.Nodes.N_NUM_LIST_END => Engine.Render_List_End (""); when Wiki.Nodes.N_LIST_ITEM => Engine.Render_List_Item_Start; when Wiki.Nodes.N_LIST_ITEM_END => Engine.Render_List_Item_End; when Wiki.Nodes.N_TEXT => Engine.Render_Paragraph (Node.Text); when Wiki.Nodes.N_QUOTE => Engine.Open_Paragraph; Engine.Output.Write (Node.Title); Engine.Empty_Line := False; when Wiki.Nodes.N_LINK => Engine.Render_Link (Node.Title, Node.Link_Attr); when Wiki.Nodes.N_IMAGE => Engine.Render_Image (Node.Title, Node.Link_Attr); when Wiki.Nodes.N_PREFORMAT => Engine.Render_Preformatted (Node.Preformatted, ""); when Wiki.Nodes.N_TAG_START => if Node.Children /= null then if Node.Tag_Start = Wiki.DT_TAG then Engine.Close_Paragraph; Engine.Indent_Level := 0; Engine.Render (Doc, Node.Children); Engine.Close_Paragraph; Engine.Indent_Level := 0; elsif Node.Tag_Start = Wiki.DD_TAG then Engine.Close_Paragraph; Engine.Empty_Line := True; Engine.Indent_Level := 4; Engine.Render (Doc, Node.Children); Engine.Close_Paragraph; Engine.Indent_Level := 0; else Engine.Render (Doc, Node.Children); if Node.Tag_Start = Wiki.DL_TAG then Engine.Close_Paragraph; Engine.New_Line; end if; end if; end if; when others => null; end case; end Render; -- ------------------------------ -- Finish the document after complete wiki text has been parsed. -- ------------------------------ overriding procedure Finish (Engine : in out Text_Renderer; Doc : in Wiki.Documents.Document) is pragma Unreferenced (Doc); begin Engine.Close_Paragraph; end Finish; end Wiki.Render.Text;
Update rendering of header content
Update rendering of header content
Ada
apache-2.0
stcarrez/ada-wiki,stcarrez/ada-wiki
f062dfa32d0057f1efc3bd61bf38e6f30ae472f3
src/sys/serialize/util-serialize-io-json.ads
src/sys/serialize/util-serialize-io-json.ads
----------------------------------------------------------------------- -- util-serialize-io-json -- JSON Serialization Driver -- Copyright (C) 2010, 2011, 2012, 2016, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Ada.Streams; with Util.Streams.Texts; with Util.Stacks; with Util.Beans.Objects; package Util.Serialize.IO.JSON is -- ------------------------------ -- JSON Output Stream -- ------------------------------ -- The <b>Output_Stream</b> provides methods for creating a JSON output stream. -- The stream object takes care of the JSON escape rules. type Output_Stream is limited new Util.Serialize.IO.Output_Stream with private; -- Set the target output stream. procedure Initialize (Stream : in out Output_Stream; Output : in Util.Streams.Texts.Print_Stream_Access); -- Flush the buffer (if any) to the sink. overriding procedure Flush (Stream : in out Output_Stream); -- Close the sink. overriding procedure Close (Stream : in out Output_Stream); -- Write the buffer array to the output stream. overriding procedure Write (Stream : in out Output_Stream; Buffer : in Ada.Streams.Stream_Element_Array); -- Write a raw character on the stream. procedure Write (Stream : in out Output_Stream; Char : in Character); -- Write a wide character on the stream doing some conversion if necessary. -- The default implementation translates the wide character to a UTF-8 sequence. procedure Write_Wide (Stream : in out Output_Stream; Item : in Wide_Wide_Character); -- Write a raw string on the stream. procedure Write (Stream : in out Output_Stream; Item : in String); -- Start a JSON document. This operation writes the initial JSON marker ('{'). overriding procedure Start_Document (Stream : in out Output_Stream); -- Finish a JSON document by writing the final JSON marker ('}'). overriding procedure End_Document (Stream : in out Output_Stream); -- Write the value as a JSON string. Special characters are escaped using the JSON -- escape rules. procedure Write_String (Stream : in out Output_Stream; Value : in String); -- Write the value as a JSON string. Special characters are escaped using the JSON -- escape rules. procedure Write_Wide_String (Stream : in out Output_Stream; Value : in Wide_Wide_String); -- Start a new JSON object. If the name is not empty, write it as a string -- followed by the ':' (colon). The JSON object starts with '{' (curly brace). -- Example: "list": { procedure Start_Entity (Stream : in out Output_Stream; Name : in String); -- Terminates the current JSON object. procedure End_Entity (Stream : in out Output_Stream; Name : in String); -- Write the attribute name/value pair. overriding procedure Write_Attribute (Stream : in out Output_Stream; Name : in String; Value : in String); overriding procedure Write_Wide_Attribute (Stream : in out Output_Stream; Name : in String; Value : in Wide_Wide_String); overriding procedure Write_Attribute (Stream : in out Output_Stream; Name : in String; Value : in Integer); overriding procedure Write_Attribute (Stream : in out Output_Stream; Name : in String; Value : in Boolean); -- Write a JSON name/value pair. The value is written according to its type -- Example: "name": null -- "name": false -- "name": 12 -- "name": "value" procedure Write_Attribute (Stream : in out Output_Stream; Name : in String; Value : in Util.Beans.Objects.Object); -- Write the attribute with a null value. overriding procedure Write_Null_Attribute (Stream : in out Output_Stream; Name : in String); -- Write a JSON name/value pair (see Write_Attribute). procedure Write_Entity (Stream : in out Output_Stream; Name : in String; Value : in Util.Beans.Objects.Object); -- Write a JSON name/value pair (see Write_Attribute). overriding procedure Write_Entity (Stream : in out Output_Stream; Name : in String; Value : in String); overriding procedure Write_Wide_Entity (Stream : in out Output_Stream; Name : in String; Value : in Wide_Wide_String); overriding procedure Write_Entity (Stream : in out Output_Stream; Name : in String; Value : in Boolean); overriding procedure Write_Entity (Stream : in out Output_Stream; Name : in String; Value : in Integer); overriding procedure Write_Entity (Stream : in out Output_Stream; Name : in String; Value : in Ada.Calendar.Time); overriding procedure Write_Long_Entity (Stream : in out Output_Stream; Name : in String; Value : in Long_Long_Integer); overriding procedure Write_Enum_Entity (Stream : in out Output_Stream; Name : in String; Value : in String); -- Write an entity with a null value. overriding procedure Write_Null_Entity (Stream : in out Output_Stream; Name : in String); -- Starts a JSON array. -- Example: "list": [ overriding procedure Start_Array (Stream : in out Output_Stream; Name : in String); -- Terminates a JSON array. overriding procedure End_Array (Stream : in out Output_Stream; Name : in String); type Parser is new Serialize.IO.Parser with private; -- Parse the stream using the JSON parser. procedure Parse (Handler : in out Parser; Stream : in out Util.Streams.Buffered.Input_Buffer_Stream'Class; Sink : in out Reader'Class); -- Get the current location (file and line) to report an error message. function Get_Location (Handler : in Parser) return String; -- Read a JSON file and return an object. function Read (Path : in String) return Util.Beans.Objects.Object; private type Node_Info is record Is_Array : Boolean := False; Is_Root : Boolean := False; Has_Fields : Boolean := False; end record; type Node_Info_Access is access all Node_Info; package Node_Info_Stack is new Util.Stacks (Element_Type => Node_Info, Element_Type_Access => Node_Info_Access); type Output_Stream is limited new Util.Serialize.IO.Output_Stream with record Stack : Node_Info_Stack.Stack; Stream : Util.Streams.Texts.Print_Stream_Access; end record; procedure Write_Field_Name (Stream : in out Output_Stream; Name : in String); type Token_Type is (T_EOF, T_LEFT_BRACE, T_RIGHT_BRACE, T_LEFT_BRACKET, T_RIGHT_BRACKET, T_COLON, T_COMMA, T_TRUE, T_FALSE, T_STRING, T_NUMBER, T_BOOLEAN, T_UNKNOWN, T_NULL); type Parser is new Util.Serialize.IO.Parser with record Token : Ada.Strings.Unbounded.Unbounded_String; Pending_Token : Token_Type := T_EOF; Line_Number : Natural := 1; Has_Pending_Char : Boolean := False; Pending_Char : Character; end record; end Util.Serialize.IO.JSON;
----------------------------------------------------------------------- -- util-serialize-io-json -- JSON Serialization Driver -- Copyright (C) 2010, 2011, 2012, 2016, 2017, 2020 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Ada.Streams; with Util.Streams.Texts; with Util.Stacks; with Util.Beans.Objects; package Util.Serialize.IO.JSON is -- ------------------------------ -- JSON Output Stream -- ------------------------------ -- The <b>Output_Stream</b> provides methods for creating a JSON output stream. -- The stream object takes care of the JSON escape rules. type Output_Stream is limited new Util.Serialize.IO.Output_Stream with private; -- Set the target output stream. procedure Initialize (Stream : in out Output_Stream; Output : in Util.Streams.Texts.Print_Stream_Access); -- Flush the buffer (if any) to the sink. overriding procedure Flush (Stream : in out Output_Stream); -- Close the sink. overriding procedure Close (Stream : in out Output_Stream); -- Write the buffer array to the output stream. overriding procedure Write (Stream : in out Output_Stream; Buffer : in Ada.Streams.Stream_Element_Array); -- Write a wide character on the stream doing some conversion if necessary. -- The default implementation translates the wide character to a UTF-8 sequence. procedure Write_Wide (Stream : in out Output_Stream; Item : in Wide_Wide_Character); -- Start a JSON document. This operation writes the initial JSON marker ('{'). overriding procedure Start_Document (Stream : in out Output_Stream); -- Finish a JSON document by writing the final JSON marker ('}'). overriding procedure End_Document (Stream : in out Output_Stream); -- Write the value as a JSON string. Special characters are escaped using the JSON -- escape rules. procedure Write_String (Stream : in out Output_Stream; Value : in String); -- Write the value as a JSON string. Special characters are escaped using the JSON -- escape rules. procedure Write_Wide_String (Stream : in out Output_Stream; Value : in Wide_Wide_String); -- Start a new JSON object. If the name is not empty, write it as a string -- followed by the ':' (colon). The JSON object starts with '{' (curly brace). -- Example: "list": { procedure Start_Entity (Stream : in out Output_Stream; Name : in String); -- Terminates the current JSON object. procedure End_Entity (Stream : in out Output_Stream; Name : in String); -- Write the attribute name/value pair. overriding procedure Write_Attribute (Stream : in out Output_Stream; Name : in String; Value : in String); overriding procedure Write_Wide_Attribute (Stream : in out Output_Stream; Name : in String; Value : in Wide_Wide_String); overriding procedure Write_Attribute (Stream : in out Output_Stream; Name : in String; Value : in Integer); overriding procedure Write_Attribute (Stream : in out Output_Stream; Name : in String; Value : in Boolean); -- Write a JSON name/value pair. The value is written according to its type -- Example: "name": null -- "name": false -- "name": 12 -- "name": "value" procedure Write_Attribute (Stream : in out Output_Stream; Name : in String; Value : in Util.Beans.Objects.Object); -- Write the attribute with a null value. overriding procedure Write_Null_Attribute (Stream : in out Output_Stream; Name : in String); -- Write a JSON name/value pair (see Write_Attribute). procedure Write_Entity (Stream : in out Output_Stream; Name : in String; Value : in Util.Beans.Objects.Object); -- Write a JSON name/value pair (see Write_Attribute). overriding procedure Write_Entity (Stream : in out Output_Stream; Name : in String; Value : in String); overriding procedure Write_Wide_Entity (Stream : in out Output_Stream; Name : in String; Value : in Wide_Wide_String); overriding procedure Write_Entity (Stream : in out Output_Stream; Name : in String; Value : in Boolean); overriding procedure Write_Entity (Stream : in out Output_Stream; Name : in String; Value : in Integer); overriding procedure Write_Entity (Stream : in out Output_Stream; Name : in String; Value : in Ada.Calendar.Time); overriding procedure Write_Long_Entity (Stream : in out Output_Stream; Name : in String; Value : in Long_Long_Integer); overriding procedure Write_Enum_Entity (Stream : in out Output_Stream; Name : in String; Value : in String); -- Write an entity with a null value. overriding procedure Write_Null_Entity (Stream : in out Output_Stream; Name : in String); -- Starts a JSON array. -- Example: "list": [ overriding procedure Start_Array (Stream : in out Output_Stream; Name : in String); -- Terminates a JSON array. overriding procedure End_Array (Stream : in out Output_Stream; Name : in String); type Parser is new Serialize.IO.Parser with private; -- Parse the stream using the JSON parser. procedure Parse (Handler : in out Parser; Stream : in out Util.Streams.Buffered.Input_Buffer_Stream'Class; Sink : in out Reader'Class); -- Get the current location (file and line) to report an error message. function Get_Location (Handler : in Parser) return String; -- Read a JSON file and return an object. function Read (Path : in String) return Util.Beans.Objects.Object; private type Node_Info is record Is_Array : Boolean := False; Is_Root : Boolean := False; Has_Fields : Boolean := False; end record; type Node_Info_Access is access all Node_Info; package Node_Info_Stack is new Util.Stacks (Element_Type => Node_Info, Element_Type_Access => Node_Info_Access); type Output_Stream is limited new Util.Serialize.IO.Output_Stream with record Stack : Node_Info_Stack.Stack; Stream : Util.Streams.Texts.Print_Stream_Access; end record; procedure Write_Field_Name (Stream : in out Output_Stream; Name : in String); type Token_Type is (T_EOF, T_LEFT_BRACE, T_RIGHT_BRACE, T_LEFT_BRACKET, T_RIGHT_BRACKET, T_COLON, T_COMMA, T_TRUE, T_FALSE, T_STRING, T_NUMBER, T_BOOLEAN, T_UNKNOWN, T_NULL); type Parser is new Util.Serialize.IO.Parser with record Token : Ada.Strings.Unbounded.Unbounded_String; Pending_Token : Token_Type := T_EOF; Line_Number : Natural := 1; Has_Pending_Char : Boolean := False; Pending_Char : Character; end record; end Util.Serialize.IO.JSON;
Remove Write procedures which are provided by Util.Streams package
Remove Write procedures which are provided by Util.Streams package
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
2f72289a566610192d0116af1f71b7c522ec39a3
mat/src/parser/mat-expressions-parser_io.adb
mat/src/parser/mat-expressions-parser_io.adb
----------------------------------------------------------------------- -- mat-expressions-parser_io -- Input IO for Lex parser -- 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; package body MAT.Expressions.Parser_IO is Input : Ada.Strings.Unbounded.Unbounded_String; Pos : Natural := 0; procedure Set_Input (Content : in String) is begin Input := Ada.Strings.Unbounded.To_Unbounded_String (Content); Pos := 1; MAT.Expressions.lexer_dfa.yy_init := True; MAT.Expressions.lexer_dfa.yy_start := 0; end Set_Input; -- gets input and stuffs it into 'buf'. number of characters read, or YY_NULL, -- is returned in 'result'. procedure YY_INPUT (Buf : out unbounded_character_array; Result : out Integer; Max_Size : in Integer) is I : Integer := 1; Loc : Integer := Buf'First; begin while I <= Max_Size loop if Pos > Ada.Strings.Unbounded.Length (Input) then yy_eof_has_been_seen := True; Result := I - 1; return; end if; Buf (Loc) := Ada.Strings.Unbounded.Element (Input, Pos); Pos := Pos + 1; Loc := Loc + 1; I := I + 1; end loop; Result := I - 1; end YY_INPUT; -- yy_get_next_buffer - try to read in new buffer -- -- returns a code representing an action -- EOB_ACT_LAST_MATCH - -- EOB_ACT_RESTART_SCAN - restart the scanner -- EOB_ACT_END_OF_FILE - end of file function yy_get_next_buffer return eob_action_type is dest : Integer := 0; source : Integer := yytext_ptr - 1; -- copy prev. char, too number_to_move : Integer; ret_val : eob_action_type; num_to_read : Integer; begin if yy_c_buf_p > yy_n_chars + 1 then raise NULL_IN_INPUT; end if; -- try to read more data -- first move last chars to start of buffer number_to_move := yy_c_buf_p - yytext_ptr; for i in 0 .. number_to_move - 1 loop yy_ch_buf (dest) := yy_ch_buf (source); dest := dest + 1; source := source + 1; end loop; if yy_eof_has_been_seen then -- don't do the read, it's not guaranteed to return an EOF, -- just force an EOF yy_n_chars := 0; else num_to_read := YY_BUF_SIZE - number_to_move - 1; if num_to_read > YY_READ_BUF_SIZE then num_to_read := YY_READ_BUF_SIZE; end if; -- read in more data YY_INPUT (yy_ch_buf (number_to_move .. yy_ch_buf'Last), yy_n_chars, num_to_read); end if; if yy_n_chars = 0 then if number_to_move = 1 then ret_val := EOB_ACT_END_OF_FILE; else ret_val := EOB_ACT_LAST_MATCH; end if; yy_eof_has_been_seen := True; else ret_val := EOB_ACT_RESTART_SCAN; end if; yy_n_chars := yy_n_chars + number_to_move; yy_ch_buf (yy_n_chars) := YY_END_OF_BUFFER_CHAR; yy_ch_buf (yy_n_chars + 1) := YY_END_OF_BUFFER_CHAR; -- yytext begins at the second character in -- yy_ch_buf; the first character is the one which -- preceded it before reading in the latest buffer; -- it needs to be kept around in case it's a -- newline, so yy_get_previous_state() will have -- with '^' rules active yytext_ptr := 1; return ret_val; end yy_get_next_buffer; function Input_Line return Ada.Text_IO.Count is begin return 1; end Input_Line; -- default yywrap function - always treat EOF as an EOF function yywrap return Boolean is begin return True; end yywrap; procedure Open_Input (Fname : in String) is pragma Unreferenced (Fname); begin yy_init := True; end Open_Input; end MAT.Expressions.Parser_IO;
----------------------------------------------------------------------- -- mat-expressions-parser_io -- Input IO for Lex parser -- 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; package body MAT.Expressions.Parser_IO is Input : Ada.Strings.Unbounded.Unbounded_String; Pos : Natural := 0; procedure Set_Input (Content : in String) is begin Input := Ada.Strings.Unbounded.To_Unbounded_String (Content); Pos := 1; MAT.Expressions.Lexer_dfa.yy_init := True; MAT.Expressions.Lexer_dfa.yy_start := 0; end Set_Input; -- gets input and stuffs it into 'buf'. number of characters read, or YY_NULL, -- is returned in 'result'. procedure YY_INPUT (Buf : out unbounded_character_array; Result : out Integer; Max_Size : in Integer) is I : Integer := 1; Loc : Integer := Buf'First; begin while I <= Max_Size loop if Pos > Ada.Strings.Unbounded.Length (Input) then yy_eof_has_been_seen := True; Result := I - 1; return; end if; Buf (Loc) := Ada.Strings.Unbounded.Element (Input, Pos); Pos := Pos + 1; Loc := Loc + 1; I := I + 1; end loop; Result := I - 1; end YY_INPUT; -- yy_get_next_buffer - try to read in new buffer -- -- returns a code representing an action -- EOB_ACT_LAST_MATCH - -- EOB_ACT_RESTART_SCAN - restart the scanner -- EOB_ACT_END_OF_FILE - end of file function yy_get_next_buffer return eob_action_type is dest : Integer := 0; source : Integer := yytext_ptr - 1; -- copy prev. char, too number_to_move : Integer; ret_val : eob_action_type; num_to_read : Integer; begin if yy_c_buf_p > yy_n_chars + 1 then raise NULL_IN_INPUT; end if; -- try to read more data -- first move last chars to start of buffer number_to_move := yy_c_buf_p - yytext_ptr; for i in 0 .. number_to_move - 1 loop yy_ch_buf (dest) := yy_ch_buf (source); dest := dest + 1; source := source + 1; end loop; if yy_eof_has_been_seen then -- don't do the read, it's not guaranteed to return an EOF, -- just force an EOF yy_n_chars := 0; else num_to_read := YY_BUF_SIZE - number_to_move - 1; if num_to_read > YY_READ_BUF_SIZE then num_to_read := YY_READ_BUF_SIZE; end if; -- read in more data YY_INPUT (yy_ch_buf (number_to_move .. yy_ch_buf'Last), yy_n_chars, num_to_read); end if; if yy_n_chars = 0 then if number_to_move = 1 then ret_val := EOB_ACT_END_OF_FILE; else ret_val := EOB_ACT_LAST_MATCH; end if; yy_eof_has_been_seen := True; else ret_val := EOB_ACT_RESTART_SCAN; end if; yy_n_chars := yy_n_chars + number_to_move; yy_ch_buf (yy_n_chars) := YY_END_OF_BUFFER_CHAR; yy_ch_buf (yy_n_chars + 1) := YY_END_OF_BUFFER_CHAR; -- yytext begins at the second character in -- yy_ch_buf; the first character is the one which -- preceded it before reading in the latest buffer; -- it needs to be kept around in case it's a -- newline, so yy_get_previous_state() will have -- with '^' rules active yytext_ptr := 1; return ret_val; end yy_get_next_buffer; function Input_Line return Ada.Text_IO.Count is begin return 1; end Input_Line; -- default yywrap function - always treat EOF as an EOF function yywrap return Boolean is begin return True; end yywrap; procedure Open_Input (Fname : in String) is pragma Unreferenced (Fname); begin yy_init := True; end Open_Input; end MAT.Expressions.Parser_IO;
Fix compilation warnings
Fix compilation warnings
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
ba37d3ee6948862a356a37b4957f67534bca0b35
src/asf-components-widgets-tabs.adb
src/asf-components-widgets-tabs.adb
----------------------------------------------------------------------- -- components-widgets-tabs -- Tab views and tabs -- Copyright (C) 2013 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Beans.Objects; with ASF.Components.Base; with ASF.Contexts.Writer; package body ASF.Components.Widgets.Tabs is -- ------------------------------ -- Render the tab start. -- ------------------------------ overriding procedure Encode_Begin (UI : in UITab; Context : in out ASF.Contexts.Faces.Faces_Context'Class) is Writer : constant Contexts.Writer.Response_Writer_Access := Context.Get_Response_Writer; begin if UI.Is_Rendered (Context) then Writer.Start_Element ("div"); Writer.Write_Attribute ("id", UI.Get_Client_Id); end if; end Encode_Begin; -- ------------------------------ -- Render the tab close. -- ------------------------------ overriding procedure Encode_End (UI : in UITab; Context : in out ASF.Contexts.Faces.Faces_Context'Class) is Writer : constant Contexts.Writer.Response_Writer_Access := Context.Get_Response_Writer; begin if UI.Is_Rendered (Context) then Writer.End_Element ("div"); end if; end Encode_End; -- ------------------------------ -- Render the tab list and prepare to render the tab contents. -- ------------------------------ overriding procedure Encode_Begin (UI : in UITabView; Context : in out ASF.Contexts.Faces.Faces_Context'Class) is procedure Render_Tab (T : in Components.Base.UIComponent_Access); Writer : constant Contexts.Writer.Response_Writer_Access := Context.Get_Response_Writer; procedure Render_Tab (T : in Components.Base.UIComponent_Access) is Id : constant Unbounded_String := T.Get_Client_Id; begin if T.all in UITab'Class then Writer.Start_Element ("li"); Writer.Start_Element ("a"); Writer.Write_Attribute ("href", "#" & To_String (Id)); Writer.Write_Text (T.Get_Attribute ("title", Context)); Writer.End_Element ("a"); Writer.End_Element ("li"); end if; end Render_Tab; procedure Render_Tabs is new ASF.Components.Base.Iterate (Process => Render_Tab); begin if UI.Is_Rendered (Context) then declare use Util.Beans.Objects; Id : constant Unbounded_String := UI.Get_Client_Id; Effect : constant Object := UI.Get_Attribute (Context, Name => EFFECT_ATTR_NAME); Collapse : constant Boolean := UI.Get_Attribute (COLLAPSIBLE_ATTR_NAME, Context); begin Writer.Start_Element ("div"); Writer.Write_Attribute ("id", Id); Writer.Start_Element ("ul"); Render_Tabs (UI); Writer.End_Element ("ul"); Writer.Queue_Script ("$(""#"); Writer.Queue_Script (Id); Writer.Queue_Script (""").tabs({"); if Collapse then Writer.Queue_Script ("collapsible: true"); end if; if not Is_Empty (Effect) then if Collapse then Writer.Queue_Script (","); end if; Writer.Queue_Script ("show:{effect:"""); Writer.Queue_Script (Effect); Writer.Queue_Script (""",duration:"); Writer.Queue_Script (UI.Get_Attribute (DURATION_ATTR_NAME, Context, "500")); Writer.Queue_Script ("}"); end if; Writer.Queue_Script ("});"); end; end if; end Encode_Begin; -- ------------------------------ -- Render the tab view close. -- ------------------------------ overriding procedure Encode_End (UI : in UITabView; Context : in out ASF.Contexts.Faces.Faces_Context'Class) is Writer : constant Contexts.Writer.Response_Writer_Access := Context.Get_Response_Writer; begin if UI.Is_Rendered (Context) then Writer.End_Element ("div"); end if; end Encode_End; end ASF.Components.Widgets.Tabs;
----------------------------------------------------------------------- -- components-widgets-tabs -- Tab views and tabs -- Copyright (C) 2013 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Beans.Objects; with ASF.Components.Base; with ASF.Contexts.Writer; package body ASF.Components.Widgets.Tabs is -- ------------------------------ -- Render the tab start. -- ------------------------------ overriding procedure Encode_Begin (UI : in UITab; Context : in out ASF.Contexts.Faces.Faces_Context'Class) is Writer : constant Contexts.Writer.Response_Writer_Access := Context.Get_Response_Writer; begin if UI.Is_Rendered (Context) then Writer.Start_Element ("div"); Writer.Write_Attribute ("id", UI.Get_Client_Id); end if; end Encode_Begin; -- ------------------------------ -- Render the tab close. -- ------------------------------ overriding procedure Encode_End (UI : in UITab; Context : in out ASF.Contexts.Faces.Faces_Context'Class) is Writer : constant Contexts.Writer.Response_Writer_Access := Context.Get_Response_Writer; begin if UI.Is_Rendered (Context) then Writer.End_Element ("div"); end if; end Encode_End; -- ------------------------------ -- Render the tab list and prepare to render the tab contents. -- ------------------------------ overriding procedure Encode_Begin (UI : in UITabView; Context : in out ASF.Contexts.Faces.Faces_Context'Class) is procedure Render_Tab (T : in Components.Base.UIComponent_Access); Writer : constant Contexts.Writer.Response_Writer_Access := Context.Get_Response_Writer; procedure Render_Tab (T : in Components.Base.UIComponent_Access) is Id : constant Unbounded_String := T.Get_Client_Id; begin if T.all in UITab'Class then Writer.Start_Element ("li"); Writer.Start_Element ("a"); Writer.Write_Attribute ("href", "#" & To_String (Id)); Writer.Write_Text (T.Get_Attribute ("title", Context)); Writer.End_Element ("a"); Writer.End_Element ("li"); end if; end Render_Tab; procedure Render_Tabs is new ASF.Components.Base.Iterate (Process => Render_Tab); begin if UI.Is_Rendered (Context) then declare use Util.Beans.Objects; Id : constant Unbounded_String := UI.Get_Client_Id; Effect : constant Object := UI.Get_Attribute (Context, Name => EFFECT_ATTR_NAME); Collapse : constant Boolean := UI.Get_Attribute (COLLAPSIBLE_ATTR_NAME, Context); begin Writer.Start_Element ("div"); Writer.Write_Attribute ("id", Id); Writer.Start_Element ("ul"); Render_Tabs (UI); Writer.End_Element ("ul"); Writer.Queue_Script ("$(""#"); Writer.Queue_Script (Id); Writer.Queue_Script (""").tabs({"); if Collapse then Writer.Queue_Script ("collapsible: true"); end if; if not Is_Empty (Effect) then if Collapse then Writer.Queue_Script (","); end if; Writer.Queue_Script ("show:{effect:"""); Writer.Queue_Script (Effect); Writer.Queue_Script (""",duration:"); Writer.Queue_Script (UI.Get_Attribute (DURATION_ATTR_NAME, Context, "500")); Writer.Queue_Script ("}"); end if; Writer.Queue_Script ("});"); end; end if; end Encode_Begin; -- ------------------------------ -- Render the tab view close. -- ------------------------------ overriding procedure Encode_End (UI : in UITabView; Context : in out ASF.Contexts.Faces.Faces_Context'Class) is Writer : constant Contexts.Writer.Response_Writer_Access := Context.Get_Response_Writer; begin if UI.Is_Rendered (Context) then Writer.End_Element ("div"); end if; end Encode_End; -- ------------------------------ -- Render the accordion list and prepare to render the tab contents. -- ------------------------------ overriding procedure Encode_Children (UI : in UIAccordion; Context : in out ASF.Contexts.Faces.Faces_Context'Class) is procedure Render_Tab (T : in Components.Base.UIComponent_Access); Writer : constant Contexts.Writer.Response_Writer_Access := Context.Get_Response_Writer; procedure Render_Tab (T : in Components.Base.UIComponent_Access) is begin if T.all in UITab'Class then Writer.Start_Element ("h3"); Writer.Write_Text (T.Get_Attribute ("title", Context)); Writer.End_Element ("h3"); T.Encode_All (Context); end if; end Render_Tab; procedure Render_Tabs is new ASF.Components.Base.Iterate (Process => Render_Tab); begin if UI.Is_Rendered (Context) then declare use Util.Beans.Objects; Id : constant Unbounded_String := UI.Get_Client_Id; Effect : constant Object := UI.Get_Attribute (Context, Name => EFFECT_ATTR_NAME); Collapse : constant Boolean := UI.Get_Attribute (COLLAPSIBLE_ATTR_NAME, Context); begin Writer.Start_Element ("div"); Writer.Write_Attribute ("id", Id); Render_Tabs (UI); Writer.End_Element ("div"); Writer.Queue_Script ("$(""#"); Writer.Queue_Script (Id); Writer.Queue_Script (""").accordion({"); if Collapse then Writer.Queue_Script ("collapsible: true"); end if; if not Is_Empty (Effect) then if Collapse then Writer.Queue_Script (","); end if; Writer.Queue_Script ("show:{effect:"""); Writer.Queue_Script (Effect); Writer.Queue_Script (""",duration:"); Writer.Queue_Script (UI.Get_Attribute (DURATION_ATTR_NAME, Context, "500")); Writer.Queue_Script ("}"); end if; Writer.Queue_Script ("});"); end; end if; end Encode_Children; end ASF.Components.Widgets.Tabs;
Implement the accordion widget
Implement the accordion widget
Ada
apache-2.0
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
f4ca6fe0161a4eb972e247f57be5a96698433868
src/security-policies.ads
src/security-policies.ads
----------------------------------------------------------------------- -- security-policies -- Security Policies -- Copyright (C) 2010, 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Finalization; with Util.Beans.Objects; with Util.Beans.Objects.Vectors; with Util.Serialize.IO.XML; with Security.Permissions; limited with Security.Controllers; limited with Security.Contexts; package Security.Policies is type Security_Context_Access is access all Contexts.Security_Context'Class; type Controller_Access is access all Security.Controllers.Controller'Class; type Controller_Access_Array is array (Permissions.Permission_Index range <>) of Controller_Access; type Policy_Index is new Positive; type Policy_Context is limited interface; type Policy_Context_Access is access all Policy_Context'Class; type Policy_Context_Array is array (Policy_Index range <>) of Policy_Context_Access; type Policy_Context_Array_Access is access Policy_Context_Array; -- ------------------------------ -- Security policy -- ------------------------------ type Policy is new Ada.Finalization.Limited_Controlled with private; type Policy_Access is access all Policy'Class; -- Get the policy name. function Get_Name (From : in Policy) return String; -- Get the policy index. function Get_Policy_Index (From : in Policy'Class) return Policy_Index; pragma Inline (Get_Policy_Index); -- Prepare the XML parser to read the policy configuration. procedure Prepare_Config (Pol : in out Policy; Reader : in out Util.Serialize.IO.XML.Parser) is null; -- Finish reading the XML policy configuration. The security policy implementation can use -- this procedure to perform any configuration setup after the configuration is parsed. procedure Finish_Config (Into : in out Policy; Reader : in out Util.Serialize.IO.XML.Parser) is null; -- Add a permission under the given permission name and associated with the controller. -- To verify the permission, the controller will be called. procedure Add_Permission (Manager : in out Policy; Name : in String; Permission : in Controller_Access); Invalid_Name : exception; Policy_Error : exception; -- ------------------------------ -- Permission Manager -- ------------------------------ -- The <b>Permission_Manager</b> verifies through some policy that a permission -- is granted to a user. type Policy_Manager (Max_Policies : Policy_Index) is new Ada.Finalization.Limited_Controlled with private; type Policy_Manager_Access is access all Policy_Manager'Class; -- Get the policy with the name <b>Name</b> registered in the policy manager. -- Returns null if there is no such policy. function Get_Policy (Manager : in Policy_Manager; Name : in String) return Policy_Access; -- Add the policy to the policy manager. After a policy is added in the manager, -- it can participate in the security policy. -- Raises Policy_Error if the policy table is full. procedure Add_Policy (Manager : in out Policy_Manager; Policy : in Policy_Access); -- Add a permission under the given permission name and associated with the controller. -- To verify the permission, the controller will be called. procedure Add_Permission (Manager : in out Policy_Manager; Name : in String; Permission : in Controller_Access); -- Checks whether the permission defined by the <b>Permission</b> controller data is granted -- by the security context passed in <b>Context</b>. -- Returns true if such permission is granted. function Has_Permission (Manager : in Policy_Manager; Context : in Security.Contexts.Security_Context'Class; Permission : in Security.Permissions.Permission'Class) return Boolean; -- Create the policy contexts to be associated with the security context. function Create_Policy_Contexts (Manager : in Policy_Manager) return Policy_Context_Array_Access; -- Get the security controller associated with the permission index <b>Index</b>. -- Returns null if there is no such controller. function Get_Controller (Manager : in Policy_Manager'Class; Index : in Permissions.Permission_Index) return Controller_Access; pragma Inline_Always (Get_Controller); -- Read the policy file procedure Read_Policy (Manager : in out Policy_Manager; File : in String); -- Initialize the permission manager. overriding procedure Initialize (Manager : in out Policy_Manager); -- Finalize the permission manager. overriding procedure Finalize (Manager : in out Policy_Manager); -- ------------------------------ -- Policy Configuration -- ------------------------------ type Policy_Config is record Id : Natural := 0; Permissions : Util.Beans.Objects.Vectors.Vector; Patterns : Util.Beans.Objects.Vectors.Vector; Manager : Policy_Manager_Access; end record; type Policy_Config_Access is access all Policy_Config; -- Setup the XML parser to read the <b>policy</b> description. For example: -- -- <policy id='1'> -- <permission>create-workspace</permission> -- <permission>admin</permission> -- <url-pattern>/workspace/create</url-pattern> -- <url-pattern>/workspace/setup/*</url-pattern> -- </policy> -- -- This policy gives access to the URL that match one of the URL pattern if the -- security context has the permission <b>create-workspace</b> or <b>admin</b>. generic Reader : in out Util.Serialize.IO.XML.Parser; Manager : in Policy_Manager_Access; package Reader_Config is Config : aliased Policy_Config; end Reader_Config; private subtype Permission_Index is Permissions.Permission_Index; type Permission_Index_Array is array (Positive range <>) of Permissions.Permission_Index; type Controller_Access_Array_Access is access all Controller_Access_Array; type Policy_Access_Array is array (Policy_Index range <>) of Policy_Access; type Policy is new Ada.Finalization.Limited_Controlled with record Manager : Policy_Manager_Access; Index : Policy_Index; end record; type Policy_Manager (Max_Policies : Policy_Index) is new Ada.Finalization.Limited_Controlled with record Permissions : Controller_Access_Array_Access; Last_Index : Permission_Index := Permission_Index'First; -- The security policies. Policies : Policy_Access_Array (1 .. Max_Policies); end record; end Security.Policies;
----------------------------------------------------------------------- -- security-policies -- Security Policies -- Copyright (C) 2010, 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Finalization; with Util.Beans.Objects; with Util.Beans.Objects.Vectors; with Util.Serialize.IO.XML; with Security.Permissions; limited with Security.Controllers; limited with Security.Contexts; package Security.Policies is type Security_Context_Access is access all Contexts.Security_Context'Class; type Controller_Access is access all Security.Controllers.Controller'Class; type Controller_Access_Array is array (Permissions.Permission_Index range <>) of Controller_Access; type Policy_Index is new Positive; type Policy_Context is limited interface; type Policy_Context_Access is access all Policy_Context'Class; type Policy_Context_Array is array (Policy_Index range <>) of Policy_Context_Access; type Policy_Context_Array_Access is access Policy_Context_Array; -- ------------------------------ -- Security policy -- ------------------------------ type Policy is new Ada.Finalization.Limited_Controlled with private; type Policy_Access is access all Policy'Class; -- Get the policy name. function Get_Name (From : in Policy) return String; -- Get the policy index. function Get_Policy_Index (From : in Policy'Class) return Policy_Index; pragma Inline (Get_Policy_Index); -- Prepare the XML parser to read the policy configuration. procedure Prepare_Config (Pol : in out Policy; Reader : in out Util.Serialize.IO.XML.Parser) is null; -- Finish reading the XML policy configuration. The security policy implementation can use -- this procedure to perform any configuration setup after the configuration is parsed. procedure Finish_Config (Into : in out Policy; Reader : in out Util.Serialize.IO.XML.Parser) is null; -- Add a permission under the given permission name and associated with the controller. -- To verify the permission, the controller will be called. procedure Add_Permission (Manager : in out Policy; Name : in String; Permission : in Controller_Access); Invalid_Name : exception; Policy_Error : exception; -- ------------------------------ -- Permission Manager -- ------------------------------ -- The <b>Permission_Manager</b> verifies through some policy that a permission -- is granted to a user. type Policy_Manager (Max_Policies : Policy_Index) is new Ada.Finalization.Limited_Controlled with private; type Policy_Manager_Access is access all Policy_Manager'Class; -- Get the policy with the name <b>Name</b> registered in the policy manager. -- Returns null if there is no such policy. function Get_Policy (Manager : in Policy_Manager; Name : in String) return Policy_Access; -- Add the policy to the policy manager. After a policy is added in the manager, -- it can participate in the security policy. -- Raises Policy_Error if the policy table is full. procedure Add_Policy (Manager : in out Policy_Manager; Policy : in Policy_Access); -- Add a permission under the given permission name and associated with the controller. -- To verify the permission, the controller will be called. procedure Add_Permission (Manager : in out Policy_Manager; Name : in String; Permission : in Controller_Access); -- Checks whether the permission defined by the <b>Permission</b> controller data is granted -- by the security context passed in <b>Context</b>. -- Returns true if such permission is granted. function Has_Permission (Manager : in Policy_Manager; Context : in Security.Contexts.Security_Context'Class; Permission : in Security.Permissions.Permission'Class) return Boolean; -- Create the policy contexts to be associated with the security context. function Create_Policy_Contexts (Manager : in Policy_Manager) return Policy_Context_Array_Access; -- Read the policy file procedure Read_Policy (Manager : in out Policy_Manager; File : in String); -- Initialize the permission manager. overriding procedure Initialize (Manager : in out Policy_Manager); -- Finalize the permission manager. overriding procedure Finalize (Manager : in out Policy_Manager); -- ------------------------------ -- Policy Configuration -- ------------------------------ type Policy_Config is record Id : Natural := 0; Permissions : Util.Beans.Objects.Vectors.Vector; Patterns : Util.Beans.Objects.Vectors.Vector; Manager : Policy_Manager_Access; end record; type Policy_Config_Access is access all Policy_Config; -- Setup the XML parser to read the <b>policy</b> description. For example: -- -- <policy id='1'> -- <permission>create-workspace</permission> -- <permission>admin</permission> -- <url-pattern>/workspace/create</url-pattern> -- <url-pattern>/workspace/setup/*</url-pattern> -- </policy> -- -- This policy gives access to the URL that match one of the URL pattern if the -- security context has the permission <b>create-workspace</b> or <b>admin</b>. generic Reader : in out Util.Serialize.IO.XML.Parser; Manager : in Policy_Manager_Access; package Reader_Config is Config : aliased Policy_Config; end Reader_Config; private subtype Permission_Index is Permissions.Permission_Index; type Permission_Index_Array is array (Positive range <>) of Permissions.Permission_Index; type Controller_Access_Array_Access is access all Controller_Access_Array; type Policy_Access_Array is array (Policy_Index range <>) of Policy_Access; type Policy is new Ada.Finalization.Limited_Controlled with record Manager : Policy_Manager_Access; Index : Policy_Index; end record; type Policy_Manager (Max_Policies : Policy_Index) is new Ada.Finalization.Limited_Controlled with record Permissions : Controller_Access_Array_Access; Last_Index : Permission_Index := Permission_Index'First; -- The security policies. Policies : Policy_Access_Array (1 .. Max_Policies); end record; end Security.Policies;
Remove the Get_Controller function
Remove the Get_Controller function
Ada
apache-2.0
Letractively/ada-security
63a81bf939c9d5abaf80cd3dcd885ca8b46d9711
arch/ARM/cortex_m/src/cm0/cortex_m_svd-nvic.ads
arch/ARM/cortex_m/src/cm0/cortex_m_svd-nvic.ads
-- This spec has been automatically generated from cm0.svd pragma Restrictions (No_Elaboration_Code); pragma Ada_2012; pragma Style_Checks (Off); with HAL; with System; package Cortex_M_SVD.NVIC is pragma Preelaborate; --------------- -- Registers -- --------------- -- Interrupt Priority Register -- Interrupt Priority Register type NVIC_IPR_Registers is array (0 .. 31) of HAL.UInt8; ----------------- -- Peripherals -- ----------------- type NVIC_Peripheral is record -- Interrupt Set-Enable Registers NVIC_ISER : HAL.UInt32; -- Interrupt Clear-Enable Registers NVIC_ICER : HAL.UInt32; -- Interrupt Set-Pending Registers NVIC_ISPR : HAL.UInt32; -- Interrupt Clear-Pending Registers NVIC_ICPR : HAL.UInt32; -- Interrupt Priority Register NVIC_IPR : NVIC_IPR_Registers; end record with Volatile; for NVIC_Peripheral use record NVIC_ISER at 16#0# range 0 .. 31; NVIC_ICER at 16#80# range 0 .. 31; NVIC_ISPR at 16#100# range 0 .. 31; NVIC_ICPR at 16#180# range 0 .. 31; NVIC_IPR at 16#300# range 0 .. 255; end record; NVIC_Periph : aliased NVIC_Peripheral with Import, Address => NVIC_Base; end Cortex_M_SVD.NVIC;
-- This spec has been automatically generated from cm0.svd pragma Restrictions (No_Elaboration_Code); pragma Ada_2012; pragma Style_Checks (Off); with HAL; with System; package Cortex_M_SVD.NVIC is pragma Preelaborate; --------------- -- Registers -- --------------- -- Interrupt Priority Register -- Interrupt Priority Register type NVIC_IPR_Registers is array (0 .. 7) of HAL.UInt32; ----------------- -- Peripherals -- ----------------- type NVIC_Peripheral is record -- Interrupt Set-Enable Registers NVIC_ISER : HAL.UInt32; -- Interrupt Clear-Enable Registers NVIC_ICER : HAL.UInt32; -- Interrupt Set-Pending Registers NVIC_ISPR : HAL.UInt32; -- Interrupt Clear-Pending Registers NVIC_ICPR : HAL.UInt32; -- Interrupt Priority Register NVIC_IPR : NVIC_IPR_Registers; end record with Volatile; for NVIC_Peripheral use record NVIC_ISER at 16#0# range 0 .. 31; NVIC_ICER at 16#80# range 0 .. 31; NVIC_ISPR at 16#100# range 0 .. 31; NVIC_ICPR at 16#180# range 0 .. 31; NVIC_IPR at 16#300# range 0 .. 255; end record; NVIC_Periph : aliased NVIC_Peripheral with Import, Address => NVIC_Base; end Cortex_M_SVD.NVIC;
Update NVIC SVD
ARM/Cortex_M0: Update NVIC SVD
Ada
bsd-3-clause
ellamosi/Ada_BMP_Library,Fabien-Chouteau/Ada_Drivers_Library,simonjwright/Ada_Drivers_Library,AdaCore/Ada_Drivers_Library,Fabien-Chouteau/Ada_Drivers_Library,simonjwright/Ada_Drivers_Library,AdaCore/Ada_Drivers_Library
218c07503320d04599056b5756e7c6daa6b55bab
awa/plugins/awa-blogs/src/awa-blogs-modules.ads
awa/plugins/awa-blogs/src/awa-blogs-modules.ads
----------------------------------------------------------------------- -- awa-blogs-module -- Blog and post management module -- Copyright (C) 2011, 2012, 2013 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with ASF.Applications; with ADO; with AWA.Modules; with AWA.Blogs.Models; with Security.Permissions; -- The <b>Blogs.Module</b> manages the creation, update, removal of blog posts in an application. -- package AWA.Blogs.Modules is NAME : constant String := "blogs"; -- Define the permissions. package ACL_Create_Blog is new Security.Permissions.Definition ("blog-create"); package ACL_Delete_Blog is new Security.Permissions.Definition ("blog-delete"); package ACL_Create_Post is new Security.Permissions.Definition ("blog-create-post"); package ACL_Delete_Post is new Security.Permissions.Definition ("blog-delete-post"); package ACL_Update_Post is new Security.Permissions.Definition ("blog-update-post"); Not_Found : exception; type Blog_Module is new AWA.Modules.Module with private; type Blog_Module_Access is access all Blog_Module'Class; -- Initialize the blog module. overriding procedure Initialize (Plugin : in out Blog_Module; App : in AWA.Modules.Application_Access; Props : in ASF.Applications.Config); -- Get the blog module instance associated with the current application. function Get_Blog_Module return Blog_Module_Access; -- Create a new blog for the user workspace. procedure Create_Blog (Model : in Blog_Module; Workspace_Id : in ADO.Identifier; Title : in String; Result : out ADO.Identifier); -- Create a new post associated with the given blog identifier. procedure Create_Post (Model : in Blog_Module; Blog_Id : in ADO.Identifier; Title : in String; URI : in String; Text : in String; Status : in AWA.Blogs.Models.Post_Status_Type; Result : out ADO.Identifier); -- Update the post title and text associated with the blog post identified by <b>Post</b>. procedure Update_Post (Model : in Blog_Module; Post_Id : in ADO.Identifier; Title : in String; Text : in String; Status : in AWA.Blogs.Models.Post_Status_Type); -- Delete the post identified by the given identifier. procedure Delete_Post (Model : in Blog_Module; Post_Id : in ADO.Identifier); private type Blog_Module is new AWA.Modules.Module with null record; end AWA.Blogs.Modules;
----------------------------------------------------------------------- -- awa-blogs-module -- Blog and post management module -- Copyright (C) 2011, 2012, 2013, 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with ASF.Applications; with ADO; with AWA.Modules; with AWA.Blogs.Models; with Security.Permissions; -- The <b>Blogs.Module</b> manages the creation, update, removal of blog posts in an application. -- package AWA.Blogs.Modules is NAME : constant String := "blogs"; -- Define the permissions. package ACL_Create_Blog is new Security.Permissions.Definition ("blog-create"); package ACL_Delete_Blog is new Security.Permissions.Definition ("blog-delete"); package ACL_Create_Post is new Security.Permissions.Definition ("blog-create-post"); package ACL_Delete_Post is new Security.Permissions.Definition ("blog-delete-post"); package ACL_Update_Post is new Security.Permissions.Definition ("blog-update-post"); Not_Found : exception; type Blog_Module is new AWA.Modules.Module with private; type Blog_Module_Access is access all Blog_Module'Class; -- Initialize the blog module. overriding procedure Initialize (Plugin : in out Blog_Module; App : in AWA.Modules.Application_Access; Props : in ASF.Applications.Config); -- Get the blog module instance associated with the current application. function Get_Blog_Module return Blog_Module_Access; -- Create a new blog for the user workspace. procedure Create_Blog (Model : in Blog_Module; Workspace_Id : in ADO.Identifier; Title : in String; Result : out ADO.Identifier); -- Create a new post associated with the given blog identifier. procedure Create_Post (Model : in Blog_Module; Blog_Id : in ADO.Identifier; Title : in String; URI : in String; Text : in String; Status : in AWA.Blogs.Models.Post_Status_Type; Result : out ADO.Identifier); -- Update the post title and text associated with the blog post identified by <b>Post</b>. procedure Update_Post (Model : in Blog_Module; Post_Id : in ADO.Identifier; Title : in String; URI : in String; Text : in String; Status : in AWA.Blogs.Models.Post_Status_Type); -- Delete the post identified by the given identifier. procedure Delete_Post (Model : in Blog_Module; Post_Id : in ADO.Identifier); private type Blog_Module is new AWA.Modules.Module with null record; end AWA.Blogs.Modules;
Add a URI parameter to the Update_Post operation to allow users to update the post URI
Add a URI parameter to the Update_Post operation to allow users to update the post URI
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
8377cb8830e133c456b7c2464a24dfdb4003d02c
regtests/security-policies-tests.ads
regtests/security-policies-tests.ads
----------------------------------------------------------------------- -- Security-policies-tests - Unit tests for Security.Permissions -- Copyright (C) 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Tests; with Util.Strings; package Security.Policies.Tests is procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite); type Test is new Util.Tests.Test with null record; -- Test Add_Permission and Get_Permission_Index procedure Test_Add_Permission (T : in out Test); -- Test Create_Role and Get_Role_Name procedure Test_Create_Role (T : in out Test); -- Test Has_Permission procedure Test_Has_Permission (T : in out Test); -- Test reading policy files procedure Test_Read_Policy (T : in out Test); -- Test reading policy files and using the <role-permission> controller procedure Test_Role_Policy (T : in out Test); -- Read the policy file <b>File</b> and perform a test on the given URI -- with a user having the given role. procedure Check_Policy (T : in out Test; File : in String; Role : in String; URI : in String); type Test_Principal is new Principal with record Name : Util.Strings.String_Ref; Roles : Security.Policies.Roles.Role_Map := (others => False); end record; -- Returns true if the given permission is stored in the user principal. function Has_Role (User : in Test_Principal; Role : in Role_Type) return Boolean; -- Get the principal name. function Get_Name (From : in Test_Principal) return String; end Security.Policies.Tests;
----------------------------------------------------------------------- -- Security-policies-tests - Unit tests for Security.Permissions -- Copyright (C) 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Tests; with Util.Strings; with Security.Policies.Roles; package Security.Policies.Tests is procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite); type Test is new Util.Tests.Test with null record; -- Test Create_Role and Get_Role_Name procedure Test_Create_Role (T : in out Test); -- Test Has_Permission procedure Test_Has_Permission (T : in out Test); -- Test reading policy files procedure Test_Read_Policy (T : in out Test); -- Test reading policy files and using the <role-permission> controller procedure Test_Role_Policy (T : in out Test); -- Read the policy file <b>File</b> and perform a test on the given URI -- with a user having the given role. procedure Check_Policy (T : in out Test; File : in String; Role : in String; URI : in String); type Test_Principal is new Principal with record Name : Util.Strings.String_Ref; Roles : Security.Policies.Roles.Role_Map := (others => False); end record; -- Returns true if the given permission is stored in the user principal. function Has_Role (User : in Test_Principal; Role : in Security.Policies.Roles.Role_Type) return Boolean; -- Get the principal name. function Get_Name (From : in Test_Principal) return String; end Security.Policies.Tests;
Fix compilation for Policies.Roles
Fix compilation for Policies.Roles
Ada
apache-2.0
stcarrez/ada-security
5458df165311111fb18e48786ae03c4dace9fd81
src/asf-components-widgets-likes.ads
src/asf-components-widgets-likes.ads
----------------------------------------------------------------------- -- components-widgets-likes -- Social Likes Components -- Copyright (C) 2013 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Strings; with ASF.Components.Html; with ASF.Contexts.Faces; package ASF.Components.Widgets.Likes is -- ------------------------------ -- UILike -- ------------------------------ -- The <b>UILike</b> component displays a social like button to recommend a page. type UILike is new ASF.Components.Html.UIHtmlComponent with null record; -- Get the link to submit in the like action. function Get_Link (UI : in UILike; Context : in ASF.Contexts.Faces.Faces_Context'Class) return String; -- Render the like button for Facebook or Google+. overriding procedure Encode_Begin (UI : in UILike; Context : in out ASF.Contexts.Faces.Faces_Context'Class); -- ------------------------------ -- Like Generator -- ------------------------------ -- The <tt>Like_Generator</tt> represents the specific method for the generation of -- a social like generator. A generator is registered under a given name with the -- <tt>Register_Like</tt> operation. The current implementation provides a Facebook -- like generator. type Like_Generator is limited interface; type Like_Generator_Access is access all Like_Generator'Class; -- Render the like button according to the generator and the component attributes. procedure Render_Like (Generator : in Like_Generator; UI : in UILike'Class; Href : in String; Context : in out ASF.Contexts.Faces.Faces_Context'Class) is abstract; -- Maximum number of generators that can be registered. MAX_LIKE_GENERATOR : constant Positive := 5; -- Register the like generator under the given name. procedure Register_Like (Name : in Util.Strings.Name_Access; Generator : in Like_Generator_Access); -- ------------------------------ -- Facebook like generator -- ------------------------------ type Facebook_Like_Generator is new Like_Generator with null record; overriding procedure Render_Like (Generator : in Facebook_Like_Generator; UI : in UILike'Class; Href : in String; Context : in out ASF.Contexts.Faces.Faces_Context'Class); -- ------------------------------ -- Google like generator -- ------------------------------ type Google_Like_Generator is new Like_Generator with null record; overriding procedure Render_Like (Generator : in Google_Like_Generator; UI : in UILike'Class; Href : in String; Context : in out ASF.Contexts.Faces.Faces_Context'Class); -- ------------------------------ -- Twitter like generator -- ------------------------------ type Twitter_Like_Generator is new Like_Generator with null record; overriding procedure Render_Like (Generator : in Twitter_Like_Generator; UI : in UILike'Class; Href : in String; Context : in out ASF.Contexts.Faces.Faces_Context'Class); end ASF.Components.Widgets.Likes;
----------------------------------------------------------------------- -- components-widgets-likes -- Social Likes Components -- Copyright (C) 2013 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Strings; with ASF.Applications; with ASF.Components.Html; with ASF.Contexts.Faces; package ASF.Components.Widgets.Likes is -- ------------------------------ -- UILike -- ------------------------------ -- The <b>UILike</b> component displays a social like button to recommend a page. type UILike is new ASF.Components.Html.UIHtmlComponent with null record; -- Get the link to submit in the like action. function Get_Link (UI : in UILike; Context : in ASF.Contexts.Faces.Faces_Context'Class) return String; -- Render the like button for Facebook or Google+. overriding procedure Encode_Begin (UI : in UILike; Context : in out ASF.Contexts.Faces.Faces_Context'Class); -- ------------------------------ -- Like Generator -- ------------------------------ -- The <tt>Like_Generator</tt> represents the specific method for the generation of -- a social like generator. A generator is registered under a given name with the -- <tt>Register_Like</tt> operation. The current implementation provides a Facebook -- like generator. type Like_Generator is limited interface; type Like_Generator_Access is access all Like_Generator'Class; -- Render the like button according to the generator and the component attributes. procedure Render_Like (Generator : in Like_Generator; UI : in UILike'Class; Href : in String; Context : in out ASF.Contexts.Faces.Faces_Context'Class) is abstract; -- Maximum number of generators that can be registered. MAX_LIKE_GENERATOR : constant Positive := 5; -- Register the like generator under the given name. procedure Register_Like (Name : in Util.Strings.Name_Access; Generator : in Like_Generator_Access); -- ------------------------------ -- Facebook like generator -- ------------------------------ type Facebook_Like_Generator is new Like_Generator with null record; overriding procedure Render_Like (Generator : in Facebook_Like_Generator; UI : in UILike'Class; Href : in String; Context : in out ASF.Contexts.Faces.Faces_Context'Class); -- The application configuration parameter that defines which Facebook client ID must be used. package P_Facebook_App_Id is new ASF.Applications.Parameter ("facebook.client_id", ""); -- ------------------------------ -- Google like generator -- ------------------------------ type Google_Like_Generator is new Like_Generator with null record; overriding procedure Render_Like (Generator : in Google_Like_Generator; UI : in UILike'Class; Href : in String; Context : in out ASF.Contexts.Faces.Faces_Context'Class); -- ------------------------------ -- Twitter like generator -- ------------------------------ type Twitter_Like_Generator is new Like_Generator with null record; overriding procedure Render_Like (Generator : in Twitter_Like_Generator; UI : in UILike'Class; Href : in String; Context : in out ASF.Contexts.Faces.Faces_Context'Class); end ASF.Components.Widgets.Likes;
Declare the P_Facebook_App_Id application configuration parameter
Declare the P_Facebook_App_Id application configuration parameter
Ada
apache-2.0
Letractively/ada-asf,Letractively/ada-asf,Letractively/ada-asf
60e226cda9e91710127d66bc3f9241122f349dce
mat/src/frames/mat-frames.adb
mat/src/frames/mat-frames.adb
----------------------------------------------------------------------- -- mat-frames - Representation of stack frames -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Unchecked_Deallocation; with Ada.Text_IO; with Util.Log.Loggers; with MAT.Frames.Print; package body MAT.Frames is use type MAT.Types.Target_Addr; procedure Free is new Ada.Unchecked_Deallocation (Frame, Frame_Type); -- The logger Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("MAT.Frames.Targets"); procedure Split (F : in out Frame_Type; Pos : in Positive); procedure Add_Frame (F : in Frame_Type; Pc : in Frame_Table; Result : out Frame_Type); function Check (Frame : in Frame_Type) return Boolean is Parent : Frame_Type; Child : Frame_Type; Result : Boolean := True; begin if Frame = null then return False; end if; Child := Frame.Children; while Child /= null loop if Child.Parent /= Frame then Log.Error ("Invalid parent link"); Result := False; end if; if Child.Children /= null and then not Check (Child) then Log.Error ("A child is now invalid"); Result := False; end if; Child := Child.Next; end loop; return Result; end Check; -- ------------------------------ -- Return the parent frame. -- ------------------------------ function Parent (Frame : in Frame_Type) return Frame_Type is begin if Frame = null then return null; else return Frame.Parent; end if; end Parent; -- ------------------------------ -- Get the root frame object. -- ------------------------------ function Get_Root (Frame : in Frame_Type) return Frame_Type is Parent : Frame_Type := Frame; begin loop if Parent.Parent = null then return Parent; end if; Parent := Parent.Parent; end loop; end Get_Root; -- ------------------------------ -- Returns the backtrace of the current frame (up to the root). -- ------------------------------ function Backtrace (Frame : in Frame_Type) return Frame_Table is Pc : Frame_Table (1 .. Frame.Depth); Current : Frame_Type := Frame; Pos : Natural := Current.Depth; New_Pos : Natural; begin while Current /= null and Pos /= 0 loop New_Pos := Pos - Current.Local_Depth + 1; Pc (New_Pos .. Pos) := Current.Calls (1 .. Current.Local_Depth); Pos := New_Pos - 1; Current := Current.Parent; end loop; return Pc; end Backtrace; -- ------------------------------ -- Returns the number of children in the frame. -- When recursive is true, compute in the sub-tree. -- ------------------------------ function Count_Children (Frame : in Frame_Type; Recursive : in Boolean := False) return Natural is Count : Natural := 0; Child : Frame_Type; begin if Frame /= null then Child := Frame.Children; while Child /= null loop Count := Count + 1; if Recursive then declare N : Natural := Count_Children (Child, True); begin if N > 0 then N := N - 1; end if; Count := Count + N; end; end if; Child := Child.Next; end loop; end if; return Count; end Count_Children; -- ------------------------------ -- Returns all the direct calls made by the current frame. -- ------------------------------ function Calls (Frame : in Frame_Type) return Frame_Table is Nb_Calls : constant Natural := Count_Children (Frame); Pc : Frame_Table (1 .. Nb_Calls); begin if Frame /= null then declare Child : Frame_Type := Frame.Children; Pos : Natural := 1; begin while Child /= null loop Pc (Pos) := Child.Calls (1); Pos := Pos + 1; Child := Child.Next; end loop; end; end if; return Pc; end Calls; -- ------------------------------ -- Returns the current stack depth (# of calls from the root -- to reach the frame). -- ------------------------------ function Current_Depth (Frame : in Frame_Type) return Natural is begin if Frame = null then return 0; else return Frame.Depth; end if; end Current_Depth; -- ------------------------------ -- Create a root for stack frame representation. -- ------------------------------ function Create_Root return Frame_Type is begin return new Frame; end Create_Root; -- ------------------------------ -- Destroy the frame tree recursively. -- ------------------------------ procedure Destroy (Frame : in out Frame_Type) is F : Frame_Type; begin if Frame = null then return; end if; -- Destroy its children recursively. while Frame.Children /= null loop F := Frame.Children; Destroy (F); end loop; -- Unlink from parent list. if Frame.Parent /= null then F := Frame.Parent.Children; if F = Frame then Frame.Parent.Children := Frame.Next; else while F /= null and then F.Next /= Frame loop F := F.Next; end loop; if F = null then -- Log.Error ("Frame is not linked to the correct parent"); -- if not Check (Get_Root (Frame)) then -- Log.Error ("Check failed"); -- else -- Log.Error ("Check is ok"); -- end if; -- MAT.Frames.Print (Ada.Text_IO.Standard_Output, Get_Root (Frame)); return; else F.Next := Frame.Next; end if; end if; end if; -- Free (Frame); end Destroy; -- ------------------------------ -- Release the frame when its reference is no longer necessary. -- ------------------------------ procedure Release (Frame : in Frame_Type) is Current : Frame_Type := Frame; begin -- Scan the frame until the root is reached -- and decrement the used counter. Free the frames -- when the used counter reaches 0. while Current /= null loop if Current.Used <= 1 then declare Tree : Frame_Type := Current; begin Current := Current.Parent; Destroy (Tree); end; else Current.Used := Current.Used - 1; Current := Current.Parent; end if; end loop; if not Check (Get_Root (Frame)) then Log.Error ("Frame is invalid"); end if; end Release; -- ------------------------------ -- Split the node pointed to by `F' at the position `Pos' -- in the caller chain. A new parent is created for the node -- and the brothers of the node become the brothers of the -- new parent. -- -- Returns in `F' the new parent node. -- ------------------------------ procedure Split (F : in out Frame_Type; Pos : in Positive) is -- Before: After: -- -- +-------+ +-------+ -- /-| P | /-| P | -- | +-------+ | +-------+ -- | ^ | ^ -- | +-------+ | +-------+ -- ...>| node |... ....>| new |... (0..N brothers) -- +-------+ +-------+ -- | ^ | ^ -- | +-------+ | +-------+ -- ->| c | ->| node |-->0 (0 brother) -- +-------+ +-------+ -- | -- +-------+ -- | c | -- +-------+ -- New_Parent : constant Frame_Type := new Frame '(Parent => F.Parent, Next => F.Next, Children => F, Used => F.Used - 1, Depth => F.Depth, Local_Depth => Pos, Calls => (others => 0)); Child : Frame_Type := F.Parent.Children; begin Log.Debug ("Split frame"); -- Move the PC values in the new parent. New_Parent.Calls (1 .. Pos) := F.Calls (1 .. Pos); F.Calls (1 .. F.Local_Depth - Pos) := F.Calls (Pos + 1 .. F.Local_Depth); F.Parent := New_Parent; F.Next := null; F.Used := F.Used - 1; New_Parent.Depth := F.Depth - F.Local_Depth + Pos; F.Local_Depth := F.Local_Depth - Pos; -- Remove F from its parent children list and replace if with New_Parent. if Child = F then New_Parent.Parent.Children := New_Parent; else while Child.Next /= F loop Child := Child.Next; end loop; Child.Next := New_Parent; end if; F := New_Parent; if not Check (Get_Root (F)) then Log.Error ("Error when splitting frame"); end if; end Split; procedure Add_Frame (F : in Frame_Type; Pc : in Frame_Table; Result : out Frame_Type) is Child : Frame_Type := F; Pos : Positive := Pc'First; Current_Depth : Natural := F.Depth; Cnt : Local_Depth_Type; begin while Pos <= Pc'Last loop Cnt := Frame_Group_Size; if Pos + Cnt > Pc'Last then Cnt := Pc'Last - Pos + 1; end if; Current_Depth := Current_Depth + Cnt; Child := new Frame '(Parent => Child, Next => Child.Children, Children => null, Used => 1, Depth => Current_Depth, Local_Depth => Cnt, Calls => (others => 0)); Child.Calls (1 .. Cnt) := Pc (Pos .. Pos + Cnt - 1); Pos := Pos + Cnt; Child.Parent.Children := Child; if not Check (Get_Root (Child)) then Log.Error ("Error when adding frame"); end if; end loop; Result := Child; end Add_Frame; -- ------------------------------ -- Insert in the frame tree the new stack frame represented by <tt>Pc</tt>. -- If the frame is already known, the frame reference counter is incremented. -- The frame represented by <tt>Pc</tt> is returned in <tt>Result</tt>. -- ------------------------------ procedure Insert (Frame : in Frame_Type; Pc : in Frame_Table; Result : out Frame_Type) is Current : Frame_Type := Frame; Child : Frame_Type; Pos : Positive := Pc'First; Lpos : Positive := 1; Addr : MAT.Types.Target_Addr; begin while Pos <= Pc'Last loop Addr := Pc (Pos); if Lpos <= Current.Local_Depth then if Addr = Current.Calls (Lpos) then Lpos := Lpos + 1; Pos := Pos + 1; -- Split this node else Current.Used := Current.Used + 1; if Lpos > 1 then Split (Current, Lpos - 1); end if; Add_Frame (Current, Pc (Pos .. Pc'Last), Result); return; end if; else -- Find the first child which has the address. Child := Current.Children; while Child /= null loop exit when Child.Calls (1) = Addr; Child := Child.Next; end loop; if Child = null then Current.Used := Current.Used + 1; Add_Frame (Current, Pc (Pos .. Pc'Last), Result); return; end if; Current.Used := Current.Used + 1; Current := Child; Lpos := 2; Pos := Pos + 1; end if; end loop; if Lpos <= Current.Local_Depth then Split (Current, Lpos - 1); end if; Result := Current; end Insert; -- ------------------------------ -- Find the child frame which has the given PC address. -- Returns that frame pointer or raises the Not_Found exception. -- ------------------------------ function Find (Frame : in Frame_Type; Pc : in MAT.Types.Target_Addr) return Frame_Type is Child : Frame_Type := Frame.Children; begin while Child /= null loop if Child.Local_Depth >= 1 and then Child.Calls (1) = Pc then return Child; end if; Child := Child.Next; end loop; raise Not_Found; end Find; -- ------------------------------ -- Find the child frame which has the given PC address. -- Returns that frame pointer or raises the Not_Found exception. -- ------------------------------ function Find (Frame : in Frame_Type; Pc : in Frame_Table) return Frame_Type is Child : Frame_Type := Frame; Pos : Positive := Pc'First; Lpos : Positive; begin while Pos <= Pc'Last loop Child := Find (Child, Pc (Pos)); Pos := Pos + 1; Lpos := 2; -- All the PC of the child frame must match. while Pos <= Pc'Last and Lpos <= Child.Local_Depth loop if Child.Calls (Lpos) /= Pc (Pos) then raise Not_Found; end if; Lpos := Lpos + 1; Pos := Pos + 1; end loop; end loop; return Child; end Find; -- ------------------------------ -- Find the child frame which has the given PC address. -- Returns that frame pointer or raises the Not_Found exception. -- ------------------------------ procedure Find (Frame : in Frame_Type; Pc : in Frame_Table; Result : out Frame_Type; Last_Pc : out Natural) is Current : Frame_Type := Frame; Pos : Positive := Pc'First; Lpos : Positive; begin Main_Search : while Pos <= Pc'Last loop declare Addr : constant MAT.Types.Target_Addr := Pc (Pos); Child : Frame_Type := Current.Children; begin -- Find the child which has the corresponding PC. loop exit Main_Search when Child = null; exit when Child.Local_Depth >= 1 and Child.Calls (1) = Addr; Child := Child.Next; end loop; Current := Child; Pos := Pos + 1; Lpos := 2; -- All the PC of the child frame must match. while Pos <= Pc'Last and Lpos <= Current.Local_Depth loop exit Main_Search when Current.Calls (Lpos) /= Pc (Pos); Lpos := Lpos + 1; Pos := Pos + 1; end loop; end; end loop Main_Search; Result := Current; if Pos > Pc'Last then Last_Pc := 0; else Last_Pc := Pos; end if; end Find; end MAT.Frames;
----------------------------------------------------------------------- -- mat-frames - Representation of stack frames -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Unchecked_Deallocation; with Ada.Text_IO; with Util.Log.Loggers; with MAT.Frames.Print; package body MAT.Frames is use type MAT.Types.Target_Addr; procedure Free is new Ada.Unchecked_Deallocation (Frame, Frame_Type); -- The logger Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("MAT.Frames.Targets"); procedure Split (F : in out Frame_Type; Pos : in Positive); procedure Add_Frame (F : in Frame_Type; Pc : in Frame_Table; Result : out Frame_Type); function Check (Frame : in Frame_Type) return Boolean is Parent : Frame_Type; Child : Frame_Type; Result : Boolean := True; begin if Frame = null then return False; end if; Child := Frame.Children; while Child /= null loop if Child.Parent /= Frame then Log.Error ("Invalid parent link"); Result := False; end if; if Child.Children /= null and then not Check (Child) then Log.Error ("A child is now invalid"); Result := False; end if; Child := Child.Next; end loop; return Result; end Check; -- ------------------------------ -- Return the parent frame. -- ------------------------------ function Parent (Frame : in Frame_Type) return Frame_Type is begin if Frame = null then return null; else return Frame.Parent; end if; end Parent; -- ------------------------------ -- Get the root frame object. -- ------------------------------ function Get_Root (Frame : in Frame_Type) return Frame_Type is Parent : Frame_Type := Frame; begin loop if Parent.Parent = null then return Parent; end if; Parent := Parent.Parent; end loop; end Get_Root; -- ------------------------------ -- Returns the backtrace of the current frame (up to the root). -- When <tt>Max_Level</tt> is positive, limit the number of PC frames to the value. -- ------------------------------ function Backtrace (Frame : in Frame_Type; Max_Level : in Natural := 0) return Frame_Table is Length : Natural; begin if Max_Level > 0 and Max_Level < Frame.Depth then Length := Max_Level; else Length := Frame.Depth; end if; declare Current : Frame_Type := Frame; Pos : Natural := Current.Depth; New_Pos : Natural; Pc : Frame_Table (1 .. Length); begin while Current /= null and Pos /= 0 loop New_Pos := Pos - Current.Local_Depth + 1; Pc (New_Pos .. Pos) := Current.Calls (1 .. Current.Local_Depth); Pos := New_Pos - 1; Current := Current.Parent; end loop; return Pc; end; end Backtrace; -- ------------------------------ -- 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 is Count : Natural := 0; Child : Frame_Type; begin if Frame /= null then Child := Frame.Children; while Child /= null loop Count := Count + 1; if Recursive then declare N : Natural := Count_Children (Child, True); begin if N > 0 then N := N - 1; end if; Count := Count + N; end; end if; Child := Child.Next; end loop; end if; return Count; end Count_Children; -- ------------------------------ -- Returns all the direct calls made by the current frame. -- ------------------------------ function Calls (Frame : in Frame_Type) return Frame_Table is Nb_Calls : constant Natural := Count_Children (Frame); Pc : Frame_Table (1 .. Nb_Calls); begin if Frame /= null then declare Child : Frame_Type := Frame.Children; Pos : Natural := 1; begin while Child /= null loop Pc (Pos) := Child.Calls (1); Pos := Pos + 1; Child := Child.Next; end loop; end; end if; return Pc; end Calls; -- ------------------------------ -- Returns the current stack depth (# of calls from the root -- to reach the frame). -- ------------------------------ function Current_Depth (Frame : in Frame_Type) return Natural is begin if Frame = null then return 0; else return Frame.Depth; end if; end Current_Depth; -- ------------------------------ -- Create a root for stack frame representation. -- ------------------------------ function Create_Root return Frame_Type is begin return new Frame; end Create_Root; -- ------------------------------ -- Destroy the frame tree recursively. -- ------------------------------ procedure Destroy (Frame : in out Frame_Type) is F : Frame_Type; begin if Frame = null then return; end if; -- Destroy its children recursively. while Frame.Children /= null loop F := Frame.Children; Destroy (F); end loop; -- Unlink from parent list. if Frame.Parent /= null then F := Frame.Parent.Children; if F = Frame then Frame.Parent.Children := Frame.Next; else while F /= null and then F.Next /= Frame loop F := F.Next; end loop; if F = null then -- Log.Error ("Frame is not linked to the correct parent"); -- if not Check (Get_Root (Frame)) then -- Log.Error ("Check failed"); -- else -- Log.Error ("Check is ok"); -- end if; -- MAT.Frames.Print (Ada.Text_IO.Standard_Output, Get_Root (Frame)); return; else F.Next := Frame.Next; end if; end if; end if; -- Free (Frame); end Destroy; -- ------------------------------ -- Release the frame when its reference is no longer necessary. -- ------------------------------ procedure Release (Frame : in Frame_Type) is Current : Frame_Type := Frame; begin -- Scan the frame until the root is reached -- and decrement the used counter. Free the frames -- when the used counter reaches 0. while Current /= null loop if Current.Used <= 1 then declare Tree : Frame_Type := Current; begin Current := Current.Parent; Destroy (Tree); end; else Current.Used := Current.Used - 1; Current := Current.Parent; end if; end loop; if not Check (Get_Root (Frame)) then Log.Error ("Frame is invalid"); end if; end Release; -- ------------------------------ -- Split the node pointed to by `F' at the position `Pos' -- in the caller chain. A new parent is created for the node -- and the brothers of the node become the brothers of the -- new parent. -- -- Returns in `F' the new parent node. -- ------------------------------ procedure Split (F : in out Frame_Type; Pos : in Positive) is -- Before: After: -- -- +-------+ +-------+ -- /-| P | /-| P | -- | +-------+ | +-------+ -- | ^ | ^ -- | +-------+ | +-------+ -- ...>| node |... ....>| new |... (0..N brothers) -- +-------+ +-------+ -- | ^ | ^ -- | +-------+ | +-------+ -- ->| c | ->| node |-->0 (0 brother) -- +-------+ +-------+ -- | -- +-------+ -- | c | -- +-------+ -- New_Parent : constant Frame_Type := new Frame '(Parent => F.Parent, Next => F.Next, Children => F, Used => F.Used - 1, Depth => F.Depth, Local_Depth => Pos, Calls => (others => 0)); Child : Frame_Type := F.Parent.Children; begin Log.Debug ("Split frame"); -- Move the PC values in the new parent. New_Parent.Calls (1 .. Pos) := F.Calls (1 .. Pos); F.Calls (1 .. F.Local_Depth - Pos) := F.Calls (Pos + 1 .. F.Local_Depth); F.Parent := New_Parent; F.Next := null; F.Used := F.Used - 1; New_Parent.Depth := F.Depth - F.Local_Depth + Pos; F.Local_Depth := F.Local_Depth - Pos; -- Remove F from its parent children list and replace if with New_Parent. if Child = F then New_Parent.Parent.Children := New_Parent; else while Child.Next /= F loop Child := Child.Next; end loop; Child.Next := New_Parent; end if; F := New_Parent; if not Check (Get_Root (F)) then Log.Error ("Error when splitting frame"); end if; end Split; procedure Add_Frame (F : in Frame_Type; Pc : in Frame_Table; Result : out Frame_Type) is Child : Frame_Type := F; Pos : Positive := Pc'First; Current_Depth : Natural := F.Depth; Cnt : Local_Depth_Type; begin while Pos <= Pc'Last loop Cnt := Frame_Group_Size; if Pos + Cnt > Pc'Last then Cnt := Pc'Last - Pos + 1; end if; Current_Depth := Current_Depth + Cnt; Child := new Frame '(Parent => Child, Next => Child.Children, Children => null, Used => 1, Depth => Current_Depth, Local_Depth => Cnt, Calls => (others => 0)); Child.Calls (1 .. Cnt) := Pc (Pos .. Pos + Cnt - 1); Pos := Pos + Cnt; Child.Parent.Children := Child; if not Check (Get_Root (Child)) then Log.Error ("Error when adding frame"); end if; end loop; Result := Child; end Add_Frame; -- ------------------------------ -- Insert in the frame tree the new stack frame represented by <tt>Pc</tt>. -- If the frame is already known, the frame reference counter is incremented. -- The frame represented by <tt>Pc</tt> is returned in <tt>Result</tt>. -- ------------------------------ procedure Insert (Frame : in Frame_Type; Pc : in Frame_Table; Result : out Frame_Type) is Current : Frame_Type := Frame; Child : Frame_Type; Pos : Positive := Pc'First; Lpos : Positive := 1; Addr : MAT.Types.Target_Addr; begin while Pos <= Pc'Last loop Addr := Pc (Pos); if Lpos <= Current.Local_Depth then if Addr = Current.Calls (Lpos) then Lpos := Lpos + 1; Pos := Pos + 1; -- Split this node else Current.Used := Current.Used + 1; if Lpos > 1 then Split (Current, Lpos - 1); end if; Add_Frame (Current, Pc (Pos .. Pc'Last), Result); return; end if; else -- Find the first child which has the address. Child := Current.Children; while Child /= null loop exit when Child.Calls (1) = Addr; Child := Child.Next; end loop; if Child = null then Current.Used := Current.Used + 1; Add_Frame (Current, Pc (Pos .. Pc'Last), Result); return; end if; Current.Used := Current.Used + 1; Current := Child; Lpos := 2; Pos := Pos + 1; end if; end loop; if Lpos <= Current.Local_Depth then Split (Current, Lpos - 1); end if; Result := Current; end Insert; -- ------------------------------ -- Find the child frame which has the given PC address. -- Returns that frame pointer or raises the Not_Found exception. -- ------------------------------ function Find (Frame : in Frame_Type; Pc : in MAT.Types.Target_Addr) return Frame_Type is Child : Frame_Type := Frame.Children; begin while Child /= null loop if Child.Local_Depth >= 1 and then Child.Calls (1) = Pc then return Child; end if; Child := Child.Next; end loop; raise Not_Found; end Find; -- ------------------------------ -- Find the child frame which has the given PC address. -- Returns that frame pointer or raises the Not_Found exception. -- ------------------------------ function Find (Frame : in Frame_Type; Pc : in Frame_Table) return Frame_Type is Child : Frame_Type := Frame; Pos : Positive := Pc'First; Lpos : Positive; begin while Pos <= Pc'Last loop Child := Find (Child, Pc (Pos)); Pos := Pos + 1; Lpos := 2; -- All the PC of the child frame must match. while Pos <= Pc'Last and Lpos <= Child.Local_Depth loop if Child.Calls (Lpos) /= Pc (Pos) then raise Not_Found; end if; Lpos := Lpos + 1; Pos := Pos + 1; end loop; end loop; return Child; end Find; -- ------------------------------ -- Find the child frame which has the given PC address. -- Returns that frame pointer or raises the Not_Found exception. -- ------------------------------ procedure Find (Frame : in Frame_Type; Pc : in Frame_Table; Result : out Frame_Type; Last_Pc : out Natural) is Current : Frame_Type := Frame; Pos : Positive := Pc'First; Lpos : Positive; begin Main_Search : while Pos <= Pc'Last loop declare Addr : constant MAT.Types.Target_Addr := Pc (Pos); Child : Frame_Type := Current.Children; begin -- Find the child which has the corresponding PC. loop exit Main_Search when Child = null; exit when Child.Local_Depth >= 1 and Child.Calls (1) = Addr; Child := Child.Next; end loop; Current := Child; Pos := Pos + 1; Lpos := 2; -- All the PC of the child frame must match. while Pos <= Pc'Last and Lpos <= Current.Local_Depth loop exit Main_Search when Current.Calls (Lpos) /= Pc (Pos); Lpos := Lpos + 1; Pos := Pos + 1; end loop; end; end loop Main_Search; Result := Current; if Pos > Pc'Last then Last_Pc := 0; else Last_Pc := Pos; end if; end Find; end MAT.Frames;
Use Max_Level to limit the backtrace operation to the N's up most frames
Use Max_Level to limit the backtrace operation to the N's up most frames
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
5a108f08ce42cb03c24e4e194d88c0b2a8d910ff
regtests/util-streams-buffered-lzma-tests.adb
regtests/util-streams-buffered-lzma-tests.adb
----------------------------------------------------------------------- -- util-streams-buffered-lzma-tests -- Unit tests for encoding buffered streams -- Copyright (C) 2018, 2019 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Test_Caller; with Util.Streams.Files; with Util.Streams.Texts; with Ada.Streams.Stream_IO; package body Util.Streams.Buffered.Lzma.Tests is use Util.Streams.Files; use Ada.Streams.Stream_IO; package Caller is new Util.Test_Caller (Test, "Streams.Buffered.Lzma"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test Util.Streams.Buffered.Lzma.Write", Test_Compress_Stream'Access); Caller.Add_Test (Suite, "Test Util.Streams.Buffered.Lzma.Write (2)", Test_Compress_File_Stream'Access); end Add_Tests; procedure Test_Compress_Stream (T : in out Test) is Stream : aliased File_Stream; Buffer : aliased Util.Streams.Buffered.Lzma.Compress_Stream; Print : Util.Streams.Texts.Print_Stream; Path : constant String := Util.Tests.Get_Test_Path ("regtests/result/test-stream.lzma"); Expect : constant String := Util.Tests.Get_Path ("regtests/expect/test-stream.lzma"); begin Stream.Create (Mode => Out_File, Name => Path); Buffer.Initialize (Output => Stream'Unchecked_Access, Size => 1024); Print.Initialize (Output => Buffer'Unchecked_Access, Size => 5); for I in 1 .. 32 loop Print.Write ("abcd"); Print.Write (" fghij"); Print.Write (ASCII.LF); end loop; Print.Flush; Stream.Close; Util.Tests.Assert_Equal_Files (T => T, Expect => Expect, Test => Path, Message => "LZMA stream"); end Test_Compress_Stream; procedure Test_Compress_File_Stream (T : in out Test) is Stream : aliased File_Stream; In_Stream : aliased File_Stream; Buffer : aliased Util.Streams.Buffered.Lzma.Compress_Stream; Path : constant String := Util.Tests.Get_Test_Path ("regtests/result/test-big-stream.lzma"); Expect : constant String := Util.Tests.Get_Path ("regtests/expect/test-big-stream.lzma"); begin In_Stream.Open (Ada.Streams.Stream_IO.In_File, Util.Tests.Get_Path ("regtests/files/test-big-stream.bin")); Stream.Create (Mode => Out_File, Name => Path); Buffer.Initialize (Output => Stream'Unchecked_Access, Size => 32768); Util.Streams.Copy (From => In_Stream, Into => Buffer); Buffer.Flush; Buffer.Close; Util.Tests.Assert_Equal_Files (T => T, Expect => Expect, Test => Path, Message => "LZMA stream"); end Test_Compress_File_Stream; end Util.Streams.Buffered.Lzma.Tests;
----------------------------------------------------------------------- -- util-streams-buffered-lzma-tests -- Unit tests for encoding buffered streams -- Copyright (C) 2018, 2019 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Test_Caller; with Util.Streams.Files; with Util.Streams.Texts; with Ada.Streams.Stream_IO; package body Util.Streams.Buffered.Lzma.Tests is use Util.Streams.Files; use Ada.Streams.Stream_IO; package Caller is new Util.Test_Caller (Test, "Streams.Buffered.Lzma"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test Util.Streams.Buffered.Lzma.Write", Test_Compress_Stream'Access); Caller.Add_Test (Suite, "Test Util.Streams.Buffered.Lzma.Write (2)", Test_Compress_File_Stream'Access); end Add_Tests; procedure Test_Compress_Stream (T : in out Test) is Stream : aliased File_Stream; Buffer : aliased Util.Streams.Buffered.Lzma.Compress_Stream; Print : Util.Streams.Texts.Print_Stream; Path : constant String := Util.Tests.Get_Test_Path ("regtests/result/test-stream.lzma"); Expect : constant String := Util.Tests.Get_Path ("regtests/expect/test-stream.lzma"); begin Stream.Create (Mode => Out_File, Name => Path); Buffer.Initialize (Output => Stream'Access, Size => 1024); Print.Initialize (Output => Buffer'Access, Size => 5); for I in 1 .. 32 loop Print.Write ("abcd"); Print.Write (" fghij"); Print.Write (ASCII.LF); end loop; Print.Flush; Stream.Close; Util.Tests.Assert_Equal_Files (T => T, Expect => Expect, Test => Path, Message => "LZMA stream"); end Test_Compress_Stream; procedure Test_Compress_File_Stream (T : in out Test) is Stream : aliased File_Stream; In_Stream : aliased File_Stream; Buffer : aliased Util.Streams.Buffered.Lzma.Compress_Stream; Path : constant String := Util.Tests.Get_Test_Path ("regtests/result/test-big-stream.lzma"); Expect : constant String := Util.Tests.Get_Path ("regtests/expect/test-big-stream.lzma"); begin In_Stream.Open (Ada.Streams.Stream_IO.In_File, Util.Tests.Get_Path ("regtests/files/test-big-stream.bin")); Stream.Create (Mode => Out_File, Name => Path); Buffer.Initialize (Output => Stream'Access, Size => 32768); Util.Streams.Copy (From => In_Stream, Into => Buffer); Buffer.Flush; Buffer.Close; Util.Tests.Assert_Equal_Files (T => T, Expect => Expect, Test => Path, Message => "LZMA stream"); end Test_Compress_File_Stream; end Util.Streams.Buffered.Lzma.Tests;
Replace Unchecked_Access by Access in stream initialization
Replace Unchecked_Access by Access in stream initialization
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
34df5eb27dfcc451c2eb076f0c3a686d7f7c4b96
awa/plugins/awa-blogs/src/awa-blogs-beans.ads
awa/plugins/awa-blogs/src/awa-blogs-beans.ads
----------------------------------------------------------------------- -- awa-blogs-beans -- Beans for blog module -- Copyright (C) 2011, 2012, 2013, 2014, 2015, 2016, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Ada.Containers.Indefinite_Hashed_Maps; with Ada.Strings.Wide_Wide_Hash; with Ada.Strings.Wide_Wide_Unbounded; with Util.Beans.Basic; with Util.Beans.Objects; with ADO; with ADO.Objects; with Wiki.Strings; with AWA.Blogs.Modules; with AWA.Blogs.Models; with AWA.Tags.Beans; with AWA.Counters.Beans; with AWA.Events; with AWA.Components.Wikis; with ASF.Rest.Definition; -- == Blog Beans == -- Several bean types are provided to represent and manage the blogs and their posts. -- The blog module registers the bean constructors when it is initialized. -- To use them, one must declare a bean definition in the application XML configuration. package AWA.Blogs.Beans is -- Attributes exposed by <b>Post_Bean</b> BLOG_ID_ATTR : constant String := "blogId"; POST_ID_ATTR : constant String := "id"; POST_UID_ATTR : constant String := "uid"; POST_TITLE_ATTR : constant String := "title"; POST_TEXT_ATTR : constant String := "text"; POST_URI_ATTR : constant String := "uri"; POST_STATUS_ATTR : constant String := "status"; POST_USERNAME_ATTR : constant String := "username"; POST_TAG_ATTR : constant String := "tags"; POST_ALLOW_COMMENTS_ATTR : constant String := "allow_comments"; COUNTER_ATTR : constant String := "counter"; use Ada.Strings.Wide_Wide_Unbounded; package Image_Info_Maps is new Ada.Containers.Indefinite_Hashed_Maps (Key_Type => Wiki.Strings.WString, Element_Type => Models.Image_Info, Hash => Ada.Strings.Wide_Wide_Hash, Equivalent_Keys => "=", "=" => Models."="); type Post_Links_Bean is new AWA.Components.Wikis.Link_Renderer_Bean with record -- The wiki space identifier. Post_Id : ADO.Identifier; Images : Image_Info_Maps.Map; end record; procedure Make_Image_Link (Renderer : in out Post_Links_Bean; Link : in Wiki.Strings.WString; Info : in AWA.Blogs.Models.Image_Info; URI : out Unbounded_Wide_Wide_String; Width : in out Natural; Height : in out Natural); procedure Find_Image_Link (Renderer : in out Post_Links_Bean; Link : in Wiki.Strings.WString; URI : out Unbounded_Wide_Wide_String; Width : in out Natural; Height : in out Natural); -- Get the image link that must be rendered from the wiki image link. overriding procedure Make_Image_Link (Renderer : in out Post_Links_Bean; Link : in Wiki.Strings.WString; URI : out Unbounded_Wide_Wide_String; Width : in out Natural; Height : in out Natural); -- Get the page link that must be rendered from the wiki page link. overriding procedure Make_Page_Link (Renderer : in out Post_Links_Bean; Link : in Wiki.Strings.WString; URI : out Unbounded_Wide_Wide_String; Exists : out Boolean); -- ------------------------------ -- Blog Bean -- ------------------------------ -- The <b>Blog_Bean</b> holds the information about the current blog. -- It allows to create the blog as well as update its primary title. type Blog_Bean is new AWA.Blogs.Models.Blog_Bean with record Module : AWA.Blogs.Modules.Blog_Module_Access := null; end record; type Blog_Bean_Access is access all Blog_Bean'Class; -- Get the value identified by the name. overriding function Get_Value (From : in Blog_Bean; Name : in String) return Util.Beans.Objects.Object; -- Set the value identified by the name. overriding procedure Set_Value (From : in out Blog_Bean; Name : in String; Value : in Util.Beans.Objects.Object); -- Create a new blog. overriding procedure Create (Bean : in out Blog_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- Load the blog information. overriding procedure Load (Bean : in out Blog_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- Handle an event to create the blog entry automatically. overriding procedure Create_Default (Bean : in out Blog_Bean; Event : in AWA.Events.Module_Event'Class); -- Create the Blog_Bean bean instance. function Create_Blog_Bean (Module : in AWA.Blogs.Modules.Blog_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access; -- ------------------------------ -- Post Bean -- ------------------------------ -- The <b>Post_Bean</b> is used to create or update a post associated with a blog. type Post_Bean is new AWA.Blogs.Models.Post_Bean with record Module : AWA.Blogs.Modules.Blog_Module_Access := null; Blog_Id : ADO.Identifier := ADO.NO_IDENTIFIER; -- List of tags associated with the post. Tags : aliased AWA.Tags.Beans.Tag_List_Bean; Tags_Bean : Util.Beans.Basic.Readonly_Bean_Access; -- The post page links. Links : aliased Post_Links_Bean; Links_Bean : Util.Beans.Basic.Readonly_Bean_Access; -- The read post counter associated with the post. Counter : aliased AWA.Counters.Beans.Counter_Bean (Of_Type => ADO.Objects.KEY_INTEGER, Of_Class => Models.POST_TABLE); Counter_Bean : Util.Beans.Basic.Readonly_Bean_Access; end record; type Post_Bean_Access is access all Post_Bean'Class; -- Get the value identified by the name. overriding function Get_Value (From : in Post_Bean; Name : in String) return Util.Beans.Objects.Object; -- Set the value identified by the name. overriding procedure Set_Value (From : in out Post_Bean; Name : in String; Value : in Util.Beans.Objects.Object); -- Load the post. procedure Load_Post (Post : in out Post_Bean; Id : in ADO.Identifier); -- Create or save the post. overriding procedure Save (Bean : in out Post_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- Delete a post. overriding procedure Delete (Bean : in out Post_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- Load the post from the URI for the public display. overriding procedure Load (Bean : in out Post_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- Load the post from the URI for the administrator. overriding procedure Load_Admin (Bean : in out Post_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- Load the post from the URI either with visible comments or with all comments. procedure Load (Bean : in out Post_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String; Publish_Only : in Boolean); -- Create the Post_Bean bean instance. function Create_Post_Bean (Module : in AWA.Blogs.Modules.Blog_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access; procedure Create (Bean : in out Post_Bean; Req : in out ASF.Rest.Request'Class; Reply : in out ASF.Rest.Response'Class); procedure Update (Bean : in out Post_Bean; Req : in out ASF.Rest.Request'Class; Reply : in out ASF.Rest.Response'Class); package Post_API is new ASF.Rest.Definition (Object_Type => Post_Bean, URI => "/blogs/:blog_id/posts"); -- -- package API_Post_Create is -- new Post_API.Definition (Create'Access, ASF.Rest.POST, ""); -- -- package API_Post_Update is -- new Post_API.Definition (Update'Access, ASF.Rest.PUT, ":id"); -- ------------------------------ -- Post List Bean -- ------------------------------ -- The <b>Post_List_Bean</b> gives a list of visible posts to be displayed to users. -- The list can be filtered by a given tag. The list pagination is supported. type Post_List_Bean is new AWA.Blogs.Models.Post_List_Bean with record Posts : aliased AWA.Blogs.Models.Post_Info_List_Bean; Service : Modules.Blog_Module_Access := null; Tags : AWA.Tags.Beans.Entity_Tag_Map; Posts_Bean : AWA.Blogs.Models.Post_Info_List_Bean_Access; -- The post page links. Links : aliased Post_Links_Bean; Links_Bean : access Post_Links_Bean; -- The read post counter associated with the post. Counter : aliased AWA.Counters.Beans.Counter_Bean (Of_Type => ADO.Objects.KEY_INTEGER, Of_Class => Models.POST_TABLE); Counter_Bean : AWA.Counters.Beans.Counter_Bean_Access; end record; type Post_List_Bean_Access is access all Post_List_Bean'Class; -- Get the value identified by the name. overriding function Get_Value (From : in Post_List_Bean; Name : in String) return Util.Beans.Objects.Object; -- Set the value identified by the name. overriding procedure Set_Value (From : in out Post_List_Bean; Name : in String; Value : in Util.Beans.Objects.Object); overriding procedure Load (From : in out Post_List_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- Load the list of posts. If a tag was set, filter the list of posts with the tag. procedure Load_List (Into : in out Post_List_Bean); -- Create the Post_List_Bean bean instance. function Create_Post_List_Bean (Module : in AWA.Blogs.Modules.Blog_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access; -- Get a select item list which contains a list of post status. function Create_Status_List (Module : in AWA.Blogs.Modules.Blog_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access; type Init_Flag is (INIT_BLOG_LIST, INIT_POST_LIST, INIT_COMMENT_LIST); type Init_Map is array (Init_Flag) of Boolean; -- ------------------------------ -- Admin List Bean -- ------------------------------ -- The <b>Blog_Admin_Bean</b> is used for the administration of a blog. It gives the -- list of posts that are created, published or not. type Blog_Admin_Bean is new Util.Beans.Basic.Bean with record Module : AWA.Blogs.Modules.Blog_Module_Access := null; -- The blog identifier. Blog_Id : ADO.Identifier := ADO.NO_IDENTIFIER; -- List of blogs. Blog_List : aliased AWA.Blogs.Models.Blog_Info_List_Bean; Blog_List_Bean : AWA.Blogs.Models.Blog_Info_List_Bean_Access; -- List of posts. Post_List : aliased AWA.Blogs.Models.Admin_Post_Info_List_Bean; Post_List_Bean : AWA.Blogs.Models.Admin_Post_Info_List_Bean_Access; -- List of comments. Comment_List : aliased AWA.Blogs.Models.Comment_Info_List_Bean; Comment_List_Bean : AWA.Blogs.Models.Comment_Info_List_Bean_Access; -- Initialization flags. Init_Flags : aliased Init_Map := (others => False); Flags : access Init_Map; end record; type Blog_Admin_Bean_Access is access all Blog_Admin_Bean; -- Get the blog identifier. function Get_Blog_Id (List : in Blog_Admin_Bean) return ADO.Identifier; -- Load the posts associated with the current blog. procedure Load_Posts (List : in Blog_Admin_Bean); -- Load the comments associated with the current blog. procedure Load_Comments (List : in Blog_Admin_Bean); overriding function Get_Value (List : in Blog_Admin_Bean; Name : in String) return Util.Beans.Objects.Object; -- Set the value identified by the name. overriding procedure Set_Value (From : in out Blog_Admin_Bean; Name : in String; Value : in Util.Beans.Objects.Object); -- Load the list of blogs. procedure Load_Blogs (List : in Blog_Admin_Bean); -- Create the Blog_Admin_Bean bean instance. function Create_Blog_Admin_Bean (Module : in AWA.Blogs.Modules.Blog_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access; -- ------------------------------ -- Blog Statistics Bean -- ------------------------------ -- The <b>Blog_Stat_Bean</b> is used to report various statistics about the blog or some post. type Blog_Stat_Bean is new AWA.Blogs.Models.Stat_List_Bean with record Module : AWA.Blogs.Modules.Blog_Module_Access := null; Stats : aliased AWA.Blogs.Models.Month_Stat_Info_List_Bean; Stats_Bean : AWA.Blogs.Models.Month_Stat_Info_List_Bean_Access; end record; type Blog_Stat_Bean_Access is access all Blog_Stat_Bean; overriding function Get_Value (List : in Blog_Stat_Bean; Name : in String) return Util.Beans.Objects.Object; -- Set the value identified by the name. overriding procedure Set_Value (From : in out Blog_Stat_Bean; Name : in String; Value : in Util.Beans.Objects.Object); -- Load the statistics information. overriding procedure Load (List : in out Blog_Stat_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- Create the Blog_Stat_Bean bean instance. function Create_Blog_Stat_Bean (Module : in AWA.Blogs.Modules.Blog_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access; end AWA.Blogs.Beans;
----------------------------------------------------------------------- -- awa-blogs-beans -- Beans for blog module -- Copyright (C) 2011, 2012, 2013, 2014, 2015, 2016, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Calendar; with Ada.Strings.Unbounded; with Ada.Containers.Indefinite_Hashed_Maps; with Ada.Strings.Wide_Wide_Hash; with Ada.Strings.Wide_Wide_Unbounded; with Util.Beans.Basic; with Util.Beans.Objects; with ADO; with ADO.Objects; with Wiki.Strings; with AWA.Blogs.Modules; with AWA.Blogs.Models; with AWA.Tags.Beans; with AWA.Counters.Beans; with AWA.Events; with AWA.Components.Wikis; with ASF.Rest.Definition; -- == Blog Beans == -- Several bean types are provided to represent and manage the blogs and their posts. -- The blog module registers the bean constructors when it is initialized. -- To use them, one must declare a bean definition in the application XML configuration. package AWA.Blogs.Beans is -- Attributes exposed by <b>Post_Bean</b> BLOG_ID_ATTR : constant String := "blogId"; POST_ID_ATTR : constant String := "id"; POST_UID_ATTR : constant String := "uid"; POST_TITLE_ATTR : constant String := "title"; POST_TEXT_ATTR : constant String := "text"; POST_URI_ATTR : constant String := "uri"; POST_STATUS_ATTR : constant String := "status"; POST_USERNAME_ATTR : constant String := "username"; POST_TAG_ATTR : constant String := "tags"; POST_ALLOW_COMMENTS_ATTR : constant String := "allow_comments"; COUNTER_ATTR : constant String := "counter"; use Ada.Strings.Wide_Wide_Unbounded; package Image_Info_Maps is new Ada.Containers.Indefinite_Hashed_Maps (Key_Type => Wiki.Strings.WString, Element_Type => Models.Image_Info, Hash => Ada.Strings.Wide_Wide_Hash, Equivalent_Keys => "=", "=" => Models."="); type Post_Links_Bean is new AWA.Components.Wikis.Link_Renderer_Bean with record -- The wiki space identifier. Post_Id : ADO.Identifier; Images : Image_Info_Maps.Map; end record; procedure Make_Image_Link (Renderer : in out Post_Links_Bean; Link : in Wiki.Strings.WString; Info : in AWA.Blogs.Models.Image_Info; URI : out Unbounded_Wide_Wide_String; Width : in out Natural; Height : in out Natural); procedure Find_Image_Link (Renderer : in out Post_Links_Bean; Link : in Wiki.Strings.WString; URI : out Unbounded_Wide_Wide_String; Width : in out Natural; Height : in out Natural); -- Get the image link that must be rendered from the wiki image link. overriding procedure Make_Image_Link (Renderer : in out Post_Links_Bean; Link : in Wiki.Strings.WString; URI : out Unbounded_Wide_Wide_String; Width : in out Natural; Height : in out Natural); -- Get the page link that must be rendered from the wiki page link. overriding procedure Make_Page_Link (Renderer : in out Post_Links_Bean; Link : in Wiki.Strings.WString; URI : out Unbounded_Wide_Wide_String; Exists : out Boolean); -- ------------------------------ -- Blog Bean -- ------------------------------ -- The <b>Blog_Bean</b> holds the information about the current blog. -- It allows to create the blog as well as update its primary title. type Blog_Bean is new AWA.Blogs.Models.Blog_Bean with record Module : AWA.Blogs.Modules.Blog_Module_Access := null; end record; type Blog_Bean_Access is access all Blog_Bean'Class; -- Get the value identified by the name. overriding function Get_Value (From : in Blog_Bean; Name : in String) return Util.Beans.Objects.Object; -- Set the value identified by the name. overriding procedure Set_Value (From : in out Blog_Bean; Name : in String; Value : in Util.Beans.Objects.Object); -- Create a new blog. overriding procedure Create (Bean : in out Blog_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- Load the blog information. overriding procedure Load (Bean : in out Blog_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- Handle an event to create the blog entry automatically. overriding procedure Create_Default (Bean : in out Blog_Bean; Event : in AWA.Events.Module_Event'Class); -- Create the Blog_Bean bean instance. function Create_Blog_Bean (Module : in AWA.Blogs.Modules.Blog_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access; -- ------------------------------ -- Post Bean -- ------------------------------ -- The <b>Post_Bean</b> is used to create or update a post associated with a blog. type Post_Bean is new AWA.Blogs.Models.Post_Bean with record Module : AWA.Blogs.Modules.Blog_Module_Access := null; Blog_Id : ADO.Identifier := ADO.NO_IDENTIFIER; -- List of tags associated with the post. Tags : aliased AWA.Tags.Beans.Tag_List_Bean; Tags_Bean : Util.Beans.Basic.Readonly_Bean_Access; -- The post page links. Links : aliased Post_Links_Bean; Links_Bean : Util.Beans.Basic.Readonly_Bean_Access; -- The read post counter associated with the post. Counter : aliased AWA.Counters.Beans.Counter_Bean (Of_Type => ADO.Objects.KEY_INTEGER, Of_Class => Models.POST_TABLE); Counter_Bean : Util.Beans.Basic.Readonly_Bean_Access; end record; type Post_Bean_Access is access all Post_Bean'Class; -- Build the URI from the post title and the post date. function Get_Predefined_Uri (Title : in String; Date : in Ada.Calendar.Time) return String; -- Get the value identified by the name. overriding function Get_Value (From : in Post_Bean; Name : in String) return Util.Beans.Objects.Object; -- Set the value identified by the name. overriding procedure Set_Value (From : in out Post_Bean; Name : in String; Value : in Util.Beans.Objects.Object); -- Load the post. procedure Load_Post (Post : in out Post_Bean; Id : in ADO.Identifier); -- Create or save the post. overriding procedure Save (Bean : in out Post_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- Delete a post. overriding procedure Delete (Bean : in out Post_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- Load the post from the URI for the public display. overriding procedure Load (Bean : in out Post_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- Load the post from the URI for the administrator. overriding procedure Load_Admin (Bean : in out Post_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- Load the post from the URI either with visible comments or with all comments. procedure Load (Bean : in out Post_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String; Publish_Only : in Boolean); -- Create the Post_Bean bean instance. function Create_Post_Bean (Module : in AWA.Blogs.Modules.Blog_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access; procedure Create (Bean : in out Post_Bean; Req : in out ASF.Rest.Request'Class; Reply : in out ASF.Rest.Response'Class); procedure Update (Bean : in out Post_Bean; Req : in out ASF.Rest.Request'Class; Reply : in out ASF.Rest.Response'Class); package Post_API is new ASF.Rest.Definition (Object_Type => Post_Bean, URI => "/blogs/:blog_id/posts"); -- -- package API_Post_Create is -- new Post_API.Definition (Create'Access, ASF.Rest.POST, ""); -- -- package API_Post_Update is -- new Post_API.Definition (Update'Access, ASF.Rest.PUT, ":id"); -- ------------------------------ -- Post List Bean -- ------------------------------ -- The <b>Post_List_Bean</b> gives a list of visible posts to be displayed to users. -- The list can be filtered by a given tag. The list pagination is supported. type Post_List_Bean is new AWA.Blogs.Models.Post_List_Bean with record Posts : aliased AWA.Blogs.Models.Post_Info_List_Bean; Service : Modules.Blog_Module_Access := null; Tags : AWA.Tags.Beans.Entity_Tag_Map; Posts_Bean : AWA.Blogs.Models.Post_Info_List_Bean_Access; -- The post page links. Links : aliased Post_Links_Bean; Links_Bean : access Post_Links_Bean; -- The read post counter associated with the post. Counter : aliased AWA.Counters.Beans.Counter_Bean (Of_Type => ADO.Objects.KEY_INTEGER, Of_Class => Models.POST_TABLE); Counter_Bean : AWA.Counters.Beans.Counter_Bean_Access; end record; type Post_List_Bean_Access is access all Post_List_Bean'Class; -- Get the value identified by the name. overriding function Get_Value (From : in Post_List_Bean; Name : in String) return Util.Beans.Objects.Object; -- Set the value identified by the name. overriding procedure Set_Value (From : in out Post_List_Bean; Name : in String; Value : in Util.Beans.Objects.Object); overriding procedure Load (From : in out Post_List_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- Load the list of posts. If a tag was set, filter the list of posts with the tag. procedure Load_List (Into : in out Post_List_Bean); -- Create the Post_List_Bean bean instance. function Create_Post_List_Bean (Module : in AWA.Blogs.Modules.Blog_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access; -- Get a select item list which contains a list of post status. function Create_Status_List (Module : in AWA.Blogs.Modules.Blog_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access; type Init_Flag is (INIT_BLOG_LIST, INIT_POST_LIST, INIT_COMMENT_LIST); type Init_Map is array (Init_Flag) of Boolean; -- ------------------------------ -- Admin List Bean -- ------------------------------ -- The <b>Blog_Admin_Bean</b> is used for the administration of a blog. It gives the -- list of posts that are created, published or not. type Blog_Admin_Bean is new Util.Beans.Basic.Bean with record Module : AWA.Blogs.Modules.Blog_Module_Access := null; -- The blog identifier. Blog_Id : ADO.Identifier := ADO.NO_IDENTIFIER; -- List of blogs. Blog_List : aliased AWA.Blogs.Models.Blog_Info_List_Bean; Blog_List_Bean : AWA.Blogs.Models.Blog_Info_List_Bean_Access; -- List of posts. Post_List : aliased AWA.Blogs.Models.Admin_Post_Info_List_Bean; Post_List_Bean : AWA.Blogs.Models.Admin_Post_Info_List_Bean_Access; -- List of comments. Comment_List : aliased AWA.Blogs.Models.Comment_Info_List_Bean; Comment_List_Bean : AWA.Blogs.Models.Comment_Info_List_Bean_Access; -- Initialization flags. Init_Flags : aliased Init_Map := (others => False); Flags : access Init_Map; end record; type Blog_Admin_Bean_Access is access all Blog_Admin_Bean; -- Get the blog identifier. function Get_Blog_Id (List : in Blog_Admin_Bean) return ADO.Identifier; -- Load the posts associated with the current blog. procedure Load_Posts (List : in Blog_Admin_Bean); -- Load the comments associated with the current blog. procedure Load_Comments (List : in Blog_Admin_Bean); overriding function Get_Value (List : in Blog_Admin_Bean; Name : in String) return Util.Beans.Objects.Object; -- Set the value identified by the name. overriding procedure Set_Value (From : in out Blog_Admin_Bean; Name : in String; Value : in Util.Beans.Objects.Object); -- Load the list of blogs. procedure Load_Blogs (List : in Blog_Admin_Bean); -- Create the Blog_Admin_Bean bean instance. function Create_Blog_Admin_Bean (Module : in AWA.Blogs.Modules.Blog_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access; -- ------------------------------ -- Blog Statistics Bean -- ------------------------------ -- The <b>Blog_Stat_Bean</b> is used to report various statistics about the blog or some post. type Blog_Stat_Bean is new AWA.Blogs.Models.Stat_List_Bean with record Module : AWA.Blogs.Modules.Blog_Module_Access := null; Stats : aliased AWA.Blogs.Models.Month_Stat_Info_List_Bean; Stats_Bean : AWA.Blogs.Models.Month_Stat_Info_List_Bean_Access; end record; type Blog_Stat_Bean_Access is access all Blog_Stat_Bean; overriding function Get_Value (List : in Blog_Stat_Bean; Name : in String) return Util.Beans.Objects.Object; -- Set the value identified by the name. overriding procedure Set_Value (From : in out Blog_Stat_Bean; Name : in String; Value : in Util.Beans.Objects.Object); -- Load the statistics information. overriding procedure Load (List : in out Blog_Stat_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- Create the Blog_Stat_Bean bean instance. function Create_Blog_Stat_Bean (Module : in AWA.Blogs.Modules.Blog_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access; end AWA.Blogs.Beans;
Make the Get_Predefined_Uri a public function
Make the Get_Predefined_Uri a public function
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
e29aa60e826ae1727848ab251b3ba48aad4718aa
awa/plugins/awa-blogs/src/awa-blogs-beans.ads
awa/plugins/awa-blogs/src/awa-blogs-beans.ads
----------------------------------------------------------------------- -- awa-blogs-beans -- Beans for blog module -- Copyright (C) 2011, 2012, 2013, 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Util.Beans.Basic; with Util.Beans.Objects; with ADO; with AWA.Blogs.Modules; with AWA.Blogs.Models; with AWA.Tags.Beans; package AWA.Blogs.Beans is -- Attributes exposed by <b>Post_Bean</b> BLOG_ID_ATTR : constant String := "blogId"; POST_ID_ATTR : constant String := "id"; POST_UID_ATTR : constant String := "uid"; POST_TITLE_ATTR : constant String := "title"; POST_TEXT_ATTR : constant String := "text"; POST_URI_ATTR : constant String := "uri"; POST_STATUS_ATTR : constant String := "status"; POST_USERNAME_ATTR : constant String := "username"; POST_TAG_ATTR : constant String := "tags"; POST_ALLOW_COMMENTS_ATTR : constant String := "allow_comments"; -- ------------------------------ -- Blog Bean -- ------------------------------ -- The <b>Blog_Bean</b> holds the information about the current blog. -- It allows to create the blog as well as update its primary title. type Blog_Bean is new AWA.Blogs.Models.Blog_Bean with record Module : AWA.Blogs.Modules.Blog_Module_Access := null; end record; type Blog_Bean_Access is access all Blog_Bean'Class; -- Get the value identified by the name. overriding function Get_Value (From : in Blog_Bean; Name : in String) return Util.Beans.Objects.Object; -- Set the value identified by the name. overriding procedure Set_Value (From : in out Blog_Bean; Name : in String; Value : in Util.Beans.Objects.Object); -- Create a new blog. overriding procedure Create (Bean : in out Blog_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); type Post_Bean is new AWA.Blogs.Models.Post_Bean with record Module : AWA.Blogs.Modules.Blog_Module_Access := null; Blog_Id : ADO.Identifier; -- List of tags associated with the post. Tags : aliased AWA.Tags.Beans.Tag_List_Bean; Tags_Bean : Util.Beans.Basic.Readonly_Bean_Access; end record; type Post_Bean_Access is access all Post_Bean'Class; -- Get the value identified by the name. overriding function Get_Value (From : in Post_Bean; Name : in String) return Util.Beans.Objects.Object; -- Set the value identified by the name. overriding procedure Set_Value (From : in out Post_Bean; Name : in String; Value : in Util.Beans.Objects.Object); -- Load the post. procedure Load_Post (Post : in out Post_Bean; Id : in ADO.Identifier); -- Create or save the post. overriding procedure Save (Bean : in out Post_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- Delete a post. overriding procedure Delete (Bean : in out Post_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- Load the post. overriding procedure Load (Bean : in out Post_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- Create the Blog_Bean bean instance. function Create_Blog_Bean (Module : in AWA.Blogs.Modules.Blog_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access; -- Create the Post_Bean bean instance. function Create_Post_Bean (Module : in AWA.Blogs.Modules.Blog_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access; -- List of posts visible to anybody. type Post_List_Bean is limited new Util.Beans.Basic.Bean with record Posts : aliased AWA.Blogs.Models.Post_Info_List_Bean; Service : Modules.Blog_Module_Access := null; Tag : Ada.Strings.Unbounded.Unbounded_String; Tags : AWA.Tags.Beans.Entity_Tag_Map; Posts_Bean : AWA.Blogs.Models.Post_Info_List_Bean_Access; end record; type Post_List_Bean_Access is access all Post_List_Bean'Class; -- Get the value identified by the name. overriding function Get_Value (From : in Post_List_Bean; Name : in String) return Util.Beans.Objects.Object; -- Set the value identified by the name. overriding procedure Set_Value (From : in out Post_List_Bean; Name : in String; Value : in Util.Beans.Objects.Object); -- Load the list of posts. If a tag was set, filter the list of posts with the tag. procedure Load_List (Into : in out Post_List_Bean); -- Create the Post_List_Bean bean instance. function Create_Post_List_Bean (Module : in AWA.Blogs.Modules.Blog_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access; -- Create the Blog_Admin_Bean bean instance. function Create_Blog_Admin_Bean (Module : in AWA.Blogs.Modules.Blog_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access; -- Get a select item list which contains a list of post status. function Create_Status_List (Module : in AWA.Blogs.Modules.Blog_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access; type Init_Flag is (INIT_BLOG_LIST, INIT_POST_LIST, INIT_COMMENT_LIST); type Init_Map is array (Init_Flag) of Boolean; type Blog_Admin_Bean is new Util.Beans.Basic.Bean with record Module : AWA.Blogs.Modules.Blog_Module_Access := null; -- The blog identifier. Blog_Id : ADO.Identifier := ADO.NO_IDENTIFIER; -- List of blogs. Blog_List : aliased AWA.Blogs.Models.Blog_Info_List_Bean; Blog_List_Bean : AWA.Blogs.Models.Blog_Info_List_Bean_Access; -- List of posts. Post_List : aliased AWA.Blogs.Models.Admin_Post_Info_List_Bean; Post_List_Bean : AWA.Blogs.Models.Admin_Post_Info_List_Bean_Access; -- List of comments. Comment_List : aliased AWA.Blogs.Models.Comment_Info_List_Bean; Comment_List_Bean : AWA.Blogs.Models.Comment_Info_List_Bean_Access; -- Initialization flags. Init_Flags : aliased Init_Map := (others => False); Flags : access Init_Map; end record; type Blog_Admin_Bean_Access is access all Blog_Admin_Bean; -- Get the blog identifier. function Get_Blog_Id (List : in Blog_Admin_Bean) return ADO.Identifier; -- Load the posts associated with the current blog. procedure Load_Posts (List : in Blog_Admin_Bean); -- Load the comments associated with the current blog. procedure Load_Comments (List : in Blog_Admin_Bean); overriding function Get_Value (List : in Blog_Admin_Bean; Name : in String) return Util.Beans.Objects.Object; -- Set the value identified by the name. overriding procedure Set_Value (From : in out Blog_Admin_Bean; Name : in String; Value : in Util.Beans.Objects.Object); -- Load the list of blogs. procedure Load_Blogs (List : in Blog_Admin_Bean); end AWA.Blogs.Beans;
----------------------------------------------------------------------- -- awa-blogs-beans -- Beans for blog module -- Copyright (C) 2011, 2012, 2013, 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Util.Beans.Basic; with Util.Beans.Objects; with ADO; with AWA.Blogs.Modules; with AWA.Blogs.Models; with AWA.Tags.Beans; package AWA.Blogs.Beans is -- Attributes exposed by <b>Post_Bean</b> BLOG_ID_ATTR : constant String := "blogId"; POST_ID_ATTR : constant String := "id"; POST_UID_ATTR : constant String := "uid"; POST_TITLE_ATTR : constant String := "title"; POST_TEXT_ATTR : constant String := "text"; POST_URI_ATTR : constant String := "uri"; POST_STATUS_ATTR : constant String := "status"; POST_USERNAME_ATTR : constant String := "username"; POST_TAG_ATTR : constant String := "tags"; POST_ALLOW_COMMENTS_ATTR : constant String := "allow_comments"; -- ------------------------------ -- Blog Bean -- ------------------------------ -- The <b>Blog_Bean</b> holds the information about the current blog. -- It allows to create the blog as well as update its primary title. type Blog_Bean is new AWA.Blogs.Models.Blog_Bean with record Module : AWA.Blogs.Modules.Blog_Module_Access := null; end record; type Blog_Bean_Access is access all Blog_Bean'Class; -- Get the value identified by the name. overriding function Get_Value (From : in Blog_Bean; Name : in String) return Util.Beans.Objects.Object; -- Set the value identified by the name. overriding procedure Set_Value (From : in out Blog_Bean; Name : in String; Value : in Util.Beans.Objects.Object); -- Create a new blog. overriding procedure Create (Bean : in out Blog_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); type Post_Bean is new AWA.Blogs.Models.Post_Bean with record Module : AWA.Blogs.Modules.Blog_Module_Access := null; Blog_Id : ADO.Identifier; -- List of tags associated with the post. Tags : aliased AWA.Tags.Beans.Tag_List_Bean; Tags_Bean : Util.Beans.Basic.Readonly_Bean_Access; end record; type Post_Bean_Access is access all Post_Bean'Class; -- Get the value identified by the name. overriding function Get_Value (From : in Post_Bean; Name : in String) return Util.Beans.Objects.Object; -- Set the value identified by the name. overriding procedure Set_Value (From : in out Post_Bean; Name : in String; Value : in Util.Beans.Objects.Object); -- Load the post. procedure Load_Post (Post : in out Post_Bean; Id : in ADO.Identifier); -- Create or save the post. overriding procedure Save (Bean : in out Post_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- Delete a post. overriding procedure Delete (Bean : in out Post_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- Load the post. overriding procedure Load (Bean : in out Post_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- Create the Blog_Bean bean instance. function Create_Blog_Bean (Module : in AWA.Blogs.Modules.Blog_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access; -- Create the Post_Bean bean instance. function Create_Post_Bean (Module : in AWA.Blogs.Modules.Blog_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access; -- List of posts visible to anybody. type Post_List_Bean is new AWA.Blogs.Models.Post_List_Bean with record Posts : aliased AWA.Blogs.Models.Post_Info_List_Bean; Service : Modules.Blog_Module_Access := null; Tags : AWA.Tags.Beans.Entity_Tag_Map; Posts_Bean : AWA.Blogs.Models.Post_Info_List_Bean_Access; end record; type Post_List_Bean_Access is access all Post_List_Bean'Class; -- Get the value identified by the name. overriding function Get_Value (From : in Post_List_Bean; Name : in String) return Util.Beans.Objects.Object; -- Set the value identified by the name. overriding procedure Set_Value (From : in out Post_List_Bean; Name : in String; Value : in Util.Beans.Objects.Object); overriding procedure Load (From : in out Post_List_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- Load the list of posts. If a tag was set, filter the list of posts with the tag. procedure Load_List (Into : in out Post_List_Bean); -- Create the Post_List_Bean bean instance. function Create_Post_List_Bean (Module : in AWA.Blogs.Modules.Blog_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access; -- Create the Blog_Admin_Bean bean instance. function Create_Blog_Admin_Bean (Module : in AWA.Blogs.Modules.Blog_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access; -- Get a select item list which contains a list of post status. function Create_Status_List (Module : in AWA.Blogs.Modules.Blog_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access; type Init_Flag is (INIT_BLOG_LIST, INIT_POST_LIST, INIT_COMMENT_LIST); type Init_Map is array (Init_Flag) of Boolean; type Blog_Admin_Bean is new Util.Beans.Basic.Bean with record Module : AWA.Blogs.Modules.Blog_Module_Access := null; -- The blog identifier. Blog_Id : ADO.Identifier := ADO.NO_IDENTIFIER; -- List of blogs. Blog_List : aliased AWA.Blogs.Models.Blog_Info_List_Bean; Blog_List_Bean : AWA.Blogs.Models.Blog_Info_List_Bean_Access; -- List of posts. Post_List : aliased AWA.Blogs.Models.Admin_Post_Info_List_Bean; Post_List_Bean : AWA.Blogs.Models.Admin_Post_Info_List_Bean_Access; -- List of comments. Comment_List : aliased AWA.Blogs.Models.Comment_Info_List_Bean; Comment_List_Bean : AWA.Blogs.Models.Comment_Info_List_Bean_Access; -- Initialization flags. Init_Flags : aliased Init_Map := (others => False); Flags : access Init_Map; end record; type Blog_Admin_Bean_Access is access all Blog_Admin_Bean; -- Get the blog identifier. function Get_Blog_Id (List : in Blog_Admin_Bean) return ADO.Identifier; -- Load the posts associated with the current blog. procedure Load_Posts (List : in Blog_Admin_Bean); -- Load the comments associated with the current blog. procedure Load_Comments (List : in Blog_Admin_Bean); overriding function Get_Value (List : in Blog_Admin_Bean; Name : in String) return Util.Beans.Objects.Object; -- Set the value identified by the name. overriding procedure Set_Value (From : in out Blog_Admin_Bean; Name : in String; Value : in Util.Beans.Objects.Object); -- Load the list of blogs. procedure Load_Blogs (List : in Blog_Admin_Bean); end AWA.Blogs.Beans;
Use the UML Post_List_Bean type and override the Load operation
Use the UML Post_List_Bean type and override the Load operation
Ada
apache-2.0
Letractively/ada-awa,tectronics/ada-awa,tectronics/ada-awa,Letractively/ada-awa,tectronics/ada-awa,Letractively/ada-awa
2adb454311718f8c7fc9deaa49b4170b54b2e543
src/asf-components-ajax-includes.ads
src/asf-components-ajax-includes.ads
----------------------------------------------------------------------- -- components-ajax-includes -- AJAX Include component -- 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 ASF.Components.Html; with ASF.Contexts.Faces; package ASF.Components.Ajax.Includes is ASYNC_ATTR_NAME : constant String := "async"; LAYOUT_ATTR_NAME : constant String := "layout"; SRC_ATTR_NAME : constant String := "src"; -- The <b>ajax:include</b> component allows to include type UIInclude is new ASF.Components.Html.UIHtmlComponent with private; -- Get the HTML layout that must be used for the include container. -- The default layout is a "div". -- Returns "div", "span", "pre", "b". function Get_Layout (UI : in UIInclude; Context : in ASF.Contexts.Faces.Faces_Context'Class) return String; -- The included XHTML file is rendered according to the <b>async</b> attribute: -- -- When <b>async</b> is false, render the specified XHTML file in such a way that inner -- forms will be posted on the included view. -- -- When <b>async</b> is true, trigger an AJAX call to include the specified -- XHTML view when the page is loaded. -- -- overriding procedure Encode_Children (UI : in UIInclude; Context : in out ASF.Contexts.Faces.Faces_Context'Class); private type UIInclude is new ASF.Components.Html.UIHtmlComponent with null record; end ASF.Components.Ajax.Includes;
----------------------------------------------------------------------- -- components-ajax-includes -- AJAX Include component -- 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 ASF.Components.Html; with ASF.Contexts.Faces; package ASF.Components.Ajax.Includes is -- @attribute -- Defines whether the inclusion is asynchronous or not. -- When true, an AJAX call will be made by the client browser to fetch the content. -- When false, the view is included in the current component tree. ASYNC_ATTR_NAME : constant String := "async"; -- @attribute -- Defines the HTML container element that will contain the included view. LAYOUT_ATTR_NAME : constant String := "layout"; -- @attribute -- Defines the view name to include. SRC_ATTR_NAME : constant String := "src"; -- @tag include -- The <b>ajax:include</b> component allows to include type UIInclude is new ASF.Components.Html.UIHtmlComponent with private; -- Get the HTML layout that must be used for the include container. -- The default layout is a "div". -- Returns "div", "span", "pre", "b". function Get_Layout (UI : in UIInclude; Context : in ASF.Contexts.Faces.Faces_Context'Class) return String; -- The included XHTML file is rendered according to the <b>async</b> attribute: -- -- When <b>async</b> is false, render the specified XHTML file in such a way that inner -- forms will be posted on the included view. -- -- When <b>async</b> is true, trigger an AJAX call to include the specified -- XHTML view when the page is loaded. -- -- overriding procedure Encode_Children (UI : in UIInclude; Context : in out ASF.Contexts.Faces.Faces_Context'Class); private type UIInclude is new ASF.Components.Html.UIHtmlComponent with null record; end ASF.Components.Ajax.Includes;
Add some documentation
Add some documentation
Ada
apache-2.0
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
c01dbc8f93b1e4160c657ec9c158fdf90410cdbd
src/asf-components-html-messages.adb
src/asf-components-html-messages.adb
----------------------------------------------------------------------- -- html.messages -- Faces messages -- 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 ASF.Utils; with ASF.Applications.Messages; with ASF.Components.Base; -- The <b>ASF.Components.Html.Messages</b> package implements the <b>h:message</b> -- and <b>h:messages</b> components. package body ASF.Components.Html.Messages is use ASF.Components.Base; use ASF.Applications.Messages; MSG_ATTRIBUTE_NAMES : Util.Strings.String_Set.Set; FATAL_ATTRIBUTE_NAMES : Util.Strings.String_Set.Set; ERROR_ATTRIBUTE_NAMES : Util.Strings.String_Set.Set; WARN_ATTRIBUTE_NAMES : Util.Strings.String_Set.Set; INFO_ATTRIBUTE_NAMES : Util.Strings.String_Set.Set; -- ------------------------------ -- Check whether the UI component whose name is given in <b>Name</b> has some messages -- associated with it. -- ------------------------------ function Has_Message (Name : in Util.Beans.Objects.Object) return Util.Beans.Objects.Object is Context : constant ASF.Contexts.Faces.Faces_Context_Access := ASF.Contexts.Faces.Current; begin if Context = null then return Util.Beans.Objects.To_Object (False); end if; declare Id : constant String := Util.Beans.Objects.To_String (Name); Msgs : constant ASF.Applications.Messages.Vectors.Cursor := Context.Get_Messages (Id); begin return Util.Beans.Objects.To_Object (Applications.Messages.Vectors.Has_Element (Msgs)); end; end Has_Message; -- ------------------------------ -- Write a single message enclosed by the tag represented by <b>Tag</b>. -- ------------------------------ procedure Write_Message (UI : in UIHtmlComponent'Class; Message : in ASF.Applications.Messages.Message; Mode : in Message_Mode; Show_Detail : in Boolean; Show_Summary : in Boolean; Context : in out Faces_Context'Class) is Writer : constant Response_Writer_Access := Context.Get_Response_Writer; begin case Mode is when SPAN_NO_STYLE => Writer.Start_Element ("span"); when SPAN => Writer.Start_Element ("span"); UI.Render_Attributes (Context, MSG_ATTRIBUTE_NAMES, Writer); when LIST => Writer.Start_Element ("li"); when TABLE => Writer.Start_Element ("tr"); end case; case Get_Severity (Message) is when FATAL => UI.Render_Attributes (Context, FATAL_ATTRIBUTE_NAMES, Writer, Write_Id => Mode /= SPAN_NO_STYLE); when ERROR => UI.Render_Attributes (Context, ERROR_ATTRIBUTE_NAMES, Writer, Write_Id => Mode /= SPAN_NO_STYLE); when WARN => UI.Render_Attributes (Context, WARN_ATTRIBUTE_NAMES, Writer, Write_Id => Mode /= SPAN_NO_STYLE); when INFO | NONE => UI.Render_Attributes (Context, INFO_ATTRIBUTE_NAMES, Writer, Write_Id => Mode /= SPAN_NO_STYLE); end case; if Mode = TABLE then Writer.Start_Element ("td"); end if; if Show_Summary then Writer.Write_Text (Get_Summary (Message)); end if; if Show_Detail then Writer.Write_Text (Get_Detail (Message)); end if; case Mode is when SPAN | SPAN_NO_STYLE => Writer.End_Element ("span"); when LIST => Writer.End_Element ("li"); when TABLE => Writer.End_Element ("td"); Writer.End_Element ("tr"); end case; end Write_Message; -- ------------------------------ -- Render a list of messages each of them being enclosed by the <b>Tag</b> element. -- ------------------------------ procedure Write_Messages (UI : in UIHtmlComponent'Class; Mode : in Message_Mode; Context : in out Faces_Context'Class; Messages : in out ASF.Applications.Messages.Vectors.Cursor) is procedure Process_Message (Message : in ASF.Applications.Messages.Message); Show_Detail : constant Boolean := UI.Get_Attribute ("showDetail", Context, True); Show_Summary : constant Boolean := UI.Get_Attribute ("showSummary", Context, False); procedure Process_Message (Message : in ASF.Applications.Messages.Message) is begin Write_Message (UI, Message, Mode, Show_Detail, Show_Summary, Context); end Process_Message; begin while ASF.Applications.Messages.Vectors.Has_Element (Messages) loop Vectors.Query_Element (Messages, Process_Message'Access); Vectors.Next (Messages); end loop; end Write_Messages; -- ------------------------------ -- Encode the begining of the <b>h:message</b> component. -- ------------------------------ procedure Encode_Begin (UI : in UIMessage; Context : in out Faces_Context'Class) is begin if not UI.Is_Rendered (Context) then return; end if; declare Name : constant Util.Beans.Objects.Object := UI.Get_Attribute (Context, "for"); Messages : ASF.Applications.Messages.Vectors.Cursor; begin -- No specification of 'for' attribute, render the global messages. if Util.Beans.Objects.Is_Null (Name) then Messages := Context.Get_Messages (""); else declare Id : constant String := Util.Beans.Objects.To_String (Name); Target : constant UIComponent_Access := UI.Find (Id => Id); begin -- If the component does not exist, report an error in the logs. if Target = null then UI.Log_Error ("Cannot find component {0}", Id); else Messages := Context.Get_Messages (Id); end if; end; end if; -- If we have some message, render the first one (as specified by <h:message>). if ASF.Applications.Messages.Vectors.Has_Element (Messages) then declare Show_Detail : constant Boolean := UI.Get_Attribute ("showDetail", Context, True); Show_Summary : constant Boolean := UI.Get_Attribute ("showSummary", Context, False); begin Write_Message (UI, ASF.Applications.Messages.Vectors.Element (Messages), SPAN, Show_Detail, Show_Summary, Context); end; end if; end; end Encode_Begin; -- Encode the end of the <b>h:message</b> component. procedure Encode_End (UI : in UIMessage; Context : in out Faces_Context'Class) is begin null; end Encode_End; -- ------------------------------ -- Encode the begining of the <b>h:message</b> component. -- ------------------------------ procedure Encode_Begin (UI : in UIMessages; Context : in out Faces_Context'Class) is begin if UI.Is_Rendered (Context) then declare Name : constant Util.Beans.Objects.Object := UI.Get_Attribute (Context, "for"); Messages : ASF.Applications.Messages.Vectors.Cursor; begin -- No specification of 'for' attribute, render the global messages. if Util.Beans.Objects.Is_Null (Name) then if UI.Get_Attribute ("globalOnly", Context) then Messages := Context.Get_Messages (""); end if; else declare Id : constant String := Util.Beans.Objects.To_String (Name); Target : constant UIComponent_Access := UI.Find (Id => Id); begin -- If the component does not exist, report an error in the logs. if Target = null then UI.Log_Error ("Cannot find component {0}", Id); else Messages := Context.Get_Messages (Id); end if; end; end if; -- If we have some message, render them. if ASF.Applications.Messages.Vectors.Has_Element (Messages) then declare Writer : constant Response_Writer_Access := Context.Get_Response_Writer; Layout : constant String := Util.Beans.Objects.To_String (UI.Get_Attribute (Context, "layout")); begin if Layout = "table" then Writer.Start_Element ("table"); UI.Render_Attributes (Context, MSG_ATTRIBUTE_NAMES, Writer); Write_Messages (UI, TABLE, Context, Messages); Writer.End_Element ("table"); else Writer.Start_Element ("ul"); UI.Render_Attributes (Context, MSG_ATTRIBUTE_NAMES, Writer); Write_Messages (UI, LIST, Context, Messages); Writer.End_Element ("ul"); end if; end; end if; end; end if; end Encode_Begin; -- Encode the end of the <b>h:message</b> component. procedure Encode_End (UI : in UIMessages; Context : in out Faces_Context'Class) is begin null; end Encode_End; FATAL_CLASS_ATTR : aliased constant String := "fatalClass"; FATAL_STYLE_CLASS_ATTR : aliased constant String := "fatalStyle"; ERROR_CLASS_ATTR : aliased constant String := "errorClass"; ERROR_STYLE_CLASS_ATTR : aliased constant String := "errorStyle"; WARN_CLASS_ATTR : aliased constant String := "warnClass"; WARN_STYLE_CLASS_ATTR : aliased constant String := "warnStyle"; INFO_CLASS_ATTR : aliased constant String := "infoClass"; INFO_STYLE_CLASS_ATTR : aliased constant String := "infoStyle"; begin ASF.Utils.Set_Text_Attributes (MSG_ATTRIBUTE_NAMES); -- ASF.Utils.Set_Text_Attributes (WARN_ATTRIBUTE_NAMES); -- ASF.Utils.Set_Text_Attributes (INFO_ATTRIBUTE_NAMES); -- -- ASF.Utils.Set_Text_Attributes (FATAL_ATTRIBUTE_NAMES); FATAL_ATTRIBUTE_NAMES.Insert (FATAL_CLASS_ATTR'Access); FATAL_ATTRIBUTE_NAMES.Insert (FATAL_STYLE_CLASS_ATTR'Access); ERROR_ATTRIBUTE_NAMES.Insert (ERROR_CLASS_ATTR'Access); ERROR_ATTRIBUTE_NAMES.Insert (ERROR_STYLE_CLASS_ATTR'Access); WARN_ATTRIBUTE_NAMES.Insert (WARN_CLASS_ATTR'Access); WARN_ATTRIBUTE_NAMES.Insert (WARN_STYLE_CLASS_ATTR'Access); INFO_ATTRIBUTE_NAMES.Insert (INFO_CLASS_ATTR'Access); INFO_ATTRIBUTE_NAMES.Insert (INFO_STYLE_CLASS_ATTR'Access); end ASF.Components.Html.Messages;
----------------------------------------------------------------------- -- html.messages -- Faces messages -- Copyright (C) 2011, 2012, 2013, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with ASF.Utils; with ASF.Applications.Messages; with ASF.Components.Base; -- The <b>ASF.Components.Html.Messages</b> package implements the <b>h:message</b> -- and <b>h:messages</b> components. package body ASF.Components.Html.Messages is use ASF.Components.Base; use ASF.Applications.Messages; MSG_ATTRIBUTE_NAMES : Util.Strings.String_Set.Set; FATAL_ATTRIBUTE_NAMES : Util.Strings.String_Set.Set; ERROR_ATTRIBUTE_NAMES : Util.Strings.String_Set.Set; WARN_ATTRIBUTE_NAMES : Util.Strings.String_Set.Set; INFO_ATTRIBUTE_NAMES : Util.Strings.String_Set.Set; -- ------------------------------ -- Check whether the UI component whose name is given in <b>Name</b> has some messages -- associated with it. -- ------------------------------ function Has_Message (Name : in Util.Beans.Objects.Object) return Util.Beans.Objects.Object is Context : constant ASF.Contexts.Faces.Faces_Context_Access := ASF.Contexts.Faces.Current; begin if Context = null then return Util.Beans.Objects.To_Object (False); end if; declare Id : constant String := Util.Beans.Objects.To_String (Name); Msgs : constant ASF.Applications.Messages.Vectors.Cursor := Context.Get_Messages (Id); begin return Util.Beans.Objects.To_Object (Applications.Messages.Vectors.Has_Element (Msgs)); end; end Has_Message; -- ------------------------------ -- Write a single message enclosed by the tag represented by <b>Tag</b>. -- ------------------------------ procedure Write_Message (UI : in UIHtmlComponent'Class; Message : in ASF.Applications.Messages.Message; Mode : in Message_Mode; Show_Detail : in Boolean; Show_Summary : in Boolean; Context : in out Faces_Context'Class) is Writer : constant Response_Writer_Access := Context.Get_Response_Writer; begin case Mode is when SPAN_NO_STYLE => Writer.Start_Element ("span"); when SPAN => Writer.Start_Element ("span"); UI.Render_Attributes (Context, MSG_ATTRIBUTE_NAMES, Writer); when LIST => Writer.Start_Element ("li"); when TABLE => Writer.Start_Element ("tr"); end case; case Get_Severity (Message) is when FATAL => UI.Render_Attributes (Context, FATAL_ATTRIBUTE_NAMES, Writer, Write_Id => Mode /= SPAN_NO_STYLE); when ERROR => UI.Render_Attributes (Context, ERROR_ATTRIBUTE_NAMES, Writer, Write_Id => Mode /= SPAN_NO_STYLE); when WARN => UI.Render_Attributes (Context, WARN_ATTRIBUTE_NAMES, Writer, Write_Id => Mode /= SPAN_NO_STYLE); when INFO | NONE => UI.Render_Attributes (Context, INFO_ATTRIBUTE_NAMES, Writer, Write_Id => Mode /= SPAN_NO_STYLE); end case; if Mode = TABLE then Writer.Start_Element ("td"); end if; if Show_Summary then Writer.Write_Text (Get_Summary (Message)); end if; if Show_Detail then Writer.Write_Text (Get_Detail (Message)); end if; case Mode is when SPAN | SPAN_NO_STYLE => Writer.End_Element ("span"); when LIST => Writer.End_Element ("li"); when TABLE => Writer.End_Element ("td"); Writer.End_Element ("tr"); end case; end Write_Message; -- ------------------------------ -- Render a list of messages each of them being enclosed by the <b>Tag</b> element. -- ------------------------------ procedure Write_Messages (UI : in UIHtmlComponent'Class; Mode : in Message_Mode; Context : in out Faces_Context'Class; Messages : in out ASF.Applications.Messages.Vectors.Cursor) is procedure Process_Message (Message : in ASF.Applications.Messages.Message); Show_Detail : constant Boolean := UI.Get_Attribute ("showDetail", Context, False); Show_Summary : constant Boolean := UI.Get_Attribute ("showSummary", Context, True); procedure Process_Message (Message : in ASF.Applications.Messages.Message) is begin Write_Message (UI, Message, Mode, Show_Detail, Show_Summary, Context); end Process_Message; begin while ASF.Applications.Messages.Vectors.Has_Element (Messages) loop Vectors.Query_Element (Messages, Process_Message'Access); Vectors.Next (Messages); end loop; end Write_Messages; -- ------------------------------ -- Encode the begining of the <b>h:message</b> component. -- ------------------------------ procedure Encode_Begin (UI : in UIMessage; Context : in out Faces_Context'Class) is begin if not UI.Is_Rendered (Context) then return; end if; declare Name : constant Util.Beans.Objects.Object := UI.Get_Attribute (Context, "for"); Messages : ASF.Applications.Messages.Vectors.Cursor; begin -- No specification of 'for' attribute, render the global messages. if Util.Beans.Objects.Is_Null (Name) then Messages := Context.Get_Messages (""); else declare Id : constant String := Util.Beans.Objects.To_String (Name); Target : constant UIComponent_Access := UI.Find (Id => Id); begin -- If the component does not exist, report an error in the logs. if Target = null then UI.Log_Error ("Cannot find component {0}", Id); else Messages := Context.Get_Messages (Id); end if; end; end if; -- If we have some message, render the first one (as specified by <h:message>). if ASF.Applications.Messages.Vectors.Has_Element (Messages) then declare Show_Detail : constant Boolean := UI.Get_Attribute ("showDetail", Context, True); Show_Summary : constant Boolean := UI.Get_Attribute ("showSummary", Context, False); begin Write_Message (UI, ASF.Applications.Messages.Vectors.Element (Messages), SPAN, Show_Detail, Show_Summary, Context); end; end if; end; end Encode_Begin; -- Encode the end of the <b>h:message</b> component. procedure Encode_End (UI : in UIMessage; Context : in out Faces_Context'Class) is begin null; end Encode_End; -- ------------------------------ -- Encode the begining of the <b>h:message</b> component. -- ------------------------------ procedure Encode_Begin (UI : in UIMessages; Context : in out Faces_Context'Class) is begin if UI.Is_Rendered (Context) then declare Name : constant Util.Beans.Objects.Object := UI.Get_Attribute (Context, "for"); Messages : ASF.Applications.Messages.Vectors.Cursor; begin -- No specification of 'for' attribute, render the global messages. if Util.Beans.Objects.Is_Null (Name) then if UI.Get_Attribute ("globalOnly", Context) then Messages := Context.Get_Messages (""); end if; else declare Id : constant String := Util.Beans.Objects.To_String (Name); Target : constant UIComponent_Access := UI.Find (Id => Id); begin -- If the component does not exist, report an error in the logs. if Target = null then UI.Log_Error ("Cannot find component {0}", Id); else Messages := Context.Get_Messages (Id); end if; end; end if; -- If we have some message, render them. if ASF.Applications.Messages.Vectors.Has_Element (Messages) then declare Writer : constant Response_Writer_Access := Context.Get_Response_Writer; Layout : constant String := Util.Beans.Objects.To_String (UI.Get_Attribute (Context, "layout")); begin if Layout = "table" then Writer.Start_Element ("table"); UI.Render_Attributes (Context, MSG_ATTRIBUTE_NAMES, Writer); Write_Messages (UI, TABLE, Context, Messages); Writer.End_Element ("table"); else Writer.Start_Element ("ul"); UI.Render_Attributes (Context, MSG_ATTRIBUTE_NAMES, Writer); Write_Messages (UI, LIST, Context, Messages); Writer.End_Element ("ul"); end if; end; end if; end; end if; end Encode_Begin; -- Encode the end of the <b>h:message</b> component. procedure Encode_End (UI : in UIMessages; Context : in out Faces_Context'Class) is begin null; end Encode_End; FATAL_CLASS_ATTR : aliased constant String := "fatalClass"; FATAL_STYLE_CLASS_ATTR : aliased constant String := "fatalStyle"; ERROR_CLASS_ATTR : aliased constant String := "errorClass"; ERROR_STYLE_CLASS_ATTR : aliased constant String := "errorStyle"; WARN_CLASS_ATTR : aliased constant String := "warnClass"; WARN_STYLE_CLASS_ATTR : aliased constant String := "warnStyle"; INFO_CLASS_ATTR : aliased constant String := "infoClass"; INFO_STYLE_CLASS_ATTR : aliased constant String := "infoStyle"; begin ASF.Utils.Set_Text_Attributes (MSG_ATTRIBUTE_NAMES); -- ASF.Utils.Set_Text_Attributes (WARN_ATTRIBUTE_NAMES); -- ASF.Utils.Set_Text_Attributes (INFO_ATTRIBUTE_NAMES); -- -- ASF.Utils.Set_Text_Attributes (FATAL_ATTRIBUTE_NAMES); FATAL_ATTRIBUTE_NAMES.Insert (FATAL_CLASS_ATTR'Access); FATAL_ATTRIBUTE_NAMES.Insert (FATAL_STYLE_CLASS_ATTR'Access); ERROR_ATTRIBUTE_NAMES.Insert (ERROR_CLASS_ATTR'Access); ERROR_ATTRIBUTE_NAMES.Insert (ERROR_STYLE_CLASS_ATTR'Access); WARN_ATTRIBUTE_NAMES.Insert (WARN_CLASS_ATTR'Access); WARN_ATTRIBUTE_NAMES.Insert (WARN_STYLE_CLASS_ATTR'Access); INFO_ATTRIBUTE_NAMES.Insert (INFO_CLASS_ATTR'Access); INFO_ATTRIBUTE_NAMES.Insert (INFO_STYLE_CLASS_ATTR'Access); end ASF.Components.Html.Messages;
Fix the default behavior for <h:messages> on global messages
Fix the default behavior for <h:messages> on global messages
Ada
apache-2.0
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
766734e360091a5e4635120ec3ad8c8abe7b2114
mat/src/mat-readers-marshaller.ads
mat/src/mat-readers-marshaller.ads
----------------------------------------------------------------------- -- 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 System; with Ada.Strings.Unbounded; with MAT.Types; with MAT.Events; package MAT.Readers.Marshaller is Buffer_Underflow_Error : exception; Buffer_Overflow_Error : exception; function Get_Raw_Uint32 (Buf : System.Address) return MAT.Types.Uint32; function Get_Uint8 (Buffer : in Buffer_Ptr) return MAT.Types.Uint8; function Get_Uint16 (Buffer : in Buffer_Ptr) return MAT.Types.Uint16; function Get_Uint32 (Buffer : in Buffer_Ptr) return MAT.Types.Uint32; 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; -- procedure Put_Uint8 (Buffer : in Buffer_Ptr; Data : in Uint8); -- procedure Put_Uint16 (Buffer : in Buffer_Ptr; Data : in Uint16); -- procedure Put_Uint32 (Buffer : in Buffer_Ptr; Data : in Uint32); 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 is new Get_Target_Value (MAT.Types.Target_Size); -- -- function Get_Target_Addr is new Get_Target_Value (MAT.Types.Target_Addr); -- -- function Get_Target_Tick is new Get_Target_Value (MAT.Types.Target_Tick_Ref); -- -- function Get_Target_Thread is new Get_Target_Value (MAT.Types.Target_Thread_Ref); 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;
----------------------------------------------------------------------- -- 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 System; with Ada.Strings.Unbounded; with MAT.Types; with MAT.Events; package MAT.Readers.Marshaller is Buffer_Underflow_Error : exception; Buffer_Overflow_Error : exception; function Get_Raw_Uint32 (Buf : System.Address) return MAT.Types.Uint32; -- Get an 8-bit value from the buffer. function Get_Uint8 (Buffer : in Buffer_Ptr) return MAT.Types.Uint8; function Get_Uint16 (Buffer : in Buffer_Ptr) return MAT.Types.Uint16; function Get_Uint32 (Buffer : in Buffer_Ptr) return MAT.Types.Uint32; 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; -- procedure Put_Uint8 (Buffer : in Buffer_Ptr; Data : in Uint8); -- procedure Put_Uint16 (Buffer : in Buffer_Ptr; Data : in Uint16); -- procedure Put_Uint32 (Buffer : in Buffer_Ptr; Data : in Uint32); 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 is new Get_Target_Value (MAT.Types.Target_Size); -- -- function Get_Target_Addr is new Get_Target_Value (MAT.Types.Target_Addr); -- -- function Get_Target_Tick is new Get_Target_Value (MAT.Types.Target_Tick_Ref); -- -- function Get_Target_Thread is new Get_Target_Value (MAT.Types.Target_Thread_Ref); 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;
Document Get_Uint8
Document Get_Uint8
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
6abae379cf949c5a611d8295adf7432fe18526c4
src/security-policies.adb
src/security-policies.adb
----------------------------------------------------------------------- -- security-policies -- Security Policies -- Copyright (C) 2010, 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Unchecked_Deallocation; with Util.Log.Loggers; with Security.Controllers; with Security.Contexts; package body Security.Policies is -- The logger Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Security.Policies"); -- Get the policy name. function Get_Name (From : in Policy) return String is begin return ""; end Get_Name; -- ------------------------------ -- Get the policy index. -- ------------------------------ function Get_Policy_Index (From : in Policy'Class) return Policy_Index is begin return From.Index; end Get_Policy_Index; -- ------------------------------ -- Add a permission under the given permission name and associated with the controller. -- To verify the permission, the controller will be called. -- ------------------------------ procedure Add_Permission (Manager : in out Policy; Name : in String; Permission : in Controller_Access) is begin Manager.Manager.Add_Permission (Name, Permission); end Add_Permission; -- ------------------------------ -- Permission Manager -- ------------------------------ -- ------------------------------ -- Get the policy with the name <b>Name</b> registered in the policy manager. -- Returns null if there is no such policy. -- ------------------------------ function Get_Policy (Manager : in Policy_Manager; Name : in String) return Policy_Access is begin for I in Manager.Policies'Range loop if Manager.Policies (I) = null then return null; elsif Manager.Policies (I).Get_Name = Name then return Manager.Policies (I); end if; end loop; return null; end Get_Policy; -- ------------------------------ -- Add the policy to the policy manager. After a policy is added in the manager, -- it can participate in the security policy. -- Raises Policy_Error if the policy table is full. -- ------------------------------ procedure Add_Policy (Manager : in out Policy_Manager; Policy : in Policy_Access) is Name : constant String := Policy.Get_Name; begin Log.Info ("Adding policy {0}", Name); for I in Manager.Policies'Range loop if Manager.Policies (I) = null then Manager.Policies (I) := Policy; Policy.Manager := Manager'Unchecked_Access; Policy.Index := I; return; end if; end loop; Log.Error ("Policy table is full, increase policy manager table to {0} to add policy {1}", Policy_Index'Image (Manager.Max_Policies + 1), Name); raise Policy_Error; end Add_Policy; -- ------------------------------ -- Add a permission under the given permission name and associated with the controller. -- To verify the permission, the controller will be called. -- ------------------------------ procedure Add_Permission (Manager : in out Policy_Manager; Name : in String; Permission : in Controller_Access) is use type Permissions.Permission_Index; Index : Permission_Index; begin Log.Info ("Adding permission {0}", Name); Permissions.Add_Permission (Name, Index); if Index >= Manager.Last_Index then declare Count : constant Permission_Index := Index + 32; Perms : constant Controller_Access_Array_Access := new Controller_Access_Array (0 .. Count); begin if Manager.Permissions /= null then Perms (Manager.Permissions'Range) := Manager.Permissions.all; end if; Manager.Permissions := Perms; Manager.Last_Index := Count; end; end if; Manager.Permissions (Index) := Permission; end Add_Permission; -- ------------------------------ -- Checks whether the permission defined by the <b>Permission</b> is granted -- for the security context passed in <b>Context</b>. -- Returns true if such permission is granted. -- ------------------------------ function Has_Permission (Manager : in Policy_Manager; Context : in Security.Contexts.Security_Context'Class; Permission : in Security.Permissions.Permission'Class) return Boolean is use type Permissions.Permission_Index; begin if Permission.Id >= Manager.Last_Index then return False; end if; declare C : constant Controller_Access := Manager.Permissions (Permission.Id); begin if C = null then return False; else return C.Has_Permission (Context, Permission); end if; end; end Has_Permission; -- ------------------------------ -- Create the policy contexts to be associated with the security context. -- ------------------------------ function Create_Policy_Contexts (Manager : in Policy_Manager) return Policy_Context_Array_Access is begin return new Policy_Context_Array (1 .. Manager.Max_Policies); end Create_Policy_Contexts; -- Read the policy file procedure Read_Policy (Manager : in out Policy_Manager; File : in String) is use Util; Reader : Util.Serialize.IO.XML.Parser; package Policy_Config is new Reader_Config (Reader, Manager'Unchecked_Access); pragma Warnings (Off, Policy_Config); begin Log.Info ("Reading policy file {0}", File); -- Prepare the reader to parse the policy configuration. for I in Manager.Policies'Range loop exit when Manager.Policies (I) = null; Manager.Policies (I).Prepare_Config (Reader); end loop; -- Read the configuration file. Reader.Parse (File); -- Finish the policy configuration. for I in Manager.Policies'Range loop exit when Manager.Policies (I) = null; Manager.Policies (I).Finish_Config (Reader); end loop; end Read_Policy; -- Initialize the permission manager. overriding procedure Initialize (Manager : in out Policy_Manager) is begin null; end Initialize; -- Finalize the permission manager. overriding procedure Finalize (Manager : in out Policy_Manager) is procedure Free is new Ada.Unchecked_Deallocation (Security.Controllers.Controller'Class, Controller_Access); procedure Free is new Ada.Unchecked_Deallocation (Controller_Access_Array, Controller_Access_Array_Access); begin if Manager.Permissions /= null then for I in Manager.Permissions.all'Range loop exit when Manager.Permissions (I) = null; -- SCz 2011-12-03: GNAT 2011 reports a compilation error: -- 'missing "with" clause on package "Security.Controllers"' -- if we use the 'Security.Controller_Access' type, even if this "with" clause exist. -- gcc 4.4.3 under Ubuntu does not have this issue. -- We use the 'Security.Controllers.Controller_Access' type to avoid the compiler bug -- but we have to use a temporary variable and do some type conversion... declare P : Controller_Access := Manager.Permissions (I).all'Access; begin Free (P); Manager.Permissions (I) := null; end; end loop; Free (Manager.Permissions); end if; end Finalize; end Security.Policies;
----------------------------------------------------------------------- -- security-policies -- Security Policies -- Copyright (C) 2010, 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Unchecked_Deallocation; with Util.Log.Loggers; with Security.Controllers; with Security.Contexts; package body Security.Policies is -- The logger Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Security.Policies"); -- ------------------------------ -- Get the policy index. -- ------------------------------ function Get_Policy_Index (From : in Policy'Class) return Policy_Index is begin return From.Index; end Get_Policy_Index; -- ------------------------------ -- Add a permission under the given permission name and associated with the controller. -- To verify the permission, the controller will be called. -- ------------------------------ procedure Add_Permission (Manager : in out Policy; Name : in String; Permission : in Controller_Access) is begin Manager.Manager.Add_Permission (Name, Permission); end Add_Permission; -- ------------------------------ -- Permission Manager -- ------------------------------ -- ------------------------------ -- Get the policy with the name <b>Name</b> registered in the policy manager. -- Returns null if there is no such policy. -- ------------------------------ function Get_Policy (Manager : in Policy_Manager; Name : in String) return Policy_Access is begin for I in Manager.Policies'Range loop if Manager.Policies (I) = null then return null; elsif Manager.Policies (I).Get_Name = Name then return Manager.Policies (I); end if; end loop; return null; end Get_Policy; -- ------------------------------ -- Add the policy to the policy manager. After a policy is added in the manager, -- it can participate in the security policy. -- Raises Policy_Error if the policy table is full. -- ------------------------------ procedure Add_Policy (Manager : in out Policy_Manager; Policy : in Policy_Access) is Name : constant String := Policy.Get_Name; begin Log.Info ("Adding policy {0}", Name); for I in Manager.Policies'Range loop if Manager.Policies (I) = null then Manager.Policies (I) := Policy; Policy.Manager := Manager'Unchecked_Access; Policy.Index := I; return; end if; end loop; Log.Error ("Policy table is full, increase policy manager table to {0} to add policy {1}", Policy_Index'Image (Manager.Max_Policies + 1), Name); raise Policy_Error; end Add_Policy; -- ------------------------------ -- Add a permission under the given permission name and associated with the controller. -- To verify the permission, the controller will be called. -- ------------------------------ procedure Add_Permission (Manager : in out Policy_Manager; Name : in String; Permission : in Controller_Access) is use type Permissions.Permission_Index; Index : Permission_Index; begin Log.Info ("Adding permission {0}", Name); Permissions.Add_Permission (Name, Index); if Index >= Manager.Last_Index then declare Count : constant Permission_Index := Index + 32; Perms : constant Controller_Access_Array_Access := new Controller_Access_Array (0 .. Count); begin if Manager.Permissions /= null then Perms (Manager.Permissions'Range) := Manager.Permissions.all; end if; Manager.Permissions := Perms; Manager.Last_Index := Count; end; end if; Manager.Permissions (Index) := Permission; end Add_Permission; -- ------------------------------ -- Checks whether the permission defined by the <b>Permission</b> is granted -- for the security context passed in <b>Context</b>. -- Returns true if such permission is granted. -- ------------------------------ function Has_Permission (Manager : in Policy_Manager; Context : in Security.Contexts.Security_Context'Class; Permission : in Security.Permissions.Permission'Class) return Boolean is use type Permissions.Permission_Index; begin if Permission.Id >= Manager.Last_Index then return False; end if; declare C : constant Controller_Access := Manager.Permissions (Permission.Id); begin if C = null then return False; else return C.Has_Permission (Context, Permission); end if; end; end Has_Permission; -- ------------------------------ -- Create the policy contexts to be associated with the security context. -- ------------------------------ function Create_Policy_Contexts (Manager : in Policy_Manager) return Policy_Context_Array_Access is begin return new Policy_Context_Array (1 .. Manager.Max_Policies); end Create_Policy_Contexts; -- Read the policy file procedure Read_Policy (Manager : in out Policy_Manager; File : in String) is use Util; Reader : Util.Serialize.IO.XML.Parser; package Policy_Config is new Reader_Config (Reader, Manager'Unchecked_Access); pragma Warnings (Off, Policy_Config); begin Log.Info ("Reading policy file {0}", File); -- Prepare the reader to parse the policy configuration. for I in Manager.Policies'Range loop exit when Manager.Policies (I) = null; Manager.Policies (I).Prepare_Config (Reader); end loop; -- Read the configuration file. Reader.Parse (File); -- Finish the policy configuration. for I in Manager.Policies'Range loop exit when Manager.Policies (I) = null; Manager.Policies (I).Finish_Config (Reader); end loop; end Read_Policy; -- Initialize the permission manager. overriding procedure Initialize (Manager : in out Policy_Manager) is begin null; end Initialize; -- Finalize the permission manager. overriding procedure Finalize (Manager : in out Policy_Manager) is procedure Free is new Ada.Unchecked_Deallocation (Security.Controllers.Controller'Class, Controller_Access); procedure Free is new Ada.Unchecked_Deallocation (Controller_Access_Array, Controller_Access_Array_Access); begin if Manager.Permissions /= null then for I in Manager.Permissions.all'Range loop exit when Manager.Permissions (I) = null; -- SCz 2011-12-03: GNAT 2011 reports a compilation error: -- 'missing "with" clause on package "Security.Controllers"' -- if we use the 'Security.Controller_Access' type, even if this "with" clause exist. -- gcc 4.4.3 under Ubuntu does not have this issue. -- We use the 'Security.Controllers.Controller_Access' type to avoid the compiler bug -- but we have to use a temporary variable and do some type conversion... declare P : Controller_Access := Manager.Permissions (I).all'Access; begin Free (P); Manager.Permissions (I) := null; end; end loop; Free (Manager.Permissions); end if; end Finalize; end Security.Policies;
Remove Get_Name
Remove Get_Name
Ada
apache-2.0
stcarrez/ada-security
d3d1eb4349d16da56f72d9e2431bfa3472109465
mat/src/mat-consoles.ads
mat/src/mat-consoles.ads
----------------------------------------------------------------------- -- mat-consoles - 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. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with MAT.Types; package MAT.Consoles is type Field_Type is (F_ADDR, F_SIZE, F_TOTAL_SIZE, F_MIN_SIZE, F_MAX_SIZE, F_MIN_ADDR, F_MAX_ADDR, F_THREAD, F_COUNT, F_FILE_NAME, F_FUNCTION_NAME, F_LINE_NUMBER); type Notice_Type is (N_PID_INFO, N_PATH_INFO); type Console_Type is abstract tagged limited private; type Console_Access is access all Console_Type'Class; -- Report an error message. procedure Error (Console : in out Console_Type; Message : in String) is abstract; -- Report a notice message. procedure Notice (Console : in out Console_Type; Kind : in Notice_Type; Message : in String) is abstract; -- Print the field value for the given field. procedure Print_Field (Console : in out Console_Type; Field : in Field_Type; Value : in String) is abstract; -- Print the title for the given field. procedure Print_Title (Console : in out Console_Type; Field : in Field_Type; Title : in String) is abstract; -- Start a new title in a report. procedure Start_Title (Console : in out Console_Type) is abstract; -- Finish a new title in a report. procedure End_Title (Console : in out Console_Type) is abstract; -- Start a new row in a report. procedure Start_Row (Console : in out Console_Type) is abstract; -- Finish a new row in a report. procedure End_Row (Console : in out Console_Type) is abstract; -- Print the title for the given field and setup the associated field size. procedure Print_Title (Console : in out Console_Type; Field : in Field_Type; Title : in String; Length : in Positive); -- Format the address and print it for the given field. procedure Print_Field (Console : in out Console_Type; Field : in Field_Type; Addr : in MAT.Types.Target_Addr); -- Format the size and print it for the given field. procedure Print_Size (Console : in out Console_Type; Field : in Field_Type; Size : in MAT.Types.Target_Size); -- Format the thread information and print it for the given field. procedure Print_Thread (Console : in out Console_Type; Field : in Field_Type; Thread : in MAT.Types.Target_Thread_Ref); -- Format the integer and print it for the given field. procedure Print_Field (Console : in out Console_Type; Field : in Field_Type; Value : in Integer); -- Format the integer and print it for the given field. procedure Print_Field (Console : in out Console_Type; Field : in Field_Type; Value : in Ada.Strings.Unbounded.Unbounded_String); private type Field_Size_Array is array (Field_Type) of Natural; type Field_List_Array is array (1 .. Field_Type'Pos (Field_Type'Last)) of Field_Type; type Console_Type is abstract tagged limited record Sizes : Field_Size_Array := (others => 1); Cols : Field_Size_Array := (others => 1); Fields : Field_List_Array; Field_Count : Natural := 0; end record; end MAT.Consoles;
----------------------------------------------------------------------- -- mat-consoles - Console interface -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with MAT.Types; package MAT.Consoles is type Field_Type is (F_ADDR, F_SIZE, F_TOTAL_SIZE, F_MIN_SIZE, F_MAX_SIZE, F_MIN_ADDR, F_MAX_ADDR, F_THREAD, F_COUNT, F_FILE_NAME, F_FUNCTION_NAME, F_LINE_NUMBER); type Notice_Type is (N_PID_INFO, N_DURATION, N_PATH_INFO); type Console_Type is abstract tagged limited private; type Console_Access is access all Console_Type'Class; -- Report an error message. procedure Error (Console : in out Console_Type; Message : in String) is abstract; -- Report a notice message. procedure Notice (Console : in out Console_Type; Kind : in Notice_Type; Message : in String) is abstract; -- Print the field value for the given field. procedure Print_Field (Console : in out Console_Type; Field : in Field_Type; Value : in String) is abstract; -- Print the title for the given field. procedure Print_Title (Console : in out Console_Type; Field : in Field_Type; Title : in String) is abstract; -- Start a new title in a report. procedure Start_Title (Console : in out Console_Type) is abstract; -- Finish a new title in a report. procedure End_Title (Console : in out Console_Type) is abstract; -- Start a new row in a report. procedure Start_Row (Console : in out Console_Type) is abstract; -- Finish a new row in a report. procedure End_Row (Console : in out Console_Type) is abstract; -- Print the title for the given field and setup the associated field size. procedure Print_Title (Console : in out Console_Type; Field : in Field_Type; Title : in String; Length : in Positive); -- Format the address and print it for the given field. procedure Print_Field (Console : in out Console_Type; Field : in Field_Type; Addr : in MAT.Types.Target_Addr); -- Format the size and print it for the given field. procedure Print_Size (Console : in out Console_Type; Field : in Field_Type; Size : in MAT.Types.Target_Size); -- Format the thread information and print it for the given field. procedure Print_Thread (Console : in out Console_Type; Field : in Field_Type; Thread : in MAT.Types.Target_Thread_Ref); -- Format the integer and print it for the given field. procedure Print_Field (Console : in out Console_Type; Field : in Field_Type; Value : in Integer); -- Format the integer and print it for the given field. procedure Print_Field (Console : in out Console_Type; Field : in Field_Type; Value : in Ada.Strings.Unbounded.Unbounded_String); private type Field_Size_Array is array (Field_Type) of Natural; type Field_List_Array is array (1 .. Field_Type'Pos (Field_Type'Last)) of Field_Type; type Console_Type is abstract tagged limited record Sizes : Field_Size_Array := (others => 1); Cols : Field_Size_Array := (others => 1); Fields : Field_List_Array; Field_Count : Natural := 0; end record; end MAT.Consoles;
Add the N_DURATION enum
Add the N_DURATION enum
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
a8e5ce99a1040e59928a428e3ae450edbf9c5914
awa/plugins/awa-questions/src/awa-questions-beans.ads
awa/plugins/awa-questions/src/awa-questions-beans.ads
----------------------------------------------------------------------- -- awa-questions-beans -- Beans for module questions -- Copyright (C) 2012, 2013 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Util.Beans.Basic; with Util.Beans.Objects; with AWA.Questions.Modules; with AWA.Questions.Models; with AWA.Questions.Services; package AWA.Questions.Beans is type Question_Bean is new AWA.Questions.Models.Question_Bean with record Service : Services.Question_Service_Access := null; end record; type Question_Bean_Access is access all Question_Bean'Class; -- Get the value identified by the name. overriding function Get_Value (From : in Question_Bean; Name : in String) return Util.Beans.Objects.Object; -- Set the value identified by the name. overriding procedure Set_Value (From : in out Question_Bean; Name : in String; Value : in Util.Beans.Objects.Object); -- Create or save the question. procedure Save (Bean : in out Question_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- Delete the question. procedure Delete (Bean : in out Question_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- Create the Questions_Bean bean instance. function Create_Question_Bean (Module : in AWA.Questions.Modules.Question_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access; type Answer_Bean is new AWA.Questions.Models.Answer_Bean with record Service : Services.Question_Service_Access := null; Question : AWA.Questions.Models.Question_Ref; end record; type Answer_Bean_Access is access all Answer_Bean'Class; -- Get the value identified by the name. overriding function Get_Value (From : in Answer_Bean; Name : in String) return Util.Beans.Objects.Object; -- Set the value identified by the name. overriding procedure Set_Value (From : in out Answer_Bean; Name : in String; Value : in Util.Beans.Objects.Object); -- Create or save the answer. procedure Save (Bean : in out Answer_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- Delete the question. procedure Delete (Bean : in out Answer_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- Create the answer bean instance. function Create_Answer_Bean (Module : in AWA.Questions.Modules.Question_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access; -- Create the Question_Info_List_Bean bean instance. function Create_Question_List_Bean (Module : in AWA.Questions.Modules.Question_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access; type Question_Display_Bean is new Util.Beans.Basic.Bean with record Service : Services.Question_Service_Access := null; Answer_List : aliased AWA.Questions.Models.Answer_Info_List_Bean; Answer_List_Bean : AWA.Questions.Models.Answer_Info_List_Bean_Access; Question : aliased AWA.Questions.Models.Question_Display_Info; Question_Bean : Util.Beans.Basic.Readonly_Bean_Access; end record; type Question_Display_Bean_Access is access all Question_Display_Bean'Class; -- Get the value identified by the name. overriding function Get_Value (From : in Question_Display_Bean; Name : in String) return Util.Beans.Objects.Object; -- Set the value identified by the name. overriding procedure Set_Value (From : in out Question_Display_Bean; Name : in String; Value : in Util.Beans.Objects.Object); -- Create the Question_Display_Bean bean instance. function Create_Question_Display_Bean (Module : in AWA.Questions.Modules.Question_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access; end AWA.Questions.Beans;
----------------------------------------------------------------------- -- awa-questions-beans -- Beans for module questions -- Copyright (C) 2012, 2013 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Util.Beans.Basic; with Util.Beans.Objects; with AWA.Questions.Modules; with AWA.Questions.Models; package AWA.Questions.Beans is type Question_Bean is new AWA.Questions.Models.Question_Bean with record Service : Modules.Question_Module_Access := null; end record; type Question_Bean_Access is access all Question_Bean'Class; -- Get the value identified by the name. overriding function Get_Value (From : in Question_Bean; Name : in String) return Util.Beans.Objects.Object; -- Set the value identified by the name. overriding procedure Set_Value (From : in out Question_Bean; Name : in String; Value : in Util.Beans.Objects.Object); -- Create or save the question. procedure Save (Bean : in out Question_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- Delete the question. procedure Delete (Bean : in out Question_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- Create the Questions_Bean bean instance. function Create_Question_Bean (Module : in AWA.Questions.Modules.Question_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access; type Answer_Bean is new AWA.Questions.Models.Answer_Bean with record Service : Modules.Question_Module_Access := null; Question : AWA.Questions.Models.Question_Ref; end record; type Answer_Bean_Access is access all Answer_Bean'Class; -- Get the value identified by the name. overriding function Get_Value (From : in Answer_Bean; Name : in String) return Util.Beans.Objects.Object; -- Set the value identified by the name. overriding procedure Set_Value (From : in out Answer_Bean; Name : in String; Value : in Util.Beans.Objects.Object); -- Create or save the answer. procedure Save (Bean : in out Answer_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- Delete the question. procedure Delete (Bean : in out Answer_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- Create the answer bean instance. function Create_Answer_Bean (Module : in AWA.Questions.Modules.Question_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access; -- Create the Question_Info_List_Bean bean instance. function Create_Question_List_Bean (Module : in AWA.Questions.Modules.Question_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access; type Question_Display_Bean is new Util.Beans.Basic.Bean with record Service : Modules.Question_Module_Access := null; Answer_List : aliased AWA.Questions.Models.Answer_Info_List_Bean; Answer_List_Bean : AWA.Questions.Models.Answer_Info_List_Bean_Access; Question : aliased AWA.Questions.Models.Question_Display_Info; Question_Bean : Util.Beans.Basic.Readonly_Bean_Access; end record; type Question_Display_Bean_Access is access all Question_Display_Bean'Class; -- Get the value identified by the name. overriding function Get_Value (From : in Question_Display_Bean; Name : in String) return Util.Beans.Objects.Object; -- Set the value identified by the name. overriding procedure Set_Value (From : in out Question_Display_Bean; Name : in String; Value : in Util.Beans.Objects.Object); -- Create the Question_Display_Bean bean instance. function Create_Question_Display_Bean (Module : in AWA.Questions.Modules.Question_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access; end AWA.Questions.Beans;
Move the question services in the question module (simplify the implementation)
Move the question services in the question module (simplify the implementation)
Ada
apache-2.0
tectronics/ada-awa,Letractively/ada-awa,tectronics/ada-awa,Letractively/ada-awa,tectronics/ada-awa,Letractively/ada-awa
7de40b2014f655cb5cf2ce60a31b7b7edb86e23e
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 := 99999.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; if (1.0 / ratio) < best_ratio then best := Ten_Million(Long_Float'Rounding(num)); best_ratio := 1.0 / ratio; end if; 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 Check(total, ratio); 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 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;
Use inverse ratio because I don't need the ratio itself.
Use inverse ratio because I don't need the ratio itself. Check the ratio (cheap) before we do the permutation check (expensive), which halves the runtime for me.
Ada
unlicense
Tim-Tom/project-euler,Tim-Tom/project-euler,Tim-Tom/project-euler
b13561bb5b13357f62d6ab22a01e8ab7eea527d1
src/natools-s_expressions-templates-dates.adb
src/natools-s_expressions-templates-dates.adb
------------------------------------------------------------------------------ -- Copyright (c) 2014, Natacha Porté -- -- -- -- Permission to use, copy, modify, and distribute this software for any -- -- purpose with or without fee is hereby granted, provided that the above -- -- copyright notice and this permission notice appear in all copies. -- -- -- -- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES -- -- WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -- -- MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR -- -- ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -- -- WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -- -- ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF -- -- OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -- ------------------------------------------------------------------------------ with Natools.S_Expressions.Interpreter_Loop; with Natools.S_Expressions.Templates.Generic_Discrete_Render; with Natools.S_Expressions.Templates.Integers; with Natools.Static_Maps.S_Expressions.Templates.Dates; with Natools.Time_IO.RFC_3339; package body Natools.S_Expressions.Templates.Dates is package Commands renames Natools.Static_Maps.S_Expressions.Templates.Dates; procedure Render_Day_Of_Week is new Natools.S_Expressions.Templates.Generic_Discrete_Render (Ada.Calendar.Formatting.Day_Name, Ada.Calendar.Formatting.Day_Name'Image, Ada.Calendar.Formatting."="); procedure Append (Output : in out Ada.Streams.Root_Stream_Type'Class; Value : in Split_Time; Data : in Atom); procedure Execute (Output : in out Ada.Streams.Root_Stream_Type'Class; Value : in Split_Time; Name : in Atom; Arguments : in out Lockable.Descriptor'Class); function Two_Digit_Image (Value : Integer) return Atom is ((1 => Character'Pos ('0') + Octet (Value / 10), 2 => Character'Pos ('0') + Octet (Value mod 10))) with Pre => Value in 0 .. 99; function Four_Digit_Image (Value : Integer) return Atom is ((1 => Character'Pos ('0') + Octet (Value / 1000), 2 => Character'Pos ('0') + Octet ((Value / 100) mod 10), 3 => Character'Pos ('0') + Octet ((Value / 10) mod 10), 4 => Character'Pos ('0') + Octet (Value mod 10))) with Pre => Value in 0 .. 9999; function Parse_Time_Offset (Image : in String; Date : in Ada.Calendar.Time) return Ada.Calendar.Time_Zones.Time_Offset; procedure Render_Triplet (Output : in out Ada.Streams.Root_Stream_Type'Class; Part_1, Part_2, Part_3 : in Atom; Template : in out Lockable.Descriptor'Class); procedure Interpreter is new Interpreter_Loop (Ada.Streams.Root_Stream_Type'Class, Split_Time, Execute, Append); ------------------------------ -- Local Helper Subprograms -- ------------------------------ function Parse_Time_Offset (Image : in String; Date : in Ada.Calendar.Time) return Ada.Calendar.Time_Zones.Time_Offset is function Value (C : Character) return Ada.Calendar.Time_Zones.Time_Offset; function Value (C : Character) return Ada.Calendar.Time_Zones.Time_Offset is begin if C in '0' .. '9' then return Ada.Calendar.Time_Zones.Time_Offset (Character'Pos (C) - Character'Pos ('0')); else raise Constraint_Error with "Unknown time offset format"; end if; end Value; begin if Image = "system" then return Ada.Calendar.Time_Zones.UTC_Time_Offset (Date); end if; Abbreviation : begin return Ada.Calendar.Time_Zones.Time_Offset (Static_Maps.S_Expressions.Templates.Dates.To_Time_Offset (Image)); exception when Constraint_Error => null; end Abbreviation; Numeric : declare use type Ada.Calendar.Time_Zones.Time_Offset; First : Integer := Image'First; Length : Natural := Image'Length; V : Ada.Calendar.Time_Zones.Time_Offset; Negative : Boolean := False; begin if First in Image'Range and then Image (First) in '-' | '+' then Negative := Image (First) = '-'; First := First + 1; Length := Length - 1; end if; case Length is when 1 => V := Value (Image (First)) * 60; when 2 => V := Value (Image (First)) * 600 + Value (Image (First + 1)) * 60; when 4 => V := Value (Image (First)) * 600 + Value (Image (First + 1)) * 60 + Value (Image (First + 2)) * 10 + Value (Image (First + 3)); when 5 => if Image (First + 2) in '0' .. '9' then raise Constraint_Error with "Unknown time offset format"; end if; V := Value (Image (First)) * 600 + Value (Image (First + 1)) * 60 + Value (Image (First + 3)) * 10 + Value (Image (First + 4)); when others => raise Constraint_Error with "Unknown time offset format"; end case; if Negative then return -V; else return V; end if; end Numeric; end Parse_Time_Offset; procedure Render_Triplet (Output : in out Ada.Streams.Root_Stream_Type'Class; Part_1, Part_2, Part_3 : in Atom; Template : in out Lockable.Descriptor'Class) is begin Output.Write (Part_1); if Template.Current_Event = Events.Add_Atom then declare Separator : constant Atom := Template.Current_Atom; Event : Events.Event; begin Template.Next (Event); Output.Write (Separator); Output.Write (Part_2); if Event = Events.Add_Atom then Output.Write (Template.Current_Atom); else Output.Write (Separator); end if; end; else Output.Write (Part_2); end if; Output.Write (Part_3); end Render_Triplet; ---------------------------- -- Interpreter Components -- ---------------------------- procedure Append (Output : in out Ada.Streams.Root_Stream_Type'Class; Value : in Split_Time; Data : in Atom) is pragma Unreferenced (Value); begin Output.Write (Data); end Append; procedure Execute (Output : in out Ada.Streams.Root_Stream_Type'Class; Value : in Split_Time; Name : in Atom; Arguments : in out Lockable.Descriptor'Class) is Format : Integers.Format; begin case Commands.Main (To_String (Name)) is when Commands.Error => null; when Commands.Big_Endian_Date => Render_Triplet (Output, Four_Digit_Image (Value.Year), Two_Digit_Image (Value.Month), Two_Digit_Image (Value.Day), Arguments); when Commands.Big_Endian_Time => Render_Triplet (Output, Two_Digit_Image (Value.Hour), Two_Digit_Image (Value.Minute), Two_Digit_Image (Value.Second), Arguments); when Commands.Day => Format.Set_Image (0, Null_Atom); Integers.Render (Output, Format, Arguments, Value.Day); when Commands.Day_Of_Week => Render_Day_Of_Week (Output, Arguments, Value.Day_Of_Week); when Commands.Hour => Format.Set_Image (-1, Null_Atom); Integers.Render (Output, Format, Arguments, Value.Hour); when Commands.Little_Endian_Date => Render_Triplet (Output, Two_Digit_Image (Value.Day), Two_Digit_Image (Value.Month), Four_Digit_Image (Value.Year), Arguments); when Commands.Little_Endian_Time => Render_Triplet (Output, Two_Digit_Image (Value.Second), Two_Digit_Image (Value.Minute), Two_Digit_Image (Value.Hour), Arguments); when Commands.Minute => Format.Set_Image (-1, Null_Atom); Integers.Render (Output, Format, Arguments, Value.Minute); when Commands.Month => Format.Set_Image (0, Null_Atom); Integers.Render (Output, Format, Arguments, Value.Month); when Commands.Padded_Day => Format.Set_Image (0, Null_Atom); Format.Set_Minimum_Width (2); Format.Set_Left_Padding ((1 => Character'Pos ('0'))); Format.Set_Align (Integers.Right_Aligned); Integers.Render (Output, Format, Arguments, Value.Day); when Commands.Padded_Hour => Format.Set_Image (-1, Null_Atom); Format.Set_Minimum_Width (2); Format.Set_Left_Padding ((1 => Character'Pos ('0'))); Format.Set_Align (Integers.Right_Aligned); Integers.Render (Output, Format, Arguments, Value.Hour); when Commands.Padded_Minute => Format.Set_Image (-1, Null_Atom); Format.Set_Minimum_Width (2); Format.Set_Left_Padding ((1 => Character'Pos ('0'))); Format.Set_Align (Integers.Right_Aligned); Integers.Render (Output, Format, Arguments, Value.Minute); when Commands.Padded_Month => Format.Set_Image (0, Null_Atom); Format.Set_Minimum_Width (2); Format.Set_Left_Padding ((1 => Character'Pos ('0'))); Format.Set_Align (Integers.Right_Aligned); Integers.Render (Output, Format, Arguments, Value.Month); when Commands.Padded_Second => Format.Set_Image (-1, Null_Atom); Format.Set_Minimum_Width (2); Format.Set_Left_Padding ((1 => Character'Pos ('0'))); Format.Set_Align (Integers.Right_Aligned); Integers.Render (Output, Format, Arguments, Value.Second); when Commands.RFC_3339 => Output.Write (To_Atom (Time_IO.RFC_3339.Image (Value.Source, Value.Time_Zone))); when Commands.Second => Format.Set_Image (-1, Null_Atom); Integers.Render (Output, Format, Arguments, Value.Second); when Commands.With_Offset => if Arguments.Current_Event = Events.Add_Atom then declare use type Ada.Calendar.Time_Zones.Time_Offset; New_Offset : Ada.Calendar.Time_Zones.Time_Offset; begin begin New_Offset := Parse_Time_Offset (S_Expressions.To_String (Arguments.Current_Atom), Value.Source); exception when Constraint_Error => return; end; Arguments.Next; if New_Offset = Value.Time_Zone then Interpreter (Arguments, Output, Value); else Render (Output, Arguments, Value.Source, New_Offset); end if; end; end if; when Commands.Year => Integers.Render (Output, Arguments, Value.Year); end case; end Execute; ---------------------- -- Public Interface -- ---------------------- function Split (Value : Ada.Calendar.Time; Time_Zone : Ada.Calendar.Time_Zones.Time_Offset) return Split_Time is Year : Ada.Calendar.Year_Number; Month : Ada.Calendar.Month_Number; Day : Ada.Calendar.Day_Number; Hour : Ada.Calendar.Formatting.Hour_Number; Minute : Ada.Calendar.Formatting.Minute_Number; Second : Ada.Calendar.Formatting.Second_Number; Sub_Second : Ada.Calendar.Formatting.Second_Duration; begin Ada.Calendar.Formatting.Split (Value, Year, Month, Day, Hour, Minute, Second, Sub_Second, Time_Zone); return Split_Time' (Source => Value, Time_Zone => Time_Zone, Year => Year, Month => Month, Day => Day, Day_Of_Week => Ada.Calendar.Formatting.Day_Of_Week (Value), Hour => Hour, Minute => Minute, Second => Second, Sub_Second => Sub_Second); end Split; procedure Render (Output : in out Ada.Streams.Root_Stream_Type'Class; Template : in out Lockable.Descriptor'Class; Value : in Ada.Calendar.Time) is begin Render (Output, Template, Value, Ada.Calendar.Time_Zones.UTC_Time_Offset (Value)); end Render; procedure Render (Output : in out Ada.Streams.Root_Stream_Type'Class; Template : in out Lockable.Descriptor'Class; Value : in Ada.Calendar.Time; Time_Zone : Ada.Calendar.Time_Zones.Time_Offset) is begin Render (Output, Template, Split (Value, Time_Zone)); end Render; procedure Render (Output : in out Ada.Streams.Root_Stream_Type'Class; Template : in out Lockable.Descriptor'Class; Value : in Split_Time) is begin Interpreter (Template, Output, Value); end Render; end Natools.S_Expressions.Templates.Dates;
------------------------------------------------------------------------------ -- Copyright (c) 2014-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. -- ------------------------------------------------------------------------------ with Natools.S_Expressions.Interpreter_Loop; with Natools.S_Expressions.Templates.Generic_Discrete_Render; with Natools.S_Expressions.Templates.Integers; with Natools.Static_Maps.S_Expressions.Templates.Dates; with Natools.Time_IO.RFC_3339; package body Natools.S_Expressions.Templates.Dates is package Commands renames Natools.Static_Maps.S_Expressions.Templates.Dates; procedure Render_Day_Of_Week is new Natools.S_Expressions.Templates.Generic_Discrete_Render (Ada.Calendar.Formatting.Day_Name, Ada.Calendar.Formatting.Day_Name'Image, Ada.Calendar.Formatting."="); procedure Append (Output : in out Ada.Streams.Root_Stream_Type'Class; Value : in Split_Time; Data : in Atom); procedure Execute (Output : in out Ada.Streams.Root_Stream_Type'Class; Value : in Split_Time; Name : in Atom; Arguments : in out Lockable.Descriptor'Class); function Two_Digit_Image (Value : Integer) return Atom is ((1 => Character'Pos ('0') + Octet (Value / 10), 2 => Character'Pos ('0') + Octet (Value mod 10))) with Pre => Value in 0 .. 99; function Four_Digit_Image (Value : Integer) return Atom is ((1 => Character'Pos ('0') + Octet (Value / 1000), 2 => Character'Pos ('0') + Octet ((Value / 100) mod 10), 3 => Character'Pos ('0') + Octet ((Value / 10) mod 10), 4 => Character'Pos ('0') + Octet (Value mod 10))) with Pre => Value in 0 .. 9999; function Parse_Time_Offset (Image : in String; Date : in Ada.Calendar.Time) return Ada.Calendar.Time_Zones.Time_Offset; procedure Render_Triplet (Output : in out Ada.Streams.Root_Stream_Type'Class; Part_1, Part_2, Part_3 : in Atom; Template : in out Lockable.Descriptor'Class); procedure Interpreter is new Interpreter_Loop (Ada.Streams.Root_Stream_Type'Class, Split_Time, Execute, Append); ------------------------------ -- Local Helper Subprograms -- ------------------------------ function Parse_Time_Offset (Image : in String; Date : in Ada.Calendar.Time) return Ada.Calendar.Time_Zones.Time_Offset is function Value (C : Character) return Ada.Calendar.Time_Zones.Time_Offset; function Value (C : Character) return Ada.Calendar.Time_Zones.Time_Offset is begin if C in '0' .. '9' then return Ada.Calendar.Time_Zones.Time_Offset (Character'Pos (C) - Character'Pos ('0')); else raise Constraint_Error with "Unknown time offset format"; end if; end Value; begin if Image = "system" then return Ada.Calendar.Time_Zones.UTC_Time_Offset (Date); end if; Abbreviation : begin return Ada.Calendar.Time_Zones.Time_Offset (Static_Maps.S_Expressions.Templates.Dates.To_Time_Offset (Image)); exception when Constraint_Error => null; end Abbreviation; Numeric : declare use type Ada.Calendar.Time_Zones.Time_Offset; First : Integer := Image'First; Length : Natural := Image'Length; V : Ada.Calendar.Time_Zones.Time_Offset; Negative : Boolean := False; begin if First in Image'Range and then Image (First) in '-' | '+' then Negative := Image (First) = '-'; First := First + 1; Length := Length - 1; end if; case Length is when 1 => V := Value (Image (First)) * 60; when 2 => V := Value (Image (First)) * 600 + Value (Image (First + 1)) * 60; when 4 => V := Value (Image (First)) * 600 + Value (Image (First + 1)) * 60 + Value (Image (First + 2)) * 10 + Value (Image (First + 3)); when 5 => if Image (First + 2) in '0' .. '9' then raise Constraint_Error with "Unknown time offset format"; end if; V := Value (Image (First)) * 600 + Value (Image (First + 1)) * 60 + Value (Image (First + 3)) * 10 + Value (Image (First + 4)); when others => raise Constraint_Error with "Unknown time offset format"; end case; if Negative then return -V; else return V; end if; end Numeric; end Parse_Time_Offset; procedure Render_Triplet (Output : in out Ada.Streams.Root_Stream_Type'Class; Part_1, Part_2, Part_3 : in Atom; Template : in out Lockable.Descriptor'Class) is begin Output.Write (Part_1); if Template.Current_Event = Events.Add_Atom then declare Separator : constant Atom := Template.Current_Atom; Event : Events.Event; begin Template.Next (Event); Output.Write (Separator); Output.Write (Part_2); if Event = Events.Add_Atom then Output.Write (Template.Current_Atom); else Output.Write (Separator); end if; end; else Output.Write (Part_2); end if; Output.Write (Part_3); end Render_Triplet; ---------------------------- -- Interpreter Components -- ---------------------------- procedure Append (Output : in out Ada.Streams.Root_Stream_Type'Class; Value : in Split_Time; Data : in Atom) is pragma Unreferenced (Value); begin Output.Write (Data); end Append; procedure Execute (Output : in out Ada.Streams.Root_Stream_Type'Class; Value : in Split_Time; Name : in Atom; Arguments : in out Lockable.Descriptor'Class) is Format : Integers.Format; begin case Commands.Main (To_String (Name)) is when Commands.Error => null; when Commands.Big_Endian_Date => Render_Triplet (Output, Four_Digit_Image (Value.Year), Two_Digit_Image (Value.Month), Two_Digit_Image (Value.Day), Arguments); when Commands.Big_Endian_Time => Render_Triplet (Output, Two_Digit_Image (Value.Hour), Two_Digit_Image (Value.Minute), Two_Digit_Image (Value.Second), Arguments); when Commands.Day => Format.Set_Image (0, Null_Atom); Integers.Render (Output, Format, Arguments, Value.Day); when Commands.Day_Of_Week => Render_Day_Of_Week (Output, Arguments, Value.Day_Of_Week); when Commands.Hour => Format.Set_Image (-1, Null_Atom); Integers.Render (Output, Format, Arguments, Value.Hour); when Commands.Little_Endian_Date => Render_Triplet (Output, Two_Digit_Image (Value.Day), Two_Digit_Image (Value.Month), Four_Digit_Image (Value.Year), Arguments); when Commands.Little_Endian_Time => Render_Triplet (Output, Two_Digit_Image (Value.Second), Two_Digit_Image (Value.Minute), Two_Digit_Image (Value.Hour), Arguments); when Commands.Minute => Format.Set_Image (-1, Null_Atom); Integers.Render (Output, Format, Arguments, Value.Minute); when Commands.Month => Format.Set_Image (0, Null_Atom); Integers.Render (Output, Format, Arguments, Value.Month); when Commands.Padded_Day => Format.Set_Image (0, Null_Atom); Format.Set_Minimum_Width (2); Format.Set_Left_Padding ((1 => Character'Pos ('0'))); Format.Set_Align (Integers.Right_Aligned); Integers.Render (Output, Format, Arguments, Value.Day); when Commands.Padded_Hour => Format.Set_Image (-1, Null_Atom); Format.Set_Minimum_Width (2); Format.Set_Left_Padding ((1 => Character'Pos ('0'))); Format.Set_Align (Integers.Right_Aligned); Integers.Render (Output, Format, Arguments, Value.Hour); when Commands.Padded_Minute => Format.Set_Image (-1, Null_Atom); Format.Set_Minimum_Width (2); Format.Set_Left_Padding ((1 => Character'Pos ('0'))); Format.Set_Align (Integers.Right_Aligned); Integers.Render (Output, Format, Arguments, Value.Minute); when Commands.Padded_Month => Format.Set_Image (0, Null_Atom); Format.Set_Minimum_Width (2); Format.Set_Left_Padding ((1 => Character'Pos ('0'))); Format.Set_Align (Integers.Right_Aligned); Integers.Render (Output, Format, Arguments, Value.Month); when Commands.Padded_Second => Format.Set_Image (-1, Null_Atom); Format.Set_Minimum_Width (2); Format.Set_Left_Padding ((1 => Character'Pos ('0'))); Format.Set_Align (Integers.Right_Aligned); Integers.Render (Output, Format, Arguments, Value.Second); when Commands.RFC_3339 => Output.Write (To_Atom (Time_IO.RFC_3339.Image (Value.Source, Value.Time_Zone))); when Commands.Second => Format.Set_Image (-1, Null_Atom); Integers.Render (Output, Format, Arguments, Value.Second); when Commands.With_Offset => if Arguments.Current_Event = Events.Add_Atom then declare use type Ada.Calendar.Time_Zones.Time_Offset; New_Offset : Ada.Calendar.Time_Zones.Time_Offset; begin begin New_Offset := Parse_Time_Offset (S_Expressions.To_String (Arguments.Current_Atom), Value.Source); exception when Constraint_Error => return; end; Arguments.Next; if New_Offset = Value.Time_Zone then Interpreter (Arguments, Output, Value); else Render (Output, Arguments, Value.Source, New_Offset); end if; end; end if; when Commands.Year => Integers.Render (Output, Arguments, Value.Year); end case; end Execute; ---------------------- -- Public Interface -- ---------------------- function Split (Value : Ada.Calendar.Time; Time_Zone : Ada.Calendar.Time_Zones.Time_Offset) return Split_Time is use type Ada.Calendar.Time_Zones.Time_Offset; Zone_Offset : constant Ada.Calendar.Time_Zones.Time_Offset := Time_Zone - Ada.Calendar.Time_Zones.UTC_Time_Offset (Value); Year : Ada.Calendar.Year_Number; Month : Ada.Calendar.Month_Number; Day : Ada.Calendar.Day_Number; Hour : Ada.Calendar.Formatting.Hour_Number; Minute : Ada.Calendar.Formatting.Minute_Number; Second : Ada.Calendar.Formatting.Second_Number; Sub_Second : Ada.Calendar.Formatting.Second_Duration; begin Ada.Calendar.Formatting.Split (Value, Year, Month, Day, Hour, Minute, Second, Sub_Second, Time_Zone); return Split_Time' (Source => Value, Time_Zone => Time_Zone, Year => Year, Month => Month, Day => Day, Day_Of_Week => Ada.Calendar.Formatting.Day_Of_Week (Ada.Calendar."+" (Value, 60 * Duration (Zone_Offset))), Hour => Hour, Minute => Minute, Second => Second, Sub_Second => Sub_Second); end Split; procedure Render (Output : in out Ada.Streams.Root_Stream_Type'Class; Template : in out Lockable.Descriptor'Class; Value : in Ada.Calendar.Time) is begin Render (Output, Template, Value, Ada.Calendar.Time_Zones.UTC_Time_Offset (Value)); end Render; procedure Render (Output : in out Ada.Streams.Root_Stream_Type'Class; Template : in out Lockable.Descriptor'Class; Value : in Ada.Calendar.Time; Time_Zone : Ada.Calendar.Time_Zones.Time_Offset) is begin Render (Output, Template, Split (Value, Time_Zone)); end Render; procedure Render (Output : in out Ada.Streams.Root_Stream_Type'Class; Template : in out Lockable.Descriptor'Class; Value : in Split_Time) is begin Interpreter (Template, Output, Value); end Render; end Natools.S_Expressions.Templates.Dates;
fix incorrect weekday w.r.t. time zone
s_expressions-templates-dates: fix incorrect weekday w.r.t. time zone
Ada
isc
faelys/natools
873af7f5a507ec557aa190ccf3930712191c7a92
mat/src/mat-commands.adb
mat/src/mat-commands.adb
----------------------------------------------------------------------- -- mat-interp -- Command interpreter -- 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.Strings; with Util.Log.Loggers; with Ada.Containers.Indefinite_Hashed_Maps; with Ada.Strings.Hash; with Ada.IO_Exceptions; with Ada.Text_IO; with Ada.Strings.Unbounded; with MAT.Types; with MAT.Readers.Files; with MAT.Memory.Tools; with MAT.Memory.Targets; with MAT.Symbols.Targets; with MAT.Frames; with MAT.Frames.Print; with MAT.Consoles; package body MAT.Commands is -- The logger Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("MAT.Commands"); package Command_Map is new Ada.Containers.Indefinite_Hashed_Maps (Key_Type => String, Element_Type => Command_Handler, Equivalent_Keys => "=", Hash => Ada.Strings.Hash); Commands : Command_Map.Map; -- ------------------------------ -- Sizes command. -- Collect statistics about the used memory slots and report the different slot -- sizes with count. -- ------------------------------ procedure Slot_Command (Target : in out MAT.Targets.Target_Type'Class; Args : in String) is Slots : MAT.Memory.Allocation_Map; Iter : MAT.Memory.Allocation_Cursor; procedure Print (Addr : in MAT.Types.Target_Addr; Slot : in MAT.Memory.Allocation) is use type MAT.Frames.Frame_Type; Backtrace : MAT.Frames.Frame_Table := MAT.Frames.Backtrace (Slot.Frame); Name : Ada.Strings.Unbounded.Unbounded_String; Func : Ada.Strings.Unbounded.Unbounded_String; Line : Natural; begin Ada.Text_IO.Put (MAT.Types.Hex_Image (Addr)); Ada.Text_IO.Set_Col (14); Ada.Text_IO.Put (MAT.Types.Target_Size'Image (Slot.Size)); Ada.Text_IO.Set_Col (30); Ada.Text_IO.Put (MAT.Types.Target_Thread_Ref'Image (Slot.Thread)); Ada.Text_IO.Set_Col (50); Ada.Text_IO.Put (MAT.Types.Target_Tick_Ref'Image (Slot.Time)); Ada.Text_IO.New_Line; for I in Backtrace'Range loop Ada.Text_IO.Put (" "); Ada.Text_IO.Put (Natural'Image (I)); Ada.Text_IO.Put (" "); Ada.Text_IO.Put (MAT.Types.Hex_Image (Backtrace (I))); MAT.Symbols.Targets.Find_Nearest_Line (Symbols => Target.Symbols, Addr => Backtrace (I), Name => Name, Func => Func, Line => Line); Ada.Text_IO.Put (" "); Ada.Text_IO.Put (Ada.Strings.Unbounded.To_String (Func)); Ada.Text_IO.Put (" "); Ada.Text_IO.Put (Ada.Strings.Unbounded.To_String (Name)); if Line /= 0 then Ada.Text_IO.Put (":"); Ada.Text_IO.Put (Util.Strings.Image (Line)); end if; Ada.Text_IO.New_Line; end loop; end Print; begin Target.Memory.Find (From => MAT.Types.Target_Addr'First, To => MAT.Types.Target_Addr'Last, Into => Slots); Iter := Slots.First; while MAT.Memory.Allocation_Maps.Has_Element (Iter) loop MAT.Memory.Allocation_Maps.Query_Element (Iter, Print'Access); MAT.Memory.Allocation_Maps.Next (Iter); end loop; end Slot_Command; -- ------------------------------ -- Sizes command. -- Collect statistics about the used memory slots and report the different slot -- sizes with count. -- ------------------------------ procedure Sizes_Command (Target : in out MAT.Targets.Target_Type'Class; Args : in String) is Sizes : MAT.Memory.Tools.Size_Info_Map; Iter : MAT.Memory.Tools.Size_Info_Cursor; Console : constant MAT.Consoles.Console_Access := Target.Console; begin Console.Start_Title; Console.Print_Title (MAT.Consoles.F_SIZE, "Slot size", 25); Console.Print_Title (MAT.Consoles.F_COUNT, "Count", 15); Console.Print_Title (MAT.Consoles.F_TOTAL_SIZE, "Total size", 15); Console.End_Title; MAT.Memory.Targets.Size_Information (Memory => Target.Memory, Sizes => Sizes); Iter := Sizes.First; while MAT.Memory.Tools.Size_Info_Maps.Has_Element (Iter) loop declare use type MAT.Types.Target_Size; Size : MAT.Types.Target_Size := MAT.Memory.Tools.Size_Info_Maps.Key (Iter); Info : MAT.Memory.Tools.Size_Info_Type := MAT.Memory.Tools.Size_Info_Maps.Element (Iter); Total : MAT.Types.Target_Size := Size * MAT.Types.Target_Size (Info.Count); begin Console.Start_Row; Console.Print_Size (MAT.Consoles.F_SIZE, Size); Console.Print_Field (MAT.Consoles.F_COUNT, Info.Count); Console.Print_Field (MAT.Consoles.F_TOTAL_SIZE, Total); Console.End_Row; end; MAT.Memory.Tools.Size_Info_Maps.Next (Iter); end loop; end Sizes_Command; -- ------------------------------ -- Symbol command. -- Load the symbols from the binary file. -- ------------------------------ procedure Symbol_Command (Target : in out MAT.Targets.Target_Type'Class; Args : in String) is begin MAT.Symbols.Targets.Open (Target.Symbols, Args); end Symbol_Command; -- ------------------------------ -- Exit command. -- ------------------------------ procedure Exit_Command (Target : in out MAT.Targets.Target_Type'Class; Args : in String) is begin raise Stop_Interp; end Exit_Command; -- ------------------------------ -- Open a MAT file and read the events. -- ------------------------------ procedure Open_Command (Target : in out MAT.Targets.Target_Type'Class; Args : in String) is Reader : MAT.Readers.Files.File_Reader_Type; begin Target.Initialize (Reader); Reader.Open (Args); Reader.Read_All; exception when E : Ada.IO_Exceptions.Name_Error => Log.Error ("Cannot open {0}", Args); end Open_Command; function Get_Command (Line : in String) return String is Pos : Natural := Util.Strings.Index (Line, ' '); begin if Pos <= 0 then return Line; else return Line (Line'First .. Pos - 1); end if; end Get_Command; -- ------------------------------ -- Execute the command given in the line. -- ------------------------------ procedure Execute (Target : in out MAT.Targets.Target_Type'Class; Line : in String) is Command : constant String := Get_Command (Line); Index : constant Natural := Util.Strings.Index (Line, ' '); Pos : constant Command_Map.Cursor := Commands.Find (Command); begin if Command_Map.Has_Element (Pos) then Command_Map.Element (Pos) (Target, Line (Index + 1 .. Line'Last)); elsif Command'Length > 0 then Ada.Text_IO.Put_Line ("Command '" & Command & "' not found"); end if; end Execute; begin Commands.Insert ("exit", Exit_Command'Access); Commands.Insert ("quit", Exit_Command'Access); Commands.Insert ("open", Open_Command'Access); Commands.Insert ("sizes", Sizes_Command'Access); Commands.Insert ("symbol", Symbol_Command'Access); Commands.Insert ("slots", Slot_Command'Access); end MAT.Commands;
----------------------------------------------------------------------- -- mat-interp -- Command interpreter -- 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.Strings; with Util.Log.Loggers; with Ada.Containers.Indefinite_Hashed_Maps; with Ada.Strings.Hash; with Ada.IO_Exceptions; with Ada.Text_IO; with Ada.Strings.Unbounded; with MAT.Types; with MAT.Readers.Files; with MAT.Memory.Tools; with MAT.Memory.Targets; with MAT.Symbols.Targets; with MAT.Frames; with MAT.Frames.Print; with MAT.Consoles; package body MAT.Commands is -- The logger Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("MAT.Commands"); package Command_Map is new Ada.Containers.Indefinite_Hashed_Maps (Key_Type => String, Element_Type => Command_Handler, Equivalent_Keys => "=", Hash => Ada.Strings.Hash); Commands : Command_Map.Map; -- ------------------------------ -- Sizes command. -- Collect statistics about the used memory slots and report the different slot -- sizes with count. -- ------------------------------ procedure Slot_Command (Target : in out MAT.Targets.Target_Type'Class; Args : in String) is Slots : MAT.Memory.Allocation_Map; Iter : MAT.Memory.Allocation_Cursor; procedure Print (Addr : in MAT.Types.Target_Addr; Slot : in MAT.Memory.Allocation) is use type MAT.Frames.Frame_Type; Backtrace : MAT.Frames.Frame_Table := MAT.Frames.Backtrace (Slot.Frame); Name : Ada.Strings.Unbounded.Unbounded_String; Func : Ada.Strings.Unbounded.Unbounded_String; Line : Natural; begin Ada.Text_IO.Put (MAT.Types.Hex_Image (Addr)); Ada.Text_IO.Set_Col (14); Ada.Text_IO.Put (MAT.Types.Target_Size'Image (Slot.Size)); Ada.Text_IO.Set_Col (30); Ada.Text_IO.Put (MAT.Types.Target_Thread_Ref'Image (Slot.Thread)); Ada.Text_IO.Set_Col (50); Ada.Text_IO.Put (MAT.Types.Target_Tick_Ref'Image (Slot.Time)); Ada.Text_IO.New_Line; for I in Backtrace'Range loop Ada.Text_IO.Put (" "); Ada.Text_IO.Put (Natural'Image (I)); Ada.Text_IO.Put (" "); Ada.Text_IO.Put (MAT.Types.Hex_Image (Backtrace (I))); MAT.Symbols.Targets.Find_Nearest_Line (Symbols => Target.Symbols, Addr => Backtrace (I), Name => Name, Func => Func, Line => Line); Ada.Text_IO.Put (" "); Ada.Text_IO.Put (Ada.Strings.Unbounded.To_String (Func)); Ada.Text_IO.Put (" "); Ada.Text_IO.Put (Ada.Strings.Unbounded.To_String (Name)); if Line /= 0 then Ada.Text_IO.Put (":"); Ada.Text_IO.Put (Util.Strings.Image (Line)); end if; Ada.Text_IO.New_Line; end loop; end Print; begin Target.Memory.Find (From => MAT.Types.Target_Addr'First, To => MAT.Types.Target_Addr'Last, Into => Slots); Iter := Slots.First; while MAT.Memory.Allocation_Maps.Has_Element (Iter) loop MAT.Memory.Allocation_Maps.Query_Element (Iter, Print'Access); MAT.Memory.Allocation_Maps.Next (Iter); end loop; end Slot_Command; -- ------------------------------ -- Sizes command. -- Collect statistics about the used memory slots and report the different slot -- sizes with count. -- ------------------------------ procedure Sizes_Command (Target : in out MAT.Targets.Target_Type'Class; Args : in String) is Sizes : MAT.Memory.Tools.Size_Info_Map; Iter : MAT.Memory.Tools.Size_Info_Cursor; Console : constant MAT.Consoles.Console_Access := Target.Console; begin Console.Start_Title; Console.Print_Title (MAT.Consoles.F_SIZE, "Slot size", 25); Console.Print_Title (MAT.Consoles.F_COUNT, "Count", 15); Console.Print_Title (MAT.Consoles.F_TOTAL_SIZE, "Total size", 15); Console.End_Title; MAT.Memory.Targets.Size_Information (Memory => Target.Memory, Sizes => Sizes); Iter := Sizes.First; while MAT.Memory.Tools.Size_Info_Maps.Has_Element (Iter) loop declare use type MAT.Types.Target_Size; Size : MAT.Types.Target_Size := MAT.Memory.Tools.Size_Info_Maps.Key (Iter); Info : MAT.Memory.Tools.Size_Info_Type := MAT.Memory.Tools.Size_Info_Maps.Element (Iter); Total : MAT.Types.Target_Size := Size * MAT.Types.Target_Size (Info.Count); begin Console.Start_Row; Console.Print_Size (MAT.Consoles.F_SIZE, Size); Console.Print_Field (MAT.Consoles.F_COUNT, Info.Count); Console.Print_Field (MAT.Consoles.F_TOTAL_SIZE, Total); Console.End_Row; end; MAT.Memory.Tools.Size_Info_Maps.Next (Iter); end loop; end Sizes_Command; -- ------------------------------ -- Symbol command. -- Load the symbols from the binary file. -- ------------------------------ procedure Symbol_Command (Target : in out MAT.Targets.Target_Type'Class; Args : in String) is begin MAT.Symbols.Targets.Open (Target.Symbols, Args); end Symbol_Command; -- ------------------------------ -- Exit command. -- ------------------------------ procedure Exit_Command (Target : in out MAT.Targets.Target_Type'Class; Args : in String) is begin raise Stop_Interp; end Exit_Command; -- ------------------------------ -- Open a MAT file and read the events. -- ------------------------------ procedure Open_Command (Target : in out MAT.Targets.Target_Type'Class; Args : in String) is Reader : MAT.Readers.Files.File_Reader_Type; begin Target.Initialize (Reader); Reader.Open (Args); Reader.Read_All; exception when E : Ada.IO_Exceptions.Name_Error => Log.Error ("Cannot open {0}", Args); end Open_Command; function Get_Command (Line : in String) return String is Pos : Natural := Util.Strings.Index (Line, ' '); begin if Pos <= 0 then return Line; else return Line (Line'First .. Pos - 1); end if; end Get_Command; -- ------------------------------ -- Execute the command given in the line. -- ------------------------------ procedure Execute (Target : in out MAT.Targets.Target_Type'Class; Line : in String) is Command : constant String := Get_Command (Line); Index : constant Natural := Util.Strings.Index (Line, ' '); Pos : constant Command_Map.Cursor := Commands.Find (Command); begin if Command_Map.Has_Element (Pos) then Command_Map.Element (Pos) (Target, Line (Index + 1 .. Line'Last)); elsif Command'Length > 0 then Target.Console.Error ("Command '" & Command & "' not found"); end if; end Execute; begin Commands.Insert ("exit", Exit_Command'Access); Commands.Insert ("quit", Exit_Command'Access); Commands.Insert ("open", Open_Command'Access); Commands.Insert ("sizes", Sizes_Command'Access); Commands.Insert ("symbol", Symbol_Command'Access); Commands.Insert ("slots", Slot_Command'Access); end MAT.Commands;
Use the console Error procedure to report an error message
Use the console Error procedure to report an error message
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
850702a57d05be4b0d8ecbd95a003d9df8d494da
awa/src/awa-permissions-controllers.adb
awa/src/awa-permissions-controllers.adb
----------------------------------------------------------------------- -- awa-permissions-controllers -- Permission controllers -- Copyright (C) 2011, 2012, 2013, 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with ADO.Sessions; with ADO.Statements; with Util.Log.Loggers; with Util.Strings; with AWA.Applications; with AWA.Users.Principals; with AWA.Permissions.Services; with AWA.Services.Contexts; package body AWA.Permissions.Controllers is use Util.Log; Log : constant Loggers.Logger := Loggers.Create ("AWA.Permissions.Controllers"); -- ------------------------------ -- Returns true if the user associated with the security context <b>Context</b> has -- the permission to access a database entity. The security context contains some -- information about the entity to check and the permission controller will use an -- SQL statement to verify the permission. -- ------------------------------ overriding function Has_Permission (Handler : in Entity_Controller; Context : in Security.Contexts.Security_Context'Class; Permission : in Security.Permissions.Permission'Class) return Boolean is use AWA.Permissions.Services; use AWA.Users.Principals; use type ADO.Identifier; use type ADO.Entity_Type; Manager : constant Permission_Manager_Access := Get_Permission_Manager (Context); User_Id : constant ADO.Identifier := Get_User_Identifier (Context.Get_User_Principal); Entity_Id : ADO.Identifier; begin -- If there is no permission manager, permission is denied. if Manager = null or else User_Id = ADO.NO_IDENTIFIER then return False; end if; -- If the user is not logged, permission is denied. if Manager = null or else User_Id = ADO.NO_IDENTIFIER then Log.Info ("No user identifier in the security context. Permission is denied"); return False; end if; if not (Permission in Entity_Permission'Class) then Log.Info ("Permission denied because the entity is not given."); return False; end if; Entity_Id := Entity_Permission'Class (Permission).Entity; -- If the security context does not contain the entity identifier, permission is denied. if Entity_Id = ADO.NO_IDENTIFIER then Log.Info ("No entity identifier in the security context. Permission is denied"); return False; end if; declare function Get_Session return ADO.Sessions.Session; -- ------------------------------ -- Get a database session from the AWA application. -- There is no guarantee that a AWA.Services.Contexts be available. -- But if we are within a service context, we must use the current session so -- that we are part of the current transaction. -- ------------------------------ function Get_Session return ADO.Sessions.Session is package ASC renames AWA.Services.Contexts; use type ASC.Service_Context_Access; Ctx : constant ASC.Service_Context_Access := ASC.Current; begin if Ctx /= null then return AWA.Services.Contexts.Get_Session (Ctx); else return Manager.Get_Application.Get_Session; end if; end Get_Session; Session : constant ADO.Sessions.Session := Get_Session; Query : ADO.Statements.Query_Statement := Session.Create_Statement (Handler.SQL); Result : Integer; begin -- Build the query Query.Bind_Param (Name => "entity_id", Value => Entity_Id); Query.Bind_Param (Name => "user_id", Value => User_Id); if Handler.Entities (2) /= ADO.NO_ENTITY_TYPE then for I in Handler.Entities'Range loop exit when Handler.Entities (I) = ADO.NO_ENTITY_TYPE; Query.Bind_Param (Name => "entity_type_" & Util.Strings.Image (I), Value => Handler.Entities (I)); end loop; else Query.Bind_Param (Name => "entity_type", Value => Handler.Entities (1)); end if; -- Run the query. We must get a single row result and the value must be > 0. Query.Execute; Result := Query.Get_Result_Integer; if Result >= 0 and Query.Has_Elements then Log.Info ("Permission granted to {0} on entity {1}", ADO.Identifier'Image (User_Id), ADO.Identifier'Image (Entity_Id)); return True; else Log.Info ("Permission denied to {0} on entity {1}", ADO.Identifier'Image (User_Id), ADO.Identifier'Image (Entity_Id)); return False; end if; end; end Has_Permission; end AWA.Permissions.Controllers;
----------------------------------------------------------------------- -- awa-permissions-controllers -- Permission controllers -- Copyright (C) 2011, 2012, 2013, 2014, 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; with ADO.Statements; with Util.Log.Loggers; with Util.Strings; with AWA.Applications; with AWA.Users.Principals; with AWA.Permissions.Services; with AWA.Services.Contexts; package body AWA.Permissions.Controllers is Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("AWA.Permissions.Controllers"); -- ------------------------------ -- Returns true if the user associated with the security context <b>Context</b> has -- the permission to access a database entity. The security context contains some -- information about the entity to check and the permission controller will use an -- SQL statement to verify the permission. -- ------------------------------ overriding function Has_Permission (Handler : in Entity_Controller; Context : in Security.Contexts.Security_Context'Class; Permission : in Security.Permissions.Permission'Class) return Boolean is use AWA.Permissions.Services; use AWA.Users.Principals; use type ADO.Identifier; use type ADO.Entity_Type; Manager : constant Permission_Manager_Access := Get_Permission_Manager (Context); User_Id : constant ADO.Identifier := Get_User_Identifier (Context.Get_User_Principal); Entity_Id : ADO.Identifier; begin -- If there is no permission manager, permission is denied. if Manager = null or else User_Id = ADO.NO_IDENTIFIER then return False; end if; -- If the user is not logged, permission is denied. if Manager = null or else User_Id = ADO.NO_IDENTIFIER then Log.Info ("No user identifier in the security context. Permission is denied"); return False; end if; if not (Permission in Entity_Permission'Class) then Log.Info ("Permission {0} denied because the entity is not given.", Security.Permissions.Permission_Index'Image (Permission.Id)); return False; end if; Entity_Id := Entity_Permission'Class (Permission).Entity; -- If the security context does not contain the entity identifier, permission is denied. if Entity_Id = ADO.NO_IDENTIFIER then Log.Info ("No entity identifier in the security context. Permission is denied"); return False; end if; declare function Get_Session return ADO.Sessions.Session; -- ------------------------------ -- Get a database session from the AWA application. -- There is no guarantee that a AWA.Services.Contexts be available. -- But if we are within a service context, we must use the current session so -- that we are part of the current transaction. -- ------------------------------ function Get_Session return ADO.Sessions.Session is package ASC renames AWA.Services.Contexts; use type ASC.Service_Context_Access; Ctx : constant ASC.Service_Context_Access := ASC.Current; begin if Ctx /= null then return AWA.Services.Contexts.Get_Session (Ctx); else return Manager.Get_Application.Get_Session; end if; end Get_Session; Session : constant ADO.Sessions.Session := Get_Session; Query : ADO.Statements.Query_Statement := Session.Create_Statement (Handler.SQL); Result : Integer; begin -- Build the query Query.Bind_Param (Name => "entity_id", Value => Entity_Id); Query.Bind_Param (Name => "user_id", Value => User_Id); if Handler.Entities (2) /= ADO.NO_ENTITY_TYPE then for I in Handler.Entities'Range loop exit when Handler.Entities (I) = ADO.NO_ENTITY_TYPE; Query.Bind_Param (Name => "entity_type_" & Util.Strings.Image (I), Value => Handler.Entities (I)); end loop; else Query.Bind_Param (Name => "entity_type", Value => Handler.Entities (1)); end if; -- Run the query. We must get a single row result and the value must be > 0. Query.Execute; Result := Query.Get_Result_Integer; if Result >= 0 and Query.Has_Elements then Log.Info ("Permission granted to {0} on entity {1}", ADO.Identifier'Image (User_Id), ADO.Identifier'Image (Entity_Id)); return True; else Log.Info ("Permission denied to {0} on entity {1}", ADO.Identifier'Image (User_Id), ADO.Identifier'Image (Entity_Id)); return False; end if; end; end Has_Permission; end AWA.Permissions.Controllers;
Add the permission id in the log message
Add the permission id in the log message
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
a9dbf55bd8ea5d2bf7af8bbb8acd8d2de81e1c01
src/wiki-render-text.adb
src/wiki-render-text.adb
----------------------------------------------------------------------- -- wiki-render-text -- Wiki Text renderer -- Copyright (C) 2011, 2012, 2013, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Characters.Conversions; with Wiki.Filters.Html; with Wiki.Helpers; package body Wiki.Render.Text is -- ------------------------------ -- Set the output writer. -- ------------------------------ procedure Set_Output_Stream (Engine : in out Text_Renderer; Stream : in Streams.Output_Stream_Access) is begin Engine.Output := Stream; end Set_Output_Stream; -- ------------------------------ -- Emit a new line. -- ------------------------------ procedure New_Line (Document : in out Text_Renderer) is begin Document.Output.Write (Wiki.Helpers.LF); Document.Empty_Line := True; end New_Line; -- ------------------------------ -- Add a line break (<br>). -- ------------------------------ procedure Add_Line_Break (Document : in out Text_Renderer) is begin Document.Output.Write (Wiki.Helpers.LF); Document.Empty_Line := True; end Add_Line_Break; -- ------------------------------ -- Add a paragraph (<p>). Close the previous paragraph if any. -- The paragraph must be closed at the next paragraph or next header. -- ------------------------------ procedure Add_Paragraph (Document : in out Text_Renderer) is begin Document.Close_Paragraph; Document.Need_Paragraph := True; Document.Add_Line_Break; end Add_Paragraph; -- ------------------------------ -- Add a blockquote (<blockquote>). The level indicates the blockquote nested level. -- The blockquote must be closed at the next header. -- ------------------------------ procedure Add_Blockquote (Document : in out Text_Renderer; Level : in Natural) is begin Document.Close_Paragraph; for I in 1 .. Level loop Document.Output.Write (" "); end loop; end Add_Blockquote; -- ------------------------------ -- Add a list item (<li>). Close the previous paragraph and list item if any. -- The list item will be closed at the next list item, next paragraph or next header. -- ------------------------------ procedure Add_List_Item (Document : in out Text_Renderer; Level : in Positive; Ordered : in Boolean) is pragma Unreferenced (Level, Ordered); begin if not Document.Empty_Line then Document.Add_Line_Break; end if; Document.Need_Paragraph := False; Document.Open_Paragraph; end Add_List_Item; procedure Close_Paragraph (Document : in out Text_Renderer) is begin if Document.Has_Paragraph then Document.Add_Line_Break; end if; Document.Has_Paragraph := False; end Close_Paragraph; procedure Open_Paragraph (Document : in out Text_Renderer) is begin if Document.Need_Paragraph then Document.Has_Paragraph := True; Document.Need_Paragraph := False; end if; end Open_Paragraph; -- ------------------------------ -- Add a link. -- ------------------------------ procedure Add_Link (Document : in out Text_Renderer; Name : in Unbounded_Wide_Wide_String; Link : in Unbounded_Wide_Wide_String; Language : in Unbounded_Wide_Wide_String; Title : in Unbounded_Wide_Wide_String) is pragma Unreferenced (Language); begin Document.Open_Paragraph; if Length (Title) > 0 then Document.Output.Write (Title); end if; Document.Output.Write (Link); if Link /= Name then Document.Output.Write (Name); end if; Document.Empty_Line := False; end Add_Link; -- ------------------------------ -- Add an image. -- ------------------------------ procedure Add_Image (Document : in out Text_Renderer; Link : in Unbounded_Wide_Wide_String; Alt : in Unbounded_Wide_Wide_String; Position : in Unbounded_Wide_Wide_String; Description : in Unbounded_Wide_Wide_String) is pragma Unreferenced (Position); begin Document.Open_Paragraph; if Length (Alt) > 0 then Document.Output.Write (Alt); end if; if Length (Description) > 0 then Document.Output.Write (Description); end if; Document.Output.Write (Link); Document.Empty_Line := False; end Add_Image; -- ------------------------------ -- Add a quote. -- ------------------------------ procedure Add_Quote (Document : in out Text_Renderer; Quote : in Unbounded_Wide_Wide_String; Link : in Unbounded_Wide_Wide_String; Language : in Unbounded_Wide_Wide_String) is pragma Unreferenced (Link, Language); begin Document.Open_Paragraph; Document.Output.Write (Quote); Document.Empty_Line := False; end Add_Quote; -- ------------------------------ -- Add a text block that is pre-formatted. -- ------------------------------ procedure Add_Preformatted (Document : in out Text_Renderer; Text : in Unbounded_Wide_Wide_String; Format : in Unbounded_Wide_Wide_String) is pragma Unreferenced (Format); begin Document.Close_Paragraph; Document.Output.Write (Text); Document.Empty_Line := False; end Add_Preformatted; procedure Start_Element (Document : in out Text_Renderer; Name : in Unbounded_Wide_Wide_String; Attributes : in Wiki.Attributes.Attribute_List_Type) is pragma Unreferenced (Attributes); use type Wiki.Filters.Html.Html_Tag_Type; Tag : constant Wiki.Filters.Html.Html_Tag_Type := Wiki.Filters.Html.Find_Tag (Name); begin if Tag = Wiki.Filters.Html.DT_TAG then Document.Close_Paragraph; Document.Indent_Level := 0; elsif Tag = Wiki.Filters.Html.DD_TAG then Document.Close_Paragraph; Document.Empty_Line := True; Document.Indent_Level := 4; end if; end Start_Element; procedure End_Element (Document : in out Text_Renderer; Name : in Unbounded_Wide_Wide_String) is use type Wiki.Filters.Html.Html_Tag_Type; Tag : constant Wiki.Filters.Html.Html_Tag_Type := Wiki.Filters.Html.Find_Tag (Name); begin if Tag = Wiki.Filters.Html.DT_TAG then Document.Close_Paragraph; Document.Indent_Level := 0; elsif Tag = Wiki.Filters.Html.DD_TAG then Document.Close_Paragraph; Document.Indent_Level := 0; elsif Tag = Wiki.Filters.Html.DL_TAG then Document.Close_Paragraph; Document.New_Line; end if; end End_Element; -- Render the node instance from the document. overriding procedure Render (Engine : in out Text_Renderer; Doc : in Wiki.Nodes.Document; Node : in Wiki.Nodes.Node_Type) is begin case Node.Kind is when Wiki.Nodes.N_HEADER => Engine.Close_Paragraph; if not Engine.Empty_Line then Engine.Add_Line_Break; end if; Engine.Output.Write (Node.Header); Engine.Add_Line_Break; when Wiki.Nodes.N_LINE_BREAK => Engine.Add_Line_Break; when Wiki.Nodes.N_HORIZONTAL_RULE => Engine.Close_Paragraph; Engine.Output.Write ("---------------------------------------------------------"); Engine.Add_Line_Break; when Wiki.Nodes.N_PARAGRAPH => Engine.Close_Paragraph; Engine.Need_Paragraph := True; Engine.Add_Line_Break; when Wiki.Nodes.N_TEXT => if Engine.Empty_Line and Engine.Indent_Level /= 0 then for I in 1 .. Engine.Indent_Level loop Engine.Output.Write (' '); end loop; end if; Engine.Output.Write (Node.Text); Engine.Empty_Line := False; end case; end Render; -- -- ------------------------------ -- Finish the document after complete wiki text has been parsed. -- ------------------------------ overriding procedure Finish (Document : in out Text_Renderer) is begin Document.Close_Paragraph; end Finish; end Wiki.Render.Text;
----------------------------------------------------------------------- -- wiki-render-text -- Wiki Text renderer -- Copyright (C) 2011, 2012, 2013, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Characters.Conversions; with Wiki.Filters.Html; with Wiki.Helpers; package body Wiki.Render.Text is -- ------------------------------ -- Set the output writer. -- ------------------------------ procedure Set_Output_Stream (Engine : in out Text_Renderer; Stream : in Streams.Output_Stream_Access) is begin Engine.Output := Stream; end Set_Output_Stream; -- ------------------------------ -- Emit a new line. -- ------------------------------ procedure New_Line (Document : in out Text_Renderer) is begin Document.Output.Write (Wiki.Helpers.LF); Document.Empty_Line := True; end New_Line; -- ------------------------------ -- Add a line break (<br>). -- ------------------------------ procedure Add_Line_Break (Document : in out Text_Renderer) is begin Document.Output.Write (Wiki.Helpers.LF); Document.Empty_Line := True; end Add_Line_Break; -- ------------------------------ -- Add a blockquote (<blockquote>). The level indicates the blockquote nested level. -- The blockquote must be closed at the next header. -- ------------------------------ procedure Add_Blockquote (Document : in out Text_Renderer; Level : in Natural) is begin Document.Close_Paragraph; for I in 1 .. Level loop Document.Output.Write (" "); end loop; end Add_Blockquote; -- ------------------------------ -- Add a list item (<li>). Close the previous paragraph and list item if any. -- The list item will be closed at the next list item, next paragraph or next header. -- ------------------------------ procedure Add_List_Item (Document : in out Text_Renderer; Level : in Positive; Ordered : in Boolean) is pragma Unreferenced (Level, Ordered); begin if not Document.Empty_Line then Document.Add_Line_Break; end if; Document.Need_Paragraph := False; Document.Open_Paragraph; end Add_List_Item; procedure Close_Paragraph (Document : in out Text_Renderer) is begin if Document.Has_Paragraph then Document.Add_Line_Break; end if; Document.Has_Paragraph := False; end Close_Paragraph; procedure Open_Paragraph (Document : in out Text_Renderer) is begin if Document.Need_Paragraph then Document.Has_Paragraph := True; Document.Need_Paragraph := False; end if; end Open_Paragraph; -- ------------------------------ -- Add a link. -- ------------------------------ procedure Add_Link (Document : in out Text_Renderer; Name : in Unbounded_Wide_Wide_String; Link : in Unbounded_Wide_Wide_String; Language : in Unbounded_Wide_Wide_String; Title : in Unbounded_Wide_Wide_String) is pragma Unreferenced (Language); begin Document.Open_Paragraph; if Length (Title) > 0 then Document.Output.Write (Title); end if; Document.Output.Write (Link); if Link /= Name then Document.Output.Write (Name); end if; Document.Empty_Line := False; end Add_Link; -- ------------------------------ -- Add an image. -- ------------------------------ procedure Add_Image (Document : in out Text_Renderer; Link : in Unbounded_Wide_Wide_String; Alt : in Unbounded_Wide_Wide_String; Position : in Unbounded_Wide_Wide_String; Description : in Unbounded_Wide_Wide_String) is pragma Unreferenced (Position); begin Document.Open_Paragraph; if Length (Alt) > 0 then Document.Output.Write (Alt); end if; if Length (Description) > 0 then Document.Output.Write (Description); end if; Document.Output.Write (Link); Document.Empty_Line := False; end Add_Image; -- ------------------------------ -- Add a quote. -- ------------------------------ procedure Add_Quote (Document : in out Text_Renderer; Quote : in Unbounded_Wide_Wide_String; Link : in Unbounded_Wide_Wide_String; Language : in Unbounded_Wide_Wide_String) is pragma Unreferenced (Link, Language); begin Document.Open_Paragraph; Document.Output.Write (Quote); Document.Empty_Line := False; end Add_Quote; -- ------------------------------ -- Add a text block that is pre-formatted. -- ------------------------------ procedure Add_Preformatted (Document : in out Text_Renderer; Text : in Unbounded_Wide_Wide_String; Format : in Unbounded_Wide_Wide_String) is pragma Unreferenced (Format); begin Document.Close_Paragraph; Document.Output.Write (Text); Document.Empty_Line := False; end Add_Preformatted; procedure Start_Element (Document : in out Text_Renderer; Name : in Unbounded_Wide_Wide_String; Attributes : in Wiki.Attributes.Attribute_List_Type) is pragma Unreferenced (Attributes); use type Wiki.Filters.Html.Html_Tag_Type; Tag : constant Wiki.Filters.Html.Html_Tag_Type := Wiki.Filters.Html.Find_Tag (Name); begin if Tag = Wiki.Filters.Html.DT_TAG then Document.Close_Paragraph; Document.Indent_Level := 0; elsif Tag = Wiki.Filters.Html.DD_TAG then Document.Close_Paragraph; Document.Empty_Line := True; Document.Indent_Level := 4; end if; end Start_Element; procedure End_Element (Document : in out Text_Renderer; Name : in Unbounded_Wide_Wide_String) is use type Wiki.Filters.Html.Html_Tag_Type; Tag : constant Wiki.Filters.Html.Html_Tag_Type := Wiki.Filters.Html.Find_Tag (Name); begin if Tag = Wiki.Filters.Html.DT_TAG then Document.Close_Paragraph; Document.Indent_Level := 0; elsif Tag = Wiki.Filters.Html.DD_TAG then Document.Close_Paragraph; Document.Indent_Level := 0; elsif Tag = Wiki.Filters.Html.DL_TAG then Document.Close_Paragraph; Document.New_Line; end if; end End_Element; -- Render the node instance from the document. overriding procedure Render (Engine : in out Text_Renderer; Doc : in Wiki.Nodes.Document; Node : in Wiki.Nodes.Node_Type) is begin case Node.Kind is when Wiki.Nodes.N_HEADER => Engine.Close_Paragraph; if not Engine.Empty_Line then Engine.Add_Line_Break; end if; Engine.Output.Write (Node.Header); Engine.Add_Line_Break; when Wiki.Nodes.N_LINE_BREAK => Engine.Add_Line_Break; when Wiki.Nodes.N_HORIZONTAL_RULE => Engine.Close_Paragraph; Engine.Output.Write ("---------------------------------------------------------"); Engine.Add_Line_Break; when Wiki.Nodes.N_PARAGRAPH => Engine.Close_Paragraph; Engine.Need_Paragraph := True; Engine.Add_Line_Break; when Wiki.Nodes.N_TEXT => if Engine.Empty_Line and Engine.Indent_Level /= 0 then for I in 1 .. Engine.Indent_Level loop Engine.Output.Write (' '); end loop; end if; Engine.Output.Write (Node.Text); Engine.Empty_Line := False; end case; end Render; -- -- ------------------------------ -- Finish the document after complete wiki text has been parsed. -- ------------------------------ overriding procedure Finish (Document : in out Text_Renderer) is begin Document.Close_Paragraph; end Finish; end Wiki.Render.Text;
Remove the Add_Paragraph procedure
Remove the Add_Paragraph procedure
Ada
apache-2.0
stcarrez/ada-wiki,stcarrez/ada-wiki
e39e41b6b5608ef75e8e772f8f24c40b3c643ab6
regtests/el-objects-discrete_tests.adb
regtests/el-objects-discrete_tests.adb
----------------------------------------------------------------------- -- el-objects-tests - Generic simple test for discrete object types -- 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 Ada.Containers; with Util.Test_Caller; with Ada.Strings.Fixed; with Ada.Text_IO; with Ada.Calendar; with EL.Objects.Hash; package body EL.Objects.Discrete_Tests is use EL.Objects; use Ada.Strings.Fixed; use Ada.Containers; procedure Test_Eq (T : Test; V : String; N : Test_Type); procedure Test_Conversion (T : Test; V : String; N : Test_Type); procedure Test_Lt_Gt (T : Test; V : String; N : Test_Type); procedure Test_Sub (T : Test; V : String; N : Test_Type); procedure Test_Add (T : Test; V : String; N : Test_Type); -- Generic test for To_Object and To_XXX types -- Several values are specified in the Test_Values string. generic with procedure Basic_Test (T : in Test; V : String; N : Test_Type); procedure Test_Basic_Object (T : in out Test); procedure Test_Basic_Object (T : in out Test) is pragma Unmodified (T); Pos, Next : Natural; begin Pos := Test_Values'First; while Pos <= Test_Values'Last loop Next := Index (Test_Values, ",", Pos); if Next < Pos then Next := Test_Values'Last + 1; end if; declare V : constant String := Test_Values (Pos .. Next - 1); N : constant Test_Type := Value (V); begin Basic_Test (T, V, N); end; Pos := Next + 1; end loop; end Test_Basic_Object; -- ------------------------------ -- Test EL.Objects.To_Object -- ------------------------------ procedure Test_Conversion (T : Test; V : String; N : Test_Type) is Value : EL.Objects.Object; begin Value := To_Object (V); T.Assert (Condition => To_Type (Value) = N, Message => Test_Name & " returned invalid value: " & To_String (Value) & " when we expected: " & V); T.Assert (Condition => V = To_String (Value), Message => Test_Name & ".To_String returned invalid value: " & To_String (Value) & " when we expected: " & V); end Test_Conversion; procedure Test_To_Object is new Test_Basic_Object (Basic_Test => Test_Conversion); -- ------------------------------ -- Test EL.Objects.Hash -- ------------------------------ procedure Test_Hash (T : in out Test) is pragma Unmodified (T); Pos, Next : Natural; Hash_Values : array (Test_Values'Range) of Hash_Type := (others => 0); Nb_Hash : Natural := 0; begin Pos := Test_Values'First; while Pos <= Test_Values'Last loop Next := Index (Test_Values, ",", Pos); if Next < Pos then Next := Test_Values'Last + 1; end if; declare V : constant String := Test_Values (Pos .. Next - 1); N : constant Test_Type := Value (V); Value : constant EL.Objects.Object := To_Object_Test (N); H : constant Hash_Type := EL.Objects.Hash (Value); Found : Boolean := False; begin for J in 1 .. Nb_Hash loop if Hash_Values (J) = H then Found := True; end if; end loop; if not Found then Nb_Hash := Nb_Hash + 1; Hash_Values (Nb_Hash) := H; end if; end; Pos := Next + 1; end loop; Ada.Text_IO.Put_Line ("Found " & Natural'Image (Nb_Hash) & " hash values"); Assert (T, Nb_Hash > 1, "Only one hash value found"); end Test_Hash; -- ------------------------------ -- Test EL.Objects."+" -- ------------------------------ procedure Test_Add (T : Test; V : String; N : Test_Type) is Value : EL.Objects.Object := To_Object_Test (N); begin Value := Value + To_Object_Test (N); T.Assert (Condition => To_Type (Value) = N + N, Message => Test_Name & " returned invalid value: " & To_String (Value) & " when we expected: " & V); end Test_Add; procedure Test_Add is new Test_Basic_Object (Test_Add); -- ------------------------------ -- Test EL.Objects."-" -- ------------------------------ procedure Test_Sub (T : Test; V : String; N : Test_Type) is pragma Unreferenced (V); Value : EL.Objects.Object; begin Value := To_Object_Test (N) - To_Object_Test (N); T.Assert (Condition => To_Type (Value) = N - N, Message => Test_Name & " returned invalid value: " & To_String (Value) & " when we expected: 0"); end Test_Sub; procedure Test_Sub is new Test_Basic_Object (Test_Sub); -- ------------------------------ -- Test EL.Objects."<" and EL.Objects.">" -- ------------------------------ procedure Test_Lt_Gt (T : Test; V : String; N : Test_Type) is Res : Boolean; Is_Neg : constant Boolean := Index (V, "-") = V'First; O : EL.Objects.Object := To_Object_Test (N); begin Res := To_Object_Test (N) < To_Object_Test (N); T.Assert (Condition => Res = False, Message => Test_Name & ".'<' returned invalid value: " & Boolean'Image (Res) & " when we expected: false"); Res := To_Object_Test (N) > To_Object_Test (N); T.Assert (Condition => Res = False, Message => Test_Name & ".'>' returned invalid value: " & Boolean'Image (Res) & " when we expected: false"); Res := To_Object_Test (N) + To_Object_Test (N) < To_Object_Test (N); T.Assert (Condition => Res = Is_Neg, Message => Test_Name & ".'<' returned invalid value: " & Boolean'Image (Res) & " when we expected: " & Boolean'Image (Is_Neg) & " with value: " & V & "Num=" & Long_Long_Integer'Image (To_Long_Long_Integer (O)) & " Sum=" & Long_Long_Integer'Image (To_Long_Long_Integer (O + O))); Res := To_Object_Test (N) > To_Object_Test (N) + To_Object_Test (N); T.Assert (Condition => Res = Is_Neg, Message => Test_Name & ".'>' returned invalid value: " & Boolean'Image (Res) & " when we expected: " & Boolean'Image (Is_Neg) & " with value: " & V); if V /= "0" and V /= "false" and V /= "true" then Res := To_Object_Test (N) < To_Object_Test (N) + To_Object_Test (N); T.Assert (Condition => Res = not Is_Neg, Message => Test_Name & ".'<' returned invalid value: " & Boolean'Image (Res) & " when we expected: " & Boolean'Image (not Is_Neg) & " with value: " & V); Res := To_Object_Test (N) + To_Object_Test (N) > To_Object_Test (N); T.Assert (Condition => Res = not Is_Neg, Message => Test_Name & ".'>' returned invalid value: " & Boolean'Image (Res) & " when we expected: " & Boolean'Image (not Is_Neg) & " with value: " & V); end if; end Test_Lt_Gt; procedure Test_Lt_Gt is new Test_Basic_Object (Test_Lt_Gt); -- ------------------------------ -- Test EL.Objects."=" -- ------------------------------ procedure Test_Eq (T : Test; V : String; N : Test_Type) is Res : Boolean; begin Res := To_Object_Test (N) = To_Object_Test (N); T.Assert (Condition => Res, Message => Test_Name & ".'=' returned invalid value: " & Boolean'Image (Res) & " when we expected: true"); Res := To_Object_Test (N) = To_Object ("Something" & V); T.Assert (Condition => Res = False, Message => Test_Name & ".'=' returned invalid value: " & Boolean'Image (Res) & " where we expected: False"); end Test_Eq; procedure Test_Eq is new Test_Basic_Object (Test_Eq); -- ------------------------------ -- Test EL.Objects."=" -- ------------------------------ procedure Test_Perf (T : Test; V : String; N : Test_Type) is pragma Unreferenced (T, V); use Ada.Calendar; Start : Ada.Calendar.Time; Value : constant EL.Objects.Object := To_Object_Test (N); D : Duration; begin Start := Ada.Calendar.Clock; for I in 1 .. 1_000 loop declare V : EL.Objects.Object := Value; begin V := V + V; pragma Unreferenced (V); end; end loop; D := Ada.Calendar.Clock - Start; Ada.Text_IO.Put_Line ("Perf " & Test_Name & ": " & Duration'Image (D * 1000.0)); end Test_Perf; procedure Test_Perf is new Test_Basic_Object (Test_Perf); package Caller is new Util.Test_Caller (Test); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test EL.Objects.To_Object." & Test_Name, Test_To_Object'Access); Caller.Add_Test (Suite, "Test EL.Objects.To_String." & Test_Name, Test_To_Object'Access); Caller.Add_Test (Suite, "Test EL.Objects.'='." & Test_Name, Test_Eq'Access); Caller.Add_Test (Suite, "Test EL.Objects.'+'." & Test_Name, Test_Add'Access); Caller.Add_Test (Suite, "Test EL.Objects.'-'." & Test_Name, Test_Sub'Access); Caller.Add_Test (Suite, "Test EL.Objects.'<'." & Test_Name, Test_Lt_Gt'Access); Caller.Add_Test (Suite, "Test EL.Objects.'>'." & Test_Name, Test_Lt_Gt'Access); Caller.Add_Test (Suite, "Performance EL.Objects.'>'." & Test_Name, Test_Perf'Access); Caller.Add_Test (Suite, "Test EL.Objects.Hash." & Test_Name, Test_Hash'Access); end Add_Tests; end EL.Objects.Discrete_Tests;
----------------------------------------------------------------------- -- el-objects-tests - Generic simple test for discrete object types -- 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 Ada.Containers; with Util.Test_Caller; with Ada.Strings.Fixed; with Ada.Text_IO; with Ada.Calendar; with EL.Objects.Hash; package body EL.Objects.Discrete_Tests is use EL.Objects; use Ada.Strings.Fixed; use Ada.Containers; procedure Test_Eq (T : Test; V : String; N : Test_Type); procedure Test_Conversion (T : Test; V : String; N : Test_Type); procedure Test_Lt_Gt (T : Test; V : String; N : Test_Type); procedure Test_Sub (T : Test; V : String; N : Test_Type); procedure Test_Add (T : Test; V : String; N : Test_Type); -- Generic test for To_Object and To_XXX types -- Several values are specified in the Test_Values string. generic with procedure Basic_Test (T : in Test; V : String; N : Test_Type); procedure Test_Basic_Object (T : in out Test); procedure Test_Basic_Object (T : in out Test) is pragma Unmodified (T); Pos, Next : Natural; begin Pos := Test_Values'First; while Pos <= Test_Values'Last loop Next := Index (Test_Values, ",", Pos); if Next < Pos then Next := Test_Values'Last + 1; end if; declare V : constant String := Test_Values (Pos .. Next - 1); N : constant Test_Type := Value (V); begin Basic_Test (T, V, N); end; Pos := Next + 1; end loop; end Test_Basic_Object; -- ------------------------------ -- Test EL.Objects.To_Object -- ------------------------------ procedure Test_Conversion (T : Test; V : String; N : Test_Type) is Value : EL.Objects.Object; begin Value := To_Object (V); T.Assert (Condition => To_Type (Value) = N, Message => Test_Name & " returned invalid value: " & To_String (Value) & " when we expected: " & V); T.Assert (Condition => V = To_String (Value), Message => Test_Name & ".To_String returned invalid value: " & To_String (Value) & " when we expected: " & V); end Test_Conversion; procedure Test_To_Object is new Test_Basic_Object (Basic_Test => Test_Conversion); -- ------------------------------ -- Test EL.Objects.Hash -- ------------------------------ procedure Test_Hash (T : in out Test) is pragma Unmodified (T); Pos, Next : Natural; Hash_Values : array (Test_Values'Range) of Hash_Type := (others => 0); Nb_Hash : Natural := 0; begin Pos := Test_Values'First; while Pos <= Test_Values'Last loop Next := Index (Test_Values, ",", Pos); if Next < Pos then Next := Test_Values'Last + 1; end if; declare V : constant String := Test_Values (Pos .. Next - 1); N : constant Test_Type := Value (V); Value : constant EL.Objects.Object := To_Object_Test (N); H : constant Hash_Type := EL.Objects.Hash (Value); Found : Boolean := False; begin for J in 1 .. Nb_Hash loop if Hash_Values (J) = H then Found := True; end if; end loop; if not Found then Nb_Hash := Nb_Hash + 1; Hash_Values (Nb_Hash) := H; end if; end; Pos := Next + 1; end loop; Ada.Text_IO.Put_Line ("Found " & Natural'Image (Nb_Hash) & " hash values"); Assert (T, Nb_Hash > 1, "Only one hash value found"); end Test_Hash; -- ------------------------------ -- Test EL.Objects."+" -- ------------------------------ procedure Test_Add (T : Test; V : String; N : Test_Type) is Value : EL.Objects.Object := To_Object_Test (N); begin Value := Value + To_Object_Test (N); T.Assert (Condition => To_Type (Value) = N + N, Message => Test_Name & " returned invalid value: " & To_String (Value) & " when we expected: " & V); end Test_Add; procedure Test_Add is new Test_Basic_Object (Test_Add); -- ------------------------------ -- Test EL.Objects."-" -- ------------------------------ procedure Test_Sub (T : Test; V : String; N : Test_Type) is pragma Unreferenced (V); Value : EL.Objects.Object; begin Value := To_Object_Test (N) - To_Object_Test (N); T.Assert (Condition => To_Type (Value) = N - N, Message => Test_Name & " returned invalid value: " & To_String (Value) & " when we expected: 0"); end Test_Sub; procedure Test_Sub is new Test_Basic_Object (Test_Sub); -- ------------------------------ -- Test EL.Objects."<" and EL.Objects.">" -- ------------------------------ procedure Test_Lt_Gt (T : Test; V : String; N : Test_Type) is Res : Boolean; Is_Neg : constant Boolean := Index (V, "-") = V'First; O : EL.Objects.Object := To_Object_Test (N); begin Res := To_Object_Test (N) < To_Object_Test (N); T.Assert (Condition => Res = False, Message => Test_Name & ".'<' returned invalid value: " & Boolean'Image (Res) & " when we expected: false"); Res := To_Object_Test (N) > To_Object_Test (N); T.Assert (Condition => Res = False, Message => Test_Name & ".'>' returned invalid value: " & Boolean'Image (Res) & " when we expected: false"); Res := To_Object_Test (N) + To_Object_Test (N) < To_Object_Test (N); T.Assert (Condition => Res = Is_Neg, Message => Test_Name & ".'<' returned invalid value: " & Boolean'Image (Res) & " when we expected: " & Boolean'Image (Is_Neg) & " with value: " & V & "Num=" & Long_Long_Integer'Image (To_Long_Long_Integer (O)) & " Sum=" & Long_Long_Integer'Image (To_Long_Long_Integer (O + O))); Res := To_Object_Test (N) > To_Object_Test (N) + To_Object_Test (N); T.Assert (Condition => Res = Is_Neg, Message => Test_Name & ".'>' returned invalid value: " & Boolean'Image (Res) & " when we expected: " & Boolean'Image (Is_Neg) & " with value: " & V); if V /= "0" and V /= "false" and V /= "true" then Res := To_Object_Test (N) < To_Object_Test (N) + To_Object_Test (N); T.Assert (Condition => Res = not Is_Neg, Message => Test_Name & ".'<' returned invalid value: " & Boolean'Image (Res) & " when we expected: " & Boolean'Image (not Is_Neg) & " with value: " & V); Res := To_Object_Test (N) + To_Object_Test (N) > To_Object_Test (N); T.Assert (Condition => Res = not Is_Neg, Message => Test_Name & ".'>' returned invalid value: " & Boolean'Image (Res) & " when we expected: " & Boolean'Image (not Is_Neg) & " with value: " & V); end if; end Test_Lt_Gt; procedure Test_Lt_Gt is new Test_Basic_Object (Test_Lt_Gt); -- ------------------------------ -- Test EL.Objects."=" -- ------------------------------ procedure Test_Eq (T : Test; V : String; N : Test_Type) is Res : Boolean; begin Res := To_Object_Test (N) = To_Object_Test (N); T.Assert (Condition => Res, Message => Test_Name & ".'=' returned invalid value: " & Boolean'Image (Res) & " when we expected: true"); Res := To_Object_Test (N) = To_Object ("Something" & V); T.Assert (Condition => Res = False, Message => Test_Name & ".'=' returned invalid value: " & Boolean'Image (Res) & " where we expected: False"); end Test_Eq; procedure Test_Eq is new Test_Basic_Object (Test_Eq); -- ------------------------------ -- Test EL.Objects."=" -- ------------------------------ procedure Test_Perf (T : Test; V : String; N : Test_Type) is pragma Unreferenced (T, V); use Ada.Calendar; Start : Ada.Calendar.Time; Value : constant EL.Objects.Object := To_Object_Test (N); D : Duration; begin Start := Ada.Calendar.Clock; for I in 1 .. 1_000 loop declare V : EL.Objects.Object := Value; begin V := V + V; pragma Unreferenced (V); end; end loop; D := Ada.Calendar.Clock - Start; Ada.Text_IO.Put_Line ("Perf " & Test_Name & ": " & Duration'Image (D * 1000.0)); end Test_Perf; procedure Test_Perf is new Test_Basic_Object (Test_Perf); package Caller is new Util.Test_Caller (Test, "EL.Objects"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test EL.Objects.To_Object." & Test_Name, Test_To_Object'Access); Caller.Add_Test (Suite, "Test EL.Objects.To_String." & Test_Name, Test_To_Object'Access); Caller.Add_Test (Suite, "Test EL.Objects.'='." & Test_Name, Test_Eq'Access); Caller.Add_Test (Suite, "Test EL.Objects.'+'." & Test_Name, Test_Add'Access); Caller.Add_Test (Suite, "Test EL.Objects.'-'." & Test_Name, Test_Sub'Access); Caller.Add_Test (Suite, "Test EL.Objects.'<'." & Test_Name, Test_Lt_Gt'Access); Caller.Add_Test (Suite, "Test EL.Objects.'>'." & Test_Name, Test_Lt_Gt'Access); Caller.Add_Test (Suite, "Performance EL.Objects.'>'." & Test_Name, Test_Perf'Access); Caller.Add_Test (Suite, "Test EL.Objects.Hash." & Test_Name, Test_Hash'Access); end Add_Tests; end EL.Objects.Discrete_Tests;
Use the test name EL.Objects
Use the test name EL.Objects
Ada
apache-2.0
stcarrez/ada-el
4ac86932c41e91019efaa2530e9a631801f71d10
src/ado-drivers-connections.ads
src/ado-drivers-connections.ads
----------------------------------------------------------------------- -- ADO Drivers -- Database Drivers -- Copyright (C) 2010, 2011, 2012, 2016, 2017, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Finalization; with ADO.Statements; with ADO.Schemas; with ADO.Configs; with Util.Strings; with Util.Strings.Vectors; with Util.Refs; -- The <b>ADO.Drivers</b> package represents the database driver that will create -- database connections and provide the database specific implementation. package ADO.Drivers.Connections is use ADO.Statements; type Driver; type Driver_Access is access all Driver'Class; -- ------------------------------ -- Database connection implementation -- ------------------------------ -- type Database_Connection is abstract new Util.Refs.Ref_Entity with record Ident : String (1 .. 8) := (others => ' '); end record; type Database_Connection_Access is access all Database_Connection'Class; -- Get the database driver index. function Get_Driver_Index (Database : in Database_Connection) return Driver_Index; function Create_Statement (Database : in Database_Connection; Table : in ADO.Schemas.Class_Mapping_Access) return Query_Statement_Access is abstract; function Create_Statement (Database : in Database_Connection; Query : in String) return Query_Statement_Access is abstract; -- Create a delete statement. function Create_Statement (Database : in Database_Connection; Table : in ADO.Schemas.Class_Mapping_Access) return Delete_Statement_Access is abstract; -- Create an insert statement. function Create_Statement (Database : in Database_Connection; Table : in ADO.Schemas.Class_Mapping_Access) return Insert_Statement_Access is abstract; -- Create an update statement. function Create_Statement (Database : in Database_Connection; Table : in ADO.Schemas.Class_Mapping_Access) return Update_Statement_Access is abstract; -- Start a transaction. procedure Begin_Transaction (Database : in out Database_Connection) is abstract; -- Commit the current transaction. procedure Commit (Database : in out Database_Connection) is abstract; -- Rollback the current transaction. procedure Rollback (Database : in out Database_Connection) is abstract; -- Load the database schema definition for the current database. procedure Load_Schema (Database : in Database_Connection; Schema : out ADO.Schemas.Schema_Definition) is abstract; -- Get the database driver which manages this connection. function Get_Driver (Database : in Database_Connection) return Driver_Access is abstract; -- Closes the database connection procedure Close (Database : in out Database_Connection) is abstract; package Ref is new Util.Refs.Indefinite_References (Element_Type => Database_Connection'Class, Element_Access => Database_Connection_Access); -- ------------------------------ -- The database configuration properties -- ------------------------------ type Configuration is new ADO.Configs.Configuration with null record; -- Get the driver index that corresponds to the driver for this database connection string. function Get_Driver (Config : in Configuration) return Driver_Index; -- Create a new connection using the configuration parameters. procedure Create_Connection (Config : in Configuration'Class; Result : in out Ref.Ref'Class); -- ------------------------------ -- Database Driver -- ------------------------------ type Driver is abstract tagged limited private; -- Create a new connection using the configuration parameters. procedure Create_Connection (D : in out Driver; Config : in Configuration'Class; Result : in out Ref.Ref'Class) is abstract; -- Create the database and initialize it with the schema SQL file. -- The `Admin` parameter describes the database connection with administrator access. -- The `Config` parameter describes the target database connection. procedure Create_Database (D : in out Driver; Admin : in Configs.Configuration'Class; Config : in Configs.Configuration'Class; Schema_Path : in String; Messages : out Util.Strings.Vectors.Vector) is abstract; -- Get the driver unique index. function Get_Driver_Index (D : in Driver) return Driver_Index; -- Get the driver name. function Get_Driver_Name (D : in Driver) return String; -- Register a database driver. procedure Register (Driver : in Driver_Access); -- Get a database driver given its name. function Get_Driver (Name : in String) return Driver_Access; private type Driver is abstract new Ada.Finalization.Limited_Controlled with record Name : Util.Strings.Name_Access; Index : Driver_Index; end record; end ADO.Drivers.Connections;
----------------------------------------------------------------------- -- ADO Drivers -- Database Drivers -- Copyright (C) 2010, 2011, 2012, 2016, 2017, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Finalization; with ADO.Statements; with ADO.Schemas; with ADO.Configs; with Util.Strings; with Util.Strings.Vectors; with Util.Refs; -- The <b>ADO.Drivers</b> package represents the database driver that will create -- database connections and provide the database specific implementation. package ADO.Drivers.Connections is use ADO.Statements; type Driver is abstract tagged limited private; type Driver_Access is access all Driver'Class; -- ------------------------------ -- Database connection implementation -- ------------------------------ -- type Database_Connection is abstract new Util.Refs.Ref_Entity with record Ident : String (1 .. 8) := (others => ' '); end record; type Database_Connection_Access is access all Database_Connection'Class; -- Get the database driver index. function Get_Driver_Index (Database : in Database_Connection) return Driver_Index; function Create_Statement (Database : in Database_Connection; Table : in ADO.Schemas.Class_Mapping_Access) return Query_Statement_Access is abstract; function Create_Statement (Database : in Database_Connection; Query : in String) return Query_Statement_Access is abstract; -- Create a delete statement. function Create_Statement (Database : in Database_Connection; Table : in ADO.Schemas.Class_Mapping_Access) return Delete_Statement_Access is abstract; -- Create an insert statement. function Create_Statement (Database : in Database_Connection; Table : in ADO.Schemas.Class_Mapping_Access) return Insert_Statement_Access is abstract; -- Create an update statement. function Create_Statement (Database : in Database_Connection; Table : in ADO.Schemas.Class_Mapping_Access) return Update_Statement_Access is abstract; -- Start a transaction. procedure Begin_Transaction (Database : in out Database_Connection) is abstract; -- Commit the current transaction. procedure Commit (Database : in out Database_Connection) is abstract; -- Rollback the current transaction. procedure Rollback (Database : in out Database_Connection) is abstract; -- Load the database schema definition for the current database. procedure Load_Schema (Database : in Database_Connection; Schema : out ADO.Schemas.Schema_Definition) is abstract; -- Get the database driver which manages this connection. function Get_Driver (Database : in Database_Connection) return Driver_Access is abstract; -- Closes the database connection procedure Close (Database : in out Database_Connection) is abstract; package Ref is new Util.Refs.Indefinite_References (Element_Type => Database_Connection'Class, Element_Access => Database_Connection_Access); -- ------------------------------ -- The database configuration properties -- ------------------------------ type Configuration is new ADO.Configs.Configuration with null record; -- Get the driver index that corresponds to the driver for this database connection string. function Get_Driver (Config : in Configuration) return Driver_Index; -- Create a new connection using the configuration parameters. procedure Create_Connection (Config : in Configuration'Class; Result : in out Ref.Ref'Class); -- ------------------------------ -- Database Driver -- ------------------------------ -- Create a new connection using the configuration parameters. procedure Create_Connection (D : in out Driver; Config : in Configuration'Class; Result : in out Ref.Ref'Class) is abstract; -- Create the database and initialize it with the schema SQL file. -- The `Admin` parameter describes the database connection with administrator access. -- The `Config` parameter describes the target database connection. procedure Create_Database (D : in out Driver; Admin : in Configs.Configuration'Class; Config : in Configs.Configuration'Class; Schema_Path : in String; Messages : out Util.Strings.Vectors.Vector) is abstract; -- Get the driver unique index. function Get_Driver_Index (D : in Driver) return Driver_Index; -- Get the driver name. function Get_Driver_Name (D : in Driver) return String; -- Register a database driver. procedure Register (Driver : in Driver_Access); -- Get a database driver given its name. function Get_Driver (Name : in String) return Driver_Access; private type Driver is abstract new Ada.Finalization.Limited_Controlled with record Name : Util.Strings.Name_Access; Index : Driver_Index; end record; end ADO.Drivers.Connections;
Revert change to make the Driver type declaration near its methods (this was ok with GNAT 2018 but fails with FSF gcc 4.9.3)
Revert change to make the Driver type declaration near its methods (this was ok with GNAT 2018 but fails with FSF gcc 4.9.3)
Ada
apache-2.0
stcarrez/ada-ado
976dcceade35adcb830a67c8b5a47b3c4b5afed3
src/bbox-api.adb
src/bbox-api.adb
----------------------------------------------------------------------- -- bbox -- Bbox API -- 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.Properties.JSON; with Util.Log.Loggers; with Util.Strings; package body Bbox.API is use Ada.Strings.Unbounded; -- The logger Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Bbox.API"); -- ------------------------------ -- Set the server IP address. -- ------------------------------ procedure Set_Server (Client : in out Client_Type; Server : in String) is begin Log.Debug ("Using bbox server {0}", Server); Client.Server := Ada.Strings.Unbounded.To_Unbounded_String (Server); end Set_Server; -- ------------------------------ -- Internal operation to get the URI based on the operation being called. -- ------------------------------ function Get_URI (Client : in Client_Type; Operation : in String) return String is begin return "http://" & To_String (Client.Server) & "/api/v1/" & Operation; end Get_URI; -- ------------------------------ -- Login to the server Bbox API with the password. -- ------------------------------ procedure Login (Client : in out Client_Type; Password : in String) is procedure Process (Name, Value : in String); URI : constant String := Client.Get_URI ("login"); Response : Util.Http.Clients.Response; procedure Process (Name, Value : in String) is Pos, Last : Natural; begin if Name = "Set-Cookie" then Pos := Util.Strings.Index (Value, '='); if Pos = 0 then return; end if; Last := Util.Strings.Index (Value, ';'); if Last = 0 or else Last < Pos then return; end if; Client.Http.Set_Header ("Cookie", Value (Value'First .. Last - 1)); end if; end Process; begin Log.Debug ("Login to {0}", URI); Client.Http.Add_Header ("X-Requested-By", "Bbox Ada Api"); Client.Http.Post (URI, "password=" & Password, Response); if Response.Get_Status = Util.Http.SC_OK then Response.Iterate_Headers (Process'Access); else Log.Error ("Connection and login to {0} failed", URI); end if; end Login; -- ------------------------------ -- Execute a GET operation on the Bbox API to retrieve the result into the property list. -- ------------------------------ procedure Get (Client : in out Client_Type; Operation : in String; Result : in out Util.Properties.Manager) is URI : constant String := Client.Get_URI (Operation); Response : Util.Http.Clients.Response; begin Log.Debug ("Get {0}", URI); Client.Http.Get (URI, Response); Util.Properties.JSON.Parse_JSON (Result, Response.Get_Body); end Get; -- ------------------------------ -- Execute a GET operation on the Bbox API to retrieve the JSON result and return it. -- ------------------------------ function Get (Client : in out Client_Type; Operation : in String) return String is URI : constant String := Client.Get_URI (Operation); Response : Util.Http.Clients.Response; begin Log.Debug ("Get {0}", URI); Client.Http.Get (URI, Response); return Response.Get_Body; end Get; -- ------------------------------ -- Execute a PUT operation on the Bbox API to change some parameter. -- ------------------------------ procedure Put (Client : in out Client_Type; Operation : in String; Params : in String) is URI : constant String := Client.Get_URI (Operation); Response : Util.Http.Clients.Response; begin Log.Debug ("Put {0}", URI); Client.Http.Put (URI, Params, Response); end Put; end Bbox.API;
----------------------------------------------------------------------- -- bbox -- Bbox API -- 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.Properties.JSON; with Util.Log.Loggers; with Util.Strings; package body Bbox.API is use Ada.Strings.Unbounded; -- The logger Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Bbox.API"); function Strip_Unecessary_Array (Content : in String) return String; -- ------------------------------ -- Set the server IP address. -- ------------------------------ procedure Set_Server (Client : in out Client_Type; Server : in String) is begin Log.Debug ("Using bbox server {0}", Server); Client.Server := Ada.Strings.Unbounded.To_Unbounded_String (Server); end Set_Server; -- ------------------------------ -- Internal operation to get the URI based on the operation being called. -- ------------------------------ function Get_URI (Client : in Client_Type; Operation : in String) return String is begin return "http://" & To_String (Client.Server) & "/api/v1/" & Operation; end Get_URI; -- ------------------------------ -- Login to the server Bbox API with the password. -- ------------------------------ procedure Login (Client : in out Client_Type; Password : in String) is procedure Process (Name, Value : in String); URI : constant String := Client.Get_URI ("login"); Response : Util.Http.Clients.Response; procedure Process (Name, Value : in String) is Pos, Last : Natural; begin if Name = "Set-Cookie" then Pos := Util.Strings.Index (Value, '='); if Pos = 0 then return; end if; Last := Util.Strings.Index (Value, ';'); if Last = 0 or else Last < Pos then return; end if; Client.Http.Set_Header ("Cookie", Value (Value'First .. Last - 1)); end if; end Process; begin Log.Debug ("Login to {0}", URI); Client.Http.Add_Header ("X-Requested-By", "Bbox Ada Api"); Client.Http.Post (URI, "password=" & Password, Response); if Response.Get_Status = Util.Http.SC_OK then Response.Iterate_Headers (Process'Access); else Log.Error ("Connection and login to {0} failed", URI); end if; end Login; -- ------------------------------ -- Strip [] for some Json content. -- We did a mistake when we designed the Bbox API and used '[' ... ']' arrays -- for most of the JSON result. Strip that unecessary array. -- ------------------------------ function Strip_Unecessary_Array (Content : in String) return String is Last : Natural := Content'Last; begin while Last > Content'First and Content (Last) = ASCII.LF loop Last := Last - 1; end loop; if Content (Content'First) = '[' and Content (Last) = ']' then return Content (Content'First + 1 .. Last - 1); else return Content; end if; end Strip_Unecessary_Array; -- ------------------------------ -- Execute a GET operation on the Bbox API to retrieve the result into the property list. -- ------------------------------ procedure Get (Client : in out Client_Type; Operation : in String; Result : in out Util.Properties.Manager) is URI : constant String := Client.Get_URI (Operation); Response : Util.Http.Clients.Response; begin Log.Debug ("Get {0}", URI); Client.Http.Get (URI, Response); Util.Properties.JSON.Parse_JSON (Result, Strip_Unecessary_Array (Response.Get_Body)); end Get; -- ------------------------------ -- Execute a GET operation on the Bbox API to retrieve the JSON result and return it. -- ------------------------------ function Get (Client : in out Client_Type; Operation : in String) return String is URI : constant String := Client.Get_URI (Operation); Response : Util.Http.Clients.Response; begin Log.Debug ("Get {0}", URI); Client.Http.Get (URI, Response); return Response.Get_Body; end Get; -- ------------------------------ -- Execute a PUT operation on the Bbox API to change some parameter. -- ------------------------------ procedure Put (Client : in out Client_Type; Operation : in String; Params : in String) is URI : constant String := Client.Get_URI (Operation); Response : Util.Http.Clients.Response; begin Log.Debug ("Put {0}", URI); Client.Http.Put (URI, Params, Response); end Put; end Bbox.API;
Declare Strip_Unecessary_Array function and use it to strip the stupid JSON array we introduced by mistake in the Bboxd API JSON output
Declare Strip_Unecessary_Array function and use it to strip the stupid JSON array we introduced by mistake in the Bboxd API JSON output
Ada
apache-2.0
stcarrez/bbox-ada-api
a26bdc3e0297ec8200cfb94ae833146479713677
mat/src/mat-commands.ads
mat/src/mat-commands.ads
----------------------------------------------------------------------- -- mat-commands -- Command support and execution -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with GNAT.Sockets; with MAT.Targets; package MAT.Commands is Stop_Interp : exception; -- The options that can be configured through the command line. type Options_Type is record Interactive : Boolean := True; Graphical : Boolean := False; Address : GNAT.Sockets.Sock_Addr_Type := (Port => 4096, others => <>); end record; -- Procedure that defines a command handler. type Command_Handler is access procedure (Target : in out MAT.Targets.Target_Type'Class; Args : in String); -- Execute the command given in the line. procedure Execute (Target : in out MAT.Targets.Target_Type'Class; Line : in String); -- Enter in the interactive loop reading the commands from the standard input -- and executing the commands. procedure Interactive (Target : in out MAT.Targets.Target_Type'Class); -- Parse the command line arguments and configure the target instance. procedure Initialize_Options (Target : in out MAT.Targets.Target_Type'Class; Options : in out Options_Type); end MAT.Commands;
----------------------------------------------------------------------- -- mat-commands -- Command support and execution -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with GNAT.Sockets; with MAT.Targets; package MAT.Commands is Stop_Interp : exception; -- The options that can be configured through the command line. type Options_Type is record Interactive : Boolean := True; Graphical : Boolean := False; Address : GNAT.Sockets.Sock_Addr_Type := (Port => 4096, others => <>); end record; -- Procedure that defines a command handler. type Command_Handler is access procedure (Target : in out MAT.Targets.Target_Type'Class; Args : in String); -- Execute the command given in the line. procedure Execute (Target : in out MAT.Targets.Target_Type'Class; Line : in String); -- Enter in the interactive loop reading the commands from the standard input -- and executing the commands. procedure Interactive (Target : in out MAT.Targets.Target_Type'Class); -- Parse the command line arguments and configure the target instance. procedure Initialize_Options (Target : in out MAT.Targets.Target_Type'Class; Options : in out Options_Type); -- Convert the string to a socket address. The string can have two forms: -- port -- host:port function To_Sock_Addr_Type (Param : in String) return GNAT.Sockets.Sock_Addr_Type; end MAT.Commands;
Declare the To_Sock_Addr_Type function
Declare the To_Sock_Addr_Type function
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
0e14887e7d24951e9054fc85967a1fcc1884fb4a
awa/plugins/awa-questions/src/awa-questions-beans.adb
awa/plugins/awa-questions/src/awa-questions-beans.adb
----------------------------------------------------------------------- -- awa-questions-beans -- Beans for module questions -- Copyright (C) 2012, 2013 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with ADO.Queries; with ADO.Sessions; with AWA.Services.Contexts; with AWA.Questions.Services; package body AWA.Questions.Beans is -- ------------------------------ -- Get the value identified by the name. -- ------------------------------ overriding function Get_Value (From : in Question_Bean; Name : in String) return Util.Beans.Objects.Object is begin if Name = "count" then return Util.Beans.Objects.To_Object (From.Count); else return Util.Beans.Objects.Null_Object; end if; end Get_Value; -- ------------------------------ -- Set the value identified by the name. -- ------------------------------ overriding procedure Set_Value (From : in out Question_Bean; Name : in String; Value : in Util.Beans.Objects.Object) is begin if Name = "count" then From.Count := Util.Beans.Objects.To_Integer (Value); end if; end Set_Value; procedure Save (Bean : in out Question_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is Manager : constant Services.Question_Service_Access := Bean.Module.Get_Question_Manager; begin Manager.Save_Question (Bean); end Save; procedure Delete (Bean : in out Question_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is begin null; end Delete; -- ------------------------------ -- Create the Question_Bean bean instance. -- ------------------------------ function Create_Question_Bean (Module : in AWA.Questions.Modules.Question_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is Object : constant Question_Bean_Access := new Question_Bean; begin Object.Module := Module; return Object.all'Access; end Create_Question_Bean; -- ------------------------------ -- Create the Question_Info_List_Bean bean instance. -- ------------------------------ function Create_Question_List_Bean (Module : in AWA.Questions.Modules.Question_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is use AWA.Questions.Models; use AWA.Services; Ctx : constant Contexts.Service_Context_Access := AWA.Services.Contexts.Current; Object : constant Question_Info_List_Bean_Access := new Question_Info_List_Bean; Session : ADO.Sessions.Session := Module.Get_Session; Query : ADO.Queries.Context; begin Query.Set_Query (AWA.Questions.Models.Query_Question_List); AWA.Questions.Models.List (Object.all, Session, Query); return Object.all'Access; end Create_Question_List_Bean; end AWA.Questions.Beans;
----------------------------------------------------------------------- -- awa-questions-beans -- Beans for module questions -- Copyright (C) 2012, 2013 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with ADO.Queries; with ADO.Sessions; with AWA.Services.Contexts; with AWA.Questions.Services; package body AWA.Questions.Beans is -- ------------------------------ -- Get the value identified by the name. -- ------------------------------ overriding function Get_Value (From : in Question_Bean; Name : in String) return Util.Beans.Objects.Object is begin if From.Is_Null then return Util.Beans.Objects.Null_Object; else return AWA.Questions.Models.Question_Bean (From).Get_Value (Name); end if; end Get_Value; -- ------------------------------ -- Set the value identified by the name. -- ------------------------------ overriding procedure Set_Value (From : in out Question_Bean; Name : in String; Value : in Util.Beans.Objects.Object) is begin if Name = "title" then From.Set_Title (Util.Beans.Objects.To_String (Value)); elsif Name = "description" then From.Set_Description (Util.Beans.Objects.To_String (Value)); elsif Name = "id" and not Util.Beans.Objects.Is_Empty (Value) then From.Service.Load_Question (From, ADO.Identifier (Util.Beans.Objects.To_Integer (Value))); end if; end Set_Value; -- ------------------------------ -- Create or save the question. -- ------------------------------ procedure Save (Bean : in out Question_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is begin Bean.Service.Save_Question (Bean); end Save; -- ------------------------------ -- Delete the question. -- ------------------------------ procedure Delete (Bean : in out Question_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is begin Bean.Service.Delete_Question (Bean); end Delete; -- ------------------------------ -- Create the Question_Bean bean instance. -- ------------------------------ function Create_Question_Bean (Module : in AWA.Questions.Modules.Question_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is Object : constant Question_Bean_Access := new Question_Bean; begin Object.Service := Module.Get_Question_Manager; return Object.all'Access; end Create_Question_Bean; -- Get the value identified by the name. overriding function Get_Value (From : in Answer_Bean; Name : in String) return Util.Beans.Objects.Object is begin if From.Is_Null then return Util.Beans.Objects.Null_Object; else return AWA.Questions.Models.Answer_Bean (From).Get_Value (Name); end if; end Get_Value; -- ------------------------------ -- Set the value identified by the name. -- ------------------------------ overriding procedure Set_Value (From : in out Answer_Bean; Name : in String; Value : in Util.Beans.Objects.Object) is begin if Name = "id" then null; elsif Name = "answer" then From.Set_Answer (Util.Beans.Objects.To_String (Value)); elsif Name = "question_id" and not Util.Beans.Objects.Is_Null (Value) then From.Service.Load_Question (From.Question, ADO.Identifier (Util.Beans.Objects.To_Integer (Value))); end if; end Set_Value; -- ------------------------------ -- Create or save the answer. -- ------------------------------ procedure Save (Bean : in out Answer_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is begin Bean.Service.Save_Answer (Question => Bean.Question, Answer => Bean); end Save; -- Delete the question. procedure Delete (Bean : in out Answer_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is begin null; end Delete; -- ------------------------------ -- Create the Question_Info_List_Bean bean instance. -- ------------------------------ function Create_Question_List_Bean (Module : in AWA.Questions.Modules.Question_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access is use AWA.Questions.Models; use AWA.Services; Ctx : constant Contexts.Service_Context_Access := AWA.Services.Contexts.Current; Object : constant Question_Info_List_Bean_Access := new Question_Info_List_Bean; Session : ADO.Sessions.Session := Module.Get_Session; Query : ADO.Queries.Context; begin Query.Set_Query (AWA.Questions.Models.Query_Question_List); AWA.Questions.Models.List (Object.all, Session, Query); return Object.all'Access; end Create_Question_List_Bean; end AWA.Questions.Beans;
Implement the answer bean
Implement the answer bean
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
1fc63783b793f6aa80b19b306100cea681e215ff
src/asf-beans.adb
src/asf-beans.adb
----------------------------------------------------------------------- -- asf.beans -- Bean Registration and Factory -- Copyright (C) 2009, 2010, 2011 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Log.Loggers; package body ASF.Beans is use Util.Log; -- The logger Log : constant Loggers.Logger := Loggers.Create ("ASF.Beans"); -- ------------------------------ -- Register under the name identified by <b>Name</b> the class instance <b>Class</b>. -- ------------------------------ procedure Register_Class (Factory : in out Bean_Factory; Name : in String; Class : in Class_Binding_Access) is begin Log.Info ("Register bean class {0}", Name); Factory.Registry.Include (Name, Class_Binding_Ref.Create (Class)); end Register_Class; -- ------------------------------ -- Register under the name identified by <b>Name</b> a function to create a bean. -- This is a simplified class registration. -- ------------------------------ procedure Register_Class (Factory : in out Bean_Factory; Name : in String; Handler : in Create_Bean_Access) is Class : Default_Class_Binding_Access := new Default_Class_Binding; begin Class.Create := Handler; Register_Class (Factory, Name, Class.all'Access); end Register_Class; -- ------------------------------ -- Register the bean identified by <b>Name</b> and associated with the class <b>Class</b>. -- The class must have been registered by using the <b>Register</b> class operation. -- The scope defines the scope of the bean. -- ------------------------------ procedure Register (Factory : in out Bean_Factory; Name : in String; Class : in String; Params : in Parameter_Bean_Ref.Ref; Scope : in Scope_Type := REQUEST_SCOPE) is begin Log.Info ("Register bean '{0}' created by '{1}' in scope {2}", Name, Class, Scope_Type'Image (Scope)); declare Pos : constant Registry_Maps.Cursor := Factory.Registry.Find (Class); Binding : Bean_Binding; begin if not Registry_Maps.Has_Element (Pos) then Log.Error ("Class '{0}' does not exist. Cannot register bean '{1}'", Class, Name); return; end if; Binding.Create := Registry_Maps.Element (Pos); Binding.Scope := Scope; Binding.Params := Params; Factory.Map.Include (Ada.Strings.Unbounded.To_Unbounded_String (Name), Binding); end; end Register; -- ------------------------------ -- Register the bean identified by <b>Name</b> and associated with the class <b>Class</b>. -- The class must have been registered by using the <b>Register</b> class operation. -- The scope defines the scope of the bean. -- ------------------------------ procedure Register (Factory : in out Bean_Factory; Name : in String; Class : in Class_Binding_Access; Params : in Parameter_Bean_Ref.Ref; Scope : in Scope_Type := REQUEST_SCOPE) is Binding : Bean_Binding; begin Log.Info ("Register bean '{0}' in scope {2}", Name, Scope_Type'Image (Scope)); Binding.Create := Class_Binding_Ref.Create (Class); Binding.Scope := Scope; Binding.Params := Params; Factory.Map.Include (Ada.Strings.Unbounded.To_Unbounded_String (Name), Binding); end Register; -- ------------------------------ -- Register all the definitions from a factory to a main factory. -- ------------------------------ procedure Register (Factory : in out Bean_Factory; From : in Bean_Factory) is begin declare Pos : Registry_Maps.Cursor := From.Registry.First; begin while Registry_Maps.Has_Element (Pos) loop Factory.Registry.Include (Key => Registry_Maps.Key (Pos), New_Item => Registry_Maps.Element (Pos)); Registry_Maps.Next (Pos); end loop; end; declare Pos : Bean_Maps.Cursor := Bean_Maps.First (From.Map); begin while Bean_Maps.Has_Element (Pos) loop Factory.Map.Include (Key => Bean_Maps.Key (Pos), New_Item => Bean_Maps.Element (Pos)); Bean_Maps.Next (Pos); end loop; end; end Register; -- ------------------------------ -- Create a bean by using the create operation registered for the name -- ------------------------------ procedure Create (Factory : in Bean_Factory; Name : in Unbounded_String; Context : in EL.Contexts.ELContext'Class; Result : out Util.Beans.Basic.Readonly_Bean_Access; Scope : out Scope_Type) is use type Util.Beans.Basic.Readonly_Bean_Access; Pos : constant Bean_Maps.Cursor := Factory.Map.Find (Name); begin if Bean_Maps.Has_Element (Pos) then declare Binding : constant Bean_Binding := Bean_Maps.Element (Pos); begin Binding.Create.Value.Create (Name, Result); if Result /= null and then not Binding.Params.Is_Null then if Result.all in Util.Beans.Basic.Bean'Class then EL.Beans.Initialize (Util.Beans.Basic.Bean'Class (Result.all), Binding.Params.Value.Params, Context); else Log.Warn ("Bean {0} cannot be set with pre-defined properties as it does " & "not implement the Bean interface", To_String (Name)); end if; end if; Scope := Binding.Scope; end; else Result := null; Scope := ANY_SCOPE; end if; end Create; -- ------------------------------ -- Create a bean by using the registered create function. -- ------------------------------ procedure Create (Factory : in Default_Class_Binding; Name : in Ada.Strings.Unbounded.Unbounded_String; Result : out Util.Beans.Basic.Readonly_Bean_Access) is pragma Unreferenced (Name); begin Result := Factory.Create.all; end Create; end ASF.Beans;
----------------------------------------------------------------------- -- asf.beans -- Bean Registration and Factory -- Copyright (C) 2009, 2010, 2011, 2012, 2013 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Log.Loggers; package body ASF.Beans is -- The logger Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("ASF.Beans"); -- ------------------------------ -- Register under the name identified by <b>Name</b> the class instance <b>Class</b>. -- ------------------------------ procedure Register_Class (Factory : in out Bean_Factory; Name : in String; Class : in Class_Binding_Access) is begin Log.Info ("Register bean class {0}", Name); Factory.Registry.Include (Name, Class_Binding_Ref.Create (Class)); end Register_Class; -- ------------------------------ -- Register under the name identified by <b>Name</b> a function to create a bean. -- This is a simplified class registration. -- ------------------------------ procedure Register_Class (Factory : in out Bean_Factory; Name : in String; Handler : in Create_Bean_Access) is Class : constant Default_Class_Binding_Access := new Default_Class_Binding; begin Class.Create := Handler; Register_Class (Factory, Name, Class.all'Access); end Register_Class; -- ------------------------------ -- Register the bean identified by <b>Name</b> and associated with the class <b>Class</b>. -- The class must have been registered by using the <b>Register</b> class operation. -- The scope defines the scope of the bean. -- ------------------------------ procedure Register (Factory : in out Bean_Factory; Name : in String; Class : in String; Params : in Parameter_Bean_Ref.Ref; Scope : in Scope_Type := REQUEST_SCOPE) is begin Log.Info ("Register bean '{0}' created by '{1}' in scope {2}", Name, Class, Scope_Type'Image (Scope)); declare Pos : constant Registry_Maps.Cursor := Factory.Registry.Find (Class); Binding : Bean_Binding; begin if not Registry_Maps.Has_Element (Pos) then Log.Error ("Class '{0}' does not exist. Cannot register bean '{1}'", Class, Name); return; end if; Binding.Create := Registry_Maps.Element (Pos); Binding.Scope := Scope; Binding.Params := Params; Factory.Map.Include (Ada.Strings.Unbounded.To_Unbounded_String (Name), Binding); end; end Register; -- ------------------------------ -- Register the bean identified by <b>Name</b> and associated with the class <b>Class</b>. -- The class must have been registered by using the <b>Register</b> class operation. -- The scope defines the scope of the bean. -- ------------------------------ procedure Register (Factory : in out Bean_Factory; Name : in String; Class : in Class_Binding_Access; Params : in Parameter_Bean_Ref.Ref; Scope : in Scope_Type := REQUEST_SCOPE) is Binding : Bean_Binding; begin Log.Info ("Register bean '{0}' in scope {2}", Name, Scope_Type'Image (Scope)); Binding.Create := Class_Binding_Ref.Create (Class); Binding.Scope := Scope; Binding.Params := Params; Factory.Map.Include (Ada.Strings.Unbounded.To_Unbounded_String (Name), Binding); end Register; -- ------------------------------ -- Register all the definitions from a factory to a main factory. -- ------------------------------ procedure Register (Factory : in out Bean_Factory; From : in Bean_Factory) is begin declare Pos : Registry_Maps.Cursor := From.Registry.First; begin while Registry_Maps.Has_Element (Pos) loop Factory.Registry.Include (Key => Registry_Maps.Key (Pos), New_Item => Registry_Maps.Element (Pos)); Registry_Maps.Next (Pos); end loop; end; declare Pos : Bean_Maps.Cursor := Bean_Maps.First (From.Map); begin while Bean_Maps.Has_Element (Pos) loop Factory.Map.Include (Key => Bean_Maps.Key (Pos), New_Item => Bean_Maps.Element (Pos)); Bean_Maps.Next (Pos); end loop; end; end Register; -- ------------------------------ -- Create a bean by using the create operation registered for the name -- ------------------------------ procedure Create (Factory : in Bean_Factory; Name : in Unbounded_String; Context : in EL.Contexts.ELContext'Class; Result : out Util.Beans.Basic.Readonly_Bean_Access; Scope : out Scope_Type) is use type Util.Beans.Basic.Readonly_Bean_Access; Pos : constant Bean_Maps.Cursor := Factory.Map.Find (Name); begin if Bean_Maps.Has_Element (Pos) then declare Binding : constant Bean_Binding := Bean_Maps.Element (Pos); begin Binding.Create.Value.Create (Name, Result); if Result /= null and then not Binding.Params.Is_Null then if Result.all in Util.Beans.Basic.Bean'Class then EL.Beans.Initialize (Util.Beans.Basic.Bean'Class (Result.all), Binding.Params.Value.Params, Context); else Log.Warn ("Bean {0} cannot be set with pre-defined properties as it does " & "not implement the Bean interface", To_String (Name)); end if; end if; Scope := Binding.Scope; end; else Result := null; Scope := ANY_SCOPE; end if; end Create; -- ------------------------------ -- Create a bean by using the registered create function. -- ------------------------------ procedure Create (Factory : in Default_Class_Binding; Name : in Ada.Strings.Unbounded.Unbounded_String; Result : out Util.Beans.Basic.Readonly_Bean_Access) is pragma Unreferenced (Name); begin Result := Factory.Create.all; end Create; end ASF.Beans;
Fix compilation warning
Fix compilation warning
Ada
apache-2.0
Letractively/ada-asf,Letractively/ada-asf,Letractively/ada-asf
dee229166939f22ca4afa2ad548c4cf64f7cb202
src/asf-parts.ads
src/asf-parts.ads
----------------------------------------------------------------------- -- asf-parts -- ASF Parts -- Copyright (C) 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Finalization; -- The <b>ASF.Parts</b> package is an Ada implementation of the Java servlet part -- (JSR 315 3. The Request) provided by the <tt>javax.servlet.http.Part</tt> class. package ASF.Parts is -- ------------------------------ -- Multi part content -- ------------------------------ -- The <b>Part</b> type describes a mime part received in a request. -- The content is stored in a file and several operations are provided -- to manage the content. type Part is abstract new Ada.Finalization.Limited_Controlled with private; -- Get the size of the mime part. function Get_Size (Data : in Part) return Natural is abstract; -- Get the content name submitted in the mime part. function Get_Name (Data : in Part) return String is abstract; -- Get the path of the local file which contains the part. function Get_Local_Filename (Data : in Part) return String is abstract; -- Get the content type of the part. function Get_Content_Type (Data : in Part) return String is abstract; -- Write the part data item to the file. This method is not guaranteed to succeed -- if called more than once for the same part. This allows a particular implementation -- to use, for example, file renaming, where possible, rather than copying all of -- the underlying data, thus gaining a significant performance benefit. procedure Save (Data : in Part; Path : in String); -- Deletes the underlying storage for a file item, including deleting any associated -- temporary disk file. procedure Delete (Data : in out Part); private type Part is abstract new Ada.Finalization.Limited_Controlled with null record; end ASF.Parts;
----------------------------------------------------------------------- -- asf-parts -- ASF Parts -- Copyright (C) 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Finalization; with Servlet.Parts; -- The <b>ASF.Parts</b> package is an Ada implementation of the Java servlet part -- (JSR 315 3. The Request) provided by the <tt>javax.servlet.http.Part</tt> class. package ASF.Parts is -- ------------------------------ -- Multi part content -- ------------------------------ -- The <b>Part</b> type describes a mime part received in a request. -- The content is stored in a file and several operations are provided -- to manage the content. subtype Part is Servlet.Parts.Part; -- Get the size of the mime part. function Get_Size (Data : in Part) return Natural is abstract; -- Get the content name submitted in the mime part. function Get_Name (Data : in Part) return String is abstract; -- Get the path of the local file which contains the part. function Get_Local_Filename (Data : in Part) return String is abstract; -- Get the content type of the part. function Get_Content_Type (Data : in Part) return String is abstract; -- Write the part data item to the file. This method is not guaranteed to succeed -- if called more than once for the same part. This allows a particular implementation -- to use, for example, file renaming, where possible, rather than copying all of -- the underlying data, thus gaining a significant performance benefit. procedure Save (Data : in Part; Path : in String); -- Deletes the underlying storage for a file item, including deleting any associated -- temporary disk file. procedure Delete (Data : in out Part); end ASF.Parts;
Package ASF.Parts moved to Servlet.Parts
Package ASF.Parts moved to Servlet.Parts
Ada
apache-2.0
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
d67e22dc2d901ea66da8b3a78692b029af834533
src/util-files.ads
src/util-files.ads
----------------------------------------------------------------------- -- Util.Files -- Various File Utility Packages -- Copyright (C) 2001, 2002, 2003, 2009, 2010, 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Util.Strings.Maps; package Util.Files is use Ada.Strings.Unbounded; subtype Direction is Ada.Strings.Direction; -- Read a complete file into a string. -- The <b>Max_Size</b> parameter indicates the maximum size that is read. procedure Read_File (Path : in String; Into : out Unbounded_String; Max_Size : in Natural := 0); -- Read the file with the given path, one line at a time and execute the <b>Process</b> -- procedure with each line as argument. procedure Read_File (Path : in String; Process : not null access procedure (Line : in String)); -- Save the string into a file creating the file if necessary procedure Write_File (Path : in String; Content : in String); -- Save the string into a file creating the file if necessary procedure Write_File (Path : in String; Content : in Unbounded_String); -- Iterate over the search directories defined in <b>Path</b> and execute -- <b>Process</b> with each directory until it returns <b>True</b> in <b>Done</b> -- or the last search directory is found. Each search directory -- is separated by ';' (yes, even on Unix). When <b>Going</b> is set to Backward, the -- directories are searched in reverse order. procedure Iterate_Path (Path : in String; Process : not null access procedure (Dir : in String; Done : out Boolean); Going : in Direction := Ada.Strings.Forward); -- Iterate over the search directories defined in <b>Path</b> and search -- for files matching the pattern defined by <b>Pattern</b>. For each file, -- execute <b>Process</b> with the file basename and the full file path. -- Stop iterating when the <b>Process</b> procedure returns True. -- Each search directory is separated by ';'. When <b>Going</b> is set to Backward, the -- directories are searched in reverse order. procedure Iterate_Files_Path (Pattern : in String; Path : in String; Process : not null access procedure (Name : in String; File : in String; Done : out Boolean); Going : in Direction := Ada.Strings.Forward); -- Find the file in one of the search directories. Each search directory -- is separated by ';' (yes, even on Unix). -- Returns the path to be used for reading the file. function Find_File_Path (Name : String; Paths : String) return String; -- Find the files which match the pattern in the directories specified in the -- search path <b>Path</b>. Each search directory is separated by ';'. -- File names are added to the string set in <b>Into</b>. procedure Find_Files_Path (Pattern : in String; Path : in String; Into : in out Util.Strings.Maps.Map); -- Returns the name of the external file with the specified directory -- and the name. Unlike the Ada.Directories.Compose, the name can represent -- a relative path and thus include directory separators. function Compose (Directory : in String; Name : in String) return String; -- Compose an existing path by adding the specified name to each path component -- and return a new paths having only existing directories. Each directory is -- separated by ';'. -- If the composed path exists, it is added to the result path. -- Example: -- paths = 'web;regtests' name = 'info' -- result = 'web/info;regtests/info' -- Returns the composed path. function Compose_Path (Paths : in String; Name : in String) return String; -- Returns a relative path whose origin is defined by <b>From</b> and which refers -- to the absolute path referenced by <b>To</b>. Both <b>From</b> and <b>To</b> are -- assumed to be absolute pathes. Returns the absolute path <b>To</b> if the relative -- path could not be found. Both paths must have at least one root component in common. function Get_Relative_Path (From : in String; To : in String) return String; end Util.Files;
----------------------------------------------------------------------- -- Util.Files -- Various File Utility Packages -- Copyright (C) 2001, 2002, 2003, 2009, 2010, 2011, 2012, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Util.Strings.Maps; with Util.Strings.Vectors; package Util.Files is use Ada.Strings.Unbounded; subtype Direction is Ada.Strings.Direction; -- Read a complete file into a string. -- The <b>Max_Size</b> parameter indicates the maximum size that is read. procedure Read_File (Path : in String; Into : out Unbounded_String; Max_Size : in Natural := 0); -- Read the file with the given path, one line at a time and execute the <b>Process</b> -- procedure with each line as argument. procedure Read_File (Path : in String; Process : not null access procedure (Line : in String)); -- Read the file with the given path, one line at a time and append each line to -- the <b>Into</b> vector. procedure Read_File (Path : in String; Into : in out Util.Strings.Vectors.Vector); -- Save the string into a file creating the file if necessary procedure Write_File (Path : in String; Content : in String); -- Save the string into a file creating the file if necessary procedure Write_File (Path : in String; Content : in Unbounded_String); -- Iterate over the search directories defined in <b>Path</b> and execute -- <b>Process</b> with each directory until it returns <b>True</b> in <b>Done</b> -- or the last search directory is found. Each search directory -- is separated by ';' (yes, even on Unix). When <b>Going</b> is set to Backward, the -- directories are searched in reverse order. procedure Iterate_Path (Path : in String; Process : not null access procedure (Dir : in String; Done : out Boolean); Going : in Direction := Ada.Strings.Forward); -- Iterate over the search directories defined in <b>Path</b> and search -- for files matching the pattern defined by <b>Pattern</b>. For each file, -- execute <b>Process</b> with the file basename and the full file path. -- Stop iterating when the <b>Process</b> procedure returns True. -- Each search directory is separated by ';'. When <b>Going</b> is set to Backward, the -- directories are searched in reverse order. procedure Iterate_Files_Path (Pattern : in String; Path : in String; Process : not null access procedure (Name : in String; File : in String; Done : out Boolean); Going : in Direction := Ada.Strings.Forward); -- Find the file in one of the search directories. Each search directory -- is separated by ';' (yes, even on Unix). -- Returns the path to be used for reading the file. function Find_File_Path (Name : String; Paths : String) return String; -- Find the files which match the pattern in the directories specified in the -- search path <b>Path</b>. Each search directory is separated by ';'. -- File names are added to the string set in <b>Into</b>. procedure Find_Files_Path (Pattern : in String; Path : in String; Into : in out Util.Strings.Maps.Map); -- Returns the name of the external file with the specified directory -- and the name. Unlike the Ada.Directories.Compose, the name can represent -- a relative path and thus include directory separators. function Compose (Directory : in String; Name : in String) return String; -- Compose an existing path by adding the specified name to each path component -- and return a new paths having only existing directories. Each directory is -- separated by ';'. -- If the composed path exists, it is added to the result path. -- Example: -- paths = 'web;regtests' name = 'info' -- result = 'web/info;regtests/info' -- Returns the composed path. function Compose_Path (Paths : in String; Name : in String) return String; -- Returns a relative path whose origin is defined by <b>From</b> and which refers -- to the absolute path referenced by <b>To</b>. Both <b>From</b> and <b>To</b> are -- assumed to be absolute pathes. Returns the absolute path <b>To</b> if the relative -- path could not be found. Both paths must have at least one root component in common. function Get_Relative_Path (From : in String; To : in String) return String; end Util.Files;
Declare a Read_File procedure to load the file line by line in a Strings.Vector object
Declare a Read_File procedure to load the file line by line in a Strings.Vector object
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
b18c96dab58fa88fceae2124828e89ab2ebdc241
src/definitions.ads
src/definitions.ads
-- This file is covered by the Internet Software Consortium (ISC) License -- Reference: ../License.txt package Definitions is pragma Pure; raven_version_major : constant String := "0"; raven_version_minor : constant String := "20"; copyright_years : constant String := "2015-2017"; raven_tool : constant String := "ravenadm"; variant_standard : constant String := "standard"; contact_nobody : constant String := "nobody"; contact_automaton : constant String := "automaton"; dlgroup_main : constant String := "main"; dlgroup_none : constant String := "none"; options_none : constant String := "none"; options_all : constant String := "all"; broken_all : constant String := "all"; boolean_yes : constant String := "yes"; homepage_none : constant String := "none"; spkg_complete : constant String := "complete"; spkg_docs : constant String := "docs"; spkg_examples : constant String := "examples"; ports_default : constant String := "floating"; default_ssl : constant String := "libressl"; default_mysql : constant String := "oracle-5.7"; default_lua : constant String := "5.3"; default_perl : constant String := "5.24"; default_pgsql : constant String := "9.6"; default_python3 : constant String := "3.5"; default_ruby : constant String := "2.4"; default_tcltk : constant String := "8.6"; default_compiler : constant String := "gcc6"; compiler_version : constant String := "6.20170202"; arc_ext : constant String := ".txz"; jobs_per_cpu : constant := 2; type supported_opsys is (dragonfly, freebsd, netbsd, openbsd, sunos, linux, macos); type supported_arch is (x86_64, i386, aarch64); type cpu_range is range 1 .. 32; type scanners is range cpu_range'First .. cpu_range'Last; type builders is range cpu_range'First .. cpu_range'Last * jobs_per_cpu; type count_type is (total, success, failure, ignored, skipped); -- Modify following with post-patch sed accordingly platform_type : constant supported_opsys := dragonfly; host_localbase : constant String := "/raven"; host_pkg8 : constant String := host_localbase & "/sbin/pkg"; ravenexec : constant String := host_localbase & "/libexec/ravenexec"; end Definitions;
-- This file is covered by the Internet Software Consortium (ISC) License -- Reference: ../License.txt package Definitions is pragma Pure; raven_version_major : constant String := "0"; raven_version_minor : constant String := "50"; copyright_years : constant String := "2015-2017"; raven_tool : constant String := "ravenadm"; variant_standard : constant String := "standard"; contact_nobody : constant String := "nobody"; contact_automaton : constant String := "automaton"; dlgroup_main : constant String := "main"; dlgroup_none : constant String := "none"; options_none : constant String := "none"; options_all : constant String := "all"; broken_all : constant String := "all"; boolean_yes : constant String := "yes"; homepage_none : constant String := "none"; spkg_complete : constant String := "complete"; spkg_docs : constant String := "docs"; spkg_examples : constant String := "examples"; ports_default : constant String := "floating"; default_ssl : constant String := "libressl"; default_mysql : constant String := "oracle-5.7"; default_lua : constant String := "5.3"; default_perl : constant String := "5.24"; default_pgsql : constant String := "9.6"; default_python3 : constant String := "3.5"; default_ruby : constant String := "2.4"; default_tcltk : constant String := "8.6"; default_compiler : constant String := "gcc6"; compiler_version : constant String := "6.20170202"; arc_ext : constant String := ".txz"; jobs_per_cpu : constant := 2; type supported_opsys is (dragonfly, freebsd, netbsd, openbsd, sunos, linux, macos); type supported_arch is (x86_64, i386, aarch64); type cpu_range is range 1 .. 32; type scanners is range cpu_range'First .. cpu_range'Last; type builders is range cpu_range'First .. cpu_range'Last * jobs_per_cpu; type count_type is (total, success, failure, ignored, skipped); -- Modify following with post-patch sed accordingly platform_type : constant supported_opsys := dragonfly; host_localbase : constant String := "/raven"; host_pkg8 : constant String := host_localbase & "/sbin/pkg"; ravenexec : constant String := host_localbase & "/libexec/ravenexec"; end Definitions;
Bump version a lot
Bump version a lot
Ada
isc
jrmarino/ravenadm,jrmarino/ravenadm,jrmarino/ravenadm
51fdcfeb5c6b93a1d0370953c005574f26b71eb3
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 MAT.Types; with MAT.Readers.Marshaller; with MAT.Memory; with MAT.Events; package body MAT.Memory.Readers is 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 := "addr"; 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_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)); ---------------------- -- Bind the servant with the object adapter to register the -- events it recognizes. ---------------------- procedure Bind (For_Servant : in out Memory_Servant) is begin Bind_Servant (For_Servant, "malloc", MSG_MALLOC, Memory_Attributes'Access); Bind_Servant (For_Servant, "free", MSG_FREE, Memory_Attributes'Access); Bind_Servant (For_Servant, "realloc", MSG_REALLOC, Memory_Attributes'Access); end Bind; ---------------------- -- A memory allocation message is received. Register the memory -- slot in the allocated memory list. An event is posted on the -- event channel to notify the listeners that a new slot is allocated. ---------------------- procedure Process_Malloc_Message (Client : in out Memory_Servant; Addr : in MAT.Types.Target_Addr; Slot : in Allocation) is Inserted : Boolean; -- Ev : MAT.Memory.Events.Memory_Event := (Kind => EV_MALLOC, Addr => Addr); begin Client.Data.Memory_Slots.Insert (Addr, Slot); -- Post (Client.Event_Channel, Ev); end Process_Malloc_Message; ---------------------- -- A memory deallocation message. Find the memory slot being freed -- and remove it from the allocated list. Post an event on the event -- channel to notify the listeners that the slot is removed. ---------------------- procedure Process_Free_Message (Client : in out Memory_Servant; Addr : in MAT.Types.Target_Addr; Slot : in Allocation) is It : MAT.Memory.Allocation_Maps.Cursor := Client.Data.Memory_Slots.Find (Addr); -- Ev : Memory_Event := (Kind => EV_FREE, Addr => Addr); begin if MAT.Memory.Allocation_Maps.Has_Element (It) then -- Address is not in the map. The application is freeing -- an already freed memory or something wrong. null; end if; -- Post (Client.Event_Channel, Ev); declare Slot : Allocation := MAT.Memory.Allocation_Maps.Element (It); begin Frames.Release (Slot.Frame); end; -- Remove the memory slot from our map. Client.Data.Memory_Slots.Delete (It); end Process_Free_Message; ---------------------- -- 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_FRAME => -- Unmarshal_Frame (Msg, Slot.Frame); null; pragma Assert (False, "must fix M_FRAME"); when M_TIME => Slot.Time := MAT.Readers.Marshaller.Get_Target_Tick (Msg.Buffer, Def.Kind); when M_THREAD => Slot.Thread := MAT.Readers.Marshaller.Get_Target_Thread (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; Msg : in out MAT.Readers.Message) is Slot : Allocation; Addr : MAT.Types.Target_Addr; Old_Addr : MAT.Types.Target_Addr := 0; begin case Id is when MSG_MALLOC => Unmarshall_Allocation (Msg, Slot, Addr, Old_Addr, Params.all); Process_Malloc_Message (For_Servant, Addr, Slot); when MSG_FREE => Unmarshall_Allocation (Msg, Slot, Addr, Old_Addr, Params.all); Process_Free_Message (For_Servant, Addr, Slot); when MSG_REALLOC => Unmarshall_Allocation (Msg, Slot, Addr, Old_Addr, Params.all); Process_Malloc_Message (For_Servant, Addr, Slot); Process_Free_Message (For_Servant, 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 MAT.Types; with MAT.Readers.Marshaller; with MAT.Memory; with MAT.Events; package body MAT.Memory.Readers is 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 := "addr"; 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_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)); ---------------------- -- 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; ---------------------- -- A memory allocation message is received. Register the memory -- slot in the allocated memory list. An event is posted on the -- event channel to notify the listeners that a new slot is allocated. ---------------------- procedure Process_Malloc_Message (Client : in out Memory_Servant; Addr : in MAT.Types.Target_Addr; Slot : in Allocation) is Inserted : Boolean; -- Ev : MAT.Memory.Events.Memory_Event := (Kind => EV_MALLOC, Addr => Addr); begin Client.Data.Memory_Slots.Insert (Addr, Slot); -- Post (Client.Event_Channel, Ev); end Process_Malloc_Message; ---------------------- -- A memory deallocation message. Find the memory slot being freed -- and remove it from the allocated list. Post an event on the event -- channel to notify the listeners that the slot is removed. ---------------------- procedure Process_Free_Message (Client : in out Memory_Servant; Addr : in MAT.Types.Target_Addr; Slot : in Allocation) is It : MAT.Memory.Allocation_Maps.Cursor := Client.Data.Memory_Slots.Find (Addr); -- Ev : Memory_Event := (Kind => EV_FREE, Addr => Addr); begin if MAT.Memory.Allocation_Maps.Has_Element (It) then -- Address is not in the map. The application is freeing -- an already freed memory or something wrong. null; end if; -- Post (Client.Event_Channel, Ev); declare Slot : Allocation := MAT.Memory.Allocation_Maps.Element (It); begin Frames.Release (Slot.Frame); end; -- Remove the memory slot from our map. Client.Data.Memory_Slots.Delete (It); end Process_Free_Message; ---------------------- -- 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_FRAME => -- Unmarshal_Frame (Msg, Slot.Frame); null; pragma Assert (False, "must fix M_FRAME"); when M_TIME => Slot.Time := MAT.Readers.Marshaller.Get_Target_Tick (Msg.Buffer, Def.Kind); when M_THREAD => Slot.Thread := MAT.Readers.Marshaller.Get_Target_Thread (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; Msg : in out MAT.Readers.Message) is Slot : Allocation; Addr : MAT.Types.Target_Addr; Old_Addr : MAT.Types.Target_Addr := 0; begin case Id is when MSG_MALLOC => Unmarshall_Allocation (Msg, Slot, Addr, Old_Addr, Params.all); Process_Malloc_Message (For_Servant, Addr, Slot); when MSG_FREE => Unmarshall_Allocation (Msg, Slot, Addr, Old_Addr, Params.all); Process_Free_Message (For_Servant, Addr, Slot); when MSG_REALLOC => Unmarshall_Allocation (Msg, Slot, Addr, Old_Addr, Params.all); Process_Malloc_Message (For_Servant, Addr, Slot); Process_Free_Message (For_Servant, Old_Addr, Slot); when others => raise Program_Error; end case; end Dispatch; end MAT.Memory.Readers;
Remove Bind and implement Register
Remove Bind and implement Register
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
dc04b0be6ef166b90401abf6453387d59e2119bf
src/util-commands.adb
src/util-commands.adb
----------------------------------------------------------------------- -- 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. ----------------------------------------------------------------------- with Ada.Command_Line; package body Util.Commands is -- ------------------------------ -- Get the number of arguments available. -- ------------------------------ overriding function Get_Count (List : in Default_Argument_List) return Natural is begin return Ada.Command_Line.Argument_Count - List.Offset; end Get_Count; -- ------------------------------ -- Get the argument at the given position. -- ------------------------------ overriding function Get_Argument (List : in Default_Argument_List; Pos : in Positive) return String is begin return Ada.Command_Line.Argument (Pos + List.Offset); end Get_Argument; -- ------------------------------ -- Get the command name. -- ------------------------------ function Get_Command_Name (List : in Default_Argument_List) return String is begin return Ada.Command_Line.Command_Name; end Get_Command_Name; 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. ----------------------------------------------------------------------- with Ada.Command_Line; package body Util.Commands is -- ------------------------------ -- Get the number of arguments available. -- ------------------------------ overriding function Get_Count (List : in Default_Argument_List) return Natural is Count : constant Natural := Ada.Command_Line.Argument_Count; begin if Count > List.Offset then return Count - List.Offset; else return 0; end if; end Get_Count; -- ------------------------------ -- Get the argument at the given position. -- ------------------------------ overriding function Get_Argument (List : in Default_Argument_List; Pos : in Positive) return String is begin return Ada.Command_Line.Argument (Pos + List.Offset); end Get_Argument; -- ------------------------------ -- Get the command name. -- ------------------------------ function Get_Command_Name (List : in Default_Argument_List) return String is begin return Ada.Command_Line.Command_Name; end Get_Command_Name; end Util.Commands;
Fix Get_Count operation
Fix Get_Count operation
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
5c9d7cf920d31d5b8a522c1e8e7e99c5e3bc4fab
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 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR 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. -- -- 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; -- ------------------------------ -- 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 := new Util.Encoders.Base64.Encoder; E.Decode := new Util.Encoders.Base64.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 Storage_Error; 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 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR 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. -- -- 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; -- ------------------------------ -- 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 := new Util.Encoders.Base64.Encoder; E.Decode := new Util.Encoders.Base64.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;
Raise the Not_Supported exception instead of Storage_Error if the encoder is not supported.
Raise the Not_Supported exception instead of Storage_Error if the encoder is not supported.
Ada
apache-2.0
flottokarotto/ada-util,Letractively/ada-util,flottokarotto/ada-util,Letractively/ada-util
c537fadbc307f4dce35af0ea62b66f8956eff656
src/el-methods-func_1.adb
src/el-methods-func_1.adb
----------------------------------------------------------------------- -- EL.Methods.Func_1 -- Function Bindings with 1 argument -- 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. ----------------------------------------------------------------------- package body EL.Methods.Func_1 is use EL.Expressions; -- ------------------------------ -- Returns True if the method is a valid method which accepts the arguments -- defined by the package instantiation. -- ------------------------------ function Is_Valid (Method : in EL.Expressions.Method_Info) return Boolean is begin if Method.Binding = null then return False; else return Method.Binding.all in Binding'Class; end if; end Is_Valid; -- ------------------------------ -- Execute the method describe by the method expression -- and with the given context. The method signature is: -- -- function F (Obj : <Bean>; Param : Param1_Type) return Return_Type; -- -- where <Bean> inherits from <b>Readonly_Bean</b> -- (See <b>Bind</b> package) -- -- Raises <b>Invalid_Method</b> if the method referenced by -- the method expression does not exist or does not match -- the signature. -- ------------------------------ function Execute (Method : in EL.Expressions.Method_Expression'Class; Param : in Param1_Type; Context : in EL.Contexts.ELContext'Class) return Return_Type is Info : constant Method_Info := Method.Get_Method_Info (Context); begin if Info.Binding = null then raise EL.Expressions.Invalid_Method with "Method not found"; end if; -- If the binding has the wrong type, we are trying to invoke -- a method with a different signature. if not (Info.Binding.all in Binding'Class) then raise EL.Expressions.Invalid_Method with "Invalid signature for method '" & Info.Binding.Name.all & "'"; end if; declare Proxy : constant Binding_Access := Binding (Info.Binding.all)'Access; begin return Proxy.Method (Info.Object.all, Param); end; end Execute; -- ------------------------------ -- Proxy for the binding. -- The proxy declares the binding definition that links -- the name to the function and it implements the necessary -- object conversion to translate the <b>Readonly_Bean</b> -- object to the target object type. -- ------------------------------ package body Bind is function Method_Access (O : Util.Beans.Basic.Readonly_Bean'Class; P1 : Param1_Type) return Return_Type is Object : constant Bean := Bean (O); Result : constant Return_Type := Method (Object, P1); begin return Result; end Method_Access; end Bind; end EL.Methods.Func_1;
----------------------------------------------------------------------- -- EL.Methods.Func_1 -- Function Bindings with 1 argument -- Copyright (C) 2010, 2011, 2012, 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.Beans.Objects; package body EL.Methods.Func_1 is use EL.Expressions; -- ------------------------------ -- Returns True if the method is a valid method which accepts the arguments -- defined by the package instantiation. -- ------------------------------ function Is_Valid (Method : in EL.Expressions.Method_Info) return Boolean is begin if Method.Binding = null then return False; else return Method.Binding.all in Binding'Class; end if; end Is_Valid; -- ------------------------------ -- Execute the method describe by the method expression -- and with the given context. The method signature is: -- -- function F (Obj : <Bean>; Param : Param1_Type) return Return_Type; -- -- where <Bean> inherits from <b>Readonly_Bean</b> -- (See <b>Bind</b> package) -- -- Raises <b>Invalid_Method</b> if the method referenced by -- the method expression does not exist or does not match -- the signature. -- ------------------------------ function Execute (Method : in EL.Expressions.Method_Expression'Class; Param : in Param1_Type; Context : in EL.Contexts.ELContext'Class) return Return_Type is Info : constant Method_Info := Method.Get_Method_Info (Context); begin if Info.Binding = null then raise EL.Expressions.Invalid_Method with "Method not found"; end if; -- If the binding has the wrong type, we are trying to invoke -- a method with a different signature. if not (Info.Binding.all in Binding'Class) then raise EL.Expressions.Invalid_Method with "Invalid signature for method '" & Info.Binding.Name.all & "'"; end if; declare use Util.Beans.Objects; Bean : constant access Util.Beans.Basic.Readonly_Bean'Class := To_Bean (Info.Object); Proxy : constant Binding_Access := Binding (Info.Binding.all)'Access; begin return Proxy.Method (Bean.all, Param); end; end Execute; -- ------------------------------ -- Proxy for the binding. -- The proxy declares the binding definition that links -- the name to the function and it implements the necessary -- object conversion to translate the <b>Readonly_Bean</b> -- object to the target object type. -- ------------------------------ package body Bind is function Method_Access (O : Util.Beans.Basic.Readonly_Bean'Class; P1 : Param1_Type) return Return_Type is Object : constant Bean := Bean (O); Result : constant Return_Type := Method (Object, P1); begin return Result; end Method_Access; end Bind; end EL.Methods.Func_1;
Update use of Method_Info record after change of type for the Object member
Update use of Method_Info record after change of type for the Object member
Ada
apache-2.0
stcarrez/ada-el
db99d17cda22f7583923000a2220eaaa903d52f2
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; package MAT.Frames is Not_Found : exception; type Frame is limited private; type Frame_Ptr is access all Frame; type PC_Table is array (Positive range <>) of Target_Addr; 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;
----------------------------------------------------------------------- -- 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;
Use the MAT.Events.Frame_Table type
Use the MAT.Events.Frame_Table type
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
d80dd950067f1de9f95ecebfe0c7dbaec2adf202
mat/src/mat-readers.ads
mat/src/mat-readers.ads
----------------------------------------------------------------------- -- mat-readers -- Reader -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Containers; with Ada.Containers.Hashed_Maps; with System; with Util.Properties; with MAT.Types; with MAT.Events; package MAT.Readers is type Buffer_Type is private; type Buffer_Ptr is access Buffer_Type; type Message is record Kind : MAT.Events.Event_Type; Size : Natural; Buf : Buffer_Ptr; end record; ----------------- -- Abstract servant definition ----------------- -- The Servant is a small proxy that binds the specific message -- handlers to the client specific dispatcher. type Reader_Base is abstract tagged limited private; type Reader_Access is access all Reader_Base'Class; procedure Dispatch (For_Servant : in out Reader_Base; Id : in MAT.Events.Internal_Reference; Msg : in out Message) is abstract; -- Dispatch the message procedure Bind (For_Servant : in out Reader_Base) is abstract; -- Bind the servant with the object adapter to register the -- events it recognizes. This is called once we have all the -- information about the structures of events that we can -- receive. ----------------- -- Ipc Client Manager ----------------- -- The Manager is a kind of object adapter. It registers a collection -- of servants and dispatches incomming messages to those servants. type Manager_Base is tagged limited private; type Manager is access all Manager_Base'Class; procedure Register_Servant (Adapter : in Manager; Proxy : in Reader_Access); -- Register the proxy servant in the object adapter. -- function Get_Manager (Refs : in ClientInfo_Ref_Map) return Manager; -- Return the object adapter manager which holds all the servant -- for the client. procedure Register_Message_Analyzer (Proxy : in Reader_Access; Name : in String; Id : in MAT.Events.Internal_Reference; Model : in MAT.Events.Attribute_Table; Table : out MAT.Events.Attribute_Table_Ptr); -- Setup the servant to receive and process messages identified -- by Name. procedure Dispatch_Message (Client : in out Manager_Base; Msg_Id : in MAT.Events.Internal_Reference; Msg : in out Message); private type Buffer_Type is record Current : System.Address; Start : System.Address; Last : System.Address; Size : Natural; Total : Natural; end record; type Reader_Base is abstract tagged limited record Owner : Manager := null; end record; -- Record a servant type Message_Handler is record For_Servant : Reader_Access; Id : MAT.Events.Internal_Reference; end record; function Hash (Key : in MAT.Events.Internal_Reference) return Ada.Containers.Hash_Type; use type MAT.Types.Uint32; -- Runtime handlers associated with the events. package Handler_Maps is new Ada.Containers.Hashed_Maps (Key_Type => MAT.Events.Internal_Reference, Element_Type => Message_Handler, Hash => Hash, Equivalent_Keys => "="); type Manager_Base is tagged limited record Handlers : Handler_Maps.Map; end record; end MAT.Readers;
----------------------------------------------------------------------- -- mat-readers -- Reader -- Copyright (C) 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Containers; with Ada.Containers.Hashed_Maps; with System; with Util.Properties; with MAT.Types; with MAT.Events; package MAT.Readers is type Buffer_Type is private; type Buffer_Ptr is access Buffer_Type; type Message is record Kind : MAT.Events.Event_Type; Size : Natural; Buffer : Buffer_Ptr; end record; ----------------- -- Abstract servant definition ----------------- -- The Servant is a small proxy that binds the specific message -- handlers to the client specific dispatcher. type Reader_Base is abstract tagged limited private; type Reader_Access is access all Reader_Base'Class; procedure Dispatch (For_Servant : in out Reader_Base; Id : in MAT.Events.Internal_Reference; Params : in MAT.Events.Const_Attribute_Table_Access; Msg : in out Message) is abstract; -- Dispatch the message procedure Bind (For_Servant : in out Reader_Base) is abstract; -- Bind the servant with the object adapter to register the -- events it recognizes. This is called once we have all the -- information about the structures of events that we can -- receive. ----------------- -- Ipc Client Manager ----------------- -- The Manager is a kind of object adapter. It registers a collection -- of servants and dispatches incomming messages to those servants. type Manager_Base is tagged limited private; type Manager is access all Manager_Base'Class; procedure Register_Servant (Adapter : in Manager; Proxy : in Reader_Access); -- Register the proxy servant in the object adapter. -- function Get_Manager (Refs : in ClientInfo_Ref_Map) return Manager; -- Return the object adapter manager which holds all the servant -- for the client. procedure Register_Message_Analyzer (Proxy : in Reader_Access; Name : in String; Id : in MAT.Events.Internal_Reference; Model : in MAT.Events.Attribute_Table; Table : out MAT.Events.Attribute_Table_Ptr); -- Setup the servant to receive and process messages identified -- by Name. procedure Dispatch_Message (Client : in out Manager_Base; Msg_Id : in MAT.Events.Internal_Reference; Msg : in out Message); private type Buffer_Type is record Current : System.Address; Start : System.Address; Last : System.Address; Size : Natural; Total : Natural; end record; type Reader_Base is abstract tagged limited record Owner : Manager := null; end record; -- Record a servant type Message_Handler is record For_Servant : Reader_Access; Id : MAT.Events.Internal_Reference; end record; function Hash (Key : in MAT.Events.Internal_Reference) return Ada.Containers.Hash_Type; use type MAT.Types.Uint32; -- Runtime handlers associated with the events. package Handler_Maps is new Ada.Containers.Hashed_Maps (Key_Type => MAT.Events.Internal_Reference, Element_Type => Message_Handler, Hash => Hash, Equivalent_Keys => "="); type Manager_Base is tagged limited record Handlers : Handler_Maps.Map; end record; end MAT.Readers;
Fix the Message and Dispatch definition
Fix the Message and Dispatch definition
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
e4c1c694231bc981e6505fc7e6a61c72bef8525f
mat/src/memory/mat-memory-tools.adb
mat/src/memory/mat-memory-tools.adb
----------------------------------------------------------------------- -- mat-memory-tools - Tools for memory maps -- 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.Memory.Tools is -- ------------------------------ -- Collect the information about memory slot sizes for the memory slots in the map. -- ------------------------------ procedure Size_Information (Memory : in MAT.Memory.Allocation_Map; Sizes : in out Size_Info_Map) is Iter : Allocation_Cursor := Memory.First; procedure Update_Count (Size : in MAT.Types.Target_Size; Info : in out Size_Info_Type) is begin Info.Count := Info.Count + 1; end Update_Count; procedure Collect (Addr : in MAT.Types.Target_Addr; Slot : in Allocation) is Pos : Size_Info_Cursor := Sizes.Find (Slot.Size); begin if Size_Info_Maps.Has_Element (Pos) then Sizes.Update_Element (Pos, Update_Count'Access); else declare Info : Size_Info_Type; begin Info.Count := 1; Sizes.Insert (Slot.Size, Info); end; end if; end Collect; begin while Allocation_Maps.Has_Element (Iter) loop Allocation_Maps.Query_Element (Iter, Collect'Access); Allocation_Maps.Next (Iter); end loop; end Size_Information; -- ------------------------------ -- Find from the <tt>Memory</tt> 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 (Memory : in MAT.Memory.Allocation_Map; From : in MAT.Types.Target_Addr; To : in MAT.Types.Target_Addr; Into : in out MAT.Memory.Allocation_Map) is Iter : MAT.Memory.Allocation_Cursor := Memory.Ceiling (From); Pos : MAT.Memory.Allocation_Cursor; begin while Allocation_Maps.Has_Element (Iter) loop declare Addr : constant MAT.Types.Target_Addr := Allocation_Maps.Key (Iter); begin exit when Addr > To; Pos := Into.Find (Addr); if not Allocation_Maps.Has_Element (Pos) then Into.Insert (Addr, Allocation_Maps.Element (Iter)); end if; end; Allocation_Maps.Next (Iter); end loop; end Find; end MAT.Memory.Tools;
----------------------------------------------------------------------- -- mat-memory-tools - Tools for memory maps -- 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.Memory.Tools is -- ------------------------------ -- Collect the information about memory slot sizes for the memory slots in the map. -- ------------------------------ procedure Size_Information (Memory : in MAT.Memory.Allocation_Map; Sizes : in out Size_Info_Map) is Iter : Allocation_Cursor := Memory.First; procedure Update_Count (Size : in MAT.Types.Target_Size; Info : in out Size_Info_Type) is begin Info.Count := Info.Count + 1; end Update_Count; procedure Collect (Addr : in MAT.Types.Target_Addr; Slot : in Allocation) is Pos : Size_Info_Cursor := Sizes.Find (Slot.Size); begin if Size_Info_Maps.Has_Element (Pos) then Sizes.Update_Element (Pos, Update_Count'Access); else declare Info : Size_Info_Type; begin Info.Count := 1; Sizes.Insert (Slot.Size, Info); end; end if; end Collect; begin while Allocation_Maps.Has_Element (Iter) loop Allocation_Maps.Query_Element (Iter, Collect'Access); Allocation_Maps.Next (Iter); end loop; end Size_Information; -- ------------------------------ -- Find from the <tt>Memory</tt> 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 (Memory : in MAT.Memory.Allocation_Map; From : in MAT.Types.Target_Addr; To : in MAT.Types.Target_Addr; Into : in out MAT.Memory.Allocation_Map) is Iter : MAT.Memory.Allocation_Cursor := Memory.Ceiling (From); Pos : MAT.Memory.Allocation_Cursor; Addr : MAT.Types.Target_Addr; Size : MAT.Types.Target_Size; begin -- If there was no slot with the ceiling From address, we have to start from the last -- node because the memory slot may intersect our region. if not Allocation_Maps.Has_Element (Iter) then Iter := Memory.Last; if not Allocation_Maps.Has_Element (Iter) then return; end if; Addr := Allocation_Maps.Key (Iter); Size := Allocation_Maps.Element (Iter).Size; if Addr + Size < From then return; end if; end if; -- Move backward until the previous memory slot does not overlap anymore our region. -- In theory, going backward once is enough but if there was a target malloc issue, -- several malloc may overlap the same region (which is bad for the target). loop Pos := Allocation_Maps.Previous (Iter); exit when not Allocation_Maps.Has_Element (Pos); Addr := Allocation_Maps.Key (Pos); Size := Allocation_Maps.Element (Pos).Size; exit when Addr + Size < From; Iter := Pos; end loop; -- Add the memory slots until we moved to the end of the region. while Allocation_Maps.Has_Element (Iter) loop Addr := Allocation_Maps.Key (Iter); exit when Addr > To; Pos := Into.Find (Addr); if not Allocation_Maps.Has_Element (Pos) then Into.Insert (Addr, Allocation_Maps.Element (Iter)); end if; Allocation_Maps.Next (Iter); end loop; end Find; end MAT.Memory.Tools;
Fix the Find procedure when the memory region overlaps the last or first memory slot
Fix the Find procedure when the memory region overlaps the last or first memory slot
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
b84789fb09b583837bb041474abb19bb2d20f4a0
awa/src/awa-modules-reader.adb
awa/src/awa-modules-reader.adb
----------------------------------------------------------------------- -- awa-modules-reader -- Read module configuration files -- 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.Serialize.IO.XML; with Util.Serialize.Mappers; with ASF.Applications.Main; with ASF.Navigations.Mappers; with ASF.Servlets.Mappers; with ASF.Beans.Mappers; -- The <b>AWA.Modules.Reader</b> package reads the module configuration files -- and initializes the module. package body AWA.Modules.Reader is -- ------------------------------ -- Read the module configuration file and configure the components -- ------------------------------ procedure Read_Configuration (Plugin : in out Module'Class; File : in String; Context : in EL.Contexts.ELContext_Access) is procedure Add_Mapper (Mapper : in Util.Serialize.Mappers.Mapper_Access); Reader : Util.Serialize.IO.XML.Parser; MBean : aliased ASF.Beans.Mappers.Managed_Bean; Navigation : aliased ASF.Navigations.Mappers.Nav_Config; Servlet : aliased ASF.Servlets.Mappers.Servlet_Config; procedure Add_Mapper (Mapper : in Util.Serialize.Mappers.Mapper_Access) is begin Reader.Add_Mapping ("faces-config", Mapper); Reader.Add_Mapping ("module", Mapper); Reader.Add_Mapping ("web-app", Mapper); end Add_Mapper; begin Log.Info ("Reading module configuration file {0}", File); Add_Mapper (ASF.Beans.Mappers.Get_Managed_Bean_Mapper); Add_Mapper (ASF.Navigations.Mappers.Get_Navigation_Mapper); Add_Mapper (ASF.Servlets.Mappers.Get_Servlet_Mapper); -- Setup the managed bean context to read the <managed-bean> elements. -- The ELContext is used for parsing EL expressions defined in property values. MBean.Factory := Plugin.Factory'Unchecked_Access; MBean.Context := Context; ASF.Beans.Mappers.Config_Mapper.Set_Context (Ctx => Reader, Element => MBean'Unchecked_Access); -- Setup the navigation context to read the <navigation-rule> elements. Navigation.Handler := Plugin.App.Get_Navigation_Handler; ASF.Navigations.Mappers.Case_Mapper.Set_Context (Ctx => Reader, Element => Navigation'Unchecked_Access); Servlet.Handler := Plugin.App.all'Unchecked_Access; ASF.Servlets.Mappers.Servlet_Mapper.Set_Context (Ctx => Reader, Element => Servlet'Unchecked_Access); Util.Serialize.IO.Dump (Reader, AWA.Modules.Log); -- Read the configuration file and record managed beans, navigation rules. Reader.Parse (File); end Read_Configuration; end AWA.Modules.Reader;
----------------------------------------------------------------------- -- awa-modules-reader -- Read module configuration files -- 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.Serialize.IO.XML; with ASF.Applications.Main; with ASF.Navigations.Mappers; with ASF.Servlets.Mappers; with ASF.Beans.Mappers; -- The <b>AWA.Modules.Reader</b> package reads the module configuration files -- and initializes the module. package body AWA.Modules.Reader is -- ------------------------------ -- Read the module configuration file and configure the components -- ------------------------------ procedure Read_Configuration (Plugin : in out Module'Class; File : in String; Context : in EL.Contexts.ELContext_Access) is Reader : Util.Serialize.IO.XML.Parser; Nav : constant ASF.Navigations.Navigation_Handler_Access := Plugin.App.Get_Navigation_Handler; package Bean_Config is new ASF.Beans.Mappers.Reader_Config (Reader, Plugin.Factory'Unchecked_Access, Context); package Navigation_Config is new ASF.Navigations.Mappers.Reader_Config (Reader, Nav); package Servlet_Config is new ASF.Servlets.Mappers.Reader_Config (Reader, Plugin.App.all'Unchecked_Access); pragma Warnings (Off, Bean_Config); pragma Warnings (Off, Navigation_Config); pragma Warnings (Off, Servlet_Config); begin Log.Info ("Reading module configuration file {0}", File); Util.Serialize.IO.Dump (Reader, AWA.Modules.Log); -- Read the configuration file and record managed beans, navigation rules. Reader.Parse (File); end Read_Configuration; end AWA.Modules.Reader;
Update Read_Configuration to use the new XXX_Config generic packages.
Update Read_Configuration to use the new XXX_Config generic packages.
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
a2ee59272fad7ac28d8224e3ae7de731cf39af2d
src/gen-model-projects.ads
src/gen-model-projects.ads
----------------------------------------------------------------------- -- gen-model-projects -- Projects meta data -- Copyright (C) 2011, 2012, 2013, 2014, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Ada.Containers.Vectors; with Util.Beans.Objects; with Util.Properties; with Gen.Utils; with Gen.Utils.GNAT; package Gen.Model.Projects is use Ada.Strings.Unbounded; type Project_Definition; type Project_Definition_Access is access all Project_Definition'Class; type Dependency_Type is (NONE, DIRECT, INDIRECT, BOTH); type Project_Reference is record Project : Project_Definition_Access := null; Name : Unbounded_String; Kind : Dependency_Type := NONE; end record; package Project_Vectors is new Ada.Containers.Vectors (Element_Type => Project_Reference, Index_Type => Natural); -- ------------------------------ -- Project Definition -- ------------------------------ type Project_Definition is new Definition with record Path : Unbounded_String; Props : Util.Properties.Manager; Modules : Project_Vectors.Vector; -- The root project definition. Root : Project_Definition_Access := null; -- The list of plugin names that this plugin or project depends on. Dependencies : Project_Vectors.Vector; -- The list of GNAT project files used by the project. Project_Files : Gen.Utils.GNAT.Project_Info_Vectors.Vector; -- The list of 'dynamo.xml' files used by the project (gathered from GNAT files -- and by scanning the 'plugins' directory). Dynamo_Files : Gen.Utils.String_List.Vector; -- Whether we did a recursive scan of GNAT project files. Recursive_Scan : Boolean := False; -- Whether we are doing a recursive operation on the project (prevent from cycles). Recursing : Boolean := False; -- Whether we did a recursive scan of Dynamo dependencies. Depend_Scan : Boolean := False; -- Whether this project is a plugin. Is_Plugin : Boolean := False; end record; -- Get the value identified by the name. -- If the name cannot be found, the method should return the Null object. overriding function Get_Value (From : Project_Definition; Name : String) return Util.Beans.Objects.Object; -- Get the project name. function Get_Project_Name (Project : in Project_Definition) return String; -- Get the GNAT project file name. The default is to use the Dynamo project -- name and add the <b>.gpr</b> extension. The <b>gnat_project</b> configuration -- property allows to override this default. function Get_GNAT_Project_Name (Project : in Project_Definition) return String; -- Get the directory path which holds application modules. -- This is controlled by the <b>modules_dir</b> configuration property. -- The default is <tt>plugins</tt>. -- ------------------------------ function Get_Module_Dir (Project : in Project_Definition) return String; -- Find the dependency for the <b>Name</b> plugin. -- Returns a null dependency if the project does not depend on that plugin. function Find_Dependency (From : in Project_Definition; Name : in String) return Project_Reference; -- Add a dependency to the plugin identified by <b>Name</b>. procedure Add_Dependency (Into : in out Project_Definition; Name : in String; Kind : in Dependency_Type); -- Add a dependency to the plugin identified by <b>Project</b>. procedure Add_Dependency (Into : in out Project_Definition; Project : in Project_Definition_Access; Kind : in Dependency_Type); -- Create a project definition instance to record a project with the dynamo XML file path. procedure Create_Project (Into : in out Project_Definition; Name : in String; Path : in String; Project : out Project_Definition_Access); -- Add the project in the global project list on the root project instance. procedure Add_Project (Into : in out Project_Definition; Project : in Project_Definition_Access); -- Add the project <b>Name</b> as a module. procedure Add_Module (Into : in out Project_Definition; Name : in String); -- Add the project represented by <b>Project</b> if it is not already part of the modules. procedure Add_Module (Into : in out Project_Definition; Project : in Project_Definition_Access); -- Find the project definition associated with the dynamo XML file <b>Path</b>. -- Returns null if there is no such project function Find_Project (From : in Project_Definition; Path : in String) return Project_Definition_Access; -- Find the project definition having the name <b>Name</b>. -- Returns null if there is no such project function Find_Project_By_Name (From : in Project_Definition; Name : in String) return Project_Definition_Access; -- Save the project description and parameters. procedure Save (Project : in out Project_Definition; Path : in String); -- Read the XML project description into the project description. procedure Read_Project (Project : in out Project_Definition); -- Scan and read the possible modules used by the application. Modules are stored in the -- <b>modules</b> directory. Each module is stored in its own directory and has its own -- <b>dynamo.xml</b> file. procedure Read_Modules (Project : in out Project_Definition); -- ------------------------------ -- Root Project Definition -- ------------------------------ -- The root project is the project that is actually read by Dynamo. -- It contains the lists of all projects that are necessary and which are found either -- by scanning GNAT projects or by looking at plugin dependencies. type Root_Project_Definition is new Project_Definition with record Projects : Project_Vectors.Vector; Install_Dir : Unbounded_String; end record; -- Add the project in the global project list on the root project instance. overriding procedure Add_Project (Into : in out Root_Project_Definition; Project : in Project_Definition_Access); -- Find the project definition having the name <b>Name</b>. -- Returns null if there is no such project overriding function Find_Project_By_Name (From : in Root_Project_Definition; Name : in String) return Project_Definition_Access; -- Find the project definition associated with the dynamo XML file <b>Path</b>. -- Returns null if there is no such project overriding function Find_Project (From : in Root_Project_Definition; Path : in String) return Project_Definition_Access; -- Read the XML project file. When <b>Recursive</b> is set, read the GNAT project -- files used by the main project and load all the <b>dynamo.xml</b> files defined -- by these project. procedure Read_Project (Project : in out Root_Project_Definition; File : in String; Config : in Util.Properties.Manager'Class; Recursive : in Boolean := False); private -- Update the project references after a project is found and initialized. procedure Update_References (Root : in out Root_Project_Definition; Project : in Project_Definition_Access); -- Iterate over the project referenced in the list and execute the <b>Process</b> procedure. procedure Iterate (List : in out Project_Vectors.Vector; Process : access procedure (Item : in out Project_Reference)); -- Find a project from the list function Find_Project (List : in Project_Vectors.Vector; Name : in String) return Project_Reference; end Gen.Model.Projects;
----------------------------------------------------------------------- -- gen-model-projects -- Projects meta data -- Copyright (C) 2011, 2012, 2013, 2014, 2017, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Ada.Containers.Vectors; with Util.Beans.Objects; with Util.Properties; with Gen.Utils; with Gen.Utils.GNAT; package Gen.Model.Projects is use Ada.Strings.Unbounded; type Project_Definition; type Project_Definition_Access is access all Project_Definition'Class; type Dependency_Type is (NONE, DIRECT, INDIRECT, BOTH); type Project_Reference is record Project : Project_Definition_Access := null; Name : Unbounded_String; Kind : Dependency_Type := NONE; end record; package Project_Vectors is new Ada.Containers.Vectors (Element_Type => Project_Reference, Index_Type => Natural); -- ------------------------------ -- Project Definition -- ------------------------------ type Project_Definition is new Definition with record Path : Unbounded_String; Props : Util.Properties.Manager; Modules : Project_Vectors.Vector; -- The root project definition. Root : Project_Definition_Access := null; -- The list of plugin names that this plugin or project depends on. Dependencies : Project_Vectors.Vector; -- The list of GNAT project files used by the project. Project_Files : Gen.Utils.GNAT.Project_Info_Vectors.Vector; -- The list of 'dynamo.xml' files used by the project (gathered from GNAT files -- and by scanning the 'plugins' directory). Dynamo_Files : Gen.Utils.String_List.Vector; -- Whether we did a recursive scan of GNAT project files. Recursive_Scan : Boolean := False; -- Whether we are doing a recursive operation on the project (prevent from cycles). Recursing : Boolean := False; -- Whether we did a recursive scan of Dynamo dependencies. Depend_Scan : Boolean := False; -- Whether this project is a plugin. Is_Plugin : Boolean := False; end record; -- Get the value identified by the name. -- If the name cannot be found, the method should return the Null object. overriding function Get_Value (From : Project_Definition; Name : String) return Util.Beans.Objects.Object; -- Get the project name. function Get_Project_Name (Project : in Project_Definition) return String; -- Get the GNAT project file name. The default is to use the Dynamo project -- name and add the <b>.gpr</b> extension. The <b>gnat_project</b> configuration -- property allows to override this default. function Get_GNAT_Project_Name (Project : in Project_Definition) return String; -- Get the directory path which holds application modules. -- This is controlled by the <b>modules_dir</b> configuration property. -- The default is <tt>plugins</tt>. -- ------------------------------ function Get_Module_Dir (Project : in Project_Definition) return String; -- Find the dependency for the <b>Name</b> plugin. -- Returns a null dependency if the project does not depend on that plugin. function Find_Dependency (From : in Project_Definition; Name : in String) return Project_Reference; -- Add a dependency to the plugin identified by <b>Name</b>. procedure Add_Dependency (Into : in out Project_Definition; Name : in String; Kind : in Dependency_Type); -- Add a dependency to the plugin identified by <b>Project</b>. procedure Add_Dependency (Into : in out Project_Definition; Project : in Project_Definition_Access; Kind : in Dependency_Type); -- Create a project definition instance to record a project with the dynamo XML file path. procedure Create_Project (Into : in out Project_Definition; Name : in String; Path : in String; Project : out Project_Definition_Access); -- Add the project in the global project list on the root project instance. procedure Add_Project (Into : in out Project_Definition; Project : in Project_Definition_Access); -- Add the project <b>Name</b> as a module. procedure Add_Module (Into : in out Project_Definition; Name : in String); -- Add the project represented by <b>Project</b> if it is not already part of the modules. procedure Add_Module (Into : in out Project_Definition; Project : in Project_Definition_Access); -- Find the project definition associated with the dynamo XML file <b>Path</b>. -- Returns null if there is no such project function Find_Project (From : in Project_Definition; Path : in String) return Project_Definition_Access; -- Find the project definition having the name <b>Name</b>. -- Returns null if there is no such project function Find_Project_By_Name (From : in Project_Definition; Name : in String) return Project_Definition_Access; -- Save the project description and parameters. procedure Save (Project : in out Project_Definition; Path : in String); -- Read the XML project description into the project description. procedure Read_Project (Project : in out Project_Definition); -- Scan and read the possible modules used by the application. Modules are stored in the -- <b>modules</b> directory. Each module is stored in its own directory and has its own -- <b>dynamo.xml</b> file. procedure Read_Modules (Project : in out Project_Definition); -- Update the project definition from the properties. procedure Update_From_Properties (Project : in out Project_Definition); -- ------------------------------ -- Root Project Definition -- ------------------------------ -- The root project is the project that is actually read by Dynamo. -- It contains the lists of all projects that are necessary and which are found either -- by scanning GNAT projects or by looking at plugin dependencies. type Root_Project_Definition is new Project_Definition with record Projects : Project_Vectors.Vector; Install_Dir : Unbounded_String; end record; -- Add the project in the global project list on the root project instance. overriding procedure Add_Project (Into : in out Root_Project_Definition; Project : in Project_Definition_Access); -- Find the project definition having the name <b>Name</b>. -- Returns null if there is no such project overriding function Find_Project_By_Name (From : in Root_Project_Definition; Name : in String) return Project_Definition_Access; -- Find the project definition associated with the dynamo XML file <b>Path</b>. -- Returns null if there is no such project overriding function Find_Project (From : in Root_Project_Definition; Path : in String) return Project_Definition_Access; -- Read the XML project file. When <b>Recursive</b> is set, read the GNAT project -- files used by the main project and load all the <b>dynamo.xml</b> files defined -- by these project. procedure Read_Project (Project : in out Root_Project_Definition; File : in String; Config : in Util.Properties.Manager'Class; Recursive : in Boolean := False); private -- Update the project references after a project is found and initialized. procedure Update_References (Root : in out Root_Project_Definition; Project : in Project_Definition_Access); -- Iterate over the project referenced in the list and execute the <b>Process</b> procedure. procedure Iterate (List : in out Project_Vectors.Vector; Process : access procedure (Item : in out Project_Reference)); -- Find a project from the list function Find_Project (List : in Project_Vectors.Vector; Name : in String) return Project_Reference; end Gen.Model.Projects;
Declare the Update_From_Properties procedure
Declare the Update_From_Properties procedure
Ada
apache-2.0
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
6b530f7e83db89934cf6e60e1a255400bde00ae8
src/wiki-render-text.adb
src/wiki-render-text.adb
----------------------------------------------------------------------- -- wiki-render-text -- Wiki Text renderer -- Copyright (C) 2011, 2012, 2013, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Characters.Conversions; with Wiki.Helpers; package body Wiki.Render.Text is -- ------------------------------ -- Set the output writer. -- ------------------------------ procedure Set_Output_Stream (Engine : in out Text_Renderer; Stream : in Streams.Output_Stream_Access) is begin Engine.Output := Stream; end Set_Output_Stream; -- ------------------------------ -- Emit a new line. -- ------------------------------ procedure New_Line (Document : in out Text_Renderer) is begin Document.Output.Write (Wiki.Helpers.LF); Document.Empty_Line := True; end New_Line; -- ------------------------------ -- Add a line break (<br>). -- ------------------------------ procedure Add_Line_Break (Document : in out Text_Renderer) is begin Document.Output.Write (Wiki.Helpers.LF); Document.Empty_Line := True; end Add_Line_Break; -- ------------------------------ -- Render a blockquote (<blockquote>). The level indicates the blockquote nested level. -- The blockquote must be closed at the next header. -- ------------------------------ procedure Render_Blockquote (Engine : in out Text_Renderer; Level : in Natural) is begin Engine.Close_Paragraph; for I in 1 .. Level loop Engine.Output.Write (" "); end loop; end Render_Blockquote; -- ------------------------------ -- Render a list item (<li>). Close the previous paragraph and list item if any. -- The list item will be closed at the next list item, next paragraph or next header. -- ------------------------------ procedure Render_List_Item (Engine : in out Text_Renderer; Level : in Positive; Ordered : in Boolean) is pragma Unreferenced (Level, Ordered); begin if not Engine.Empty_Line then Engine.Add_Line_Break; end if; Engine.Need_Paragraph := False; Engine.Open_Paragraph; end Render_List_Item; procedure Close_Paragraph (Document : in out Text_Renderer) is begin if Document.Has_Paragraph then Document.Add_Line_Break; end if; Document.Has_Paragraph := False; end Close_Paragraph; procedure Open_Paragraph (Document : in out Text_Renderer) is begin if Document.Need_Paragraph then Document.Has_Paragraph := True; Document.Need_Paragraph := False; end if; end Open_Paragraph; -- ------------------------------ -- Add a link. -- ------------------------------ procedure Add_Link (Document : in out Text_Renderer; Title : in Wiki.Strings.WString; Attr : in Wiki.Attributes.Attribute_List) is begin Document.Open_Paragraph; if Title'Length /= 0 then Document.Output.Write (Title); end if; Document.Empty_Line := False; end Add_Link; -- ------------------------------ -- Add an image. -- ------------------------------ procedure Add_Image (Document : in out Text_Renderer; Link : in Unbounded_Wide_Wide_String; Alt : in Unbounded_Wide_Wide_String; Position : in Unbounded_Wide_Wide_String; Description : in Unbounded_Wide_Wide_String) is pragma Unreferenced (Position); begin Document.Open_Paragraph; -- if Length (Alt) > 0 then -- Document.Output.Write (Alt); -- end if; -- if Length (Description) > 0 then -- Document.Output.Write (Description); -- end if; -- Document.Output.Write (Link); Document.Empty_Line := False; end Add_Image; -- ------------------------------ -- Render a text block that is pre-formatted. -- ------------------------------ procedure Render_Preformatted (Engine : in out Text_Renderer; Text : in Wiki.Strings.WString; Format : in Wiki.Strings.WString) is pragma Unreferenced (Format); begin Engine.Close_Paragraph; Engine.Output.Write (Text); Engine.Empty_Line := False; end Render_Preformatted; -- Render the node instance from the document. overriding procedure Render (Engine : in out Text_Renderer; Doc : in Wiki.Documents.Document; Node : in Wiki.Nodes.Node_Type) is use type Wiki.Html_Tag; use type Wiki.Nodes.Node_List_Access; begin case Node.Kind is when Wiki.Nodes.N_HEADER => Engine.Close_Paragraph; if not Engine.Empty_Line then Engine.Add_Line_Break; end if; Engine.Output.Write (Node.Header); Engine.Add_Line_Break; when Wiki.Nodes.N_LINE_BREAK => Engine.Add_Line_Break; when Wiki.Nodes.N_HORIZONTAL_RULE => Engine.Close_Paragraph; Engine.Output.Write ("---------------------------------------------------------"); Engine.Add_Line_Break; when Wiki.Nodes.N_PARAGRAPH => Engine.Close_Paragraph; Engine.Need_Paragraph := True; Engine.Add_Line_Break; when Wiki.Nodes.N_INDENT => Engine.Indent_Level := Node.Level; when Wiki.Nodes.N_BLOCKQUOTE => Engine.Render_Blockquote (Node.Level); when Wiki.Nodes.N_LIST => Engine.Render_List_Item (Node.Level, False); when Wiki.Nodes.N_NUM_LIST => Engine.Render_List_Item (Node.Level, True); when Wiki.Nodes.N_TEXT => if Engine.Empty_Line and Engine.Indent_Level /= 0 then for I in 1 .. Engine.Indent_Level loop Engine.Output.Write (' '); end loop; end if; Engine.Output.Write (Node.Text); Engine.Empty_Line := False; when Wiki.Nodes.N_QUOTE => Engine.Open_Paragraph; Engine.Output.Write (Node.Title); Engine.Empty_Line := False; when Wiki.Nodes.N_LINK => Engine.Add_Link (Node.Title, Node.Link_Attr); when Wiki.Nodes.N_PREFORMAT => Engine.Render_Preformatted (Node.Preformatted, ""); when Wiki.Nodes.N_TAG_START => if Node.Children /= null then if Node.Tag_Start = Wiki.DT_TAG then Engine.Close_Paragraph; Engine.Indent_Level := 0; Engine.Render (Doc, Node.Children); Engine.Close_Paragraph; Engine.Indent_Level := 0; elsif Node.Tag_Start = Wiki.DD_TAG then Engine.Close_Paragraph; Engine.Empty_Line := True; Engine.Indent_Level := 4; Engine.Render (Doc, Node.Children); Engine.Close_Paragraph; Engine.Indent_Level := 0; else Engine.Render (Doc, Node.Children); if Node.Tag_Start = Wiki.DL_TAG then Engine.Close_Paragraph; Engine.New_Line; end if; end if; end if; when others => null; end case; end Render; -- ------------------------------ -- Finish the document after complete wiki text has been parsed. -- ------------------------------ overriding procedure Finish (Document : in out Text_Renderer) is begin Document.Close_Paragraph; end Finish; end Wiki.Render.Text;
----------------------------------------------------------------------- -- wiki-render-text -- Wiki Text renderer -- Copyright (C) 2011, 2012, 2013, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Characters.Conversions; with Wiki.Helpers; package body Wiki.Render.Text is -- ------------------------------ -- Set the output writer. -- ------------------------------ procedure Set_Output_Stream (Engine : in out Text_Renderer; Stream : in Streams.Output_Stream_Access) is begin Engine.Output := Stream; end Set_Output_Stream; -- ------------------------------ -- Emit a new line. -- ------------------------------ procedure New_Line (Document : in out Text_Renderer) is begin Document.Output.Write (Wiki.Helpers.LF); Document.Empty_Line := True; end New_Line; -- ------------------------------ -- Add a line break (<br>). -- ------------------------------ procedure Add_Line_Break (Document : in out Text_Renderer) is begin Document.Output.Write (Wiki.Helpers.LF); Document.Empty_Line := True; end Add_Line_Break; -- ------------------------------ -- Render a blockquote (<blockquote>). The level indicates the blockquote nested level. -- The blockquote must be closed at the next header. -- ------------------------------ procedure Render_Blockquote (Engine : in out Text_Renderer; Level : in Natural) is begin Engine.Close_Paragraph; for I in 1 .. Level loop Engine.Output.Write (" "); end loop; end Render_Blockquote; -- ------------------------------ -- Render a list item (<li>). Close the previous paragraph and list item if any. -- The list item will be closed at the next list item, next paragraph or next header. -- ------------------------------ procedure Render_List_Item (Engine : in out Text_Renderer; Level : in Positive; Ordered : in Boolean) is pragma Unreferenced (Level, Ordered); begin if not Engine.Empty_Line then Engine.Add_Line_Break; end if; Engine.Need_Paragraph := False; Engine.Open_Paragraph; end Render_List_Item; procedure Close_Paragraph (Document : in out Text_Renderer) is begin if Document.Has_Paragraph then Document.Add_Line_Break; end if; Document.Has_Paragraph := False; end Close_Paragraph; procedure Open_Paragraph (Document : in out Text_Renderer) is begin if Document.Need_Paragraph then Document.Has_Paragraph := True; Document.Need_Paragraph := False; end if; end Open_Paragraph; -- ------------------------------ -- Add a link. -- ------------------------------ procedure Add_Link (Document : in out Text_Renderer; Title : in Wiki.Strings.WString; Attr : in Wiki.Attributes.Attribute_List) is begin Document.Open_Paragraph; if Title'Length /= 0 then Document.Output.Write (Title); end if; Document.Empty_Line := False; end Add_Link; -- ------------------------------ -- Add an image. -- ------------------------------ procedure Add_Image (Document : in out Text_Renderer; Link : in Unbounded_Wide_Wide_String; Alt : in Unbounded_Wide_Wide_String; Position : in Unbounded_Wide_Wide_String; Description : in Unbounded_Wide_Wide_String) is pragma Unreferenced (Position); begin Document.Open_Paragraph; -- if Length (Alt) > 0 then -- Document.Output.Write (Alt); -- end if; -- if Length (Description) > 0 then -- Document.Output.Write (Description); -- end if; -- Document.Output.Write (Link); Document.Empty_Line := False; end Add_Image; -- ------------------------------ -- Render a text block that is pre-formatted. -- ------------------------------ procedure Render_Preformatted (Engine : in out Text_Renderer; Text : in Wiki.Strings.WString; Format : in Wiki.Strings.WString) is pragma Unreferenced (Format); begin Engine.Close_Paragraph; Engine.Output.Write (Text); Engine.Empty_Line := False; end Render_Preformatted; -- Render the node instance from the document. overriding procedure Render (Engine : in out Text_Renderer; Doc : in Wiki.Documents.Document; Node : in Wiki.Nodes.Node_Type) is use type Wiki.Html_Tag; use type Wiki.Nodes.Node_List_Access; begin case Node.Kind is when Wiki.Nodes.N_HEADER => Engine.Close_Paragraph; if not Engine.Empty_Line then Engine.Add_Line_Break; end if; Engine.Output.Write (Node.Header); Engine.Add_Line_Break; when Wiki.Nodes.N_LINE_BREAK => Engine.Add_Line_Break; when Wiki.Nodes.N_HORIZONTAL_RULE => Engine.Close_Paragraph; Engine.Output.Write ("---------------------------------------------------------"); Engine.Add_Line_Break; when Wiki.Nodes.N_PARAGRAPH => Engine.Close_Paragraph; Engine.Need_Paragraph := True; Engine.Add_Line_Break; when Wiki.Nodes.N_INDENT => Engine.Indent_Level := Node.Level; when Wiki.Nodes.N_BLOCKQUOTE => Engine.Render_Blockquote (Node.Level); when Wiki.Nodes.N_LIST => Engine.Render_List_Item (Node.Level, False); when Wiki.Nodes.N_NUM_LIST => Engine.Render_List_Item (Node.Level, True); when Wiki.Nodes.N_TEXT => if Engine.Empty_Line and Engine.Indent_Level /= 0 then for I in 1 .. Engine.Indent_Level loop Engine.Output.Write (' '); end loop; end if; Engine.Output.Write (Node.Text); Engine.Empty_Line := False; when Wiki.Nodes.N_QUOTE => Engine.Open_Paragraph; Engine.Output.Write (Node.Title); Engine.Empty_Line := False; when Wiki.Nodes.N_LINK => Engine.Add_Link (Node.Title, Node.Link_Attr); when Wiki.Nodes.N_PREFORMAT => Engine.Render_Preformatted (Node.Preformatted, ""); when Wiki.Nodes.N_TAG_START => if Node.Children /= null then if Node.Tag_Start = Wiki.DT_TAG then Engine.Close_Paragraph; Engine.Indent_Level := 0; Engine.Render (Doc, Node.Children); Engine.Close_Paragraph; Engine.Indent_Level := 0; elsif Node.Tag_Start = Wiki.DD_TAG then Engine.Close_Paragraph; Engine.Empty_Line := True; Engine.Indent_Level := 4; Engine.Render (Doc, Node.Children); Engine.Close_Paragraph; Engine.Indent_Level := 0; else Engine.Render (Doc, Node.Children); if Node.Tag_Start = Wiki.DL_TAG then Engine.Close_Paragraph; Engine.New_Line; end if; end if; end if; when others => null; end case; end Render; -- ------------------------------ -- Finish the document after complete wiki text has been parsed. -- ------------------------------ overriding procedure Finish (Engine : in out Text_Renderer; Doc : in Wiki.Documents.Document) is begin Engine.Close_Paragraph; end Finish; end Wiki.Render.Text;
Add the document to the Finish procedure
Add the document to the Finish procedure
Ada
apache-2.0
stcarrez/ada-wiki,stcarrez/ada-wiki
adb159264080fd1e497cbc4f3ab6272ecace21d1
src/gen-model-projects.ads
src/gen-model-projects.ads
----------------------------------------------------------------------- -- gen-model-projects -- Projects meta data -- Copyright (C) 2011, 2012, 2013, 2014, 2017, 2018, 2021 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Containers.Vectors; with Util.Properties; with Gen.Utils; with Gen.Utils.GNAT; package Gen.Model.Projects is type Project_Definition is tagged; type Project_Definition_Access is access all Project_Definition'Class; type Dependency_Type is (NONE, DIRECT, INDIRECT, BOTH); type Project_Reference is record Project : Project_Definition_Access := null; Name : UString; Kind : Dependency_Type := NONE; end record; package Project_Vectors is new Ada.Containers.Vectors (Element_Type => Project_Reference, Index_Type => Natural); -- ------------------------------ -- Project Definition -- ------------------------------ type Project_Definition is new Definition with record Path : UString; Props : Util.Properties.Manager; Modules : Project_Vectors.Vector; -- The root project definition. Root : Project_Definition_Access := null; -- The list of plugin names that this plugin or project depends on. Dependencies : Project_Vectors.Vector; -- The list of GNAT project files used by the project. Project_Files : Gen.Utils.GNAT.Project_Info_Vectors.Vector; -- The list of 'dynamo.xml' files used by the project (gathered from GNAT files -- and by scanning the 'plugins' directory). Dynamo_Files : Gen.Utils.String_List.Vector; -- Whether we did a recursive scan of GNAT project files. Recursive_Scan : Boolean := False; -- Whether we are doing a recursive operation on the project (prevent from cycles). Recursing : Boolean := False; -- Whether we did a recursive scan of Dynamo dependencies. Depend_Scan : Boolean := False; -- Whether this project is a plugin. Is_Plugin : Boolean := False; -- Whether the project needs the generation for the different databases Use_Mysql : Boolean := True; Use_Sqlite : Boolean := True; Use_Postgresql : Boolean := True; end record; -- Get the value identified by the name. -- If the name cannot be found, the method should return the Null object. overriding function Get_Value (From : Project_Definition; Name : String) return UBO.Object; -- Get the project name. function Get_Project_Name (Project : in Project_Definition) return String; -- Get the GNAT project file name. The default is to use the Dynamo project -- name and add the <b>.gpr</b> extension. The <b>gnat_project</b> configuration -- property allows to override this default. function Get_GNAT_Project_Name (Project : in Project_Definition) return String; -- Get the directory path which holds application modules. -- This is controlled by the <b>modules_dir</b> configuration property. -- The default is <tt>plugins</tt>. -- ------------------------------ function Get_Module_Dir (Project : in Project_Definition) return String; -- Find the dependency for the <b>Name</b> plugin. -- Returns a null dependency if the project does not depend on that plugin. function Find_Dependency (From : in Project_Definition; Name : in String) return Project_Reference; -- Add a dependency to the plugin identified by <b>Name</b>. procedure Add_Dependency (Into : in out Project_Definition; Name : in String; Kind : in Dependency_Type); -- Add a dependency to the plugin identified by <b>Project</b>. procedure Add_Dependency (Into : in out Project_Definition; Project : in Project_Definition_Access; Kind : in Dependency_Type); -- Create a project definition instance to record a project with the dynamo XML file path. procedure Create_Project (Into : in out Project_Definition; Name : in String; Path : in String; Project : out Project_Definition_Access); -- Add the project in the global project list on the root project instance. procedure Add_Project (Into : in out Project_Definition; Project : in Project_Definition_Access); -- Add the project <b>Name</b> as a module. procedure Add_Module (Into : in out Project_Definition; Name : in String); -- Add the project represented by <b>Project</b> if it is not already part of the modules. procedure Add_Module (Into : in out Project_Definition; Project : in Project_Definition_Access); -- Find the project definition associated with the dynamo XML file <b>Path</b>. -- Returns null if there is no such project function Find_Project (From : in Project_Definition; Path : in String) return Project_Definition_Access; -- Find the project definition having the name <b>Name</b>. -- Returns null if there is no such project function Find_Project_By_Name (From : in Project_Definition; Name : in String) return Project_Definition_Access; -- Save the project description and parameters. procedure Save (Project : in out Project_Definition; Path : in String); -- Read the XML project description into the project description. procedure Read_Project (Project : in out Project_Definition); -- Scan and read the possible modules used by the application. Modules are stored in the -- <b>modules</b> directory. Each module is stored in its own directory and has its own -- <b>dynamo.xml</b> file. procedure Read_Modules (Project : in out Project_Definition); -- Update the project definition from the properties. procedure Update_From_Properties (Project : in out Project_Definition); -- ------------------------------ -- Root Project Definition -- ------------------------------ -- The root project is the project that is actually read by Dynamo. -- It contains the lists of all projects that are necessary and which are found either -- by scanning GNAT projects or by looking at plugin dependencies. type Root_Project_Definition is new Project_Definition with record Projects : Project_Vectors.Vector; Install_Dir : UString; end record; -- Add the project in the global project list on the root project instance. overriding procedure Add_Project (Into : in out Root_Project_Definition; Project : in Project_Definition_Access); -- Find the project definition having the name <b>Name</b>. -- Returns null if there is no such project overriding function Find_Project_By_Name (From : in Root_Project_Definition; Name : in String) return Project_Definition_Access; -- Find the project definition associated with the dynamo XML file <b>Path</b>. -- Returns null if there is no such project overriding function Find_Project (From : in Root_Project_Definition; Path : in String) return Project_Definition_Access; -- Read the XML project file. When <b>Recursive</b> is set, read the GNAT project -- files used by the main project and load all the <b>dynamo.xml</b> files defined -- by these project. procedure Read_Project (Project : in out Root_Project_Definition; File : in String; Config : in Util.Properties.Manager'Class; Recursive : in Boolean := False); private -- Update the project references after a project is found and initialized. procedure Update_References (Root : in out Root_Project_Definition; Project : in Project_Definition_Access); -- Iterate over the project referenced in the list and execute the <b>Process</b> procedure. procedure Iterate (List : in out Project_Vectors.Vector; Process : access procedure (Item : in out Project_Reference)); -- Find a project from the list function Find_Project (List : in Project_Vectors.Vector; Name : in String) return Project_Reference; end Gen.Model.Projects;
----------------------------------------------------------------------- -- gen-model-projects -- Projects meta data -- Copyright (C) 2011, 2012, 2013, 2014, 2017, 2018, 2021 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Containers.Vectors; with Util.Properties; with Gen.Utils; with Gen.Utils.GNAT; package Gen.Model.Projects is type Project_Definition is tagged; type Project_Definition_Access is access all Project_Definition'Class; type Dependency_Type is (NONE, DIRECT, INDIRECT, BOTH); type Project_Reference is record Project : Project_Definition_Access := null; Name : UString; Kind : Dependency_Type := NONE; end record; package Project_Vectors is new Ada.Containers.Vectors (Element_Type => Project_Reference, Index_Type => Natural); -- ------------------------------ -- Project Definition -- ------------------------------ type Project_Definition is new Definition with record Path : UString; Props : Util.Properties.Manager; Modules : Project_Vectors.Vector; -- The root project definition. Root : Project_Definition_Access := null; -- The list of plugin names that this plugin or project depends on. Dependencies : Project_Vectors.Vector; -- The list of GNAT project files used by the project. Project_Files : Gen.Utils.GNAT.Project_Info_Vectors.Vector; -- The list of 'dynamo.xml' files used by the project (gathered from GNAT files -- and by scanning the 'plugins' directory). Dynamo_Files : Gen.Utils.String_List.Vector; -- Whether we did a recursive scan of GNAT project files. Recursive_Scan : Boolean := False; -- Whether we are doing a recursive operation on the project (prevent from cycles). Recursing : Boolean := False; -- Whether we did a recursive scan of Dynamo dependencies. Depend_Scan : Boolean := False; -- Whether this project is a plugin. Is_Plugin : Boolean := False; -- Whether the project needs the generation for the different databases Use_Mysql : Boolean := True; Use_Sqlite : Boolean := True; Use_Postgresql : Boolean := True; end record; -- Get the value identified by the name. -- If the name cannot be found, the method should return the Null object. overriding function Get_Value (From : Project_Definition; Name : String) return UBO.Object; -- Get the project name. function Get_Project_Name (Project : in Project_Definition) return String; -- Get the GNAT project file name. The default is to use the Dynamo project -- name and add the <b>.gpr</b> extension. The <b>gnat_project</b> configuration -- property allows to override this default. function Get_GNAT_Project_Name (Project : in Project_Definition) return String; -- Get the directory path which holds application modules. -- This is controlled by the <b>modules_dir</b> configuration property. -- The default is <tt>plugins</tt>. function Get_Module_Dir (Project : in Project_Definition) return String; -- Get the directory path which holds database model files. -- This is controlled by the <b>db_dir</b> configuration property. -- The default is <tt>db</tt>. function Get_Database_Dir (Project : in Project_Definition) return String; -- Find the dependency for the <b>Name</b> plugin. -- Returns a null dependency if the project does not depend on that plugin. function Find_Dependency (From : in Project_Definition; Name : in String) return Project_Reference; -- Add a dependency to the plugin identified by <b>Name</b>. procedure Add_Dependency (Into : in out Project_Definition; Name : in String; Kind : in Dependency_Type); -- Add a dependency to the plugin identified by <b>Project</b>. procedure Add_Dependency (Into : in out Project_Definition; Project : in Project_Definition_Access; Kind : in Dependency_Type); -- Create a project definition instance to record a project with the dynamo XML file path. procedure Create_Project (Into : in out Project_Definition; Name : in String; Path : in String; Project : out Project_Definition_Access); -- Add the project in the global project list on the root project instance. procedure Add_Project (Into : in out Project_Definition; Project : in Project_Definition_Access); -- Add the project <b>Name</b> as a module. procedure Add_Module (Into : in out Project_Definition; Name : in String); -- Add the project represented by <b>Project</b> if it is not already part of the modules. procedure Add_Module (Into : in out Project_Definition; Project : in Project_Definition_Access); -- Find the project definition associated with the dynamo XML file <b>Path</b>. -- Returns null if there is no such project function Find_Project (From : in Project_Definition; Path : in String) return Project_Definition_Access; -- Find the project definition having the name <b>Name</b>. -- Returns null if there is no such project function Find_Project_By_Name (From : in Project_Definition; Name : in String) return Project_Definition_Access; -- Save the project description and parameters. procedure Save (Project : in out Project_Definition; Path : in String); -- Read the XML project description into the project description. procedure Read_Project (Project : in out Project_Definition); -- Scan and read the possible modules used by the application. Modules are stored in the -- <b>modules</b> directory. Each module is stored in its own directory and has its own -- <b>dynamo.xml</b> file. procedure Read_Modules (Project : in out Project_Definition); -- Update the project definition from the properties. procedure Update_From_Properties (Project : in out Project_Definition); -- ------------------------------ -- Root Project Definition -- ------------------------------ -- The root project is the project that is actually read by Dynamo. -- It contains the lists of all projects that are necessary and which are found either -- by scanning GNAT projects or by looking at plugin dependencies. type Root_Project_Definition is new Project_Definition with record Projects : Project_Vectors.Vector; Install_Dir : UString; end record; -- Add the project in the global project list on the root project instance. overriding procedure Add_Project (Into : in out Root_Project_Definition; Project : in Project_Definition_Access); -- Find the project definition having the name <b>Name</b>. -- Returns null if there is no such project overriding function Find_Project_By_Name (From : in Root_Project_Definition; Name : in String) return Project_Definition_Access; -- Find the project definition associated with the dynamo XML file <b>Path</b>. -- Returns null if there is no such project overriding function Find_Project (From : in Root_Project_Definition; Path : in String) return Project_Definition_Access; -- Read the XML project file. When <b>Recursive</b> is set, read the GNAT project -- files used by the main project and load all the <b>dynamo.xml</b> files defined -- by these project. procedure Read_Project (Project : in out Root_Project_Definition; File : in String; Config : in Util.Properties.Manager'Class; Recursive : in Boolean := False); private -- Update the project references after a project is found and initialized. procedure Update_References (Root : in out Root_Project_Definition; Project : in Project_Definition_Access); -- Iterate over the project referenced in the list and execute the <b>Process</b> procedure. procedure Iterate (List : in out Project_Vectors.Vector; Process : access procedure (Item : in out Project_Reference)); -- Find a project from the list function Find_Project (List : in Project_Vectors.Vector; Name : in String) return Project_Reference; end Gen.Model.Projects;
Declare the Get_Database_Dir function to get the path where the database configuration files are located
Declare the Get_Database_Dir function to get the path where the database configuration files are located
Ada
apache-2.0
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
70bb665918c269da0ed0cbf6bd1dd7e9397ee320
src/asf-contexts-facelets.adb
src/asf-contexts-facelets.adb
----------------------------------------------------------------------- -- contexts-facelets -- Contexts for facelets -- Copyright (C) 2009, 2010, 2011, 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 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 -- The logger Log : constant Util.Log.Loggers.Logger := Util.Log.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; end ASF.Contexts.Facelets;
----------------------------------------------------------------------- -- contexts-facelets -- Contexts for facelets -- Copyright (C) 2009, 2010, 2011, 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 Ada.Directories; with Util.Files; with Util.Log.Loggers; with EL.Variables; with ASF.Views.Nodes.Facelets; package body ASF.Contexts.Facelets is -- The logger Log : constant Util.Log.Loggers.Logger := Util.Log.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; end ASF.Contexts.Facelets;
Remove unused with clauses
Remove unused with clauses
Ada
apache-2.0
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
ae16865755edb54c157c1fd0e9eade4f3b73af87
src/babel-base-text.adb
src/babel-base-text.adb
----------------------------------------------------------------------- -- 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 Util.Dates.ISO8601; with Babel.Files.Sets; with Babel.Files.Lifecycles; with Ada.Text_IO; package body Babel.Base.Text is -- ------------------------------ -- Insert the file in the database. -- ------------------------------ overriding procedure Insert (Into : in out Text_Database; File : in Babel.Files.File_Type) is begin Into.Files.Insert (File); end Insert; overriding procedure Iterate (From : in Text_Database; Process : not null access procedure (File : in Babel.Files.File_Type)) is procedure Process_One (Pos : in Babel.Files.Sets.File_Cursor) is begin Process (Babel.Files.Sets.File_Sets.Element (Pos)); end Process_One; begin From.Files.Iterate (Process_One'Access); end Iterate; -- ------------------------------ -- Write the SHA1 checksum for the files stored in the map. -- ------------------------------ procedure Save (Database : in Text_Database; Path : in String) is Checksum : Ada.Text_IO.File_Type; procedure Write_Checksum (Position : in Babel.Files.Sets.File_Cursor) is File : constant Babel.Files.File_Type := Babel.Files.Sets.File_Sets.Element (Position); SHA1 : constant String := Babel.Files.Get_SHA1 (File); Path : constant String := Babel.Files.Get_Path (File); begin Ada.Text_IO.Put (Checksum, SHA1); Ada.Text_IO.Put (Checksum, Babel.Uid_Type'Image (Babel.Files.Get_User (File))); Ada.Text_IO.Put (Checksum, Babel.Gid_Type'Image (Babel.Files.Get_Group (File))); Ada.Text_IO.Put (Checksum, " "); Ada.Text_IO.Put (Checksum, Util.Dates.ISO8601.Image (Babel.Files.Get_Date (File))); Ada.Text_IO.Put (Checksum, Babel.Files.File_Size'Image (Babel.Files.Get_Size (File))); Ada.Text_IO.Put (Checksum, " "); Ada.Text_IO.Put (Checksum, Path); Ada.Text_IO.New_Line (Checksum); end Write_Checksum; begin Ada.Text_IO.Create (File => Checksum, Name => Path); Database.Files.Iterate (Write_Checksum'Access); Ada.Text_IO.Close (File => Checksum); end Save; end Babel.Base.Text;
----------------------------------------------------------------------- -- 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.Streams; with Ada.Calendar; with Ada.Exceptions; with Util.Dates.ISO8601; with Util.Files; with Util.Strings; with Util.Encoders.Base16; with Util.Encoders.SHA1; with Util.Log.Loggers; with Babel.Files.Sets; with Babel.Files.Maps; with Babel.Files.Lifecycles; with Ada.Text_IO; package body Babel.Base.Text is Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Babel.Base.Text"); -- ------------------------------ -- Insert the file in the database. -- ------------------------------ overriding procedure Insert (Into : in out Text_Database; File : in Babel.Files.File_Type) is begin Into.Files.Insert (File); end Insert; overriding procedure Iterate (From : in Text_Database; Process : not null access procedure (File : in Babel.Files.File_Type)) is procedure Process_One (Pos : in Babel.Files.Sets.File_Cursor) is begin Process (Babel.Files.Sets.File_Sets.Element (Pos)); end Process_One; begin From.Files.Iterate (Process_One'Access); end Iterate; -- ------------------------------ -- Save the database file description in the file. -- ------------------------------ procedure Save (Database : in Text_Database; Path : in String) is Checksum : Ada.Text_IO.File_Type; procedure Write_Checksum (Position : in Babel.Files.Sets.File_Cursor) is File : constant Babel.Files.File_Type := Babel.Files.Sets.File_Sets.Element (Position); SHA1 : constant String := Babel.Files.Get_SHA1 (File); Path : constant String := Babel.Files.Get_Path (File); begin Ada.Text_IO.Put (Checksum, SHA1); Ada.Text_IO.Put (Checksum, Babel.Uid_Type'Image (Babel.Files.Get_User (File))); Ada.Text_IO.Put (Checksum, Babel.Gid_Type'Image (Babel.Files.Get_Group (File))); Ada.Text_IO.Put (Checksum, " "); Ada.Text_IO.Put (Checksum, Util.Dates.ISO8601.Image (Babel.Files.Get_Date (File))); Ada.Text_IO.Put (Checksum, Babel.Files.File_Size'Image (Babel.Files.Get_Size (File))); Ada.Text_IO.Put (Checksum, " "); Ada.Text_IO.Put (Checksum, Path); Ada.Text_IO.New_Line (Checksum); end Write_Checksum; begin Log.Info ("Save text database {0}", Path); Ada.Text_IO.Create (File => Checksum, Name => Path); Database.Files.Iterate (Write_Checksum'Access); Ada.Text_IO.Close (File => Checksum); end Save; -- ------------------------------ -- Load the database file description from the file. -- ------------------------------ procedure Load (Database : in out Text_Database; Path : in String) is Checksum : Ada.Text_IO.File_Type; Dirs : Babel.Files.Maps.Directory_Map; Files : Babel.Files.Maps.File_Map; Hex_Decoder : Util.Encoders.Base16.Decoder; Line_Number : Natural := 0; procedure Read_Line (Line : in String) is File : Babel.Files.File_Type; Pos : Natural; First : Natural; Sign : Util.Encoders.SHA1.Hash_Array; Sign_Size : Ada.Streams.Stream_Element_Offset; User : Uid_Type; Group : Gid_Type; Date : Ada.Calendar.Time; Size : Babel.Files.File_Size; begin Line_Number := Line_Number + 1; Pos := Util.Strings.Index (Line, ' '); if Pos = 0 then return; end if; Hex_Decoder.Transform (Line (Line'First .. Pos - 1), Sign, Sign_Size); -- Extract the user ID. First := Pos + 1; Pos := Util.Strings.Index (Line, ' ', First); if Pos = 0 then return; end if; User := Uid_Type'Value (Line (First .. Pos - 1)); -- Extract the group ID. First := Pos + 1; Pos := Util.Strings.Index (Line, ' ', First); if Pos = 0 then return; end if; Group := Uid_Type'Value (Line (First .. Pos - 1)); -- Extract the file date. First := Pos + 1; Pos := Util.Strings.Index (Line, ' ', First); if Pos = 0 then return; end if; Date := Util.Dates.ISO8601.Value (Line (First .. Pos - 1)); -- Extract the file size. First := Pos + 1; Pos := Util.Strings.Index (Line, ' ', First); if Pos = 0 then return; end if; Size := Babel.Files.File_Size'Value (Line (First .. Pos - 1)); Babel.Files.Maps.Add_File (Dirs, Files, Line (Pos + 1 .. Line'Last), File); Babel.Files.Set_Owner (File, User, Group); Babel.Files.Set_Size (File, Size); Babel.Files.Set_Signature (File, Sign); Babel.Files.Set_Date (File, Date); Database.Insert (File); exception when E : others => Log.Error ("{0}:{1}: Error: {2}: {3}: " & Line, Path, Natural'Image (Line_Number), Ada.Exceptions.Exception_Message (E)); end Read_Line; begin Log.Info ("Load text database {0}", Path); Util.Files.Read_File (Path, Read_Line'Access); end Load; end Babel.Base.Text;
Implement the Load procedure to load a database from a text file
Implement the Load procedure to load a database from a text file
Ada
apache-2.0
stcarrez/babel
5458c139ae016b91928338d8eb1bbf6de6e7cf84
src/drivers/adabase-driver-base-mysql.adb
src/drivers/adabase-driver-base-mysql.adb
-- This file is covered by the Internet Software Consortium (ISC) License -- Reference: ../../License.txt package body AdaBase.Driver.Base.MySQL is ------------------ -- disconnect -- ------------------ overriding procedure disconnect (driver : out MySQL_Driver) is msg : constant CT.Text := CT.SUS ("Disconnect From " & CT.USS (driver.database) & "database"); err : constant CT.Text := CT.SUS ("ACK! Disconnect attempted on inactive connection"); begin if driver.connection_active then driver.connection.disconnect; driver.connection_active := False; driver.log_nominal (category => disconnecting, message => msg); else -- Non-fatal attempt to disconnect db when none is connected driver.log_problem (category => disconnecting, message => err); end if; end disconnect; ---------------- -- rollback -- ---------------- overriding procedure rollback (driver : MySQL_Driver) is use type TransIsolation; err1 : constant CT.Text := CT.SUS ("ACK! Rollback attempted on inactive connection"); err2 : constant CT.Text := CT.SUS ("ACK! Rollback attempted when autocommit mode set on"); err3 : constant CT.Text := CT.SUS ("Rollback attempt failed"); begin if not driver.connection_active then -- Non-fatal attempt to roll back when no database is connected driver.log_problem (category => miscellaneous, message => err1); return; end if; if driver.connection.autoCommit then -- Non-fatal attempt to roll back when autocommit is on driver.log_problem (category => miscellaneous, message => err2); return; end if; driver.connection.rollback; exception when ACM.ROLLBACK_FAIL => driver.log_problem (category => miscellaneous, message => err3, pull_codes => True); end rollback; -------------- -- commit -- -------------- overriding procedure commit (driver : MySQL_Driver) is use type TransIsolation; err1 : constant CT.Text := CT.SUS ("ACK! Commit attempted on inactive connection"); err2 : constant CT.Text := CT.SUS ("ACK! Commit attempted when autocommit mode set on"); err3 : constant CT.Text := CT.SUS ("Commit attempt failed"); begin if not driver.connection_active then -- Non-fatal attempt to commit when no database is connected driver.log_problem (category => transaction, message => err1); return; end if; if driver.connection.autoCommit then -- Non-fatal attempt to commit when autocommit is on driver.log_problem (category => transaction, message => err2); return; end if; driver.connection.all.commit; exception when ACM.COMMIT_FAIL => driver.log_problem (category => transaction, message => err3, pull_codes => True); end commit; ---------------------- -- last_insert_id -- ---------------------- overriding function last_insert_id (driver : MySQL_Driver) return TraxID is begin return driver.connection.all.lastInsertID; end last_insert_id; ------------------------ -- last_driver_code -- ------------------------ overriding function last_sql_state (driver : MySQL_Driver) return TSqlState is begin return driver.connection.all.SqlState; end last_sql_state; ------------------------ -- last_driver_code -- ------------------------ overriding function last_driver_code (driver : MySQL_Driver) return DriverCodes is begin return driver.connection.all.driverCode; end last_driver_code; --------------------------- -- last_driver_message -- --------------------------- overriding function last_driver_message (driver : MySQL_Driver) return String is begin return driver.connection.all.driverMessage; end last_driver_message; --------------- -- execute -- --------------- overriding function execute (driver : MySQL_Driver; sql : String) return AffectedRows is result : AffectedRows := 0; err1 : constant CT.Text := CT.SUS ("ACK! Execution attempted on inactive connection"); begin if driver.connection_active then driver.connection.all.execute (sql => sql); result := driver.connection.all.rows_affected_by_execution; driver.log_nominal (category => execution, message => CT.SUS (sql)); else -- Non-fatal attempt to query an unccnnected database driver.log_problem (category => execution, message => err1); end if; return result; exception when ACM.QUERY_FAIL => driver.log_problem (category => execution, message => CT.SUS (sql), pull_codes => True); return 0; end execute; ------------------------------------------------------------------------ -- ROUTINES OF ALL DRIVERS NOT COVERED BY INTERFACES (TECH REASON) -- ------------------------------------------------------------------------ ------------- -- query -- ------------- function query (driver : MySQL_Driver; sql : String) return ASM.MySQL_statement_access is begin return driver.private_query (sql); end query; -------------------- -- query_select -- -------------------- function query_select (driver : MySQL_Driver; distinct : Boolean := False; tables : String; columns : String; conditions : String := ""; groupby : String := ""; having : String := ""; order : String := ""; limit : TraxID := 0; offset : TraxID := 0) return ASM.MySQL_statement_access is vanilla : String := assembly_common_select (distinct, tables, columns, conditions, groupby, having, order); begin if limit > 0 then if offset > 0 then return driver.private_query (vanilla & " LIMIT" & limit'Img & " OFFSET" & offset'Img); else return driver.private_query (vanilla & " LIMIT" & limit'Img); end if; end if; return driver.private_query (vanilla); end query_select; ------------------------------------------------------------------------ -- PUBLIC ROUTINES NOT COVERED BY INTERFACES -- ------------------------------------------------------------------------ --------------------------------- -- trait_compressed_protocol -- --------------------------------- function trait_protocol_compressed (driver : MySQL_Driver) return Boolean is begin return driver.local_connection.all.compressed; end trait_protocol_compressed; -------------------------------- -- trait_multiquery_enabled -- -------------------------------- function trait_multiquery_enabled (driver : MySQL_Driver) return Boolean is begin return driver.local_connection.all.multiquery; end trait_multiquery_enabled; -------------------------------- -- trait_query_buffers_used -- -------------------------------- function trait_query_buffers_used (driver : MySQL_Driver) return Boolean is begin return driver.local_connection.all.useBuffer; end trait_query_buffers_used; -------------------------------------- -- set_trait_compressed_protocol -- ------------------------------------- procedure set_trait_protocol_compressed (driver : MySQL_Driver; trait : Boolean) is begin driver.local_connection.all.setCompressed (compressed => trait); end set_trait_protocol_compressed; ------------------------------------ -- set_trait_multiquery_enabled -- ------------------------------------ procedure set_trait_multiquery_enabled (driver : MySQL_Driver; trait : Boolean) is begin driver.local_connection.all.setMultiQuery (multiple => trait); end set_trait_multiquery_enabled; ------------------------------ -- set_query_buffers_used -- ------------------------------ procedure set_trait_query_buffers_used (driver : MySQL_Driver; trait : Boolean) is begin driver.local_connection.all.setUseBuffer (buffered => trait); end set_trait_query_buffers_used; --------------------- -- basic_connect -- --------------------- overriding procedure basic_connect (driver : out MySQL_Driver; database : String; username : String; password : String; socket : String) is begin driver.private_connect (database => database, username => username, password => password, socket => socket); end basic_connect; --------------------- -- basic_connect -- --------------------- overriding procedure basic_connect (driver : out MySQL_Driver; database : String; username : String; password : String; hostname : String; port : PosixPort) is begin driver.private_connect (database => database, username => username, password => password, hostname => hostname, port => port); end basic_connect; ------------------------------------------------------------------------ -- PRIVATE ROUTINES NOT COVERED BY INTERFACES -- ------------------------------------------------------------------------ ------------------ -- initialize -- ------------------ overriding procedure initialize (Object : in out MySQL_Driver) is begin Object.connection := backend'Access; Object.local_connection := backend'Access; Object.dialect := driver_mysql; end initialize; ----------------------- -- private_connect -- ----------------------- procedure private_connect (driver : out MySQL_Driver; database : String; username : String; password : String; hostname : String := blankstring; socket : String := blankstring; port : PosixPort := portless) is err1 : constant CT.Text := CT.SUS ("ACK! Reconnection attempted on active connection"); nom : constant CT.Text := CT.SUS ("Connection to " & database & " database succeeded."); begin if driver.connection_active then driver.log_problem (category => execution, message => err1); return; end if; driver.connection.connect (database => database, username => username, password => password, socket => socket, hostname => hostname, port => port); driver.connection_active := driver.connection.all.connected; driver.log_nominal (category => connecting, message => nom); exception when Error : others => driver.log_problem (category => connecting, break => True, message => CT.SUS (ACM.EX.Exception_Message (X => Error))); end private_connect; --------------------- -- private_query -- --------------------- function private_query (driver : MySQL_Driver; sql : String) return ASM.MySQL_statement_access is err1 : constant CT.Text := CT.SUS ("ACK! Query attempted on inactive connection"); duplicate : aliased constant CT.Text := CT.SUS (sql); shadow : AID.ASB.stmttext_access := duplicate'Unrestricted_Access; statement : constant ASM.MySQL_statement_access := new ASM.MySQL_statement (type_of_statement => AID.ASB.direct_statement, log_handler => logger'Access, mysql_conn => driver.local_connection, initial_sql => shadow, con_error_mode => driver.trait_error_mode, con_case_mode => driver.trait_column_case, con_max_blob => driver.trait_max_blob_size, con_buffered => driver.trait_query_buffers_used); begin if driver.connection_active then driver.log_nominal (category => execution, message => CT.SUS ("query succeeded," & statement.rows_returned'Img & " rows returned")); else -- Non-fatal attempt to query an unccnnected database driver.log_problem (category => execution, message => err1); end if; return statement; end private_query; end AdaBase.Driver.Base.MySQL;
-- This file is covered by the Internet Software Consortium (ISC) License -- Reference: ../../License.txt package body AdaBase.Driver.Base.MySQL is ------------------ -- disconnect -- ------------------ overriding procedure disconnect (driver : out MySQL_Driver) is msg : constant CT.Text := CT.SUS ("Disconnect From " & CT.USS (driver.database) & "database"); err : constant CT.Text := CT.SUS ("ACK! Disconnect attempted on inactive connection"); begin if driver.connection_active then driver.connection.disconnect; driver.connection_active := False; driver.log_nominal (category => disconnecting, message => msg); else -- Non-fatal attempt to disconnect db when none is connected driver.log_problem (category => disconnecting, message => err); end if; end disconnect; ---------------- -- rollback -- ---------------- overriding procedure rollback (driver : MySQL_Driver) is use type TransIsolation; err1 : constant CT.Text := CT.SUS ("ACK! Rollback attempted on inactive connection"); err2 : constant CT.Text := CT.SUS ("ACK! Rollback attempted when autocommit mode set on"); err3 : constant CT.Text := CT.SUS ("Rollback attempt failed"); begin if not driver.connection_active then -- Non-fatal attempt to roll back when no database is connected driver.log_problem (category => miscellaneous, message => err1); return; end if; if driver.connection.autoCommit then -- Non-fatal attempt to roll back when autocommit is on driver.log_problem (category => miscellaneous, message => err2); return; end if; driver.connection.rollback; exception when ACM.ROLLBACK_FAIL => driver.log_problem (category => miscellaneous, message => err3, pull_codes => True); end rollback; -------------- -- commit -- -------------- overriding procedure commit (driver : MySQL_Driver) is use type TransIsolation; err1 : constant CT.Text := CT.SUS ("ACK! Commit attempted on inactive connection"); err2 : constant CT.Text := CT.SUS ("ACK! Commit attempted when autocommit mode set on"); err3 : constant CT.Text := CT.SUS ("Commit attempt failed"); begin if not driver.connection_active then -- Non-fatal attempt to commit when no database is connected driver.log_problem (category => transaction, message => err1); return; end if; if driver.connection.autoCommit then -- Non-fatal attempt to commit when autocommit is on driver.log_problem (category => transaction, message => err2); return; end if; driver.connection.all.commit; exception when ACM.COMMIT_FAIL => driver.log_problem (category => transaction, message => err3, pull_codes => True); end commit; ---------------------- -- last_insert_id -- ---------------------- overriding function last_insert_id (driver : MySQL_Driver) return TraxID is begin return driver.connection.all.lastInsertID; end last_insert_id; ------------------------ -- last_driver_code -- ------------------------ overriding function last_sql_state (driver : MySQL_Driver) return TSqlState is begin return driver.connection.all.SqlState; end last_sql_state; ------------------------ -- last_driver_code -- ------------------------ overriding function last_driver_code (driver : MySQL_Driver) return DriverCodes is begin return driver.connection.all.driverCode; end last_driver_code; --------------------------- -- last_driver_message -- --------------------------- overriding function last_driver_message (driver : MySQL_Driver) return String is begin return driver.connection.all.driverMessage; end last_driver_message; --------------- -- execute -- --------------- overriding function execute (driver : MySQL_Driver; sql : String) return AffectedRows is result : AffectedRows := 0; err1 : constant CT.Text := CT.SUS ("ACK! Execution attempted on inactive connection"); begin if driver.connection_active then driver.connection.all.execute (sql => sql); result := driver.connection.all.rows_affected_by_execution; driver.log_nominal (category => execution, message => CT.SUS (sql)); else -- Non-fatal attempt to query an unccnnected database driver.log_problem (category => execution, message => err1); end if; return result; exception when ACM.QUERY_FAIL => driver.log_problem (category => execution, message => CT.SUS (sql), pull_codes => True); return 0; end execute; ------------------------------------------------------------------------ -- ROUTINES OF ALL DRIVERS NOT COVERED BY INTERFACES (TECH REASON) -- ------------------------------------------------------------------------ ------------- -- query -- ------------- function query (driver : MySQL_Driver; sql : String) return ASM.MySQL_statement_access is begin return driver.private_query (sql); end query; -------------------- -- query_select -- -------------------- function query_select (driver : MySQL_Driver; distinct : Boolean := False; tables : String; columns : String; conditions : String := ""; groupby : String := ""; having : String := ""; order : String := ""; limit : TraxID := 0; offset : TraxID := 0) return ASM.MySQL_statement_access is vanilla : String := assembly_common_select (distinct, tables, columns, conditions, groupby, having, order); begin if limit > 0 then if offset > 0 then return driver.private_query (vanilla & " LIMIT" & limit'Img & " OFFSET" & offset'Img); else return driver.private_query (vanilla & " LIMIT" & limit'Img); end if; end if; return driver.private_query (vanilla); end query_select; ------------------------------------------------------------------------ -- PUBLIC ROUTINES NOT COVERED BY INTERFACES -- ------------------------------------------------------------------------ --------------------------------- -- trait_compressed_protocol -- --------------------------------- function trait_protocol_compressed (driver : MySQL_Driver) return Boolean is begin return driver.local_connection.all.compressed; end trait_protocol_compressed; -------------------------------- -- trait_multiquery_enabled -- -------------------------------- function trait_multiquery_enabled (driver : MySQL_Driver) return Boolean is begin return driver.local_connection.all.multiquery; end trait_multiquery_enabled; -------------------------------- -- trait_query_buffers_used -- -------------------------------- function trait_query_buffers_used (driver : MySQL_Driver) return Boolean is begin return driver.local_connection.all.useBuffer; end trait_query_buffers_used; -------------------------------------- -- set_trait_compressed_protocol -- ------------------------------------- procedure set_trait_protocol_compressed (driver : MySQL_Driver; trait : Boolean) is begin driver.local_connection.all.setCompressed (compressed => trait); end set_trait_protocol_compressed; ------------------------------------ -- set_trait_multiquery_enabled -- ------------------------------------ procedure set_trait_multiquery_enabled (driver : MySQL_Driver; trait : Boolean) is begin driver.local_connection.all.setMultiQuery (multiple => trait); end set_trait_multiquery_enabled; ------------------------------ -- set_query_buffers_used -- ------------------------------ procedure set_trait_query_buffers_used (driver : MySQL_Driver; trait : Boolean) is begin driver.local_connection.all.setUseBuffer (buffered => trait); end set_trait_query_buffers_used; --------------------- -- basic_connect -- --------------------- overriding procedure basic_connect (driver : out MySQL_Driver; database : String; username : String; password : String; socket : String) is begin driver.private_connect (database => database, username => username, password => password, socket => socket); end basic_connect; --------------------- -- basic_connect -- --------------------- overriding procedure basic_connect (driver : out MySQL_Driver; database : String; username : String; password : String; hostname : String; port : PosixPort) is begin driver.private_connect (database => database, username => username, password => password, hostname => hostname, port => port); end basic_connect; ------------------------------------------------------------------------ -- PRIVATE ROUTINES NOT COVERED BY INTERFACES -- ------------------------------------------------------------------------ ------------------ -- initialize -- ------------------ overriding procedure initialize (Object : in out MySQL_Driver) is begin Object.connection := backend'Access; Object.local_connection := backend'Access; Object.dialect := driver_mysql; end initialize; ----------------------- -- private_connect -- ----------------------- procedure private_connect (driver : out MySQL_Driver; database : String; username : String; password : String; hostname : String := blankstring; socket : String := blankstring; port : PosixPort := portless) is err1 : constant CT.Text := CT.SUS ("ACK! Reconnection attempted on active connection"); nom : constant CT.Text := CT.SUS ("Connection to " & database & " database succeeded."); begin if driver.connection_active then driver.log_problem (category => execution, message => err1); return; end if; driver.connection.connect (database => database, username => username, password => password, socket => socket, hostname => hostname, port => port); driver.connection_active := driver.connection.all.connected; driver.log_nominal (category => connecting, message => nom); exception when Error : others => driver.log_problem (category => connecting, break => True, message => CT.SUS (ACM.EX.Exception_Message (X => Error))); end private_connect; --------------------- -- private_query -- --------------------- function private_query (driver : MySQL_Driver; sql : String) return ASM.MySQL_statement_access is err1 : constant CT.Text := CT.SUS ("ACK! Query attempted on inactive connection"); err2 : constant CT.Text := CT.SUS ("Query failed!"); duplicate : aliased constant CT.Text := CT.SUS (sql); shadow : AID.ASB.stmttext_access := duplicate'Unrestricted_Access; statement : constant ASM.MySQL_statement_access := new ASM.MySQL_statement (type_of_statement => AID.ASB.direct_statement, log_handler => logger'Access, mysql_conn => driver.local_connection, initial_sql => shadow, con_error_mode => driver.trait_error_mode, con_case_mode => driver.trait_column_case, con_max_blob => driver.trait_max_blob_size, con_buffered => driver.trait_query_buffers_used); begin if driver.connection_active then if statement.successful then driver.log_nominal (category => execution, message => CT.SUS ("query succeeded," & statement.rows_returned'Img & " rows returned")); else driver.log_nominal (category => execution, message => err2); end if; else -- Non-fatal attempt to query an unccnnected database driver.log_problem (category => execution, message => err1); end if; return statement; end private_query; end AdaBase.Driver.Base.MySQL;
Handle failed SELECT query (MySQL)
Handle failed SELECT query (MySQL)
Ada
isc
jrmarino/AdaBase
381086b9ea1f53252ec4dee1fffd0135fdcdffb4
boards/OpenMV2/openmv.ads
boards/OpenMV2/openmv.ads
with STM32.Device; use STM32.Device; with STM32.GPIO; use STM32.GPIO; use STM32; -- for base addresses with STM32.SPI; with STM32.Timers; use STM32.Timers; with STM32.DMA; with HAL; use HAL; with STM32.I2C; use STM32.I2C; package OpenMV is pragma Elaborate_Body; type LED_Color is (White, Red, Green, Blue, Magenta, Cyan, Yellow, Off); Image_Width : constant := 128; Image_Height : constant := 160; subtype Width is Natural range 0 .. Image_Width - 1; subtype Height is Natural range 0 .. Image_Height - 1; procedure Initialize_LEDs; -- MUST be called prior to any use of the LEDs procedure Set_RGB_LED (C : LED_Color); procedure Turn_On_IR; procedure Turn_Off_IR; procedure Initialize_Shield_SPI; -- Initialize the SPI port available for shields (SPI2) Shield_MOSI : GPIO_Point renames PB15; Shield_MISO : GPIO_Point renames PB14; Shield_SCK : GPIO_Point renames PB13; Shield_SEL : GPIO_Point renames PB12; Shield_TXD : GPIO_Point renames PB10; Shield_RXD : GPIO_Point renames PB11; Shield_ADC : GPIO_Point renames PA5; Shield_SWC : GPIO_Point renames PA14; Shield_SWD : GPIO_Point renames PA13; Shield_PWM1 : GPIO_Point renames PD12; Shield_PWM2 : GPIO_Point renames PD13; private subtype Pixel_Data is Short_Array (0 .. (Image_Width * Image_Height) - 1); type Pixel_Data_Access is not null access all Pixel_Data; type Frame_Buffer_Internal is record Data : Pixel_Data_Access; end record; type Frame_Buffer is not null access all Frame_Buffer_Internal; Pix_Data : aliased Pixel_Data with Size => 16 * (Image_Width * Image_Height); FB : aliased Frame_Buffer_Internal := (Data => Pix_Data'Access); -------------- -- LED Pins -- -------------- Red_LED : GPIO_Point renames PC0; Blue_LED : GPIO_Point renames PC1; Green_LED : GPIO_Point renames PC2; IR_LED : GPIO_Point renames PE2; All_LEDs : constant GPIO_Points := (Red_LED, Blue_LED, Green_LED, IR_LED); --------------- -- SPI2 Pins -- --------------- SPI2_SCK : GPIO_Point renames PB13; SPI2_MISO : GPIO_Point renames PB14; SPI2_MOSI : GPIO_Point renames PB15; SPI2_NSS : GPIO_Point renames PB12; Shield_SPI : STM32.SPI.SPI_Port renames STM32.Device.SPI_2; Shield_SPI_Points : constant STM32.GPIO.GPIO_Points := (Shield_MISO, Shield_MOSI, Shield_SCK); --------------- -- I2C1 Pins -- --------------- Sensor_I2C : I2C_Port renames I2C_1; Sensor_I2C_SCL : GPIO_Point renames PB8; Sensor_I2C_SDA : GPIO_Point renames PB9; Sensor_I2C_SCL_AF : GPIO_Alternate_Function renames GPIO_AF_I2C; Sensor_I2C_SDA_AF : GPIO_Alternate_Function renames GPIO_AF_I2C; ----------------- -- Sensor DMA -- ----------------- Sensor_DMA : STM32.DMA.DMA_Controller renames DMA_2; Sensor_DMA_Chan : STM32.DMA.DMA_Channel_Selector renames STM32.DMA.Channel_1; Sensor_DMA_Stream : STM32.DMA.DMA_Stream_Selector renames STM32.DMA.Stream_1; --------------- -- I2C2 Pins -- --------------- I2C2_SCL : GPIO_Point renames PB10; I2C2_SDA : GPIO_Point renames PB11; --------------- -- DCMI Pins -- --------------- DCMI_HSYNC : GPIO_Point renames PA4; DCMI_PCLK : GPIO_Point renames PA6; DCMI_RST : GPIO_Point renames PA10; DCMI_PWDN : GPIO_Point renames PB5; DCMI_VSYNC : GPIO_Point renames PB7; DCMI_D0 : GPIO_Point renames PC6; DCMI_D1 : GPIO_Point renames PC7; DCMI_D2 : GPIO_Point renames PE0; DCMI_D3 : GPIO_Point renames PE1; DCMI_D4 : GPIO_Point renames PE4; DCMI_D5 : GPIO_Point renames PB6; DCMI_D6 : GPIO_Point renames PE5; DCMI_D7 : GPIO_Point renames PE6; FS_IN : GPIO_Point renames PD3; SENSOR_CLK_IO : GPIO_Point renames PA8; SENSOR_CLK_AF : GPIO_Alternate_Function renames GPIO_AF_TIM1; SENSOR_CLK_TIM : Timer renames Timer_1; SENSOR_CLK_CHAN : constant Timer_Channel := Channel_1; SENSOR_CLK_FREQ : constant := 12_000_000; -- SENSOR_CLK_IO : GPIO_Point renames PD12; -- SENSOR_CLK_AF : GPIO_Alternate_Function renames GPIO_AF_TIM4; -- SENSOR_CLK_TIM : Timer renames Timer_4; -- SENSOR_CLK_CHAN : constant Timer_Channel := Channel_1; -- SENSOR_CLK_FREQ : constant := 12_000_000; ------------------ -- USB OTG Pins -- ------------------ OTG_FS_DM : GPIO_Point renames PA11; OTG_FS_DP : GPIO_Point renames PA12; --------------- -- SDIO Pins -- --------------- SDIO_CMD : GPIO_Point renames PD2; SDIO_CLK : GPIO_Point renames PC12; SDIO_D0 : GPIO_Point renames PC8; SDIO_D1 : GPIO_Point renames PC9; SDIO_D2 : GPIO_Point renames PC10; SDIO_D3 : GPIO_Point renames PC11; SD_CD : GPIO_Point renames PA15; --------------- -- TIM4 Pins -- --------------- TIM4_CH1 : GPIO_Point renames PD12; TIM4_CH2 : GPIO_Point renames PD13; end OpenMV;
with STM32.Device; use STM32.Device; with STM32.GPIO; use STM32.GPIO; use STM32; -- for base addresses with STM32.SPI; with STM32.Timers; use STM32.Timers; with STM32.DMA; with STM32.I2C; use STM32.I2C; package OpenMV is pragma Elaborate_Body; type LED_Color is (White, Red, Green, Blue, Magenta, Cyan, Yellow, Off); Image_Width : constant := 128; Image_Height : constant := 160; subtype Width is Natural range 0 .. Image_Width - 1; subtype Height is Natural range 0 .. Image_Height - 1; procedure Initialize_LEDs; -- MUST be called prior to any use of the LEDs procedure Set_RGB_LED (C : LED_Color); procedure Turn_On_IR; procedure Turn_Off_IR; procedure Initialize_Shield_SPI; -- Initialize the SPI port available for shields (SPI2) Shield_MOSI : GPIO_Point renames PB15; Shield_MISO : GPIO_Point renames PB14; Shield_SCK : GPIO_Point renames PB13; Shield_SEL : GPIO_Point renames PB12; Shield_TXD : GPIO_Point renames PB10; Shield_RXD : GPIO_Point renames PB11; Shield_ADC : GPIO_Point renames PA5; Shield_SWC : GPIO_Point renames PA14; Shield_SWD : GPIO_Point renames PA13; Shield_PWM1 : GPIO_Point renames PD12; Shield_PWM2 : GPIO_Point renames PD13; private -------------- -- LED Pins -- -------------- Red_LED : GPIO_Point renames PC0; Blue_LED : GPIO_Point renames PC1; Green_LED : GPIO_Point renames PC2; IR_LED : GPIO_Point renames PE2; All_LEDs : constant GPIO_Points := (Red_LED, Blue_LED, Green_LED, IR_LED); --------------- -- SPI2 Pins -- --------------- SPI2_SCK : GPIO_Point renames PB13; SPI2_MISO : GPIO_Point renames PB14; SPI2_MOSI : GPIO_Point renames PB15; SPI2_NSS : GPIO_Point renames PB12; Shield_SPI : STM32.SPI.SPI_Port renames STM32.Device.SPI_2; Shield_SPI_Points : constant STM32.GPIO.GPIO_Points := (Shield_MISO, Shield_MOSI, Shield_SCK); --------------- -- I2C1 Pins -- --------------- Sensor_I2C : I2C_Port renames I2C_1; Sensor_I2C_SCL : GPIO_Point renames PB8; Sensor_I2C_SDA : GPIO_Point renames PB9; Sensor_I2C_SCL_AF : GPIO_Alternate_Function renames GPIO_AF_I2C; Sensor_I2C_SDA_AF : GPIO_Alternate_Function renames GPIO_AF_I2C; ----------------- -- Sensor DMA -- ----------------- Sensor_DMA : STM32.DMA.DMA_Controller renames DMA_2; Sensor_DMA_Chan : STM32.DMA.DMA_Channel_Selector renames STM32.DMA.Channel_1; Sensor_DMA_Stream : STM32.DMA.DMA_Stream_Selector renames STM32.DMA.Stream_1; --------------- -- I2C2 Pins -- --------------- I2C2_SCL : GPIO_Point renames PB10; I2C2_SDA : GPIO_Point renames PB11; --------------- -- DCMI Pins -- --------------- DCMI_HSYNC : GPIO_Point renames PA4; DCMI_PCLK : GPIO_Point renames PA6; DCMI_RST : GPIO_Point renames PA10; DCMI_PWDN : GPIO_Point renames PB5; DCMI_VSYNC : GPIO_Point renames PB7; DCMI_D0 : GPIO_Point renames PC6; DCMI_D1 : GPIO_Point renames PC7; DCMI_D2 : GPIO_Point renames PE0; DCMI_D3 : GPIO_Point renames PE1; DCMI_D4 : GPIO_Point renames PE4; DCMI_D5 : GPIO_Point renames PB6; DCMI_D6 : GPIO_Point renames PE5; DCMI_D7 : GPIO_Point renames PE6; FS_IN : GPIO_Point renames PD3; SENSOR_CLK_IO : GPIO_Point renames PA8; SENSOR_CLK_AF : GPIO_Alternate_Function renames GPIO_AF_TIM1; SENSOR_CLK_TIM : Timer renames Timer_1; SENSOR_CLK_CHAN : constant Timer_Channel := Channel_1; SENSOR_CLK_FREQ : constant := 12_000_000; -- SENSOR_CLK_IO : GPIO_Point renames PD12; -- SENSOR_CLK_AF : GPIO_Alternate_Function renames GPIO_AF_TIM4; -- SENSOR_CLK_TIM : Timer renames Timer_4; -- SENSOR_CLK_CHAN : constant Timer_Channel := Channel_1; -- SENSOR_CLK_FREQ : constant := 12_000_000; ------------------ -- USB OTG Pins -- ------------------ OTG_FS_DM : GPIO_Point renames PA11; OTG_FS_DP : GPIO_Point renames PA12; --------------- -- SDIO Pins -- --------------- SDIO_CMD : GPIO_Point renames PD2; SDIO_CLK : GPIO_Point renames PC12; SDIO_D0 : GPIO_Point renames PC8; SDIO_D1 : GPIO_Point renames PC9; SDIO_D2 : GPIO_Point renames PC10; SDIO_D3 : GPIO_Point renames PC11; SD_CD : GPIO_Point renames PA15; --------------- -- TIM4 Pins -- --------------- TIM4_CH1 : GPIO_Point renames PD12; TIM4_CH2 : GPIO_Point renames PD13; end OpenMV;
Remove internal frame buffer from OpenMV
Remove internal frame buffer from OpenMV For the moment, only Bitmap from OpenMV.LCD_Shield can be used. In the future, OpenMV may implement bitmap manipulations (allocation, copy, etc.).
Ada
bsd-3-clause
Fabien-Chouteau/Ada_Drivers_Library,AdaCore/Ada_Drivers_Library,ellamosi/Ada_BMP_Library,simonjwright/Ada_Drivers_Library,AdaCore/Ada_Drivers_Library,lambourg/Ada_Drivers_Library,simonjwright/Ada_Drivers_Library,Fabien-Chouteau/Ada_Drivers_Library
4d1dcc4453c271858c0b91bd46fa45c6c425f933
src/gen-commands-database.adb
src/gen-commands-database.adb
----------------------------------------------------------------------- -- gen-commands-database -- Database creation from application model -- Copyright (C) 2011, 2012, 2016, 2017, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Text_IO; with Ada.Strings.Fixed; with Ada.IO_Exceptions; with Ada.Directories; with Ada.Exceptions; with Util.Strings; with Util.Files; with Util.Log.Loggers; with Util.Strings.Vectors; with ADO.Drivers; with ADO.Sessions.Sources; with ADO.Schemas.Databases; package body Gen.Commands.Database is Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Gen.Commands.Database"); function Get_Schema_Path (Model_Dir : in String; Model : in String; Config : in ADO.Sessions.Sources.Data_Source) return String; function Get_Schema_Path (Model_Dir : in String; Model : in String; Config : in ADO.Sessions.Sources.Data_Source) return String is Driver : constant String := Config.Get_Driver; Dir : constant String := Util.Files.Compose (Model_Dir, Driver); begin return Util.Files.Compose (Dir, "create-" & Model & "-" & Driver & ".sql"); end Get_Schema_Path; -- ------------------------------ -- 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); procedure Create_Database (Model_Dir : in String; Database : in String; Username : in String; Password : in String); -- ------------------------------ -- Create the database, the user and the tables. -- ------------------------------ procedure Create_Database (Model_Dir : in String; Database : in String; Username : in String; Password : in String) is Admin : ADO.Sessions.Sources.Data_Source; Config : ADO.Sessions.Sources.Data_Source; Messages : Util.Strings.Vectors.Vector; begin Config.Set_Connection (Database); Admin := Config; if Config.Get_Database = "" then Generator.Error ("Invalid database connection: no database name specified"); return; end if; declare Name : constant String := Generator.Get_Project_Name; Path : constant String := Get_Schema_Path (Model_Dir, Name, Config); begin Log.Info ("Creating database tables using schema '{0}'", Path); if not Ada.Directories.Exists (Path) then Generator.Error ("SQL file '{0}' does not exist.", Path); Generator.Error ("Please, run the following command: dynamo generate db"); return; end if; if Config.Get_Driver = "mysql" or Config.Get_Driver = "postgresql" then if Config.Get_Property ("user") = "" then Generator.Error ("Invalid database connection: missing user property"); return; end if; Admin.Set_Property ("user", Username); Admin.Set_Property ("password", Password); elsif Config.Get_Driver /= "sqlite" then Generator.Error ("Database driver {0} is not supported.", Config.Get_Driver); return; end if; Admin.Set_Database (""); ADO.Schemas.Databases.Create_Database (Admin, Config, Path, Messages); -- Report the messages for Msg of Messages loop Log.Error ("{0}", Msg); end loop; end; -- Remember the database connection string. Generator.Set_Project_Property ("database", Database); Generator.Save_Project; exception when E : others => Generator.Error (Ada.Exceptions.Exception_Message (E)); end Create_Database; Model : constant String := (if Args.Get_Count > 0 then Args.Get_Argument (1) else ""); Arg1 : constant String := (if Args.Get_Count > 1 then Args.Get_Argument (2) else ""); Arg2 : constant String := (if Args.Get_Count > 2 then Args.Get_Argument (3) else ""); Arg3 : constant String := (if Args.Get_Count > 3 then Args.Get_Argument (4) else ""); begin Generator.Read_Project ("dynamo.xml"); -- Initialize the database drivers. ADO.Drivers.Initialize (Generator.Get_Properties); -- Check if a database is specified in the command line and use it. if Ada.Strings.Fixed.Index (Arg1, "://") > 0 or Arg3'Length > 0 then Create_Database (Model, Arg1, Arg2, Arg3); else declare Database : constant String := Generator.Get_Project_Property ("database"); begin -- Otherwise, get the database identification from dynamo.xml configuration. if Ada.Strings.Fixed.Index (Database, "://") = 0 then Generator.Error ("No database specified."); return; end if; Create_Database (Model, Database, Arg1, Arg2); end; end if; end Execute; -- ------------------------------ -- Write the help associated with the command. -- ------------------------------ procedure Help (Cmd : in out Command; Generator : in out Gen.Generator.Handler) is pragma Unreferenced (Cmd, Generator); use Ada.Text_IO; begin Put_Line ("create-database: Creates the database"); Put_Line ("Usage: create-database MODEL [CONNECTION] ADMIN-USER [ADMIN-PASSWORD]"); New_Line; Put_Line (" Create the database specified by the connection string."); Put_Line (" The connection string has the form:"); Put_Line (" driver://host[:port]/database"); New_Line; Put_Line (" The database must not exist. The user specified in the connection string"); Put_Line (" is granted the access to the new database."); end Help; end Gen.Commands.Database;
----------------------------------------------------------------------- -- gen-commands-database -- Database creation from application model -- Copyright (C) 2011, 2012, 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.Text_IO; with Ada.Strings.Fixed; with Ada.Directories; with Ada.Exceptions; with Util.Strings; with Util.Files; with Util.Log.Loggers; with Util.Strings.Vectors; with ADO.Drivers; with ADO.Sessions.Sources; with ADO.Schemas.Databases; package body Gen.Commands.Database is Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Gen.Commands.Database"); function Get_Schema_Path (Model_Dir : in String; Model : in String; Config : in ADO.Sessions.Sources.Data_Source) return String; function Get_Schema_Path (Model_Dir : in String; Model : in String; Config : in ADO.Sessions.Sources.Data_Source) return String is Driver : constant String := Config.Get_Driver; Dir : constant String := Util.Files.Compose (Model_Dir, Driver); begin return Util.Files.Compose (Dir, "create-" & Model & "-" & Driver & ".sql"); end Get_Schema_Path; -- ------------------------------ -- 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); procedure Create_Database (Model_Dir : in String; Database : in String; Username : in String; Password : in String); -- ------------------------------ -- Create the database, the user and the tables. -- ------------------------------ procedure Create_Database (Model_Dir : in String; Database : in String; Username : in String; Password : in String) is Admin : ADO.Sessions.Sources.Data_Source; Config : ADO.Sessions.Sources.Data_Source; Messages : Util.Strings.Vectors.Vector; begin Config.Set_Connection (Database); Admin := Config; if Config.Get_Database = "" then Generator.Error ("Invalid database connection: no database name specified"); return; end if; declare Name : constant String := Generator.Get_Project_Name; Path : constant String := Get_Schema_Path (Model_Dir, Name, Config); begin Log.Info ("Creating database tables using schema '{0}'", Path); if not Ada.Directories.Exists (Path) then Generator.Error ("SQL file '{0}' does not exist.", Path); Generator.Error ("Please, run the following command: dynamo generate db"); return; end if; if Config.Get_Driver = "mysql" or Config.Get_Driver = "postgresql" then if Config.Get_Property ("user") = "" then Generator.Error ("Invalid database connection: missing user property"); return; end if; Admin.Set_Property ("user", Username); Admin.Set_Property ("password", Password); elsif Config.Get_Driver /= "sqlite" then Generator.Error ("Database driver {0} is not supported.", Config.Get_Driver); return; end if; Admin.Set_Database (""); ADO.Schemas.Databases.Create_Database (Admin, Config, Path, Messages); -- Report the messages for Msg of Messages loop Log.Error ("{0}", Msg); end loop; end; -- Remember the database connection string. Generator.Set_Project_Property ("database", Database); Generator.Save_Project; exception when E : others => Generator.Error (Ada.Exceptions.Exception_Message (E)); end Create_Database; Model : constant String := (if Args.Get_Count > 0 then Args.Get_Argument (1) else ""); Arg1 : constant String := (if Args.Get_Count > 1 then Args.Get_Argument (2) else ""); Arg2 : constant String := (if Args.Get_Count > 2 then Args.Get_Argument (3) else ""); Arg3 : constant String := (if Args.Get_Count > 3 then Args.Get_Argument (4) else ""); begin Generator.Read_Project ("dynamo.xml"); -- Initialize the database drivers. ADO.Drivers.Initialize (Generator.Get_Properties); -- Check if a database is specified in the command line and use it. if Ada.Strings.Fixed.Index (Arg1, "://") > 0 or Arg3'Length > 0 then Create_Database (Model, Arg1, Arg2, Arg3); else declare Database : constant String := Generator.Get_Project_Property ("database"); begin -- Otherwise, get the database identification from dynamo.xml configuration. if Ada.Strings.Fixed.Index (Database, "://") = 0 then Generator.Error ("No database specified."); return; end if; Create_Database (Model, Database, Arg1, Arg2); end; end if; end Execute; -- ------------------------------ -- Write the help associated with the command. -- ------------------------------ procedure Help (Cmd : in out Command; Generator : in out Gen.Generator.Handler) is pragma Unreferenced (Cmd, Generator); use Ada.Text_IO; begin Put_Line ("create-database: Creates the database"); Put_Line ("Usage: create-database MODEL [CONNECTION] ADMIN-USER [ADMIN-PASSWORD]"); New_Line; Put_Line (" Create the database specified by the connection string."); Put_Line (" The connection string has the form:"); Put_Line (" driver://host[:port]/database"); New_Line; Put_Line (" The database must not exist. The user specified in the connection string"); Put_Line (" is granted the access to the new database."); end Help; end Gen.Commands.Database;
Remove unecessary with Ada.IO_Exceptions
Remove unecessary with Ada.IO_Exceptions
Ada
apache-2.0
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
cb50d2a6a6b056717c627286b380b2313c8f83f5
src/gl/interface/gl-objects-buffers.ads
src/gl/interface/gl-objects-buffers.ads
-- Copyright (c) 2012 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.Pointers; private with GL.Low_Level.Enums; package GL.Objects.Buffers is pragma Preelaborate; function Minimum_Alignment return Types.Size with Post => Minimum_Alignment'Result >= 64; -- Minimum byte alignment of pointers returned by Map_Range -- (at least 64 bytes to support SIMD CPU instructions) type Access_Kind is (Read_Only, Write_Only, Read_Write); type Access_Bits is record Read : Boolean := False; Write : Boolean := False; Invalidate_Range : Boolean := False; Invalidate_Buffer : Boolean := False; Flush_Explicit : Boolean := False; Unsynchronized : Boolean := False; Persistent : Boolean := False; Coherent : Boolean := False; end record; type Storage_Bits is record Read : Boolean := False; Write : Boolean := False; Persistent : Boolean := False; Coherent : Boolean := False; Dynamic_Storage : Boolean := False; Client_Storage : Boolean := False; end record; type Buffer_Target (<>) is tagged limited private; type Buffer is new GL_Object with private; procedure Bind (Target : Buffer_Target; Object : Buffer'Class); -- Bind the buffer object to the target procedure Bind_Base (Target : Buffer_Target; Object : Buffer'Class; Index : Natural); -- Bind the buffer object to the index of the target as well as to -- the target itself. -- -- Target must be one of the following: -- -- * Atomic_Counter_Buffer -- * Transform_Feedback_Buffer -- * Uniform_Buffer -- * Shader_Storage_Buffer procedure Allocate (Object : Buffer; Number_Of_Elements : Long; Kind : Numeric_Type; Storage_Flags : Storage_Bits); -- Use this instead of Load_To_Immutable_Buffer when you don't want -- to copy any data function Current_Object (Target : Buffer_Target) return Buffer'Class; function Access_Type (Object : Buffer) return Access_Kind; function Immutable (Object : Buffer) return Boolean; function Mapped (Object : Buffer) return Boolean; function Size (Object : Buffer) return Long_Size; function Storage_Flags (Object : Buffer) return Storage_Bits; overriding procedure Initialize_Id (Object : in out Buffer); overriding procedure Delete_Id (Object : in out Buffer); overriding function Identifier (Object : Buffer) return Types.Debug.Identifier is (Types.Debug.Buffer); procedure Unmap (Object : in out Buffer); procedure Clear_With_Zeros (Object : Buffer); procedure Invalidate_Data (Object : in out Buffer); generic with package Pointers is new Interfaces.C.Pointers (<>); package Buffer_Pointers is subtype Pointer is Pointers.Pointer; procedure Bind_Range (Target : Buffer_Target; Object : Buffer'Class; Index : Natural; Offset, Length : Types.Size); -- Bind a part of the buffer object to the index of the target as -- well as to the target itself. -- -- Target must be one of the following: -- -- * Atomic_Counter_Buffer -- * Transform_Feedback_Buffer -- * Uniform_Buffer -- * Shader_Storage_Buffer procedure Load_To_Immutable_Buffer (Object : Buffer; Data : Pointers.Element_Array; Storage_Flags : Storage_Bits); procedure Map_Range (Object : in out Buffer; Access_Flags : Access_Bits; Offset, Length : Types.Size; Pointer : out Pointers.Pointer); function Get_Mapped_Data (Pointer : not null Pointers.Pointer; Offset, Length : Types.Size) return Pointers.Element_Array with Pre => Length > 0, Post => Get_Mapped_Data'Result'Length = Length; procedure Set_Mapped_Data (Pointer : not null Pointers.Pointer; Offset : Types.Size; Data : Pointers.Element_Array) with Pre => Data'Length > 0; procedure Set_Mapped_Data (Pointer : not null Pointers.Pointer; Offset : Types.Size; Value : Pointers.Element); procedure Flush_Buffer_Range (Object : in out Buffer; Offset, Length : Types.Size); function To_Pointer (Object : Buffer) return Pointers.Pointer; procedure Clear_Data (Object : Buffer; Kind : Numeric_Type; Data : in out Pointers.Element_Array) with Pre => Data'Length in 1 .. 4 and then Kind /= Double_Type and then (if Data'Length = 3 then Kind not in Byte_Type | UByte_Type | Short_Type | UShort_Type | Half_Type); procedure Clear_Sub_Data (Object : Buffer; Offset, Length : Types.Size; Kind : Numeric_Type; Data : in out Pointers.Element_Array) with Pre => Data'Length in 1 .. 4 and then Kind /= Double_Type and then (if Data'Length = 3 then Kind not in Byte_Type | UByte_Type | Short_Type | UShort_Type | Half_Type); procedure Clear_With_Zeros (Object : Buffer; Offset, Length : Types.Size); procedure Copy_Sub_Data (Object, Target_Object : Buffer; Read_Offset, Write_Offset, Length : Types.Size); procedure Set_Sub_Data (Object : Buffer; Offset : Types.Size; Data : in out Pointers.Element_Array); procedure Get_Sub_Data (Object : Buffer; Offset : Types.Size; Data : out Pointers.Element_Array); procedure Invalidate_Sub_Data (Object : Buffer; Offset, Length : Types.Size); end Buffer_Pointers; Array_Buffer : constant Buffer_Target; Element_Array_Buffer : constant Buffer_Target; Pixel_Pack_Buffer : constant Buffer_Target; Pixel_Unpack_Buffer : constant Buffer_Target; Uniform_Buffer : constant Buffer_Target; Texture_Buffer : constant Buffer_Target; Transform_Feedback_Buffer : constant Buffer_Target; Copy_Read_Buffer : constant Buffer_Target; Copy_Write_Buffer : constant Buffer_Target; Draw_Indirect_Buffer : constant Buffer_Target; Parameter_Buffer : constant Buffer_Target; Shader_Storage_Buffer : constant Buffer_Target; Dispatch_Indirect_Buffer : constant Buffer_Target; Query_Buffer : constant Buffer_Target; Atomic_Counter_Buffer : constant Buffer_Target; private for Access_Kind use (Read_Only => 16#88B8#, Write_Only => 16#88B9#, Read_Write => 16#88BA#); for Access_Kind'Size use Low_Level.Enum'Size; for Access_Bits use record Read at 0 range 0 .. 0; Write at 0 range 1 .. 1; Invalidate_Range at 0 range 2 .. 2; Invalidate_Buffer at 0 range 3 .. 3; Flush_Explicit at 0 range 4 .. 4; Unsynchronized at 0 range 5 .. 5; Persistent at 0 range 6 .. 6; Coherent at 0 range 7 .. 7; end record; for Access_Bits'Size use Low_Level.Bitfield'Size; for Storage_Bits use record Read at 0 range 0 .. 0; Write at 0 range 1 .. 1; Persistent at 0 range 6 .. 6; Coherent at 0 range 7 .. 7; Dynamic_Storage at 0 range 8 .. 8; Client_Storage at 0 range 9 .. 9; end record; for Storage_Bits'Size use Low_Level.Bitfield'Size; type Buffer_Target (Kind : Low_Level.Enums.Buffer_Kind) is tagged limited null record; type Buffer is new GL_Object with null record; Array_Buffer : constant Buffer_Target := Buffer_Target'(Kind => Low_Level.Enums.Array_Buffer); Element_Array_Buffer : constant Buffer_Target := Buffer_Target'(Kind => Low_Level.Enums.Element_Array_Buffer); Pixel_Pack_Buffer : constant Buffer_Target := Buffer_Target'(Kind => Low_Level.Enums.Pixel_Pack_Buffer); Pixel_Unpack_Buffer : constant Buffer_Target := Buffer_Target'(Kind => Low_Level.Enums.Pixel_Unpack_Buffer); Uniform_Buffer : constant Buffer_Target := Buffer_Target'(Kind => Low_Level.Enums.Uniform_Buffer); Texture_Buffer : constant Buffer_Target := Buffer_Target'(Kind => Low_Level.Enums.Texture_Buffer); Transform_Feedback_Buffer : constant Buffer_Target := Buffer_Target'(Kind => Low_Level.Enums.Transform_Feedback_Buffer); Copy_Read_Buffer : constant Buffer_Target := Buffer_Target'(Kind => Low_Level.Enums.Copy_Read_Buffer); Copy_Write_Buffer : constant Buffer_Target := Buffer_Target'(Kind => Low_Level.Enums.Copy_Write_Buffer); Draw_Indirect_Buffer : constant Buffer_Target := Buffer_Target'(Kind => Low_Level.Enums.Draw_Indirect_Buffer); Parameter_Buffer : constant Buffer_Target := Buffer_Target'(Kind => Low_Level.Enums.Parameter_Buffer); Shader_Storage_Buffer : constant Buffer_Target := Buffer_Target'(Kind => Low_Level.Enums.Shader_Storage_Buffer); Dispatch_Indirect_Buffer : constant Buffer_Target := Buffer_Target'(Kind => Low_Level.Enums.Dispatch_Indirect_Buffer); Query_Buffer : constant Buffer_Target := Buffer_Target'(Kind => Low_Level.Enums.Query_Buffer); Atomic_Counter_Buffer : constant Buffer_Target := Buffer_Target'(Kind => Low_Level.Enums.Atomic_Counter_Buffer); end GL.Objects.Buffers;
-- Copyright (c) 2012 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.Pointers; private with GL.Low_Level.Enums; package GL.Objects.Buffers is pragma Preelaborate; function Minimum_Alignment return Types.Size with Post => Minimum_Alignment'Result >= 64; -- Minimum byte alignment of pointers returned by Map_Range -- (at least 64 bytes to support SIMD CPU instructions) type Access_Kind is (Read_Only, Write_Only, Read_Write); type Access_Bits is record Read : Boolean := False; Write : Boolean := False; Invalidate_Range : Boolean := False; Invalidate_Buffer : Boolean := False; Flush_Explicit : Boolean := False; Unsynchronized : Boolean := False; Persistent : Boolean := False; Coherent : Boolean := False; end record; type Storage_Bits is record Read : Boolean := False; Write : Boolean := False; Persistent : Boolean := False; Coherent : Boolean := False; Dynamic_Storage : Boolean := False; Client_Storage : Boolean := False; end record with Dynamic_Predicate => (if Storage_Bits.Coherent then Storage_Bits.Persistent) and (if Storage_Bits.Persistent then Storage_Bits.Read or Storage_Bits.Write); type Buffer_Target (<>) is tagged limited private; type Buffer is new GL_Object with private; procedure Bind (Target : Buffer_Target; Object : Buffer'Class); -- Bind the buffer object to the target procedure Bind_Base (Target : Buffer_Target; Object : Buffer'Class; Index : Natural); -- Bind the buffer object to the index of the target as well as to -- the target itself. -- -- Target must be one of the following: -- -- * Atomic_Counter_Buffer -- * Transform_Feedback_Buffer -- * Uniform_Buffer -- * Shader_Storage_Buffer procedure Allocate (Object : Buffer; Number_Of_Elements : Long; Kind : Numeric_Type; Storage_Flags : Storage_Bits); -- Use this instead of Load_To_Immutable_Buffer when you don't want -- to copy any data function Current_Object (Target : Buffer_Target) return Buffer'Class; function Access_Type (Object : Buffer) return Access_Kind; function Immutable (Object : Buffer) return Boolean; function Mapped (Object : Buffer) return Boolean; function Size (Object : Buffer) return Long_Size; function Storage_Flags (Object : Buffer) return Storage_Bits; overriding procedure Initialize_Id (Object : in out Buffer); overriding procedure Delete_Id (Object : in out Buffer); overriding function Identifier (Object : Buffer) return Types.Debug.Identifier is (Types.Debug.Buffer); procedure Unmap (Object : in out Buffer); procedure Clear_With_Zeros (Object : Buffer); procedure Invalidate_Data (Object : in out Buffer); generic with package Pointers is new Interfaces.C.Pointers (<>); package Buffer_Pointers is subtype Pointer is Pointers.Pointer; procedure Bind_Range (Target : Buffer_Target; Object : Buffer'Class; Index : Natural; Offset, Length : Types.Size); -- Bind a part of the buffer object to the index of the target as -- well as to the target itself. -- -- Target must be one of the following: -- -- * Atomic_Counter_Buffer -- * Transform_Feedback_Buffer -- * Uniform_Buffer -- * Shader_Storage_Buffer procedure Load_To_Immutable_Buffer (Object : Buffer; Data : Pointers.Element_Array; Storage_Flags : Storage_Bits); procedure Map_Range (Object : in out Buffer; Access_Flags : Access_Bits; Offset, Length : Types.Size; Pointer : out Pointers.Pointer); function Get_Mapped_Data (Pointer : not null Pointers.Pointer; Offset, Length : Types.Size) return Pointers.Element_Array with Pre => Length > 0, Post => Get_Mapped_Data'Result'Length = Length; procedure Set_Mapped_Data (Pointer : not null Pointers.Pointer; Offset : Types.Size; Data : Pointers.Element_Array) with Pre => Data'Length > 0; procedure Set_Mapped_Data (Pointer : not null Pointers.Pointer; Offset : Types.Size; Value : Pointers.Element); procedure Flush_Buffer_Range (Object : in out Buffer; Offset, Length : Types.Size); function To_Pointer (Object : Buffer) return Pointers.Pointer; procedure Clear_Data (Object : Buffer; Kind : Numeric_Type; Data : in out Pointers.Element_Array) with Pre => Data'Length in 1 .. 4 and then Kind /= Double_Type and then (if Data'Length = 3 then Kind not in Byte_Type | UByte_Type | Short_Type | UShort_Type | Half_Type); procedure Clear_Sub_Data (Object : Buffer; Offset, Length : Types.Size; Kind : Numeric_Type; Data : in out Pointers.Element_Array) with Pre => Data'Length in 1 .. 4 and then Kind /= Double_Type and then (if Data'Length = 3 then Kind not in Byte_Type | UByte_Type | Short_Type | UShort_Type | Half_Type); procedure Clear_With_Zeros (Object : Buffer; Offset, Length : Types.Size); procedure Copy_Sub_Data (Object, Target_Object : Buffer; Read_Offset, Write_Offset, Length : Types.Size); procedure Set_Sub_Data (Object : Buffer; Offset : Types.Size; Data : in out Pointers.Element_Array); procedure Get_Sub_Data (Object : Buffer; Offset : Types.Size; Data : out Pointers.Element_Array); procedure Invalidate_Sub_Data (Object : Buffer; Offset, Length : Types.Size); end Buffer_Pointers; Array_Buffer : constant Buffer_Target; Element_Array_Buffer : constant Buffer_Target; Pixel_Pack_Buffer : constant Buffer_Target; Pixel_Unpack_Buffer : constant Buffer_Target; Uniform_Buffer : constant Buffer_Target; Texture_Buffer : constant Buffer_Target; Transform_Feedback_Buffer : constant Buffer_Target; Copy_Read_Buffer : constant Buffer_Target; Copy_Write_Buffer : constant Buffer_Target; Draw_Indirect_Buffer : constant Buffer_Target; Parameter_Buffer : constant Buffer_Target; Shader_Storage_Buffer : constant Buffer_Target; Dispatch_Indirect_Buffer : constant Buffer_Target; Query_Buffer : constant Buffer_Target; Atomic_Counter_Buffer : constant Buffer_Target; private for Access_Kind use (Read_Only => 16#88B8#, Write_Only => 16#88B9#, Read_Write => 16#88BA#); for Access_Kind'Size use Low_Level.Enum'Size; for Access_Bits use record Read at 0 range 0 .. 0; Write at 0 range 1 .. 1; Invalidate_Range at 0 range 2 .. 2; Invalidate_Buffer at 0 range 3 .. 3; Flush_Explicit at 0 range 4 .. 4; Unsynchronized at 0 range 5 .. 5; Persistent at 0 range 6 .. 6; Coherent at 0 range 7 .. 7; end record; for Access_Bits'Size use Low_Level.Bitfield'Size; for Storage_Bits use record Read at 0 range 0 .. 0; Write at 0 range 1 .. 1; Persistent at 0 range 6 .. 6; Coherent at 0 range 7 .. 7; Dynamic_Storage at 0 range 8 .. 8; Client_Storage at 0 range 9 .. 9; end record; for Storage_Bits'Size use Low_Level.Bitfield'Size; type Buffer_Target (Kind : Low_Level.Enums.Buffer_Kind) is tagged limited null record; type Buffer is new GL_Object with null record; Array_Buffer : constant Buffer_Target := Buffer_Target'(Kind => Low_Level.Enums.Array_Buffer); Element_Array_Buffer : constant Buffer_Target := Buffer_Target'(Kind => Low_Level.Enums.Element_Array_Buffer); Pixel_Pack_Buffer : constant Buffer_Target := Buffer_Target'(Kind => Low_Level.Enums.Pixel_Pack_Buffer); Pixel_Unpack_Buffer : constant Buffer_Target := Buffer_Target'(Kind => Low_Level.Enums.Pixel_Unpack_Buffer); Uniform_Buffer : constant Buffer_Target := Buffer_Target'(Kind => Low_Level.Enums.Uniform_Buffer); Texture_Buffer : constant Buffer_Target := Buffer_Target'(Kind => Low_Level.Enums.Texture_Buffer); Transform_Feedback_Buffer : constant Buffer_Target := Buffer_Target'(Kind => Low_Level.Enums.Transform_Feedback_Buffer); Copy_Read_Buffer : constant Buffer_Target := Buffer_Target'(Kind => Low_Level.Enums.Copy_Read_Buffer); Copy_Write_Buffer : constant Buffer_Target := Buffer_Target'(Kind => Low_Level.Enums.Copy_Write_Buffer); Draw_Indirect_Buffer : constant Buffer_Target := Buffer_Target'(Kind => Low_Level.Enums.Draw_Indirect_Buffer); Parameter_Buffer : constant Buffer_Target := Buffer_Target'(Kind => Low_Level.Enums.Parameter_Buffer); Shader_Storage_Buffer : constant Buffer_Target := Buffer_Target'(Kind => Low_Level.Enums.Shader_Storage_Buffer); Dispatch_Indirect_Buffer : constant Buffer_Target := Buffer_Target'(Kind => Low_Level.Enums.Dispatch_Indirect_Buffer); Query_Buffer : constant Buffer_Target := Buffer_Target'(Kind => Low_Level.Enums.Query_Buffer); Atomic_Counter_Buffer : constant Buffer_Target := Buffer_Target'(Kind => Low_Level.Enums.Atomic_Counter_Buffer); end GL.Objects.Buffers;
Add dynamic predicate to type Storage_Bits
gl: Add dynamic predicate to type Storage_Bits Signed-off-by: onox <[email protected]>
Ada
apache-2.0
onox/orka
353f8c139eba013d48ec30013832c48a49d771e7
src/asf-components.adb
src/asf-components.adb
----------------------------------------------------------------------- -- components -- Component tree -- 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.Contexts.Default; with Ada.Unchecked_Deallocation; package body ASF.Components is -- ------------------------------ -- Get the parent component. -- Returns null if the node is the root element. -- ------------------------------ function Get_Parent (UI : UIComponent) return UIComponent_Access is begin return UI.Parent; end Get_Parent; -- ------------------------------ -- Return a client-side identifier for this component, generating -- one if necessary. -- ------------------------------ function Get_Client_Id (UI : UIComponent) return Unbounded_String is begin return UI.Id; end Get_Client_Id; -- ------------------------------ -- Get the list of children. -- ------------------------------ function Get_Children (UI : UIComponent) return UIComponent_List is Result : UIComponent_List; begin Result.Child := UI.First_Child; return Result; end Get_Children; function Create_UIComponent (Parent : UIComponent_Access; Tag : access ASF.Views.Nodes.Tag_Node'Class) return UIComponent_Access is Result : UIComponent_Access := new UIComponent; begin Append (Parent, Result, Tag); return Result; end Create_UIComponent; procedure Append (UI : in UIComponent_Access; Child : in UIComponent_Access; Tag : access ASF.Views.Nodes.Tag_Node'Class) is begin Child.Tag := Tag; Child.Parent := UI; Child.Next := null; if UI.Last_Child = null then UI.First_Child := Child; else UI.Last_Child.Next := Child; end if; UI.Last_Child := Child; end Append; -- ------------------------------ -- Search for and return the {@link UIComponent} with an <code>id</code> -- that matches the specified search expression (if any), according to -- the algorithm described below. -- ------------------------------ function Find (UI : UIComponent; Name : String) return UIComponent_Access is begin return null; end Find; function Get_Context (UI : in UIComponent) return ASF.Contexts.Faces.Faces_Context_Access is begin return ASF.Contexts.Faces.Current; end Get_Context; -- ------------------------------ -- Check whether the component and its children must be rendered. -- ------------------------------ function Is_Rendered (UI : UIComponent; Context : Faces_Context'Class) return Boolean is Attr : constant EL.Objects.Object := UI.Get_Attribute (Context, "rendered"); begin return EL.Objects.To_Boolean (Attr); end Is_Rendered; -- ------------------------------ -- Set whether the component is rendered. -- ------------------------------ procedure Set_Rendered (UI : in out UIComponent; Rendered : in Boolean) is begin null; end Set_Rendered; function Get_Attribute (UI : UIComponent; Context : Faces_Context'Class; Name : String) return EL.Objects.Object is N : Unbounded_String; begin -- N := ASF.Views.Nodes.Get_Name (UI.Tag.all); if UI.Tag = null then return EL.Objects.Null_Object; end if; -- Attr := ASF.Views.Nodes.Get_Attribute (UI.Tag.all, Name); raise Constraint_Error; end Get_Attribute; -- ------------------------------ -- Get the attribute tag -- ------------------------------ function Get_Attribute (UI : UIComponent; Name : String) return access ASF.Views.Nodes.Tag_Attribute is begin return null; end Get_Attribute; procedure Set_Attribute (UI : in out UIComponent; Name : in String; Value : in EL.Objects.Object) is begin null; end Set_Attribute; procedure Encode_Begin (UI : in UIComponent; Context : in out Faces_Context'Class) is begin null; end Encode_Begin; procedure Encode_Children (UI : in UIComponent; Context : in out Faces_Context'Class) is Child : UIComponent_Access := UI.First_Child; begin while Child /= null loop Child.Encode_All (Context); Child := Child.Next; end loop; end Encode_Children; procedure Encode_End (UI : in UIComponent; Context : in out Faces_Context'Class) is begin null; end Encode_End; procedure Encode_All (UI : in UIComponent'Class; Context : in out Faces_Context'Class) is begin UI.Encode_Begin (Context); UI.Encode_Children (Context); UI.Encode_End (Context); end Encode_All; function Get_Value (Attr : UIAttribute; UI : UIComponent'Class) return EL.Objects.Object is begin return EL.Objects.Null_Object; -- if not Is_Null (Attr.Object) then -- return Attr.Object; -- else -- return Attr.Definition.Binding.Get_Value (UI.Get_Context); -- end if; end Get_Value; procedure Free_Component is new Ada.Unchecked_Deallocation (Object => UIComponent'Class, Name => UIComponent_Access); -- ------------------------------ -- Delete the component tree recursively. -- ------------------------------ procedure Delete (UI : in out UIComponent_Access) is begin if UI /= null then declare C : UIComponent_Access := UI.First_Child; begin while C /= null loop UI.First_Child := C.Next; Delete (C); C := UI.First_Child; end loop; end; Free_Component (UI); end if; end Delete; end ASF.Components;
----------------------------------------------------------------------- -- components -- Component tree -- 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 Ada.Unchecked_Deallocation; with ASF.Views.Nodes; package body ASF.Components is -- ------------------------------ -- Get the parent component. -- Returns null if the node is the root element. -- ------------------------------ function Get_Parent (UI : UIComponent) return UIComponent_Access is begin return UI.Parent; end Get_Parent; -- ------------------------------ -- Return a client-side identifier for this component, generating -- one if necessary. -- ------------------------------ function Get_Client_Id (UI : UIComponent) return Unbounded_String is begin return UI.Id; end Get_Client_Id; -- ------------------------------ -- Get the list of children. -- ------------------------------ function Get_Children (UI : UIComponent) return UIComponent_List is Result : UIComponent_List; begin Result.Child := UI.First_Child; return Result; end Get_Children; function Create_UIComponent (Parent : UIComponent_Access; Tag : access ASF.Views.Nodes.Tag_Node'Class) return UIComponent_Access is Result : constant UIComponent_Access := new UIComponent; begin Append (Parent, Result, Tag); return Result; end Create_UIComponent; procedure Append (UI : in UIComponent_Access; Child : in UIComponent_Access; Tag : access ASF.Views.Nodes.Tag_Node'Class) is begin Child.Tag := Tag; Child.Parent := UI; Child.Next := null; if UI.Last_Child = null then UI.First_Child := Child; else UI.Last_Child.Next := Child; end if; UI.Last_Child := Child; end Append; -- ------------------------------ -- Search for and return the {@link UIComponent} with an <code>id</code> -- that matches the specified search expression (if any), according to -- the algorithm described below. -- ------------------------------ function Find (UI : UIComponent; Name : String) return UIComponent_Access is begin return null; end Find; function Get_Context (UI : in UIComponent) return ASF.Contexts.Faces.Faces_Context_Access is begin return ASF.Contexts.Faces.Current; end Get_Context; -- ------------------------------ -- Check whether the component and its children must be rendered. -- ------------------------------ function Is_Rendered (UI : UIComponent; Context : Faces_Context'Class) return Boolean is Attr : constant EL.Objects.Object := UI.Get_Attribute (Context, "rendered"); begin return EL.Objects.To_Boolean (Attr); end Is_Rendered; -- ------------------------------ -- Set whether the component is rendered. -- ------------------------------ procedure Set_Rendered (UI : in out UIComponent; Rendered : in Boolean) is begin null; end Set_Rendered; function Get_Attribute (UI : UIComponent; Context : Faces_Context'Class; Name : String) return EL.Objects.Object is Attr : constant access ASF.Views.Nodes.Tag_Attribute := UI.Get_Attribute (Name); begin if Attr = null then return EL.Objects.Null_Object; end if; return ASF.Views.Nodes.Get_Value (Attr.all, UI); end Get_Attribute; -- ------------------------------ -- Get the attribute tag -- ------------------------------ function Get_Attribute (UI : UIComponent; Name : String) return access ASF.Views.Nodes.Tag_Attribute is begin return null; end Get_Attribute; procedure Set_Attribute (UI : in out UIComponent; Name : in String; Value : in EL.Objects.Object) is begin null; end Set_Attribute; procedure Encode_Begin (UI : in UIComponent; Context : in out Faces_Context'Class) is begin null; end Encode_Begin; procedure Encode_Children (UI : in UIComponent; Context : in out Faces_Context'Class) is Child : UIComponent_Access := UI.First_Child; begin while Child /= null loop Child.Encode_All (Context); Child := Child.Next; end loop; end Encode_Children; procedure Encode_End (UI : in UIComponent; Context : in out Faces_Context'Class) is begin null; end Encode_End; procedure Encode_All (UI : in UIComponent'Class; Context : in out Faces_Context'Class) is begin UI.Encode_Begin (Context); UI.Encode_Children (Context); UI.Encode_End (Context); end Encode_All; -- ------------------------------ -- Get the attribute value. -- ------------------------------ function Get_Value (Attr : UIAttribute; UI : UIComponent'Class) return EL.Objects.Object is begin if not EL.Objects.Is_Null (Attr.Value) then return Attr.Value; else return ASF.Views.Nodes.Get_Value (Attr.Definition.all, UI); end if; end Get_Value; procedure Free_Component is new Ada.Unchecked_Deallocation (Object => UIComponent'Class, Name => UIComponent_Access); -- ------------------------------ -- Delete the component tree recursively. -- ------------------------------ procedure Delete (UI : in out UIComponent_Access) is begin if UI /= null then declare C : UIComponent_Access := UI.First_Child; begin while C /= null loop UI.First_Child := C.Next; Delete (C); C := UI.First_Child; end loop; end; Free_Component (UI); end if; end Delete; end ASF.Components;
Implement UIComponent.Get_Attribute
Implement UIComponent.Get_Attribute
Ada
apache-2.0
Letractively/ada-asf,Letractively/ada-asf,Letractively/ada-asf
6b8cb71e43d6ea7b477510ed6700f6790dba2c78
src/gen-model-beans.ads
src/gen-model-beans.ads
----------------------------------------------------------------------- -- gen-model-beans -- Ada Bean declarations -- Copyright (C) 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Util.Beans.Objects; with Gen.Model.Tables; with Gen.Model.Operations; package Gen.Model.Beans is use Ada.Strings.Unbounded; -- ------------------------------ -- Bean Definition -- ------------------------------ type Bean_Definition is new Tables.Table_Definition with null record; type Bean_Definition_Access is access all Bean_Definition'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 Bean_Definition; Name : in String) return Util.Beans.Objects.Object; -- Prepare the generation of the model. overriding procedure Prepare (O : in out Bean_Definition); -- Initialize the table definition instance. overriding procedure Initialize (O : in out Bean_Definition); -- Create an attribute with the given name and add it to the bean. procedure Add_Attribute (Bean : in out Bean_Definition; Name : in Unbounded_String; Column : out Gen.Model.Tables.Column_Definition_Access); -- Create a bean with the given name. function Create_Bean (Name : in Unbounded_String) return Bean_Definition_Access; end Gen.Model.Beans;
----------------------------------------------------------------------- -- gen-model-beans -- Ada Bean declarations -- Copyright (C) 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Util.Beans.Objects; with Gen.Model.Tables; package Gen.Model.Beans is use Ada.Strings.Unbounded; -- ------------------------------ -- Bean Definition -- ------------------------------ type Bean_Definition is new Tables.Table_Definition with null record; type Bean_Definition_Access is access all Bean_Definition'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 Bean_Definition; Name : in String) return Util.Beans.Objects.Object; -- Prepare the generation of the model. overriding procedure Prepare (O : in out Bean_Definition); -- Initialize the table definition instance. overriding procedure Initialize (O : in out Bean_Definition); -- Create an attribute with the given name and add it to the bean. procedure Add_Attribute (Bean : in out Bean_Definition; Name : in Unbounded_String; Column : out Gen.Model.Tables.Column_Definition_Access); -- Create a bean with the given name. function Create_Bean (Name : in Unbounded_String) return Bean_Definition_Access; end Gen.Model.Beans;
Fix compilation warning
Fix compilation warning
Ada
apache-2.0
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
ca31f451961e11fe72f19f73fb03804bbcccfcb0
src/security-openid.ads
src/security-openid.ads
----------------------------------------------------------------------- -- security-openid -- Open ID 2.0 Support -- Copyright (C) 2009, 2010, 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Ada.Calendar; with Ada.Finalization; -- == OpenID == -- The <b>Security.Openid</b> package implements an authentication framework based -- on OpenID 2.0. -- -- See OpenID Authentication 2.0 - Final -- http://openid.net/specs/openid-authentication-2_0.html -- -- There are basically two steps that an application must implement: -- -- * Discovery to resolve and use the OpenID provider and redirect the user to the -- provider authentication form. -- * Verify to decode the authentication and check its result. -- -- [http://ada-security.googlecode.com/svn/wiki/OpenID.png] -- -- The authentication process is the following: -- -- * The <b>Initialize</b> procedure is called to configure the OpenID realm and set the -- OpenID return callback CB. -- * 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. -- * 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. -- * The <b>Get_Authentication_URL</b> builds the provider OpenID authentication -- URL for the association. -- * 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. -- -- -- == 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>. -- -- Mgr : Openid.Manager; -- OP : Openid.End_Point; -- Assoc : constant Association_Access := new Association; -- -- The -- -- Server.Initialize (Mgr); -- 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. -- -- Mgr : Openid.Manager; -- Assoc : Association_Access := ...; -- Get the association saved in the session. -- Auth : Openid.Authentication; -- Params : Auth_Params; -- -- The OpenID 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. -- -- Server.Initialize (Mgr); -- Mgr.Verify (Assoc.all, Params, Auth); -- if Openid.Get_Status (Auth) /= Openid.AUTHENTICATED then ... -- Failure. -- -- -- package Security.Openid is 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; -- ------------------------------ -- OpenID provider -- ------------------------------ -- The <b>End_Point</b> represents the OpenID provider that will authenticate -- the user. type End_Point is private; function To_String (OP : End_Point) return String; -- ------------------------------ -- Association -- ------------------------------ -- The OpenID association contains the shared secret between the relying party -- and the OpenID provider. The association can be cached and reused to authenticate -- different users using the same OpenID provider. The association also has an -- expiration date. type Association is private; -- 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); -- ------------------------------ -- OpenID provider -- ------------------------------ -- 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; -- ------------------------------ -- OpenID 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; -- ------------------------------ -- OpenID Manager -- ------------------------------ -- The <b>Manager</b> provides the core operations for the OpenID process. type Manager is tagged limited private; -- Initialize the OpenID realm. procedure Initialize (Realm : in out Manager; Name : in String; Return_To : in String); -- Discover the OpenID 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. -- (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 OpenID 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); 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); -- Verify the authentication result procedure Verify_Discovered (Realm : in out Manager; Assoc : in Association; Request : in Parameters'Class; Result : out Authentication); -- Verify the signature part of the result procedure Verify_Signature (Realm : in Manager; Assoc : in Association; Request : in Parameters'Class; Result : in out Authentication); -- Read the XRDS document from the URI and initialize the OpenID provider end point. procedure Discover_XRDS (Realm : in out Manager; URI : in String; Result : out End_Point); -- Extract from the XRDS content the OpenID provider URI. -- The default implementation is very basic as it returns the first <URI> -- available in the stream without validating the XRDS document. -- Raises the <b>Invalid_End_Point</b> exception if the URI cannot be found. procedure Extract_XRDS (Realm : in out Manager; Content : in String; Result : out End_Point); private use Ada.Strings.Unbounded; type Association is record 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 is new Ada.Finalization.Limited_Controlled with record Realm : Unbounded_String; Return_To : Unbounded_String; end record; type Principal is new Security.Principal with record Auth : Authentication; end record; end Security.Openid;
----------------------------------------------------------------------- -- security-openid -- Open ID 2.0 Support -- Copyright (C) 2009, 2010, 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Ada.Calendar; with Ada.Finalization; -- == OpenID == -- The <b>Security.Openid</b> package implements an authentication framework based -- on OpenID 2.0. -- -- See OpenID Authentication 2.0 - Final -- http://openid.net/specs/openid-authentication-2_0.html -- -- 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 OpenID manager must be declared and configured. -- -- Mgr : Openid.Manager; -- -- For the configuration, the <b>Initialize</b> procedure is called to configure -- the OpenID realm and set the OpenID return callback CB. 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"); -- -- After this initialization, the OpenID manager can be used in the authentication process. -- -- === 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>. -- -- OP : Openid.End_Point; -- Assoc : constant Association_Access := new 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. -- Auth : Openid.Authentication; -- Params : Auth_Params; -- -- The OpenID 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, Auth); -- if Openid.Get_Status (Auth) /= Openid.AUTHENTICATED then ... -- Failure. -- -- -- package Security.Openid is 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; -- ------------------------------ -- OpenID provider -- ------------------------------ -- The <b>End_Point</b> represents the OpenID provider that will authenticate -- the user. type End_Point is private; function To_String (OP : End_Point) return String; -- ------------------------------ -- Association -- ------------------------------ -- The OpenID association contains the shared secret between the relying party -- and the OpenID provider. The association can be cached and reused to authenticate -- different users using the same OpenID provider. The association also has an -- expiration date. type Association is private; -- 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); -- ------------------------------ -- OpenID provider -- ------------------------------ -- 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; -- ------------------------------ -- OpenID 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; -- ------------------------------ -- OpenID Manager -- ------------------------------ -- The <b>Manager</b> provides the core operations for the OpenID process. type Manager is tagged limited private; -- Initialize the OpenID realm. procedure Initialize (Realm : in out Manager; Name : in String; Return_To : in String); -- Discover the OpenID 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. -- (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 OpenID 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); 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); -- Verify the authentication result procedure Verify_Discovered (Realm : in out Manager; Assoc : in Association; Request : in Parameters'Class; Result : out Authentication); -- Verify the signature part of the result procedure Verify_Signature (Realm : in Manager; Assoc : in Association; Request : in Parameters'Class; Result : in out Authentication); -- Read the XRDS document from the URI and initialize the OpenID provider end point. procedure Discover_XRDS (Realm : in out Manager; URI : in String; Result : out End_Point); -- Extract from the XRDS content the OpenID provider URI. -- The default implementation is very basic as it returns the first <URI> -- available in the stream without validating the XRDS document. -- Raises the <b>Invalid_End_Point</b> exception if the URI cannot be found. procedure Extract_XRDS (Realm : in out Manager; Content : in String; Result : out End_Point); private use Ada.Strings.Unbounded; type Association is record 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 is new Ada.Finalization.Limited_Controlled with record Realm : Unbounded_String; Return_To : Unbounded_String; end record; type Principal is new Security.Principal with record Auth : Authentication; end record; end Security.Openid;
Update the documentation
Update the documentation
Ada
apache-2.0
stcarrez/ada-security
19cca32b9c1006d135fc0ec9cb9cc977b0e2dc40
src/sys/streams/util-streams-buffered.adb
src/sys/streams/util-streams-buffered.adb
----------------------------------------------------------------------- -- util-streams-buffered -- Buffered streams utilities -- Copyright (C) 2010, 2011, 2013, 2014, 2016, 2017, 2018, 2019, 2020 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Interfaces; with Ada.IO_Exceptions; with Ada.Unchecked_Deallocation; package body Util.Streams.Buffered is procedure Free_Buffer is new Ada.Unchecked_Deallocation (Object => Stream_Element_Array, Name => Buffer_Access); -- ------------------------------ -- Initialize the stream to read or write on the given streams. -- An internal buffer is allocated for writing the stream. -- ------------------------------ procedure Initialize (Stream : in out Output_Buffer_Stream; Output : access Output_Stream'Class; Size : in Positive) is begin Free_Buffer (Stream.Buffer); Stream.Last := Stream_Element_Offset (Size); Stream.Buffer := new Stream_Element_Array (1 .. Stream.Last); Stream.Output := Output; Stream.Write_Pos := 1; Stream.Read_Pos := 1; Stream.No_Flush := False; end Initialize; -- ------------------------------ -- Initialize the stream to read from the string. -- ------------------------------ procedure Initialize (Stream : in out Input_Buffer_Stream; Content : in String) is begin Free_Buffer (Stream.Buffer); Stream.Last := Stream_Element_Offset (Content'Length); Stream.Buffer := new Stream_Element_Array (1 .. Content'Length); Stream.Input := null; Stream.Write_Pos := Stream.Last + 1; Stream.Read_Pos := 1; for I in Content'Range loop Stream.Buffer (Stream_Element_Offset (I - Content'First + 1)) := Character'Pos (Content (I)); end loop; end Initialize; -- ------------------------------ -- Initialize the stream with a buffer of <b>Size</b> bytes. -- ------------------------------ procedure Initialize (Stream : in out Output_Buffer_Stream; Size : in Positive) is begin Stream.Initialize (Output => null, Size => Size); Stream.No_Flush := True; Stream.Read_Pos := 1; end Initialize; -- ------------------------------ -- Initialize the stream to read or write on the given streams. -- An internal buffer is allocated for writing the stream. -- ------------------------------ procedure Initialize (Stream : in out Input_Buffer_Stream; Input : access Input_Stream'Class; Size : in Positive) is begin Free_Buffer (Stream.Buffer); Stream.Last := Stream_Element_Offset (Size); Stream.Buffer := new Stream_Element_Array (1 .. Stream.Last); Stream.Input := Input; Stream.Write_Pos := 1; Stream.Read_Pos := 1; end Initialize; -- ------------------------------ -- Initialize the stream from the buffer created for an output stream. -- ------------------------------ procedure Initialize (Stream : in out Input_Buffer_Stream; From : in out Output_Buffer_Stream'Class) is begin Free_Buffer (Stream.Buffer); Stream.Buffer := From.Buffer; From.Buffer := null; Stream.Input := null; Stream.Read_Pos := 1; Stream.Write_Pos := From.Write_Pos + 1; Stream.Last := From.Last; end Initialize; -- ------------------------------ -- Close the sink. -- ------------------------------ overriding procedure Close (Stream : in out Output_Buffer_Stream) is begin if Stream.Output /= null then Output_Buffer_Stream'Class (Stream).Flush; Stream.Output.Close; Free_Buffer (Stream.Buffer); end if; end Close; -- ------------------------------ -- Get the direct access to the buffer. -- ------------------------------ function Get_Buffer (Stream : in Output_Buffer_Stream) return Buffer_Access is begin return Stream.Buffer; end Get_Buffer; -- ------------------------------ -- Get the number of element in the stream. -- ------------------------------ function Get_Size (Stream : in Output_Buffer_Stream) return Natural is begin return Natural (Stream.Write_Pos - Stream.Read_Pos); end Get_Size; -- ------------------------------ -- Write the buffer array to the output stream. -- ------------------------------ overriding procedure Write (Stream : in out Output_Buffer_Stream; Buffer : in Ada.Streams.Stream_Element_Array) is Start : Stream_Element_Offset := Buffer'First; Pos : Stream_Element_Offset := Stream.Write_Pos; Avail : Stream_Element_Offset; Size : Stream_Element_Offset; begin while Start <= Buffer'Last loop Size := Buffer'Last - Start + 1; Avail := Stream.Last - Pos + 1; if Avail = 0 then if Stream.Output = null then raise Ada.IO_Exceptions.End_Error with "Buffer is full"; end if; Stream.Output.Write (Stream.Buffer (1 .. Pos - 1)); Stream.Write_Pos := 1; Pos := 1; Avail := Stream.Last - Pos + 1; end if; if Avail < Size then Size := Avail; end if; Stream.Buffer (Pos .. Pos + Size - 1) := Buffer (Start .. Start + Size - 1); Start := Start + Size; Pos := Pos + Size; Stream.Write_Pos := Pos; -- If we have still more data than the buffer size, flush and write -- the buffer directly. if Start < Buffer'Last and then Buffer'Last - Start > Stream.Buffer'Length then if Stream.Output = null then raise Ada.IO_Exceptions.End_Error with "Buffer is full"; end if; Stream.Output.Write (Stream.Buffer (1 .. Pos - 1)); Stream.Write_Pos := 1; Stream.Output.Write (Buffer (Start .. Buffer'Last)); return; end if; end loop; end Write; -- ------------------------------ -- Flush the stream. -- ------------------------------ overriding procedure Flush (Stream : in out Output_Buffer_Stream) is begin if not Stream.No_Flush then if Stream.Write_Pos > 1 then if Stream.Output /= null then Stream.Output.Write (Stream.Buffer (1 .. Stream.Write_Pos - 1)); end if; Stream.Write_Pos := 1; end if; if Stream.Output /= null then Stream.Output.Flush; end if; end if; end Flush; -- ------------------------------ -- Flush the buffer in the <tt>Into</tt> array and return the index of the -- last element (inclusive) in <tt>Last</tt>. -- ------------------------------ procedure Flush (Stream : in out Output_Buffer_Stream; Into : out Ada.Streams.Stream_Element_Array; Last : out Ada.Streams.Stream_Element_Offset) is begin if Stream.Write_Pos > 1 then Into (Into'First .. Into'First + Stream.Write_Pos - 1) := Stream.Buffer (Stream.Buffer'First .. Stream.Write_Pos - 1); Stream.Write_Pos := 1; Last := Into'First + Stream.Write_Pos - 1; else Last := Into'First - 1; end if; end Flush; -- ------------------------------ -- Flush the buffer stream to the unbounded string. -- ------------------------------ procedure Flush (Stream : in out Output_Buffer_Stream; Into : out Ada.Strings.Unbounded.Unbounded_String) is begin Ada.Strings.Unbounded.Set_Unbounded_String (Into, ""); if Stream.Write_Pos > 1 then for I in 1 .. Stream.Write_Pos - 1 loop Ada.Strings.Unbounded.Append (Into, Character'Val (Stream.Buffer (I))); end loop; Stream.Write_Pos := 1; end if; end Flush; -- ------------------------------ -- Fill the buffer by reading the input stream. -- Raises Data_Error if there is no input stream; -- ------------------------------ procedure Fill (Stream : in out Input_Buffer_Stream) is begin if Stream.Input = null then Stream.Eof := True; else Stream.Input.Read (Stream.Buffer (1 .. Stream.Last - 1), Stream.Write_Pos); Stream.Eof := Stream.Write_Pos < 1; if not Stream.Eof then Stream.Write_Pos := Stream.Write_Pos + 1; end if; Stream.Read_Pos := 1; end if; end Fill; -- ------------------------------ -- Read one character from the input stream. -- ------------------------------ procedure Read (Stream : in out Input_Buffer_Stream; Char : out Character) is begin if Stream.Read_Pos >= Stream.Write_Pos then Stream.Fill; if Stream.Eof then raise Ada.IO_Exceptions.Data_Error with "End of buffer"; end if; end if; Char := Character'Val (Stream.Buffer (Stream.Read_Pos)); Stream.Read_Pos := Stream.Read_Pos + 1; end Read; procedure Read (Stream : in out Input_Buffer_Stream; Value : out Ada.Streams.Stream_Element) is begin if Stream.Read_Pos >= Stream.Write_Pos then Stream.Fill; if Stream.Eof then raise Ada.IO_Exceptions.Data_Error with "End of buffer"; end if; end if; Value := Stream.Buffer (Stream.Read_Pos); Stream.Read_Pos := Stream.Read_Pos + 1; end Read; -- ------------------------------ -- Read one character from the input stream. -- ------------------------------ procedure Read (Stream : in out Input_Buffer_Stream; Char : out Wide_Wide_Character) is use Interfaces; Val : Ada.Streams.Stream_Element; Result : Unsigned_32; begin Stream.Read (Val); -- UTF-8 conversion -- 7 U+0000 U+007F 1 0xxxxxxx if Val <= 16#7F# then Char := Wide_Wide_Character'Val (Val); -- 11 U+0080 U+07FF 2 110xxxxx 10xxxxxx elsif Val <= 16#DF# then Result := Shift_Left (Unsigned_32 (Val and 16#1F#), 6); Stream.Read (Val); Result := Result or Unsigned_32 (Val and 16#3F#); Char := Wide_Wide_Character'Val (Result); -- 16 U+0800 U+FFFF 3 1110xxxx 10xxxxxx 10xxxxxx elsif Val <= 16#EF# then Result := Shift_Left (Unsigned_32 (Val and 16#0F#), 12); Stream.Read (Val); Result := Result or Shift_Left (Unsigned_32 (Val and 16#3F#), 6); Stream.Read (Val); Result := Result or Unsigned_32 (Val and 16#3F#); Char := Wide_Wide_Character'Val (Result); -- 21 U+10000 U+1FFFFF 4 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx else Result := Shift_Left (Unsigned_32 (Val and 16#07#), 18); Stream.Read (Val); Result := Result or Shift_Left (Unsigned_32 (Val and 16#3F#), 12); Stream.Read (Val); Result := Result or Shift_Left (Unsigned_32 (Val and 16#3F#), 6); Stream.Read (Val); Result := Result or Unsigned_32 (Val and 16#3F#); Char := Wide_Wide_Character'Val (Result); end if; end Read; -- ------------------------------ -- Read into the buffer as many bytes as possible and return in -- <b>last</b> the position of the last byte read. -- ------------------------------ overriding procedure Read (Stream : in out Input_Buffer_Stream; Into : out Ada.Streams.Stream_Element_Array; Last : out Ada.Streams.Stream_Element_Offset) is Start : Stream_Element_Offset := Into'First; Pos : Stream_Element_Offset := Stream.Read_Pos; Avail : Stream_Element_Offset; Size : Stream_Element_Offset; Total : Stream_Element_Offset := 0; begin while Start <= Into'Last loop Size := Into'Last - Start + 1; Avail := Stream.Write_Pos - Pos; if Avail = 0 then Stream.Fill; Pos := Stream.Read_Pos; Avail := Stream.Write_Pos - Pos; exit when Avail <= 0; end if; if Avail < Size then Size := Avail; end if; Into (Start .. Start + Size - 1) := Stream.Buffer (Pos .. Pos + Size - 1); Start := Start + Size; Pos := Pos + Size; Total := Total + Size; Stream.Read_Pos := Pos; end loop; Last := Total; end Read; -- ------------------------------ -- Read into the buffer as many bytes as possible and return in -- <b>last</b> the position of the last byte read. -- ------------------------------ procedure Read (Stream : in out Input_Buffer_Stream; Into : in out Ada.Strings.Unbounded.Unbounded_String) is Pos : Stream_Element_Offset := Stream.Read_Pos; Avail : Stream_Element_Offset; begin loop Avail := Stream.Write_Pos - Pos; if Avail = 0 then Stream.Fill; if Stream.Eof then return; end if; Pos := Stream.Read_Pos; Avail := Stream.Write_Pos - Pos; end if; for I in 1 .. Avail loop Ada.Strings.Unbounded.Append (Into, Character'Val (Stream.Buffer (Pos))); Pos := Pos + 1; end loop; Stream.Read_Pos := Pos; end loop; end Read; procedure Read (Stream : in out Input_Buffer_Stream; Into : in out Ada.Strings.Wide_Wide_Unbounded.Unbounded_Wide_Wide_String) is Pos : Stream_Element_Offset; Avail : Stream_Element_Offset; C : Wide_Wide_Character; begin loop Pos := Stream.Read_Pos; Avail := Stream.Write_Pos - Pos; if Avail = 0 then Stream.Fill; if Stream.Eof then return; end if; Pos := Stream.Read_Pos; Avail := Stream.Write_Pos - Pos; end if; Stream.Read (C); Ada.Strings.Wide_Wide_Unbounded.Append (Into, C); end loop; end Read; -- ------------------------------ -- Flush the stream and release the buffer. -- ------------------------------ overriding procedure Finalize (Stream : in out Output_Buffer_Stream) is begin if Stream.Buffer /= null then if Stream.Output /= null then Stream.Flush; end if; Free_Buffer (Stream.Buffer); end if; end Finalize; -- ------------------------------ -- Returns True if the end of the stream is reached. -- ------------------------------ function Is_Eof (Stream : in Input_Buffer_Stream) return Boolean is begin return Stream.Eof; end Is_Eof; -- ------------------------------ -- Flush the stream and release the buffer. -- ------------------------------ overriding procedure Finalize (Object : in out Input_Buffer_Stream) is begin if Object.Buffer /= null then Free_Buffer (Object.Buffer); end if; end Finalize; end Util.Streams.Buffered;
----------------------------------------------------------------------- -- util-streams-buffered -- Buffered streams utilities -- Copyright (C) 2010 - 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 Interfaces; with Ada.IO_Exceptions; with Ada.Unchecked_Deallocation; package body Util.Streams.Buffered is procedure Free_Buffer is new Ada.Unchecked_Deallocation (Object => Stream_Element_Array, Name => Buffer_Access); -- ------------------------------ -- Initialize the stream to read or write on the given streams. -- An internal buffer is allocated for writing the stream. -- ------------------------------ procedure Initialize (Stream : in out Buffer_Stream; Size : in Positive) is begin Free_Buffer (Stream.Buffer); Stream.Last := Stream_Element_Offset (Size); Stream.Buffer := new Stream_Element_Array (1 .. Stream.Last); Stream.Write_Pos := 1; Stream.Read_Pos := 1; end Initialize; -- ------------------------------ -- Initialize the stream to read from the string. -- ------------------------------ procedure Initialize (Stream : in out Buffer_Stream; Content : in String) is begin Free_Buffer (Stream.Buffer); Stream.Last := Stream_Element_Offset (Content'Length); Stream.Buffer := new Stream_Element_Array (1 .. Content'Length); Stream.Write_Pos := Stream.Last + 1; Stream.Read_Pos := 1; for I in Content'Range loop Stream.Buffer (Stream_Element_Offset (I - Content'First + 1)) := Character'Pos (Content (I)); end loop; end Initialize; -- ------------------------------ -- Initialize the stream to read or write on the given streams. -- An internal buffer is allocated for writing the stream. -- ------------------------------ procedure Initialize (Stream : in out Output_Buffer_Stream; Output : access Output_Stream'Class; Size : in Positive) is begin Stream.Initialize (Size); Stream.Output := Output; Stream.No_Flush := False; end Initialize; -- ------------------------------ -- Initialize the stream to read from the string. -- ------------------------------ procedure Initialize (Stream : in out Input_Buffer_Stream; Content : in String) is begin Buffer_Stream (Stream).Initialize (Content); Stream.Input := null; end Initialize; -- ------------------------------ -- Initialize the stream with a buffer of <b>Size</b> bytes. -- ------------------------------ procedure Initialize (Stream : in out Output_Buffer_Stream; Size : in Positive) is begin Buffer_Stream (Stream).Initialize (Size => Size); Stream.Output := null; Stream.No_Flush := True; Stream.Read_Pos := 1; end Initialize; -- ------------------------------ -- Initialize the stream to read or write on the given streams. -- An internal buffer is allocated for writing the stream. -- ------------------------------ procedure Initialize (Stream : in out Input_Buffer_Stream; Input : access Input_Stream'Class; Size : in Positive) is begin Free_Buffer (Stream.Buffer); Stream.Last := Stream_Element_Offset (Size); Stream.Buffer := new Stream_Element_Array (1 .. Stream.Last); Stream.Input := Input; Stream.Write_Pos := 1; Stream.Read_Pos := 1; end Initialize; -- ------------------------------ -- Initialize the stream from the buffer created for an output stream. -- ------------------------------ procedure Initialize (Stream : in out Input_Buffer_Stream; From : in out Buffer_Stream'Class) is begin Free_Buffer (Stream.Buffer); Stream.Buffer := From.Buffer; From.Buffer := null; Stream.Input := null; Stream.Read_Pos := 1; Stream.Write_Pos := From.Write_Pos + 1; Stream.Last := From.Last; end Initialize; -- ------------------------------ -- Close the sink. -- ------------------------------ overriding procedure Close (Stream : in out Output_Buffer_Stream) is begin if Stream.Output /= null then Output_Buffer_Stream'Class (Stream).Flush; Stream.Output.Close; Free_Buffer (Stream.Buffer); end if; end Close; -- ------------------------------ -- Get the direct access to the buffer. -- ------------------------------ function Get_Buffer (Stream : in Buffer_Stream) return Buffer_Access is begin return Stream.Buffer; end Get_Buffer; -- ------------------------------ -- Get the number of element in the stream. -- ------------------------------ function Get_Size (Stream : in Buffer_Stream) return Natural is begin return Natural (Stream.Write_Pos - Stream.Read_Pos); end Get_Size; -- ------------------------------ -- Write the buffer array to the output stream. -- ------------------------------ overriding procedure Write (Stream : in out Output_Buffer_Stream; Buffer : in Ada.Streams.Stream_Element_Array) is Start : Stream_Element_Offset := Buffer'First; Pos : Stream_Element_Offset := Stream.Write_Pos; Avail : Stream_Element_Offset; Size : Stream_Element_Offset; begin while Start <= Buffer'Last loop Size := Buffer'Last - Start + 1; Avail := Stream.Last - Pos + 1; if Avail = 0 then if Stream.Output = null then raise Ada.IO_Exceptions.End_Error with "Buffer is full"; end if; Stream.Output.Write (Stream.Buffer (1 .. Pos - 1)); Stream.Write_Pos := 1; Pos := 1; Avail := Stream.Last - Pos + 1; end if; if Avail < Size then Size := Avail; end if; Stream.Buffer (Pos .. Pos + Size - 1) := Buffer (Start .. Start + Size - 1); Start := Start + Size; Pos := Pos + Size; Stream.Write_Pos := Pos; -- If we have still more data than the buffer size, flush and write -- the buffer directly. if Start < Buffer'Last and then Buffer'Last - Start > Stream.Buffer'Length then if Stream.Output = null then raise Ada.IO_Exceptions.End_Error with "Buffer is full"; end if; Stream.Output.Write (Stream.Buffer (1 .. Pos - 1)); Stream.Write_Pos := 1; Stream.Output.Write (Buffer (Start .. Buffer'Last)); return; end if; end loop; end Write; -- ------------------------------ -- Flush the stream. -- ------------------------------ overriding procedure Flush (Stream : in out Output_Buffer_Stream) is begin if not Stream.No_Flush then if Stream.Write_Pos > 1 then if Stream.Output /= null then Stream.Output.Write (Stream.Buffer (1 .. Stream.Write_Pos - 1)); end if; Stream.Write_Pos := 1; end if; if Stream.Output /= null then Stream.Output.Flush; end if; end if; end Flush; -- ------------------------------ -- Flush the buffer in the `Into` array and return the index of the -- last element (inclusive) in `Last`. -- ------------------------------ procedure Flush (Stream : in out Output_Buffer_Stream; Into : out Ada.Streams.Stream_Element_Array; Last : out Ada.Streams.Stream_Element_Offset) is begin if Stream.Write_Pos > 1 then Into (Into'First .. Into'First + Stream.Write_Pos - 1) := Stream.Buffer (Stream.Buffer'First .. Stream.Write_Pos - 1); Stream.Write_Pos := 1; Last := Into'First + Stream.Write_Pos - 1; else Last := Into'First - 1; end if; end Flush; -- ------------------------------ -- Flush the buffer stream to the unbounded string. -- ------------------------------ procedure Flush (Stream : in out Output_Buffer_Stream; Into : out Ada.Strings.Unbounded.Unbounded_String) is begin Ada.Strings.Unbounded.Set_Unbounded_String (Into, ""); if Stream.Write_Pos > 1 then for I in 1 .. Stream.Write_Pos - 1 loop Ada.Strings.Unbounded.Append (Into, Character'Val (Stream.Buffer (I))); end loop; Stream.Write_Pos := 1; end if; end Flush; -- ------------------------------ -- Fill the buffer by reading the input stream. -- Raises Data_Error if there is no input stream; -- ------------------------------ procedure Fill (Stream : in out Input_Buffer_Stream) is begin if Stream.Input = null then Stream.Eof := True; else Stream.Input.Read (Stream.Buffer (1 .. Stream.Last - 1), Stream.Write_Pos); Stream.Eof := Stream.Write_Pos < 1; if not Stream.Eof then Stream.Write_Pos := Stream.Write_Pos + 1; end if; Stream.Read_Pos := 1; end if; end Fill; -- ------------------------------ -- Read one character from the input stream. -- ------------------------------ procedure Read (Stream : in out Input_Buffer_Stream; Char : out Character) is begin if Stream.Read_Pos >= Stream.Write_Pos then Stream.Fill; if Stream.Eof then raise Ada.IO_Exceptions.Data_Error with "End of buffer"; end if; end if; Char := Character'Val (Stream.Buffer (Stream.Read_Pos)); Stream.Read_Pos := Stream.Read_Pos + 1; end Read; procedure Read (Stream : in out Input_Buffer_Stream; Value : out Ada.Streams.Stream_Element) is begin if Stream.Read_Pos >= Stream.Write_Pos then Stream.Fill; if Stream.Eof then raise Ada.IO_Exceptions.Data_Error with "End of buffer"; end if; end if; Value := Stream.Buffer (Stream.Read_Pos); Stream.Read_Pos := Stream.Read_Pos + 1; end Read; -- ------------------------------ -- Read one character from the input stream. -- ------------------------------ procedure Read (Stream : in out Input_Buffer_Stream; Char : out Wide_Wide_Character) is use Interfaces; Val : Ada.Streams.Stream_Element; Result : Unsigned_32; begin Stream.Read (Val); -- UTF-8 conversion -- 7 U+0000 U+007F 1 0xxxxxxx if Val <= 16#7F# then Char := Wide_Wide_Character'Val (Val); -- 11 U+0080 U+07FF 2 110xxxxx 10xxxxxx elsif Val <= 16#DF# then Result := Shift_Left (Unsigned_32 (Val and 16#1F#), 6); Stream.Read (Val); Result := Result or Unsigned_32 (Val and 16#3F#); Char := Wide_Wide_Character'Val (Result); -- 16 U+0800 U+FFFF 3 1110xxxx 10xxxxxx 10xxxxxx elsif Val <= 16#EF# then Result := Shift_Left (Unsigned_32 (Val and 16#0F#), 12); Stream.Read (Val); Result := Result or Shift_Left (Unsigned_32 (Val and 16#3F#), 6); Stream.Read (Val); Result := Result or Unsigned_32 (Val and 16#3F#); Char := Wide_Wide_Character'Val (Result); -- 21 U+10000 U+1FFFFF 4 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx else Result := Shift_Left (Unsigned_32 (Val and 16#07#), 18); Stream.Read (Val); Result := Result or Shift_Left (Unsigned_32 (Val and 16#3F#), 12); Stream.Read (Val); Result := Result or Shift_Left (Unsigned_32 (Val and 16#3F#), 6); Stream.Read (Val); Result := Result or Unsigned_32 (Val and 16#3F#); Char := Wide_Wide_Character'Val (Result); end if; end Read; -- ------------------------------ -- Read into the buffer as many bytes as possible and return in -- `last` the position of the last byte read. -- ------------------------------ overriding procedure Read (Stream : in out Input_Buffer_Stream; Into : out Ada.Streams.Stream_Element_Array; Last : out Ada.Streams.Stream_Element_Offset) is Start : Stream_Element_Offset := Into'First; Pos : Stream_Element_Offset := Stream.Read_Pos; Avail : Stream_Element_Offset; Size : Stream_Element_Offset; Total : Stream_Element_Offset := 0; begin while Start <= Into'Last loop Size := Into'Last - Start + 1; Avail := Stream.Write_Pos - Pos; if Avail = 0 then Stream.Fill; Pos := Stream.Read_Pos; Avail := Stream.Write_Pos - Pos; exit when Avail <= 0; end if; if Avail < Size then Size := Avail; end if; Into (Start .. Start + Size - 1) := Stream.Buffer (Pos .. Pos + Size - 1); Start := Start + Size; Pos := Pos + Size; Total := Total + Size; Stream.Read_Pos := Pos; end loop; Last := Total; end Read; -- ------------------------------ -- Read into the buffer as many bytes as possible and return in -- `last` the position of the last byte read. -- ------------------------------ procedure Read (Stream : in out Input_Buffer_Stream; Into : in out Ada.Strings.Unbounded.Unbounded_String) is Pos : Stream_Element_Offset := Stream.Read_Pos; Avail : Stream_Element_Offset; begin loop Avail := Stream.Write_Pos - Pos; if Avail = 0 then Stream.Fill; if Stream.Eof then return; end if; Pos := Stream.Read_Pos; Avail := Stream.Write_Pos - Pos; end if; for I in 1 .. Avail loop Ada.Strings.Unbounded.Append (Into, Character'Val (Stream.Buffer (Pos))); Pos := Pos + 1; end loop; Stream.Read_Pos := Pos; end loop; end Read; procedure Read (Stream : in out Input_Buffer_Stream; Into : in out Ada.Strings.Wide_Wide_Unbounded.Unbounded_Wide_Wide_String) is Pos : Stream_Element_Offset; Avail : Stream_Element_Offset; C : Wide_Wide_Character; begin loop Pos := Stream.Read_Pos; Avail := Stream.Write_Pos - Pos; if Avail = 0 then Stream.Fill; if Stream.Eof then return; end if; Pos := Stream.Read_Pos; Avail := Stream.Write_Pos - Pos; end if; Stream.Read (C); Ada.Strings.Wide_Wide_Unbounded.Append (Into, C); end loop; end Read; -- ------------------------------ -- Flush the stream and release the buffer. -- ------------------------------ overriding procedure Finalize (Stream : in out Output_Buffer_Stream) is begin if Stream.Buffer /= null then if Stream.Output /= null then Stream.Flush; end if; Free_Buffer (Stream.Buffer); end if; end Finalize; -- ------------------------------ -- Returns True if the end of the stream is reached. -- ------------------------------ function Is_Eof (Stream : in Input_Buffer_Stream) return Boolean is begin return Stream.Eof; end Is_Eof; -- ------------------------------ -- Flush the stream and release the buffer. -- ------------------------------ overriding procedure Finalize (Object : in out Buffer_Stream) is begin if Object.Buffer /= null then Free_Buffer (Object.Buffer); end if; end Finalize; end Util.Streams.Buffered;
Refactor the Util.Streams.Buffered to use the Buffer_Stream type
Refactor the Util.Streams.Buffered to use the Buffer_Stream type
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
eef219972297d9f4c34b997e9b94af1782f0a3eb
src/security-oauth.ads
src/security-oauth.ads
----------------------------------------------------------------------- -- security-oauth -- OAuth Security -- Copyright (C) 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- -- The <b>Security.OAuth</b> package defines and implements the OAuth 2.0 authorization -- framework as defined by the IETF working group. -- See http://tools.ietf.org/html/draft-ietf-oauth-v2-26 package Security.OAuth is -- OAuth 2.0: Section 10.2.2. Initial Registry Contents Client_Id : constant String := "client_id"; Client_Secret : constant String := "client_secret"; Response_Type : constant String := "response_type"; Redirect_Uri : constant String := "redirect_uri"; Scope : constant String := "scope"; State : constant String := "state"; Code : constant String := "code"; Error_Description : constant String := "error_description"; Error_Uri : constant String := "error_uri"; Grant_Type : constant String := "grant_type"; Access_Token : constant String := "access_token"; Token_Type : constant String := "token_type"; Expires_In : constant String := "expires_in"; Username : constant String := "username"; Password : constant String := "password"; Refresh_Token : constant String := "refresh_token"; end Security.OAuth;
----------------------------------------------------------------------- -- security-oauth -- OAuth Security -- Copyright (C) 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- -- == OAuth == -- The <b>Security.OAuth</b> package defines and implements the OAuth 2.0 authorization -- framework as defined by the IETF working group. -- See http://tools.ietf.org/html/draft-ietf-oauth-v2-26 package Security.OAuth is -- OAuth 2.0: Section 10.2.2. Initial Registry Contents Client_Id : constant String := "client_id"; Client_Secret : constant String := "client_secret"; Response_Type : constant String := "response_type"; Redirect_Uri : constant String := "redirect_uri"; Scope : constant String := "scope"; State : constant String := "state"; Code : constant String := "code"; Error_Description : constant String := "error_description"; Error_Uri : constant String := "error_uri"; Grant_Type : constant String := "grant_type"; Access_Token : constant String := "access_token"; Token_Type : constant String := "token_type"; Expires_In : constant String := "expires_in"; Username : constant String := "username"; Password : constant String := "password"; Refresh_Token : constant String := "refresh_token"; end Security.OAuth;
Include in generated documentation by Dynamo
Include in generated documentation by Dynamo
Ada
apache-2.0
Letractively/ada-security
5a1d0e2388cde2dac0beab26e43d256db9e0579c
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. ----------------------------------------------------------------------- with Ada.Wide_Wide_Characters.Handling; with Ada.Unchecked_Deallocation; 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 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 if Into.Current.Children = null then Into.Current.Children := new Node_List; -- Into.Current.Children.Current := Into.Current.Children.First'Access; -- Into.Current.Children.Parent := Into.Current; end if; Append (Into.Current.Children.all, 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)); 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; overriding procedure Initialize (Doc : in out Document) is begin -- Doc.Nodes := Node_List_Refs.Create; -- Doc.Nodes.Value.Current := Doc.Nodes.Value.First'Access; null; end Initialize; 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 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 if Into.Current.Children = null then Into.Current.Children := new Node_List; -- Into.Current.Children.Current := Into.Current.Children.First'Access; -- Into.Current.Children.Parent := Into.Current; end if; Append (Into.Current.Children.all, 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)); 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; overriding procedure Initialize (Doc : in out Document) is begin -- Doc.Nodes := Node_List_Refs.Create; -- Doc.Nodes.Value.Current := Doc.Nodes.Value.First'Access; null; end Initialize; end Wiki.Documents;
Remove unused with clauses
Remove unused with clauses
Ada
apache-2.0
stcarrez/ada-wiki,stcarrez/ada-wiki
2c826db5fc896089e279419137aa3aca48ff7b3f
src/sys/streams/util-streams-buffered-encoders.ads
src/sys/streams/util-streams-buffered-encoders.ads
----------------------------------------------------------------------- -- util-streams-encoders -- Streams with encoding and decoding capabilities -- Copyright (C) 2017, 2019 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Encoders; -- == Encoding Streams == -- The <tt>Encoding_Stream</tt> tagged record represents a stream with encoding capabilities. -- The stream passes the data to be written to the <tt>Transformer</tt> interface that -- allows to make transformations on the data before being written. -- -- Encode : Util.Streams.Buffered.Encoders.Encoding_Stream; -- -- The encoding stream manages a buffer that is used to hold the encoded data before it is -- written to the target stream. The <tt>Initialize</tt> procedure must be called to indicate -- the target stream, the size of the buffer and the encoding format to be used. -- -- Encode.Initialize (Output => File'Access, Size => 4096, Format => "base64"); -- generic type Encoder is limited new Util.Encoders.Transformer with private; package Util.Streams.Buffered.Encoders is -- ----------------------- -- Encoding stream -- ----------------------- -- The <b>Encoding_Stream</b> is an output stream which uses an encoder to -- transform the data before writing it to the output. The transformer can -- change the data by encoding it in Base64, Base16 or encrypting it. type Encoder_Stream is limited new Util.Streams.Buffered.Output_Buffer_Stream with record Transform : Encoder; end record; -- Initialize the stream to write on the given stream. -- An internal buffer is allocated for writing the stream. overriding procedure Initialize (Stream : in out Encoder_Stream; Output : access Output_Stream'Class; Size : in Positive); -- Close the sink. overriding procedure Close (Stream : in out Encoder_Stream); -- Write the buffer array to the output stream. overriding procedure Write (Stream : in out Encoder_Stream; Buffer : in Ada.Streams.Stream_Element_Array); -- Flush the buffer by writing on the output stream. -- Raises Data_Error if there is no output stream. overriding procedure Flush (Stream : in out Encoder_Stream); end Util.Streams.Buffered.Encoders;
----------------------------------------------------------------------- -- util-streams-encoders -- Streams with encoding and decoding capabilities -- Copyright (C) 2017, 2019 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Encoders; -- == Encoding Streams == -- The <tt>Encoding_Stream</tt> tagged record represents a stream with encoding capabilities. -- The stream passes the data to be written to the <tt>Transformer</tt> interface that -- allows to make transformations on the data before being written. -- -- Encode : Util.Streams.Buffered.Encoders.Encoding_Stream; -- -- The encoding stream manages a buffer that is used to hold the encoded data before it is -- written to the target stream. The <tt>Initialize</tt> procedure must be called to indicate -- the target stream, the size of the buffer and the encoding format to be used. -- -- Encode.Initialize (Output => File'Access, Size => 4096, Format => "base64"); -- generic type Encoder is limited new Util.Encoders.Transformer with private; package Util.Streams.Buffered.Encoders is -- ----------------------- -- Encoding stream -- ----------------------- -- The <b>Encoding_Stream</b> is an output stream which uses an encoder to -- transform the data before writing it to the output. The transformer can -- change the data by encoding it in Base64, Base16 or encrypting it. type Encoder_Stream is limited new Util.Streams.Buffered.Output_Buffer_Stream with record Transform : Encoder; Flushed : Boolean := False; end record; -- Initialize the stream to write on the given stream. -- An internal buffer is allocated for writing the stream. overriding procedure Initialize (Stream : in out Encoder_Stream; Output : access Output_Stream'Class; Size : in Positive); -- Close the sink. overriding procedure Close (Stream : in out Encoder_Stream); -- Write the buffer array to the output stream. overriding procedure Write (Stream : in out Encoder_Stream; Buffer : in Ada.Streams.Stream_Element_Array); -- Flush the buffer by writing on the output stream. -- Raises Data_Error if there is no output stream. overriding procedure Flush (Stream : in out Encoder_Stream); end Util.Streams.Buffered.Encoders;
Add a Flushed boolean member
Add a Flushed boolean member
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
79598eed4286fe9b710454628620cf248b8097ca
src/gen-artifacts-docs-markdown.adb
src/gen-artifacts-docs-markdown.adb
----------------------------------------------------------------------- -- gen-artifacts-docs-markdown -- Artifact for GitHub Markdown documentation format -- Copyright (C) 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- package body Gen.Artifacts.Docs.Markdown is -- ------------------------------ -- Get the document name from the file document (ex: <name>.wiki or <name>.md). -- ------------------------------ overriding function Get_Document_Name (Formatter : in Document_Formatter; Document : in File_Document) return String is begin return Ada.Strings.Unbounded.To_String (Document.Name) & ".md"; end Get_Document_Name; -- ------------------------------ -- Start a new document. -- ------------------------------ overriding procedure Start_Document (Formatter : in out Document_Formatter; Document : in File_Document; File : in Ada.Text_IO.File_Type) is begin Ada.Text_IO.Put_Line (File, "#summary " & Ada.Strings.Unbounded.To_String (Document.Title)); Ada.Text_IO.New_Line (File); end Start_Document; -- ------------------------------ -- Write a line in the target document formatting the line if necessary. -- ------------------------------ overriding procedure Write_Line (Formatter : in out Document_Formatter; File : in Ada.Text_IO.File_Type; Line : in Line_Type) is begin if Line.Kind = L_LIST then Ada.Text_IO.New_Line (File); Ada.Text_IO.Put (File, Line.Content); Formatter.Need_Newline := True; elsif Line.Kind = L_LIST_ITEM then Ada.Text_IO.Put (File, Line.Content); Formatter.Need_Newline := True; else if Formatter.Need_Newline then Ada.Text_IO.New_Line (File); Formatter.Need_Newline := False; end if; Ada.Text_IO.Put_Line (File, Line.Content); end if; end Write_Line; -- ------------------------------ -- Finish the document. -- ------------------------------ overriding procedure Finish_Document (Formatter : in out Document_Formatter; Document : in File_Document; File : in Ada.Text_IO.File_Type; Source : in String) is begin Ada.Text_IO.New_Line (File); Ada.Text_IO.Put_Line (File, "----"); Ada.Text_IO.Put_Line (File, "[Generated by Dynamo](https://github.com/stcarrez/dynamo) from _" & Source & "_"); end Finish_Document; end Gen.Artifacts.Docs.Markdown;
----------------------------------------------------------------------- -- gen-artifacts-docs-markdown -- Artifact for GitHub Markdown documentation format -- Copyright (C) 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- package body Gen.Artifacts.Docs.Markdown is -- ------------------------------ -- Get the document name from the file document (ex: <name>.wiki or <name>.md). -- ------------------------------ overriding function Get_Document_Name (Formatter : in Document_Formatter; Document : in File_Document) return String is begin return Ada.Strings.Unbounded.To_String (Document.Name) & ".md"; end Get_Document_Name; -- ------------------------------ -- Start a new document. -- ------------------------------ overriding procedure Start_Document (Formatter : in out Document_Formatter; Document : in File_Document; File : in Ada.Text_IO.File_Type) is begin Ada.Text_IO.Put_Line (File, "#summary " & Ada.Strings.Unbounded.To_String (Document.Title)); Ada.Text_IO.New_Line (File); end Start_Document; -- ------------------------------ -- Write a line in the target document formatting the line if necessary. -- ------------------------------ overriding procedure Write_Line (Formatter : in out Document_Formatter; File : in Ada.Text_IO.File_Type; Line : in Line_Type) is begin if Line.Kind = L_LIST then Ada.Text_IO.New_Line (File); Ada.Text_IO.Put (File, Line.Content); Formatter.Need_Newline := True; elsif Line.Kind = L_LIST_ITEM then Ada.Text_IO.Put (File, Line.Content); Formatter.Need_Newline := True; elsif Line.Kind = L_START_CODE or Line.Kind = L_END_CODE then if Formatter.Need_NewLine then Ada.Text_IO.New_Line (File); Formatter.Need_Newline := False; end if; Ada.Text_IO.Put_Line (File, "```"); else if Formatter.Need_Newline then Ada.Text_IO.New_Line (File); Formatter.Need_Newline := False; end if; Ada.Text_IO.Put_Line (File, Line.Content); end if; end Write_Line; -- ------------------------------ -- Finish the document. -- ------------------------------ overriding procedure Finish_Document (Formatter : in out Document_Formatter; Document : in File_Document; File : in Ada.Text_IO.File_Type; Source : in String) is begin Ada.Text_IO.New_Line (File); Ada.Text_IO.Put_Line (File, "----"); Ada.Text_IO.Put_Line (File, "[Generated by Dynamo](https://github.com/stcarrez/dynamo) from _" & Source & "_"); end Finish_Document; end Gen.Artifacts.Docs.Markdown;
Format the L_START_CODE and L_END_CODE blocks
Format the L_START_CODE and L_END_CODE blocks
Ada
apache-2.0
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
288c81569c37ed1f3f2349360c9fc3ac0b0b09be
tests/natools-chunked_strings-tests-coverage.adb
tests/natools-chunked_strings-tests-coverage.adb
------------------------------------------------------------------------------ -- Copyright (c) 2013, Natacha Porté -- -- -- -- Permission to use, copy, modify, and distribute this software for any -- -- purpose with or without fee is hereby granted, provided that the above -- -- copyright notice and this permission notice appear in all copies. -- -- -- -- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES -- -- WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -- -- MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR -- -- ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -- -- WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -- -- ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF -- -- OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -- ------------------------------------------------------------------------------ with Ada.Exceptions; with Ada.Strings.Fixed; procedure Natools.Chunked_Strings.Tests.Coverage (Report : in out Natools.Tests.Reporter'Class) is package NT renames Natools.Tests; begin NT.Section (Report, "Extra tests for complete coverage"); declare Name : constant String := "Index_Error raised in Element"; C : Character; begin C := Element (To_Chunked_String (Name), Name'Length + 1); NT.Item (Report, Name, NT.Fail); NT.Info (Report, "No exception has been raised."); NT.Info (Report, "Return value: " & Character'Image (C)); exception when Ada.Strings.Index_Error => NT.Item (Report, Name, NT.Success); when Error : others => NT.Item (Report, Name, NT.Fail); NT.Info (Report, "Wrong exception " & Ada.Exceptions.Exception_Name (Error) & "has been raised."); end; declare Name : constant String := "Index_Error raised in Replace_Element"; CS : Chunked_String := To_Chunked_String (Name); begin Replace_Element (CS, Name'Length + 1, '*'); NT.Item (Report, Name, NT.Fail); NT.Info (Report, "No exception has been raised."); NT.Info (Report, "Final value: """ & To_String (CS) & '"'); exception when Ada.Strings.Index_Error => NT.Item (Report, Name, NT.Success); when Error : others => NT.Item (Report, Name, NT.Fail); NT.Info (Report, "Wrong exception " & Ada.Exceptions.Exception_Name (Error) & "has been raised."); end; declare Name : constant String := "Function Duplicate"; S, T : Chunked_String; begin S := To_Chunked_String (Name); T := Duplicate (S); S.Unappend ("cate"); if To_String (T) /= Name then NT.Item (Report, Name, NT.Fail); NT.Info (Report, "Duplicate """ & To_String (T) & " does not match original"); else NT.Item (Report, Name, NT.Success); end if; exception when Error : others => NT.Report_Exception (Report, Name, Error); end; declare Name : constant String := "Procedure Set_Chunked_String (Chunked_String, String)"; CS : Chunked_String; begin Set_Chunked_String (CS, Name); if To_String (CS) /= Name then NT.Item (Report, Name, NT.Fail); NT.Info (Report, "Final value: """ & To_String (CS) & '"'); NT.Info (Report, "Expected: """ & Name & '"'); else NT.Item (Report, Name, NT.Success); end if; exception when Error : others => NT.Report_Exception (Report, Name, Error); end; declare Name : constant String := "Function Delete with empty range"; CS : Chunked_String; begin CS := Delete (To_Chunked_String (Name), 1, 0); if To_String (CS) /= Name then NT.Item (Report, Name, NT.Fail); NT.Info (Report, "Final value: """ & To_String (CS) & '"'); NT.Info (Report, "Expected: """ & Name & '"'); else NT.Item (Report, Name, NT.Success); end if; exception when Error : others => NT.Report_Exception (Report, Name, Error); end; declare Name : constant String := "Function Head with oversized Count and parameter override"; Pad : constant Character := ' '; Shadow : constant String (1 .. Name'Length) := (others => Pad); CS : Chunked_String; begin CS := Head (To_Chunked_String (Name), 2 * Name'Length, Pad, 10, 5); if To_String (CS) /= Name & Shadow then NT.Item (Report, Name, NT.Fail); NT.Info (Report, "Final value: """ & To_String (CS) & '"'); NT.Info (Report, "Expected: """ & Name & Shadow & '"'); else NT.Item (Report, Name, NT.Success); end if; exception when Error : others => NT.Report_Exception (Report, Name, Error); end; declare Name : constant String := "Function Tail with oversized Count and parameter override"; Pad : constant Character := ' '; Shadow : constant String (1 .. Name'Length) := (others => Pad); CS : Chunked_String; begin CS := Tail (To_Chunked_String (Name), 2 * Name'Length, Pad, 10, 5); if To_String (CS) /= Shadow & Name then NT.Item (Report, Name, NT.Fail); NT.Info (Report, "Final value: """ & To_String (CS) & '"'); NT.Info (Report, "Expected: """ & Shadow & Name & '"'); else NT.Item (Report, Name, NT.Success); end if; exception when Error : others => NT.Report_Exception (Report, Name, Error); end; declare Name : constant String := "Function ""*"" (Character) over multiple chunks"; CS : Chunked_String; Count : constant Positive := 3 * Default_Chunk_Size + 2; Template : constant Character := '$'; Ref : constant String := Ada.Strings.Fixed."*" (Count, Template); begin CS := Count * Template; if To_String (CS) /= Ref then NT.Item (Report, Name, NT.Fail); NT.Info (Report, "Final value: """ & To_String (CS) & '"'); NT.Info (Report, "Expected: """ & Ref & '"'); else NT.Item (Report, Name, NT.Success); end if; exception when Error : others => NT.Report_Exception (Report, Name, Error); end; declare Name : constant String := "Function ""*"" (String) over multiple chunks"; CS : Chunked_String; Count : constant Positive := Default_Chunk_Size + 2; Template : constant String := "<>"; Ref : constant String := Ada.Strings.Fixed."*" (Count, Template); begin CS := Count * Template; if To_String (CS) /= Ref then NT.Item (Report, Name, NT.Fail); NT.Info (Report, "Final value: """ & To_String (CS) & '"'); NT.Info (Report, "Expected: """ & Ref & '"'); else NT.Item (Report, Name, NT.Success); end if; exception when Error : others => NT.Report_Exception (Report, Name, Error); end; Natools.Tests.End_Section (Report); end Natools.Chunked_Strings.Tests.Coverage;
------------------------------------------------------------------------------ -- Copyright (c) 2013, Natacha Porté -- -- -- -- Permission to use, copy, modify, and distribute this software for any -- -- purpose with or without fee is hereby granted, provided that the above -- -- copyright notice and this permission notice appear in all copies. -- -- -- -- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES -- -- WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -- -- MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR -- -- ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -- -- WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -- -- ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF -- -- OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -- ------------------------------------------------------------------------------ with Ada.Exceptions; with Ada.Strings.Fixed; procedure Natools.Chunked_Strings.Tests.Coverage (Report : in out Natools.Tests.Reporter'Class) is package NT renames Natools.Tests; begin NT.Section (Report, "Extra tests for complete coverage"); declare Name : constant String := "Index_Error raised in Element"; C : Character; begin C := Element (To_Chunked_String (Name), Name'Length + 1); NT.Item (Report, Name, NT.Fail); NT.Info (Report, "No exception has been raised."); NT.Info (Report, "Return value: " & Character'Image (C)); exception when Ada.Strings.Index_Error => NT.Item (Report, Name, NT.Success); when Error : others => NT.Item (Report, Name, NT.Fail); NT.Info (Report, "Wrong exception " & Ada.Exceptions.Exception_Name (Error) & "has been raised."); end; declare Name : constant String := "Index_Error raised in Replace_Element"; CS : Chunked_String := To_Chunked_String (Name); begin Replace_Element (CS, Name'Length + 1, '*'); NT.Item (Report, Name, NT.Fail); NT.Info (Report, "No exception has been raised."); NT.Info (Report, "Final value: """ & To_String (CS) & '"'); exception when Ada.Strings.Index_Error => NT.Item (Report, Name, NT.Success); when Error : others => NT.Item (Report, Name, NT.Fail); NT.Info (Report, "Wrong exception " & Ada.Exceptions.Exception_Name (Error) & "has been raised."); end; declare Name : constant String := "Function Duplicate"; S, T : Chunked_String; begin S := To_Chunked_String (Name); T := Duplicate (S); S.Unappend ("cate"); if To_String (T) /= Name then NT.Item (Report, Name, NT.Fail); NT.Info (Report, "Duplicate """ & To_String (T) & " does not match original"); else NT.Item (Report, Name, NT.Success); end if; exception when Error : others => NT.Report_Exception (Report, Name, Error); end; declare Name : constant String := "Procedure Set_Chunked_String (Chunked_String, String)"; CS : Chunked_String; begin Set_Chunked_String (CS, Name); if To_String (CS) /= Name then NT.Item (Report, Name, NT.Fail); NT.Info (Report, "Final value: """ & To_String (CS) & '"'); NT.Info (Report, "Expected: """ & Name & '"'); else NT.Item (Report, Name, NT.Success); end if; exception when Error : others => NT.Report_Exception (Report, Name, Error); end; declare Name : constant String := "Function Delete with empty range"; CS : Chunked_String; begin CS := Delete (To_Chunked_String (Name), 1, 0); if To_String (CS) /= Name then NT.Item (Report, Name, NT.Fail); NT.Info (Report, "Final value: """ & To_String (CS) & '"'); NT.Info (Report, "Expected: """ & Name & '"'); else NT.Item (Report, Name, NT.Success); end if; exception when Error : others => NT.Report_Exception (Report, Name, Error); end; declare Name : constant String := "Function Head with oversized Count and parameter override"; Pad : constant Character := ' '; Shadow : constant String (1 .. Name'Length) := (others => Pad); CS : Chunked_String; begin CS := Head (To_Chunked_String (Name), 2 * Name'Length, Pad, 10, 5); if To_String (CS) /= Name & Shadow then NT.Item (Report, Name, NT.Fail); NT.Info (Report, "Final value: """ & To_String (CS) & '"'); NT.Info (Report, "Expected: """ & Name & Shadow & '"'); else NT.Item (Report, Name, NT.Success); end if; exception when Error : others => NT.Report_Exception (Report, Name, Error); end; declare Name : constant String := "Function Tail with oversized Count and parameter override"; Pad : constant Character := ' '; Shadow : constant String (1 .. Name'Length) := (others => Pad); CS : Chunked_String; begin CS := Tail (To_Chunked_String (Name), 2 * Name'Length, Pad, 10, 5); if To_String (CS) /= Shadow & Name then NT.Item (Report, Name, NT.Fail); NT.Info (Report, "Final value: """ & To_String (CS) & '"'); NT.Info (Report, "Expected: """ & Shadow & Name & '"'); else NT.Item (Report, Name, NT.Success); end if; exception when Error : others => NT.Report_Exception (Report, Name, Error); end; declare Name : constant String := "Function ""*"" (Character) over multiple chunks"; CS : Chunked_String; Count : constant Positive := 3 * Default_Chunk_Size + 2; Template : constant Character := '$'; Ref : constant String := Ada.Strings.Fixed."*" (Count, Template); begin CS := Count * Template; if To_String (CS) /= Ref then NT.Item (Report, Name, NT.Fail); NT.Info (Report, "Final value: """ & To_String (CS) & '"'); NT.Info (Report, "Expected: """ & Ref & '"'); else NT.Item (Report, Name, NT.Success); end if; exception when Error : others => NT.Report_Exception (Report, Name, Error); end; declare Name : constant String := "Function ""*"" (String) over multiple chunks"; CS : Chunked_String; Count : constant Positive := Default_Chunk_Size + 2; Template : constant String := "<>"; Ref : constant String := Ada.Strings.Fixed."*" (Count, Template); begin CS := Count * Template; if To_String (CS) /= Ref then NT.Item (Report, Name, NT.Fail); NT.Info (Report, "Final value: """ & To_String (CS) & '"'); NT.Info (Report, "Expected: """ & Ref & '"'); else NT.Item (Report, Name, NT.Success); end if; exception when Error : others => NT.Report_Exception (Report, Name, Error); end; declare Name : constant String := "Procedure Chunked_Slice"; CS : Chunked_String; Low : constant Positive := 11; High : constant Positive := 17; begin Chunked_Slice (To_Chunked_String (Name), CS, Low, High); if To_String (CS) /= Name (Low .. High) then NT.Item (Report, Name, NT.Fail); NT.Info (Report, "Final value: """ & To_String (CS) & '"'); NT.Info (Report, "Expected: """ & Name (Low .. High) & '"'); else NT.Item (Report, Name, NT.Success); end if; exception when Error : others => NT.Report_Exception (Report, Name, Error); end; declare Name : constant String := "Procedure Chunked_Slice (empty)"; CS : Chunked_String; begin Chunked_Slice (To_Chunked_String (Name), CS, 1, 0); if To_String (CS) /= "" then NT.Item (Report, Name, NT.Fail); NT.Info (Report, "Final value: """ & To_String (CS) & '"'); else NT.Item (Report, Name, NT.Success); end if; exception when Error : others => NT.Report_Exception (Report, Name, Error); end; declare Name : constant String := "Function Index_Non_Blank with From"; CS : constant Chunked_String := To_Chunked_String (Name); M, N : Natural; begin M := Index (CS, " "); N := Index_Non_Blank (CS, M); if N /= M + 1 then NT.Item (Report, Name, NT.Fail); NT.Info (Report, "Final value:" & Natural'Image (N)); NT.Info (Report, "Expected:" & Natural'Image (M + 1)); else NT.Item (Report, Name, NT.Success); end if; exception when Error : others => NT.Report_Exception (Report, Name, Error); end; declare Name : constant String := "Function Find_Token at string end"; CS : constant Chunked_String := To_Chunked_String ("--end"); First : Positive; Last : Natural; begin Find_Token (Source => CS, Set => Maps.To_Set ("abcdefghijklmnopqrst"), Test => Ada.Strings.Inside, First => First, Last => Last); if First /= 3 or Last /= 5 then NT.Item (Report, Name, NT.Fail); NT.Info (Report, "Final interval:" & Natural'Image (First) & " .." & Natural'Image (Last)); NT.Info (Report, "Expected: 3 .. 5"); else NT.Item (Report, Name, NT.Success); end if; exception when Error : others => NT.Report_Exception (Report, Name, Error); end; Natools.Tests.End_Section (Report); end Natools.Chunked_Strings.Tests.Coverage;
add a few more tests
chunked_strings-tests-coverage: add a few more tests
Ada
isc
faelys/natools
ce3ddf0b0beb9a412f3af1f2d617b797e26c22eb
src/asf-applications-views.adb
src/asf-applications-views.adb
----------------------------------------------------------------------- -- applications -- Ada Web Application -- Copyright (C) 2009, 2010, 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Fixed; with ASF.Contexts.Facelets; with ASF.Applications.Main; with ASF.Components.Base; with ASF.Components.Core; with ASF.Components.Core.Views; with ASF.Requests; package body ASF.Applications.Views is use ASF.Components; type Facelet_Context is new ASF.Contexts.Facelets.Facelet_Context with record Facelets : access ASF.Views.Facelets.Facelet_Factory; Application : access ASF.Applications.Main.Application'Class; end record; -- Include the definition having the given name. overriding procedure Include_Facelet (Context : in out Facelet_Context; Source : in String; Parent : in Base.UIComponent_Access); -- Get the application associated with this facelet context. overriding function Get_Application (Context : in Facelet_Context) return access ASF.Applications.Main.Application'Class; -- Compose a URI path with two components. Unlike the Ada.Directories.Compose, -- and Util.Files.Compose the path separator must be a URL path separator (ie, '/'). -- ------------------------------ function Compose (Directory : in String; Name : in String) return String; -- ------------------------------ -- Include the definition having the given name. -- ------------------------------ overriding procedure Include_Facelet (Context : in out Facelet_Context; Source : in String; Parent : in Base.UIComponent_Access) is use ASF.Views; Path : constant String := Context.Resolve_Path (Source); Tree : Facelets.Facelet; begin Facelets.Find_Facelet (Factory => Context.Facelets.all, Name => Path, Context => Context, Result => Tree); Facelets.Build_View (View => Tree, Context => Context, Root => Parent); end Include_Facelet; -- ------------------------------ -- Get the application associated with this facelet context. -- ------------------------------ overriding function Get_Application (Context : in Facelet_Context) return access ASF.Applications.Main.Application'Class is begin return Context.Application; end Get_Application; -- ------------------------------ -- Get the facelet name from the view name. -- ------------------------------ function Get_Facelet_Name (Handler : in View_Handler; Name : in String) return String is use Ada.Strings.Fixed; use Ada.Strings.Unbounded; Pos : constant Natural := Index (Name, ".", Ada.Strings.Backward); begin if Pos > 0 and then Handler.View_Ext = Name (Pos .. Name'Last) then return Name (Name'First .. Pos - 1) & To_String (Handler.File_Ext); elsif Pos > 0 and then Handler.File_Ext = Name (Pos .. Name'Last) then return Name; end if; return Name & To_String (Handler.File_Ext); end Get_Facelet_Name; -- ------------------------------ -- Restore the view identified by the given name in the faces context -- and create the component tree representing that view. -- ------------------------------ procedure Restore_View (Handler : in out View_Handler; Name : in String; Context : in out ASF.Contexts.Faces.Faces_Context'Class; View : out ASF.Components.Root.UIViewRoot) is use ASF.Views; use Util.Locales; Ctx : Facelet_Context; Tree : Facelets.Facelet; View_Name : constant String := Handler.Get_Facelet_Name (Name); begin Ctx.Facelets := Handler.Facelets'Unchecked_Access; Ctx.Application := Context.Get_Application; Ctx.Set_ELContext (Context.Get_ELContext); Facelets.Find_Facelet (Factory => Handler.Facelets, Name => View_Name, Context => Ctx, Result => Tree); -- If the view could not be found, do not report any error yet. -- The SC_NOT_FOUND response will be returned when rendering the response. if Facelets.Is_Null (Tree) then return; end if; -- Build the component tree for this request. declare Root : aliased Core.UIComponentBase; Node : Base.UIComponent_Access; begin Facelets.Build_View (View => Tree, Context => Ctx, Root => Root'Unchecked_Access); ASF.Components.Base.Steal_Root_Component (Root, Node); ASF.Components.Root.Set_Root (View, Node, View_Name); if Context.Get_Locale = NULL_LOCALE then if Node.all in Core.Views.UIView'Class then Context.Set_Locale (Core.Views.UIView'Class (Node.all).Get_Locale (Context)); else Context.Set_Locale (Handler.Calculate_Locale (Context)); end if; end if; end; end Restore_View; -- ------------------------------ -- Create a new UIViewRoot instance initialized from the context and with -- the view identifier. If the view is a valid view, create the component tree -- representing that view. -- ------------------------------ procedure Create_View (Handler : in out View_Handler; Name : in String; Context : in out ASF.Contexts.Faces.Faces_Context'Class; View : out ASF.Components.Root.UIViewRoot) is Pos : constant Natural := Util.Strings.Rindex (Name, '.'); begin if Pos > 0 then Handler.Restore_View (Name (Name'First .. Pos - 1), Context, View); else Handler.Restore_View (Name, Context, View); end if; end Create_View; -- ------------------------------ -- Render the view represented by the component tree. The view is -- rendered using the context. -- ------------------------------ procedure Render_View (Handler : in out View_Handler; Context : in out ASF.Contexts.Faces.Faces_Context'Class; View : in ASF.Components.Root.UIViewRoot) is pragma Unreferenced (Handler); Root : constant access ASF.Components.Base.UIComponent'Class := ASF.Components.Root.Get_Root (View); begin if Root /= null then Root.Encode_All (Context); end if; end Render_View; -- ------------------------------ -- Compute the locale that must be used according to the <b>Accept-Language</b> request -- header and the application supported locales. -- ------------------------------ function Calculate_Locale (Handler : in View_Handler; Context : in ASF.Contexts.Faces.Faces_Context'Class) return Util.Locales.Locale is pragma Unreferenced (Handler); App : constant ASF.Contexts.Faces.Application_Access := Context.Get_Application; begin return App.Calculate_Locale (Context); end Calculate_Locale; -- ------------------------------ -- Compose a URI path with two components. Unlike the Ada.Directories.Compose, -- and Util.Files.Compose the path separator must be a URL path separator (ie, '/'). -- ------------------------------ function Compose (Directory : in String; Name : in String) return String is begin if Directory'Length = 0 then return Name; elsif Directory (Directory'Last) = '/' and Name (Name'First) = '/' then return Directory & Name (Name'First + 1 .. Name'Last); elsif Directory (Directory'Last) = '/' or Name (Name'First) = '/' then return Directory & Name; else return Directory & "/" & Name; end if; end Compose; -- ------------------------------ -- Get the URL suitable for encoding and rendering the view specified by the <b>View</b> -- identifier. -- ------------------------------ function Get_Action_URL (Handler : in View_Handler; Context : in ASF.Contexts.Faces.Faces_Context'Class; View : in String) return String is use Ada.Strings.Unbounded; Pos : constant Natural := Util.Strings.Rindex (View, '.'); Context_Path : constant String := Context.Get_Request.Get_Context_Path; begin if Pos > 0 and then View (Pos .. View'Last) = Handler.File_Ext then return Compose (Context_Path, View (View'First .. Pos - 1) & To_String (Handler.View_Ext)); end if; if Pos > 0 and then View (Pos .. View'Last) = Handler.View_Ext then return Compose (Context_Path, View); end if; return Compose (Context_Path, View); end Get_Action_URL; -- ------------------------------ -- Get the URL for redirecting the user to the specified view. -- ------------------------------ function Get_Redirect_URL (Handler : in View_Handler; Context : in ASF.Contexts.Faces.Faces_Context'Class; View : in String) return String is Pos : constant Natural := Util.Strings.Rindex (View, '?'); begin if Pos > 0 then return Handler.Get_Action_URL (Context, View (View'First .. Pos - 1)) & View (Pos .. View'Last); else return Handler.Get_Action_URL (Context, View); end if; end Get_Redirect_URL; -- ------------------------------ -- Initialize the view handler. -- ------------------------------ procedure Initialize (Handler : out View_Handler; Components : access ASF.Factory.Component_Factory; Conf : in Config) is use ASF.Views; use Ada.Strings.Unbounded; begin Handler.Paths := To_Unbounded_String (Conf.Get (VIEW_DIR_PARAM)); Handler.View_Ext := To_Unbounded_String (Conf.Get (VIEW_EXT_PARAM)); Handler.File_Ext := To_Unbounded_String (Conf.Get (VIEW_FILE_EXT_PARAM)); Facelets.Initialize (Factory => Handler.Facelets, Components => Components, Paths => To_String (Handler.Paths), Ignore_White_Spaces => Conf.Get (VIEW_IGNORE_WHITE_SPACES_PARAM), Ignore_Empty_Lines => Conf.Get (VIEW_IGNORE_EMPTY_LINES_PARAM), Escape_Unknown_Tags => Conf.Get (VIEW_ESCAPE_UNKNOWN_TAGS_PARAM)); end Initialize; -- ------------------------------ -- Closes the view handler -- ------------------------------ procedure Close (Handler : in out View_Handler) is use ASF.Views; begin Facelets.Clear_Cache (Handler.Facelets); end Close; -- ------------------------------ -- Set the extension mapping rule to find the facelet file from -- the name. -- ------------------------------ procedure Set_Extension_Mapping (Handler : in out View_Handler; From : in String; Into : in String) is use Ada.Strings.Unbounded; begin Handler.View_Ext := To_Unbounded_String (From); Handler.File_Ext := To_Unbounded_String (Into); end Set_Extension_Mapping; end ASF.Applications.Views;
----------------------------------------------------------------------- -- applications -- Ada Web Application -- 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.Fixed; with ASF.Contexts.Facelets; with ASF.Applications.Main; with ASF.Components.Base; with ASF.Components.Core; with ASF.Components.Core.Views; package body ASF.Applications.Views is use ASF.Components; type Facelet_Context is new ASF.Contexts.Facelets.Facelet_Context with record Facelets : access ASF.Views.Facelets.Facelet_Factory; Application : access ASF.Applications.Main.Application'Class; end record; -- Include the definition having the given name. overriding procedure Include_Facelet (Context : in out Facelet_Context; Source : in String; Parent : in Base.UIComponent_Access); -- Get the application associated with this facelet context. overriding function Get_Application (Context : in Facelet_Context) return access ASF.Applications.Main.Application'Class; -- Compose a URI path with two components. Unlike the Ada.Directories.Compose, -- and Util.Files.Compose the path separator must be a URL path separator (ie, '/'). -- ------------------------------ function Compose (Directory : in String; Name : in String) return String; -- ------------------------------ -- Include the definition having the given name. -- ------------------------------ overriding procedure Include_Facelet (Context : in out Facelet_Context; Source : in String; Parent : in Base.UIComponent_Access) is use ASF.Views; Path : constant String := Context.Resolve_Path (Source); Tree : Facelets.Facelet; begin Facelets.Find_Facelet (Factory => Context.Facelets.all, Name => Path, Context => Context, Result => Tree); Facelets.Build_View (View => Tree, Context => Context, Root => Parent); end Include_Facelet; -- ------------------------------ -- Get the application associated with this facelet context. -- ------------------------------ overriding function Get_Application (Context : in Facelet_Context) return access ASF.Applications.Main.Application'Class is begin return Context.Application; end Get_Application; -- ------------------------------ -- Get the facelet name from the view name. -- ------------------------------ function Get_Facelet_Name (Handler : in View_Handler; Name : in String) return String is use Ada.Strings.Fixed; use Ada.Strings.Unbounded; Pos : constant Natural := Index (Name, ".", Ada.Strings.Backward); begin if Pos > 0 and then Handler.View_Ext = Name (Pos .. Name'Last) then return Name (Name'First .. Pos - 1) & To_String (Handler.File_Ext); elsif Pos > 0 and then Handler.File_Ext = Name (Pos .. Name'Last) then return Name; end if; return Name & To_String (Handler.File_Ext); end Get_Facelet_Name; -- ------------------------------ -- Restore the view identified by the given name in the faces context -- and create the component tree representing that view. -- ------------------------------ procedure Restore_View (Handler : in out View_Handler; Name : in String; Context : in out ASF.Contexts.Faces.Faces_Context'Class; View : out ASF.Components.Root.UIViewRoot) is use ASF.Views; use Util.Locales; Ctx : Facelet_Context; Tree : Facelets.Facelet; View_Name : constant String := Handler.Get_Facelet_Name (Name); begin Ctx.Facelets := Handler.Facelets'Unchecked_Access; Ctx.Application := Context.Get_Application; Ctx.Set_ELContext (Context.Get_ELContext); Facelets.Find_Facelet (Factory => Handler.Facelets, Name => View_Name, Context => Ctx, Result => Tree); -- If the view could not be found, do not report any error yet. -- The SC_NOT_FOUND response will be returned when rendering the response. if Facelets.Is_Null (Tree) then return; end if; -- Build the component tree for this request. declare Root : aliased Core.UIComponentBase; Node : Base.UIComponent_Access; begin Facelets.Build_View (View => Tree, Context => Ctx, Root => Root'Unchecked_Access); ASF.Components.Base.Steal_Root_Component (Root, Node); ASF.Components.Root.Set_Root (View, Node, View_Name); if Context.Get_Locale = NULL_LOCALE then if Node.all in Core.Views.UIView'Class then Context.Set_Locale (Core.Views.UIView'Class (Node.all).Get_Locale (Context)); else Context.Set_Locale (Handler.Calculate_Locale (Context)); end if; end if; end; end Restore_View; -- ------------------------------ -- Create a new UIViewRoot instance initialized from the context and with -- the view identifier. If the view is a valid view, create the component tree -- representing that view. -- ------------------------------ procedure Create_View (Handler : in out View_Handler; Name : in String; Context : in out ASF.Contexts.Faces.Faces_Context'Class; View : out ASF.Components.Root.UIViewRoot) is Pos : constant Natural := Util.Strings.Rindex (Name, '.'); begin if Pos > 0 then Handler.Restore_View (Name (Name'First .. Pos - 1), Context, View); else Handler.Restore_View (Name, Context, View); end if; end Create_View; -- ------------------------------ -- Render the view represented by the component tree. The view is -- rendered using the context. -- ------------------------------ procedure Render_View (Handler : in out View_Handler; Context : in out ASF.Contexts.Faces.Faces_Context'Class; View : in ASF.Components.Root.UIViewRoot) is pragma Unreferenced (Handler); Root : constant access ASF.Components.Base.UIComponent'Class := ASF.Components.Root.Get_Root (View); begin if Root /= null then Root.Encode_All (Context); end if; end Render_View; -- ------------------------------ -- Compute the locale that must be used according to the <b>Accept-Language</b> request -- header and the application supported locales. -- ------------------------------ function Calculate_Locale (Handler : in View_Handler; Context : in ASF.Contexts.Faces.Faces_Context'Class) return Util.Locales.Locale is pragma Unreferenced (Handler); App : constant ASF.Contexts.Faces.Application_Access := Context.Get_Application; begin return App.Calculate_Locale (Context); end Calculate_Locale; -- ------------------------------ -- Compose a URI path with two components. Unlike the Ada.Directories.Compose, -- and Util.Files.Compose the path separator must be a URL path separator (ie, '/'). -- ------------------------------ function Compose (Directory : in String; Name : in String) return String is begin if Directory'Length = 0 then return Name; elsif Directory (Directory'Last) = '/' and Name (Name'First) = '/' then return Directory & Name (Name'First + 1 .. Name'Last); elsif Directory (Directory'Last) = '/' or Name (Name'First) = '/' then return Directory & Name; else return Directory & "/" & Name; end if; end Compose; -- ------------------------------ -- Get the URL suitable for encoding and rendering the view specified by the <b>View</b> -- identifier. -- ------------------------------ function Get_Action_URL (Handler : in View_Handler; Context : in ASF.Contexts.Faces.Faces_Context'Class; View : in String) return String is use Ada.Strings.Unbounded; Pos : constant Natural := Util.Strings.Rindex (View, '.'); Context_Path : constant String := Context.Get_Request.Get_Context_Path; begin if Pos > 0 and then View (Pos .. View'Last) = Handler.File_Ext then return Compose (Context_Path, View (View'First .. Pos - 1) & To_String (Handler.View_Ext)); end if; if Pos > 0 and then View (Pos .. View'Last) = Handler.View_Ext then return Compose (Context_Path, View); end if; return Compose (Context_Path, View); end Get_Action_URL; -- ------------------------------ -- Get the URL for redirecting the user to the specified view. -- ------------------------------ function Get_Redirect_URL (Handler : in View_Handler; Context : in ASF.Contexts.Faces.Faces_Context'Class; View : in String) return String is Pos : constant Natural := Util.Strings.Rindex (View, '?'); begin if Pos > 0 then return Handler.Get_Action_URL (Context, View (View'First .. Pos - 1)) & View (Pos .. View'Last); else return Handler.Get_Action_URL (Context, View); end if; end Get_Redirect_URL; -- ------------------------------ -- Initialize the view handler. -- ------------------------------ procedure Initialize (Handler : out View_Handler; Components : access ASF.Factory.Component_Factory; Conf : in Config) is use ASF.Views; use Ada.Strings.Unbounded; begin Handler.Paths := To_Unbounded_String (Conf.Get (VIEW_DIR_PARAM)); Handler.View_Ext := To_Unbounded_String (Conf.Get (VIEW_EXT_PARAM)); Handler.File_Ext := To_Unbounded_String (Conf.Get (VIEW_FILE_EXT_PARAM)); Facelets.Initialize (Factory => Handler.Facelets, Components => Components, Paths => To_String (Handler.Paths), Ignore_White_Spaces => Conf.Get (VIEW_IGNORE_WHITE_SPACES_PARAM), Ignore_Empty_Lines => Conf.Get (VIEW_IGNORE_EMPTY_LINES_PARAM), Escape_Unknown_Tags => Conf.Get (VIEW_ESCAPE_UNKNOWN_TAGS_PARAM)); end Initialize; -- ------------------------------ -- Closes the view handler -- ------------------------------ procedure Close (Handler : in out View_Handler) is use ASF.Views; begin Facelets.Clear_Cache (Handler.Facelets); end Close; -- ------------------------------ -- Set the extension mapping rule to find the facelet file from -- the name. -- ------------------------------ procedure Set_Extension_Mapping (Handler : in out View_Handler; From : in String; Into : in String) is use Ada.Strings.Unbounded; begin Handler.View_Ext := To_Unbounded_String (From); Handler.File_Ext := To_Unbounded_String (Into); end Set_Extension_Mapping; end ASF.Applications.Views;
Fix compilation warning
Fix compilation warning
Ada
apache-2.0
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
7decb3bcb3a87e9ebcbde23d94c7dfa871cdf02f
src/gen-commands-templates.adb
src/gen-commands-templates.adb
----------------------------------------------------------------------- -- gen-commands-templates -- Template based command -- Copyright (C) 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Text_IO; with Ada.IO_Exceptions; with Ada.Directories; with GNAT.Command_Line; with Gen.Artifacts; with Util.Log.Loggers; with Util.Files; with Util.Beans.Objects; with Util.Serialize.Mappers.Record_Mapper; with Util.Serialize.IO.XML; package body Gen.Commands.Templates is use Ada.Strings.Unbounded; use Util.Log; use GNAT.Command_Line; Log : constant Loggers.Logger := Loggers.Create ("Gen.Commands.Templates"); -- ------------------------------ -- Page Creation Command -- ------------------------------ -- This command adds a XHTML page to the web application. -- Execute the command with the arguments. procedure Execute (Cmd : in Command; Generator : in out Gen.Generator.Handler) is function Get_Output_Dir return String; function Get_Output_Dir return String is Dir : constant String := Generator.Get_Result_Directory; begin if Length (Cmd.Base_Dir) = 0 then return Dir; else return Util.Files.Compose (Dir, To_String (Cmd.Base_Dir)); end if; end Get_Output_Dir; Out_Dir : constant String := Get_Output_Dir; Iter : Param_Vectors.Cursor := Cmd.Params.First; begin Generator.Read_Project ("dynamo.xml", False); while Param_Vectors.Has_Element (Iter) loop declare P : constant Param := Param_Vectors.Element (Iter); Value : constant String := Get_Argument; begin if not P.Is_Optional and Value'Length = 0 then Generator.Error ("Missing argument for {0}", To_String (P.Argument)); return; end if; Generator.Set_Global (To_String (P.Name), Value); end; Param_Vectors.Next (Iter); end loop; Generator.Set_Force_Save (False); Generator.Set_Result_Directory (Out_Dir); declare Iter : Util.Strings.Sets.Cursor := Cmd.Templates.First; begin while Util.Strings.Sets.Has_Element (Iter) loop Gen.Generator.Generate (Generator, Gen.Artifacts.ITERATION_TABLE, Util.Strings.Sets.Element (Iter)); Util.Strings.Sets.Next (Iter); end loop; end; end Execute; -- ------------------------------ -- Write the help associated with the command. -- ------------------------------ procedure Help (Cmd : in Command; Generator : in out Gen.Generator.Handler) is pragma Unreferenced (Generator); use Ada.Text_IO; begin Put_Line (To_String (Cmd.Name) & ": " & To_String (Cmd.Title)); Put_Line ("Usage: " & To_String (Cmd.Usage)); New_Line; Put_Line (To_String (Cmd.Help_Msg)); end Help; type Command_Fields is (FIELD_NAME, FIELD_HELP, FIELD_USAGE, FIELD_TITLE, FIELD_BASEDIR, FIELD_PARAM, FIELD_PARAM_NAME, FIELD_PARAM_OPTIONAL, FIELD_PARAM_ARG, FIELD_TEMPLATE, FIELD_COMMAND); type Command_Loader is record Command : Command_Access := null; P : Param; end record; type Command_Loader_Access is access all Command_Loader; procedure Set_Member (Closure : in out Command_Loader; Field : in Command_Fields; Value : in Util.Beans.Objects.Object); function To_String (Value : in Util.Beans.Objects.Object) return Unbounded_String; -- ------------------------------ -- Convert the object value into a string and trim any space/tab/newlines. -- ------------------------------ function To_String (Value : in Util.Beans.Objects.Object) return Unbounded_String is Result : constant String := Util.Beans.Objects.To_String (Value); First_Pos : Natural := Result'First; Last_Pos : Natural := Result'Last; C : Character; begin while First_Pos <= Last_Pos loop C := Result (First_Pos); exit when C /= ' ' and C /= ASCII.LF and C /= ASCII.CR and C /= ASCII.HT; First_Pos := First_Pos + 1; end loop; while Last_Pos >= First_Pos loop C := Result (Last_Pos); exit when C /= ' ' and C /= ASCII.LF and C /= ASCII.CR and C /= ASCII.HT; Last_Pos := Last_Pos - 1; end loop; return To_Unbounded_String (Result (First_Pos .. Last_Pos)); end To_String; procedure Set_Member (Closure : in out Command_Loader; Field : in Command_Fields; Value : in Util.Beans.Objects.Object) is use Util.Beans.Objects; begin if Field = FIELD_COMMAND then if Closure.Command /= null then Log.Info ("Adding command {0}", Closure.Command.Name); Add_Command (Name => To_String (Closure.Command.Name), Cmd => Closure.Command.all'Access); Closure.Command := null; end if; else if Closure.Command = null then Closure.Command := new Gen.Commands.Templates.Command; end if; case Field is when FIELD_NAME => Closure.Command.Name := To_String (Value); when FIELD_TITLE => Closure.Command.Title := To_String (Value); when FIELD_USAGE => Closure.Command.Usage := To_String (Value); when FIELD_HELP => Closure.Command.Help_Msg := To_String (Value); when FIELD_TEMPLATE => Closure.Command.Templates.Include (To_String (Value)); when FIELD_PARAM_NAME => Closure.P.Name := To_Unbounded_String (Value); when FIELD_PARAM_OPTIONAL => Closure.P.Is_Optional := To_Boolean (Value); when FIELD_PARAM_ARG => Closure.P.Argument := To_Unbounded_String (Value); when FIELD_PARAM => Closure.P.Value := To_Unbounded_String (Value); Closure.Command.Params.Append (Closure.P); Closure.P.Name := Ada.Strings.Unbounded.Null_Unbounded_String; Closure.P.Argument := Ada.Strings.Unbounded.Null_Unbounded_String; Closure.P.Is_Optional := False; when FIELD_BASEDIR => Closure.Command.Base_Dir := To_Unbounded_String (Value); when FIELD_COMMAND => null; end case; end if; end Set_Member; package Command_Mapper is new Util.Serialize.Mappers.Record_Mapper (Element_Type => Command_Loader, Element_Type_Access => Command_Loader_Access, Fields => Command_Fields, Set_Member => Set_Member); Cmd_Mapper : aliased Command_Mapper.Mapper; -- ------------------------------ -- Read the template commands defined in dynamo configuration directory. -- ------------------------------ procedure Read_Commands (Generator : in out Gen.Generator.Handler) is procedure Read_Command (Name : in String; File_Path : in String; Done : out Boolean); -- ------------------------------ -- Read the XML command file. -- ------------------------------ procedure Read_Command (Name : in String; File_Path : in String; Done : out Boolean) is pragma Unreferenced (Name); Loader : aliased Command_Loader; Reader : Util.Serialize.IO.XML.Parser; begin Log.Info ("Reading command file '{0}'", File_Path); Done := False; -- Create the mapping to load the XML command file. Reader.Add_Mapping ("commands", Cmd_Mapper'Access); -- Set the context for Set_Member. Command_Mapper.Set_Context (Reader, Loader'Unchecked_Access); -- Read the XML command file. Reader.Parse (File_Path); exception when Ada.IO_Exceptions.Name_Error => Generator.Error ("Command file {0} does not exist", File_Path); end Read_Command; Config_Dir : constant String := Generator.Get_Config_Directory; Cmd_Dir : constant String := Generator.Get_Parameter ("generator.commands.dir"); Path : constant String := Util.Files.Compose (Config_Dir, Cmd_Dir); begin Log.Debug ("Checking commands in {0}", Path); if Ada.Directories.Exists (Path) then Util.Files.Iterate_Files_Path (Path => Path, Pattern => "*.xml", Process => Read_Command'Access); end if; end Read_Commands; begin -- Setup the mapper to load XML commands. Cmd_Mapper.Add_Mapping ("command/name", FIELD_NAME); Cmd_Mapper.Add_Mapping ("command/title", FIELD_TITLE); Cmd_Mapper.Add_Mapping ("command/usage", FIELD_USAGE); Cmd_Mapper.Add_Mapping ("command/help", FIELD_HELP); Cmd_Mapper.Add_Mapping ("command/basedir", FIELD_BASEDIR); Cmd_Mapper.Add_Mapping ("command/param", FIELD_PARAM); Cmd_Mapper.Add_Mapping ("command/param/@name", FIELD_PARAM_NAME); Cmd_Mapper.Add_Mapping ("command/param/@optional", FIELD_PARAM_OPTIONAL); Cmd_Mapper.Add_Mapping ("command/param/@arg", FIELD_PARAM_ARG); Cmd_Mapper.Add_Mapping ("command/template", FIELD_TEMPLATE); Cmd_Mapper.Add_Mapping ("command", FIELD_COMMAND); end Gen.Commands.Templates;
----------------------------------------------------------------------- -- gen-commands-templates -- Template based command -- Copyright (C) 2011, 2012, 2013 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Text_IO; with Ada.IO_Exceptions; with Ada.Directories; with Ada.Streams.Stream_IO; with GNAT.Command_Line; with Gen.Artifacts; with EL.Contexts.Default; with EL.Expressions; with EL.Variables.Default; with Util.Log.Loggers; with Util.Files; with Util.Streams.Files; with Util.Streams.Texts; with Util.Beans.Objects; with Util.Serialize.Mappers.Record_Mapper; with Util.Serialize.IO.XML; package body Gen.Commands.Templates is use Ada.Strings.Unbounded; use GNAT.Command_Line; Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Gen.Commands.Templates"); -- Apply the patch instruction procedure Patch_File (Generator : in out Gen.Generator.Handler; Info : in Patch); function Match_Line (Line : in String; Pattern : in String) return Boolean; -- ------------------------------ -- Check if the line matches the pseudo pattern. -- ------------------------------ function Match_Line (Line : in String; Pattern : in String) return Boolean is L_Pos : Natural := Line'First; P_Pos : Natural := Pattern'First; begin while P_Pos <= Pattern'Last loop if L_Pos > Line'Last then return False; end if; if Line (L_Pos) = Pattern (P_Pos) then if Pattern (P_Pos) /= ' ' then P_Pos := P_Pos + 1; end if; L_Pos := L_Pos + 1; elsif Pattern (P_Pos) = ' ' and Line (L_Pos) = Pattern (P_Pos + 1) then P_Pos := P_Pos + 2; L_Pos := L_Pos + 1; elsif Pattern (P_Pos) = ' ' and Pattern (P_Pos + 1) = '*' then P_Pos := P_Pos + 1; L_Pos := L_Pos + 1; elsif Pattern (P_Pos) = '*' and Line (L_Pos) = Pattern (P_Pos + 1) then P_Pos := P_Pos + 2; L_Pos := L_Pos + 1; elsif Pattern (P_Pos) = '*' and Line (L_Pos) /= ' ' then L_Pos := L_Pos + 1; else return False; end if; end loop; return True; end Match_Line; -- ------------------------------ -- Apply the patch instruction -- ------------------------------ procedure Patch_File (Generator : in out Gen.Generator.Handler; Info : in Patch) is procedure Save_Output (H : in out Gen.Generator.Handler; File : in String; Content : in Ada.Strings.Unbounded.Unbounded_String); Ctx : EL.Contexts.Default.Default_Context; Variables : aliased EL.Variables.Default.Default_Variable_Mapper; procedure Save_Output (H : in out Gen.Generator.Handler; File : in String; Content : in Ada.Strings.Unbounded.Unbounded_String) is type State is (MATCH_AFTER, MATCH_BEFORE, MATCH_DONE); Output_Dir : constant String := H.Get_Result_Directory; Path : constant String := Util.Files.Compose (Output_Dir, File); Tmp_File : constant String := Path & ".tmp"; Line_Number : Natural := 0; After_Pos : Natural := 1; Current_State : State := MATCH_AFTER; Tmp_Output : aliased Util.Streams.Files.File_Stream; Output : Util.Streams.Texts.Print_Stream; procedure Process (Line : in String); procedure Process (Line : in String) is begin Line_Number := Line_Number + 1; case Current_State is when MATCH_AFTER => if Match_Line (Line, Info.After.Element (After_Pos)) then Log.Info ("Match after at line {0}", Natural'Image (Line_Number)); After_Pos := After_Pos + 1; if After_Pos >= Natural (Info.After.Length) then Current_State := MATCH_BEFORE; end if; end if; when MATCH_BEFORE => if Match_Line (Line, To_String (Info.Before)) then Log.Info ("Match before at line {0}", Natural'Image (Line_Number)); Log.Info ("Add content {0}", Content); Output.Write (Content); Current_State := MATCH_DONE; end if; when MATCH_DONE => null; end case; Output.Write (Line); Output.Write (ASCII.LF); end Process; begin Tmp_Output.Create (Name => Tmp_File, Mode => Ada.Streams.Stream_IO.Out_File); Output.Initialize (Tmp_Output'Unchecked_Access); Util.Files.Read_File (Path, Process'Access); Output.Close; if Current_State /= MATCH_DONE then H.Error ("Patch {0} failed", Path); Ada.Directories.Delete_File (Tmp_File); else Ada.Directories.Delete_File (Path); Ada.Directories.Rename (Old_Name => Tmp_File, New_Name => Path); end if; exception when Ada.IO_Exceptions.Name_Error => H.Error ("Cannot patch file {0}", Path); end Save_Output; begin Ctx.Set_Variable_Mapper (Variables'Unchecked_Access); Gen.Generator.Generate (Generator, Gen.Artifacts.ITERATION_TABLE, To_String (Info.Template), Save_Output'Access); end Patch_File; -- Execute the command with the arguments. procedure Execute (Cmd : in Command; Generator : in out Gen.Generator.Handler) is function Get_Output_Dir return String; function Get_Output_Dir return String is Dir : constant String := Generator.Get_Result_Directory; begin if Length (Cmd.Base_Dir) = 0 then return Dir; else return Util.Files.Compose (Dir, To_String (Cmd.Base_Dir)); end if; end Get_Output_Dir; Out_Dir : constant String := Get_Output_Dir; Iter : Param_Vectors.Cursor := Cmd.Params.First; begin Generator.Read_Project ("dynamo.xml", False); while Param_Vectors.Has_Element (Iter) loop declare P : constant Param := Param_Vectors.Element (Iter); Value : constant String := Get_Argument; begin if not P.Is_Optional and Value'Length = 0 then Generator.Error ("Missing argument for {0}", To_String (P.Argument)); return; end if; Generator.Set_Global (To_String (P.Name), Value); end; Param_Vectors.Next (Iter); end loop; Generator.Set_Force_Save (False); Generator.Set_Result_Directory (Out_Dir); declare Iter : Util.Strings.Sets.Cursor := Cmd.Templates.First; begin while Util.Strings.Sets.Has_Element (Iter) loop Gen.Generator.Generate (Generator, Gen.Artifacts.ITERATION_TABLE, Util.Strings.Sets.Element (Iter), Gen.Generator.Save_Content'Access); Util.Strings.Sets.Next (Iter); end loop; end; -- Apply the patch instructions defined for the command. declare Iter : Patch_Vectors.Cursor := Cmd.Patches.First; begin while Patch_Vectors.Has_Element (Iter) loop Patch_File (Generator, Patch_Vectors.Element (Iter)); Patch_Vectors.Next (Iter); end loop; end; end Execute; -- ------------------------------ -- Write the help associated with the command. -- ------------------------------ procedure Help (Cmd : in Command; Generator : in out Gen.Generator.Handler) is pragma Unreferenced (Generator); use Ada.Text_IO; begin Put_Line (To_String (Cmd.Name) & ": " & To_String (Cmd.Title)); Put_Line ("Usage: " & To_String (Cmd.Usage)); New_Line; Put_Line (To_String (Cmd.Help_Msg)); end Help; type Command_Fields is (FIELD_NAME, FIELD_HELP, FIELD_USAGE, FIELD_TITLE, FIELD_BASEDIR, FIELD_PARAM, FIELD_PARAM_NAME, FIELD_PARAM_OPTIONAL, FIELD_PARAM_ARG, FIELD_TEMPLATE, FIELD_PATCH, FIELD_AFTER, FIELD_BEFORE, FIELD_INSERT_TEMPLATE, FIELD_COMMAND); type Command_Loader is record Command : Command_Access := null; P : Param; Info : Patch; end record; type Command_Loader_Access is access all Command_Loader; procedure Set_Member (Closure : in out Command_Loader; Field : in Command_Fields; Value : in Util.Beans.Objects.Object); function To_String (Value : in Util.Beans.Objects.Object) return Unbounded_String; -- ------------------------------ -- Convert the object value into a string and trim any space/tab/newlines. -- ------------------------------ function To_String (Value : in Util.Beans.Objects.Object) return Unbounded_String is Result : constant String := Util.Beans.Objects.To_String (Value); First_Pos : Natural := Result'First; Last_Pos : Natural := Result'Last; C : Character; begin while First_Pos <= Last_Pos loop C := Result (First_Pos); exit when C /= ' ' and C /= ASCII.LF and C /= ASCII.CR and C /= ASCII.HT; First_Pos := First_Pos + 1; end loop; while Last_Pos >= First_Pos loop C := Result (Last_Pos); exit when C /= ' ' and C /= ASCII.LF and C /= ASCII.CR and C /= ASCII.HT; Last_Pos := Last_Pos - 1; end loop; return To_Unbounded_String (Result (First_Pos .. Last_Pos)); end To_String; procedure Set_Member (Closure : in out Command_Loader; Field : in Command_Fields; Value : in Util.Beans.Objects.Object) is use Util.Beans.Objects; begin if Field = FIELD_COMMAND then if Closure.Command /= null then Log.Info ("Adding command {0}", Closure.Command.Name); Add_Command (Name => To_String (Closure.Command.Name), Cmd => Closure.Command.all'Access); Closure.Command := null; end if; else if Closure.Command = null then Closure.Command := new Gen.Commands.Templates.Command; end if; case Field is when FIELD_NAME => Closure.Command.Name := To_String (Value); when FIELD_TITLE => Closure.Command.Title := To_String (Value); when FIELD_USAGE => Closure.Command.Usage := To_String (Value); when FIELD_HELP => Closure.Command.Help_Msg := To_String (Value); when FIELD_TEMPLATE => Closure.Command.Templates.Include (To_String (Value)); when FIELD_PARAM_NAME => Closure.P.Name := To_Unbounded_String (Value); when FIELD_PARAM_OPTIONAL => Closure.P.Is_Optional := To_Boolean (Value); when FIELD_PARAM_ARG => Closure.P.Argument := To_Unbounded_String (Value); when FIELD_PARAM => Closure.P.Value := To_Unbounded_String (Value); Closure.Command.Params.Append (Closure.P); Closure.P.Name := Ada.Strings.Unbounded.Null_Unbounded_String; Closure.P.Argument := Ada.Strings.Unbounded.Null_Unbounded_String; Closure.P.Is_Optional := False; when FIELD_BASEDIR => Closure.Command.Base_Dir := To_Unbounded_String (Value); when FIELD_COMMAND => null; when FIELD_INSERT_TEMPLATE => Closure.Info.Template := To_Unbounded_String (Value); when FIELD_AFTER => Closure.Info.After.Append (To_String (Value)); when FIELD_BEFORE => Closure.Info.Before := To_Unbounded_String (Value); when FIELD_PATCH => Closure.Command.Patches.Append (Closure.Info); Closure.Info.After.Clear; Closure.Info.Before := To_Unbounded_String (""); end case; end if; end Set_Member; package Command_Mapper is new Util.Serialize.Mappers.Record_Mapper (Element_Type => Command_Loader, Element_Type_Access => Command_Loader_Access, Fields => Command_Fields, Set_Member => Set_Member); Cmd_Mapper : aliased Command_Mapper.Mapper; -- ------------------------------ -- Read the template commands defined in dynamo configuration directory. -- ------------------------------ procedure Read_Commands (Generator : in out Gen.Generator.Handler) is procedure Read_Command (Name : in String; File_Path : in String; Done : out Boolean); -- ------------------------------ -- Read the XML command file. -- ------------------------------ procedure Read_Command (Name : in String; File_Path : in String; Done : out Boolean) is pragma Unreferenced (Name); Loader : aliased Command_Loader; Reader : Util.Serialize.IO.XML.Parser; begin Log.Info ("Reading command file '{0}'", File_Path); Done := False; -- Create the mapping to load the XML command file. Reader.Add_Mapping ("commands", Cmd_Mapper'Access); -- Set the context for Set_Member. Command_Mapper.Set_Context (Reader, Loader'Unchecked_Access); -- Read the XML command file. Reader.Parse (File_Path); exception when Ada.IO_Exceptions.Name_Error => Generator.Error ("Command file {0} does not exist", File_Path); end Read_Command; Config_Dir : constant String := Generator.Get_Config_Directory; Cmd_Dir : constant String := Generator.Get_Parameter ("generator.commands.dir"); Path : constant String := Util.Files.Compose (Config_Dir, Cmd_Dir); begin Log.Debug ("Checking commands in {0}", Path); if Ada.Directories.Exists (Path) then Util.Files.Iterate_Files_Path (Path => Path, Pattern => "*.xml", Process => Read_Command'Access); end if; end Read_Commands; begin -- Setup the mapper to load XML commands. Cmd_Mapper.Add_Mapping ("command/name", FIELD_NAME); Cmd_Mapper.Add_Mapping ("command/title", FIELD_TITLE); Cmd_Mapper.Add_Mapping ("command/usage", FIELD_USAGE); Cmd_Mapper.Add_Mapping ("command/help", FIELD_HELP); Cmd_Mapper.Add_Mapping ("command/basedir", FIELD_BASEDIR); Cmd_Mapper.Add_Mapping ("command/param", FIELD_PARAM); Cmd_Mapper.Add_Mapping ("command/param/@name", FIELD_PARAM_NAME); Cmd_Mapper.Add_Mapping ("command/param/@optional", FIELD_PARAM_OPTIONAL); Cmd_Mapper.Add_Mapping ("command/param/@arg", FIELD_PARAM_ARG); Cmd_Mapper.Add_Mapping ("command/patch/template", FIELD_INSERT_TEMPLATE); Cmd_Mapper.Add_Mapping ("command/patch/after", FIELD_AFTER); Cmd_Mapper.Add_Mapping ("command/patch/before", FIELD_BEFORE); Cmd_Mapper.Add_Mapping ("command/template", FIELD_TEMPLATE); Cmd_Mapper.Add_Mapping ("command/patch", FIELD_PATCH); Cmd_Mapper.Add_Mapping ("command", FIELD_COMMAND); end Gen.Commands.Templates;
Implement some basic support to patch files and insert some template generation content in existing files
Implement some basic support to patch files and insert some template generation content in existing files
Ada
apache-2.0
stcarrez/dynamo,stcarrez/dynamo,stcarrez/dynamo
57d347942c8157ceaa4f82a79c5dbc747d6f978b
src/security-oauth-clients.ads
src/security-oauth-clients.ads
----------------------------------------------------------------------- -- security-oauth -- OAuth Security -- Copyright (C) 2012, 2013, 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; -- The <b>Security.OAuth.Clients</b> package implements the client OAuth 2.0 authorization. -- -- Note: OAuth 1.0 could be implemented but since it's being deprecated it's not worth doing it. package Security.OAuth.Clients is -- ------------------------------ -- Access Token -- ------------------------------ -- Access tokens are credentials used to access protected resources. -- The access token is represented as a <b>Principal</b>. This is an opaque -- value for an application. type Access_Token (Len : Natural) is new Security.Principal with private; type Access_Token_Access is access all Access_Token'Class; -- Get the principal name. This is the OAuth access token. function Get_Name (From : in Access_Token) return String; type OpenID_Token (Len, Id_Len, Refresh_Len : Natural) is new Access_Token with private; type OpenID_Token_Access is access all OpenID_Token'Class; -- Get the id_token that was returned by the authentication process. function Get_Id_Token (From : in OpenID_Token) return String; -- Generate a random nonce with at last the number of random bits. -- The number of bits is rounded up to a multiple of 32. -- The random bits are then converted to base64url in the returned string. function Create_Nonce (Bits : in Positive := 256) return String; type Grant_Type is new Security.Principal with private; -- Get the principal name. This is the OAuth access token. function Get_Name (From : in Grant_Type) return String; -- ------------------------------ -- Application -- ------------------------------ -- The <b>Application</b> holds the necessary information to let a user -- grant access to its protected resources on the resource server. It contains -- information that allows the OAuth authorization server to identify the -- application (client id and secret key). type Application is new Security.OAuth.Application with private; -- Set the OAuth authorization server URI that the application must use -- to exchange the OAuth code into an access token. procedure Set_Provider_URI (App : in out Application; URI : in String); -- OAuth 2.0 Section 4.1.1 Authorization Request -- Build a unique opaque value used to prevent cross-site request forgery. -- The <b>Nonce</b> parameters is an optional but recommended unique value -- used only once. The state value will be returned back by the OAuth provider. -- This protects the <tt>client_id</tt> and <tt>redirect_uri</tt> parameters. function Get_State (App : in Application; Nonce : in String) return String; -- Get the authenticate parameters to build the URI to redirect the user to -- the OAuth authorization form. function Get_Auth_Params (App : in Application; State : in String; Scope : in String := "") return String; -- OAuth 2.0 Section 4.1.2 Authorization Response -- Verify that the <b>State</b> opaque value was created by the <b>Get_State</b> -- operation with the given client and redirect URL. function Is_Valid_State (App : in Application; Nonce : in String; State : in String) return Boolean; -- OAuth 2.0 Section 4.1.3. Access Token Request -- Section 4.1.4. Access Token Response -- Exchange the OAuth code into an access token. function Request_Access_Token (App : in Application; Code : in String) return Access_Token_Access; -- Get a request token with username and password. -- RFC 6749: 4.3. Resource Owner Password Credentials Grant procedure Request_Token (App : in Application; Username : in String; Password : in String; Scope : in String; Token : in out Grant_Type'Class); -- Create the access token function Create_Access_Token (App : in Application; Token : in String; Refresh : in String; Id_Token : in String; Expires : in Natural) return Access_Token_Access; private type Access_Token (Len : Natural) is new Security.Principal with record Access_Id : String (1 .. Len); end record; type OpenID_Token (Len, Id_Len, Refresh_Len : Natural) is new Access_Token (Len) with record Id_Token : String (1 .. Id_Len); Refresh_Token : String (1 .. Refresh_Len); end record; type Application is new Security.OAuth.Application with record Request_URI : Ada.Strings.Unbounded.Unbounded_String; end record; type Grant_Type is new Security.Principal with record Access_Token : Ada.Strings.Unbounded.Unbounded_String; Refresh_Token : Ada.Strings.Unbounded.Unbounded_String; Id_Token : Ada.Strings.Unbounded.Unbounded_String; end record; end Security.OAuth.Clients;
----------------------------------------------------------------------- -- security-oauth -- OAuth Security -- Copyright (C) 2012, 2013, 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; -- The <b>Security.OAuth.Clients</b> package implements the client OAuth 2.0 authorization. -- -- Note: OAuth 1.0 could be implemented but since it's being deprecated it's not worth doing it. package Security.OAuth.Clients is -- ------------------------------ -- Access Token -- ------------------------------ -- Access tokens are credentials used to access protected resources. -- The access token is represented as a <b>Principal</b>. This is an opaque -- value for an application. type Access_Token (Len : Natural) is new Security.Principal with private; type Access_Token_Access is access all Access_Token'Class; -- Get the principal name. This is the OAuth access token. function Get_Name (From : in Access_Token) return String; type OpenID_Token (Len, Id_Len, Refresh_Len : Natural) is new Access_Token with private; type OpenID_Token_Access is access all OpenID_Token'Class; -- Get the id_token that was returned by the authentication process. function Get_Id_Token (From : in OpenID_Token) return String; -- Generate a random nonce with at last the number of random bits. -- The number of bits is rounded up to a multiple of 32. -- The random bits are then converted to base64url in the returned string. function Create_Nonce (Bits : in Positive := 256) return String; type Grant_Type is new Security.Principal with private; -- Get the principal name. This is the OAuth access token. function Get_Name (From : in Grant_Type) return String; -- Get the Authorization header to be used for accessing a protected resource. -- (See RFC 6749 7. Accessing Protected Resources) function Get_Authorization (From : in Grant_Type) return String; -- ------------------------------ -- Application -- ------------------------------ -- The <b>Application</b> holds the necessary information to let a user -- grant access to its protected resources on the resource server. It contains -- information that allows the OAuth authorization server to identify the -- application (client id and secret key). type Application is new Security.OAuth.Application with private; -- Set the OAuth authorization server URI that the application must use -- to exchange the OAuth code into an access token. procedure Set_Provider_URI (App : in out Application; URI : in String); -- OAuth 2.0 Section 4.1.1 Authorization Request -- Build a unique opaque value used to prevent cross-site request forgery. -- The <b>Nonce</b> parameters is an optional but recommended unique value -- used only once. The state value will be returned back by the OAuth provider. -- This protects the <tt>client_id</tt> and <tt>redirect_uri</tt> parameters. function Get_State (App : in Application; Nonce : in String) return String; -- Get the authenticate parameters to build the URI to redirect the user to -- the OAuth authorization form. function Get_Auth_Params (App : in Application; State : in String; Scope : in String := "") return String; -- OAuth 2.0 Section 4.1.2 Authorization Response -- Verify that the <b>State</b> opaque value was created by the <b>Get_State</b> -- operation with the given client and redirect URL. function Is_Valid_State (App : in Application; Nonce : in String; State : in String) return Boolean; -- OAuth 2.0 Section 4.1.3. Access Token Request -- Section 4.1.4. Access Token Response -- Exchange the OAuth code into an access token. function Request_Access_Token (App : in Application; Code : in String) return Access_Token_Access; -- Get a request token with username and password. -- RFC 6749: 4.3. Resource Owner Password Credentials Grant procedure Request_Token (App : in Application; Username : in String; Password : in String; Scope : in String; Token : in out Grant_Type'Class); -- Create the access token function Create_Access_Token (App : in Application; Token : in String; Refresh : in String; Id_Token : in String; Expires : in Natural) return Access_Token_Access; private type Access_Token (Len : Natural) is new Security.Principal with record Access_Id : String (1 .. Len); end record; type OpenID_Token (Len, Id_Len, Refresh_Len : Natural) is new Access_Token (Len) with record Id_Token : String (1 .. Id_Len); Refresh_Token : String (1 .. Refresh_Len); end record; type Application is new Security.OAuth.Application with record Request_URI : Ada.Strings.Unbounded.Unbounded_String; end record; type Grant_Type is new Security.Principal with record Access_Token : Ada.Strings.Unbounded.Unbounded_String; Refresh_Token : Ada.Strings.Unbounded.Unbounded_String; Id_Token : Ada.Strings.Unbounded.Unbounded_String; end record; end Security.OAuth.Clients;
Declare the Get_Authorization function
Declare the Get_Authorization function
Ada
apache-2.0
stcarrez/ada-security
c1555d6cca6f2a8ddbacc57a635d7cd52fad2cbc
examples/shared/common/gui/lcd_std_out.adb
examples/shared/common/gui/lcd_std_out.adb
------------------------------------------------------------------------------ -- -- -- Copyright (C) 2015-2016, AdaCore -- -- -- -- Redistribution and use in source and binary forms, with or without -- -- modification, are permitted provided that the following conditions are -- -- met: -- -- 1. Redistributions of source code must retain the above copyright -- -- notice, this list of conditions and the following disclaimer. -- -- 2. Redistributions in binary form must reproduce the above copyright -- -- notice, this list of conditions and the following disclaimer in -- -- the documentation and/or other materials provided with the -- -- distribution. -- -- 3. Neither the name of the copyright holder nor the names of its -- -- contributors may be used to endorse or promote products derived -- -- from this software without specific prior written permission. -- -- -- -- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -- -- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -- -- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -- -- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -- -- HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -- -- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -- -- LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -- -- DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -- -- THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -- -- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -- -- OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -- -- -- ------------------------------------------------------------------------------ with STM32.Board; use STM32.Board; with Bitmapped_Drawing; with Bitmap_Color_Conversion; use Bitmap_Color_Conversion; package body LCD_Std_Out is -- We don't make the current font visible to clients because changing it -- requires recomputation of the screen layout (eg the char height) and -- issuance of commands to the LCD component driver (eg to refill). Current_Font : BMP_Font := Default_Font; Char_Width : Natural := BMP_Fonts.Char_Width (Current_Font); Char_Height : Natural := BMP_Fonts.Char_Height (Current_Font); Max_Width : Natural := LCD_Natural_Width - Char_Width; -- The last place on the current "line" on the LCD where a char of the -- current font size can be printed Max_Height : Natural := LCD_Natural_Height - Char_Height; -- The last "line" on the LCD where a char of this current font size can be -- printed Current_Y : Natural := 0; -- The current "line" that the text will appear upon. Note this wraps -- around to the top of the screen. Char_Count : Natural := 0; -- The number of characters currently printed on the current line Initialized : Boolean := False; procedure Draw_Char (X, Y : Natural; Msg : Character); -- Convenience routine for call Drawing.Draw_Char procedure Recompute_Screen_Dimensions (Font : BMP_Font); -- Determins the max height and width for the specified font, given the -- current LCD orientation procedure Check_Initialized with Inline; -- Ensures that the LCD display is initialized and DMA2D -- is up and running procedure Internal_Put (Msg : String); -- Puts a new String in the frame buffer procedure Internal_Put (Msg : Character); -- Puts a new character in the frame buffer. ----------------------- -- Check_Initialized -- ----------------------- procedure Check_Initialized is begin if Initialized then return; end if; Initialized := True; if Display.Initialized then -- Ensure we use polling here: LCD_Std_Out may be called from the -- Last chance handler, and we don't want unexpected tasks or -- protected objects calling an entry not meant for that Display.Set_Mode (HAL.Framebuffer.Polling); else Display.Initialize (Mode => HAL.Framebuffer.Polling); Display.Initialize_Layer (1, HAL.Bitmap.RGB_565); Clear_Screen; end if; end Check_Initialized; --------------------------------- -- Recompute_Screen_Dimensions -- --------------------------------- procedure Recompute_Screen_Dimensions (Font : BMP_Font) is begin Check_Initialized; Char_Width := BMP_Fonts.Char_Width (Font); Char_Height := BMP_Fonts.Char_Height (Font); Max_Width := Display.Width - Char_Width - 1; Max_Height := Display.Height - Char_Height - 1; end Recompute_Screen_Dimensions; -------------- -- Set_Font -- -------------- procedure Set_Font (To : in BMP_Font) is begin Current_Font := To; Recompute_Screen_Dimensions (Current_Font); end Set_Font; --------------------- -- Set_Orientation -- --------------------- procedure Set_Orientation (To : in HAL.Framebuffer.Display_Orientation) is begin Display.Set_Orientation (To); Recompute_Screen_Dimensions (Current_Font); Clear_Screen; end Set_Orientation; ------------------ -- Clear_Screen -- ------------------ procedure Clear_Screen is begin Check_Initialized; Display.Hidden_Buffer (1).Set_Source (Current_Background_Color); Display.Hidden_Buffer (1).Fill; Current_Y := 0; Char_Count := 0; Display.Update_Layer (1, True); end Clear_Screen; ------------------ -- Internal_Put -- ------------------ procedure Internal_Put (Msg : String) is begin for C of Msg loop if C = ASCII.LF then New_Line; else Internal_Put (C); end if; end loop; end Internal_Put; --------- -- Put -- --------- procedure Put (Msg : String) is begin Internal_Put (Msg); Display.Update_Layer (1, True); end Put; --------------- -- Draw_Char -- --------------- procedure Draw_Char (X, Y : Natural; Msg : Character) is begin Check_Initialized; Bitmapped_Drawing.Draw_Char (Display.Hidden_Buffer (1).all, Start => (X, Y), Char => Msg, Font => Current_Font, Foreground => Bitmap_Color_To_Word (Display.Color_Mode (1), Current_Text_Color), Background => Bitmap_Color_To_Word (Display.Color_Mode (1), Current_Background_Color)); end Draw_Char; --------- -- Put -- --------- procedure Internal_Put (Msg : Character) is X : Natural; begin if Char_Count * Char_Width > Max_Width then -- go to the next line down Current_Y := Current_Y + Char_Height; if Current_Y > Max_Height then Current_Y := 0; end if; -- and start at beginning of the line X := 0; Char_Count := 0; else X := Char_Count * Char_Width; end if; Draw_Char (X, Current_Y, Msg); Char_Count := Char_Count + 1; end Internal_Put; --------- -- Put -- --------- procedure Put (Msg : Character) is begin Internal_Put (Msg); Display.Update_Layer (1, True); end Put; -------------- -- New_Line -- -------------- procedure New_Line is begin Char_Count := 0; -- next char printed will be at the start of a new line if Current_Y + Char_Height > Max_Height then Current_Y := 0; else Current_Y := Current_Y + Char_Height; end if; end New_Line; -------------- -- Put_Line -- -------------- procedure Put_Line (Msg : String) is begin Put (Msg); New_Line; end Put_Line; --------- -- Put -- --------- procedure Put (X, Y : Natural; Msg : Character) is begin Draw_Char (X, Y, Msg); Display.Update_Layer (1, True); end Put; --------- -- Put -- --------- procedure Put (X, Y : Natural; Msg : String) is Count : Natural := 0; Next_X : Natural; begin for C of Msg loop Next_X := X + Count * Char_Width; Draw_Char (Next_X, Y, C); Count := Count + 1; end loop; Display.Update_Layer (1, True); end Put; end LCD_Std_Out;
------------------------------------------------------------------------------ -- -- -- Copyright (C) 2015-2016, AdaCore -- -- -- -- Redistribution and use in source and binary forms, with or without -- -- modification, are permitted provided that the following conditions are -- -- met: -- -- 1. Redistributions of source code must retain the above copyright -- -- notice, this list of conditions and the following disclaimer. -- -- 2. Redistributions in binary form must reproduce the above copyright -- -- notice, this list of conditions and the following disclaimer in -- -- the documentation and/or other materials provided with the -- -- distribution. -- -- 3. Neither the name of the copyright holder nor the names of its -- -- contributors may be used to endorse or promote products derived -- -- from this software without specific prior written permission. -- -- -- -- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -- -- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -- -- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -- -- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -- -- HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -- -- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -- -- LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -- -- DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -- -- THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -- -- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -- -- OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -- -- -- ------------------------------------------------------------------------------ with STM32.Board; use STM32.Board; with Bitmapped_Drawing; with Bitmap_Color_Conversion; use Bitmap_Color_Conversion; package body LCD_Std_Out is -- We don't make the current font visible to clients because changing it -- requires recomputation of the screen layout (eg the char height) and -- issuance of commands to the LCD component driver (eg to refill). Current_Font : BMP_Font := Default_Font; Char_Width : Natural := BMP_Fonts.Char_Width (Current_Font); Char_Height : Natural := BMP_Fonts.Char_Height (Current_Font); Max_Width : Natural := LCD_Natural_Width - Char_Width; -- The last place on the current "line" on the LCD where a char of the -- current font size can be printed Max_Height : Natural := LCD_Natural_Height - Char_Height; -- The last "line" on the LCD where a char of this current font size can be -- printed Current_Y : Natural := 0; -- The current "line" that the text will appear upon. Note this wraps -- around to the top of the screen. Char_Count : Natural := 0; -- The number of characters currently printed on the current line Initialized : Boolean := False; procedure Draw_Char (X, Y : Natural; Msg : Character); -- Convenience routine for call Drawing.Draw_Char procedure Recompute_Screen_Dimensions (Font : BMP_Font); -- Determins the max height and width for the specified font, given the -- current LCD orientation procedure Check_Initialized with Inline; -- Ensures that the LCD display is initialized and DMA2D -- is up and running procedure Internal_Put (Msg : String); -- Puts a new String in the frame buffer procedure Internal_Put (Msg : Character); -- Puts a new character in the frame buffer. ----------------------- -- Check_Initialized -- ----------------------- procedure Check_Initialized is begin if Initialized then return; end if; Initialized := True; if Display.Initialized then -- Ensure we use polling here: LCD_Std_Out may be called from the -- Last chance handler, and we don't want unexpected tasks or -- protected objects calling an entry not meant for that Display.Set_Mode (HAL.Framebuffer.Polling); else Display.Initialize (Mode => HAL.Framebuffer.Polling); Display.Initialize_Layer (1, HAL.Bitmap.RGB_565); Clear_Screen; end if; end Check_Initialized; --------------------------------- -- Recompute_Screen_Dimensions -- --------------------------------- procedure Recompute_Screen_Dimensions (Font : BMP_Font) is begin Check_Initialized; Char_Width := BMP_Fonts.Char_Width (Font); Char_Height := BMP_Fonts.Char_Height (Font); Max_Width := Display.Width - Char_Width - 1; Max_Height := Display.Height - Char_Height - 1; end Recompute_Screen_Dimensions; -------------- -- Set_Font -- -------------- procedure Set_Font (To : in BMP_Font) is begin Current_Font := To; Recompute_Screen_Dimensions (Current_Font); end Set_Font; --------------------- -- Set_Orientation -- --------------------- procedure Set_Orientation (To : in HAL.Framebuffer.Display_Orientation) is begin Display.Set_Orientation (To); Recompute_Screen_Dimensions (Current_Font); Clear_Screen; end Set_Orientation; ------------------ -- Clear_Screen -- ------------------ procedure Clear_Screen is begin Check_Initialized; Display.Hidden_Buffer (1).Set_Source (Current_Background_Color); Display.Hidden_Buffer (1).Fill; Current_Y := 0; Char_Count := 0; Display.Update_Layer (1, True); end Clear_Screen; ------------------ -- Internal_Put -- ------------------ procedure Internal_Put (Msg : String) is begin for C of Msg loop if C = ASCII.LF then New_Line; else Internal_Put (C); end if; end loop; end Internal_Put; --------- -- Put -- --------- procedure Put (Msg : String) is begin Internal_Put (Msg); Display.Update_Layer (1, True); end Put; --------------- -- Draw_Char -- --------------- procedure Draw_Char (X, Y : Natural; Msg : Character) is begin Check_Initialized; Bitmapped_Drawing.Draw_Char (Display.Hidden_Buffer (1).all, Start => (X, Y), Char => Msg, Font => Current_Font, Foreground => Bitmap_Color_To_Word (Display.Color_Mode (1), Current_Text_Color), Background => Bitmap_Color_To_Word (Display.Color_Mode (1), Current_Background_Color)); end Draw_Char; --------- -- Put -- --------- procedure Internal_Put (Msg : Character) is begin if Char_Count * Char_Width > Max_Width then New_Line; end if; Draw_Char (Char_Count * Char_Width, Current_Y, Msg); Char_Count := Char_Count + 1; end Internal_Put; --------- -- Put -- --------- procedure Put (Msg : Character) is begin Internal_Put (Msg); Display.Update_Layer (1, True); end Put; -------------- -- New_Line -- -------------- procedure New_Line is begin Char_Count := 0; -- next char printed will be at the start of a new line if Current_Y + Char_Height > Max_Height then Current_Y := 0; else Current_Y := Current_Y + Char_Height; end if; end New_Line; -------------- -- Put_Line -- -------------- procedure Put_Line (Msg : String) is begin Put (Msg); New_Line; end Put_Line; --------- -- Put -- --------- procedure Put (X, Y : Natural; Msg : Character) is begin Draw_Char (X, Y, Msg); Display.Update_Layer (1, True); end Put; --------- -- Put -- --------- procedure Put (X, Y : Natural; Msg : String) is Count : Natural := 0; Next_X : Natural; begin for C of Msg loop Next_X := X + Count * Char_Width; Draw_Char (Next_X, Y, C); Count := Count + 1; end loop; Display.Update_Layer (1, True); end Put; end LCD_Std_Out;
Simplify lcd_std_out character emission
Examples: Simplify lcd_std_out character emission
Ada
bsd-3-clause
simonjwright/Ada_Drivers_Library,simonjwright/Ada_Drivers_Library,AdaCore/Ada_Drivers_Library,AdaCore/Ada_Drivers_Library
884a34b19acbe057b25f776f4bbf8ea11197edc7
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, 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;
----------------------------------------------------------------------- -- 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; subtype File_Type is Util.Systems.Types.File_Type; -- 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 use type Util.Systems.Types.File_Type; -- This use clause is required by GNAT 2018 for the -1! 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;
Change File_Type declaration
Change File_Type declaration
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
e7b4fe71ff2630fd4cad1c08b30e096657adb874
awa/plugins/awa-setup/src/awa-commands-setup.adb
awa/plugins/awa-setup/src/awa-commands-setup.adb
----------------------------------------------------------------------- -- awa-commands-setup -- Setup command to start and configure the application -- Copyright (C) 2020 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with GNAT.Command_Line; with AWA.Applications; with AWA.Setup.Applications; with Servlet.Core; package body AWA.Commands.Setup is use AWA.Applications; package Command_Drivers renames Start_Command.Command_Drivers; overriding procedure Execute (Command : in out Command_Type; Name : in String; Args : in Argument_List'Class; Context : in out Context_Type) is procedure Find_Application (Name : in String); procedure Enable_Application (URI : in String; App : in Servlet.Core.Servlet_Registry_Access); Count : Natural := 0; Selected : Application_Access; procedure Find_Application (Name : in String) is procedure Find (URI : in String; App : in Servlet.Core.Servlet_Registry_Access); procedure Find (URI : in String; App : in Servlet.Core.Servlet_Registry_Access) is begin App.Disable; if URI (URI'First + 1 .. URI'Last) = Name then if App.all in Application'Class then Selected := Application'Class (App.all)'Unchecked_Access; Count := Count + 1; end if; end if; end Find; begin Command_Drivers.WS.Iterate (Find'Access); end Find_Application; procedure Enable_Application (URI : in String; App : in Servlet.Core.Servlet_Registry_Access) is begin App.Enable; App.Start; end Enable_Application; S : aliased AWA.Setup.Applications.Application; begin if Args.Get_Count /= 1 then Context.Console.Notice (N_ERROR, -("Missing application name")); return; end if; declare Name : constant String := Args.Get_Argument (1); begin Find_Application (Name); if Count /= 1 then Context.Console.Notice (N_ERROR, -("No application found")); return; end if; Command.Configure_Server (Context); Command.Start_Server (Context); S.Setup (Name, Command_Drivers.WS); Command.Configure_Applications (Context); S.Status.Set (AWA.Setup.Applications.READY); delay 2.0; Command_Drivers.WS.Remove_Application (S'Unchecked_Access); Command_Drivers.WS.Iterate (Enable_Application'Access); Command.Wait_Server (Context); end; end Execute; -- Setup the command before parsing the arguments and executing it. overriding procedure Setup (Command : in out Command_Type; Config : in out GNAT.Command_Line.Command_Line_Configuration; Context : in out Context_Type) is begin Start_Command.Command_Type (Command).Setup (Config, Context); end Setup; begin Command_Drivers.Driver.Add_Command ("setup", -("start the web server and setup the application"), Command'Access); end AWA.Commands.Setup;
----------------------------------------------------------------------- -- awa-commands-setup -- Setup command to start and configure the application -- Copyright (C) 2020 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with GNAT.Command_Line; with AWA.Applications; with AWA.Setup.Applications; with Servlet.Core; package body AWA.Commands.Setup is use AWA.Applications; package Command_Drivers renames Start_Command.Command_Drivers; overriding procedure Execute (Command : in out Command_Type; Name : in String; Args : in Argument_List'Class; Context : in out Context_Type) is procedure Find_Application (Name : in String); procedure Enable_Application (URI : in String; App : in Servlet.Core.Servlet_Registry_Access); Count : Natural := 0; Selected : Application_Access; procedure Find_Application (Name : in String) is procedure Find (URI : in String; App : in Servlet.Core.Servlet_Registry_Access); procedure Find (URI : in String; App : in Servlet.Core.Servlet_Registry_Access) is begin App.Disable; if URI (URI'First + 1 .. URI'Last) = Name then if App.all in Application'Class then Selected := Application'Class (App.all)'Unchecked_Access; Count := Count + 1; end if; end if; end Find; begin Command_Drivers.WS.Iterate (Find'Access); end Find_Application; procedure Enable_Application (URI : in String; App : in Servlet.Core.Servlet_Registry_Access) is pragma Unreferenced (URI); begin App.Enable; App.Start; end Enable_Application; S : aliased AWA.Setup.Applications.Application; begin if Args.Get_Count /= 1 then Context.Console.Notice (N_ERROR, -("Missing application name")); return; end if; declare Name : constant String := Args.Get_Argument (1); begin Find_Application (Name); if Count /= 1 then Context.Console.Notice (N_ERROR, -("No application found")); return; end if; Command.Configure_Server (Context); Command.Start_Server (Context); S.Setup (Name, Command_Drivers.WS); Command.Configure_Applications (Context); S.Status.Set (AWA.Setup.Applications.READY); delay 2.0; Command_Drivers.WS.Remove_Application (S'Unchecked_Access); Command_Drivers.WS.Iterate (Enable_Application'Access); Command.Wait_Server (Context); end; end Execute; -- Setup the command before parsing the arguments and executing it. overriding procedure Setup (Command : in out Command_Type; Config : in out GNAT.Command_Line.Command_Line_Configuration; Context : in out Context_Type) is begin Start_Command.Command_Type (Command).Setup (Config, Context); end Setup; begin Command_Drivers.Driver.Add_Command ("setup", -("start the web server and setup the application"), Command'Access); end AWA.Commands.Setup;
Fix compilation warning
Fix compilation warning
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
03838cbab041dfff9915cb1e2381a42a1c5aab46
src/ado-sessions.ads
src/ado-sessions.ads
----------------------------------------------------------------------- -- ADO Sessions -- Sessions Management -- Copyright (C) 2009, 2010, 2011, 2012, 2013, 2015, 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Finalization; with ADO.Schemas; with ADO.Statements; with ADO.Objects; with ADO.Objects.Cache; with ADO.Drivers.Connections; with ADO.Queries; with ADO.SQL; with ADO.Caches; with Util.Concurrent.Counters; limited with ADO.Sequences; limited with ADO.Schemas.Entities; -- = Session = -- The `ADO.Sessions` package defines the control and management of database sessions. -- The database session is represented by the `Session` or `Master_Session` types. -- It provides operation to create a database statement that can be executed. -- The `Session` type is used to represent read-only database sessions. It provides -- operations to query the database but it does not allow to update or delete content. -- The `Master_Session` type extends the `Session` type to provide write -- access and it provides operations to get update or delete statements. The differentiation -- between the two sessions is provided for the support of database replications with -- databases such as MySQL. -- -- @include ado-sessions-sources.ads -- @include ado-sessions-factory.ads -- @include ado-caches.ads package ADO.Sessions is use ADO.Statements; -- Raised for all errors reported by the database DB_Error : exception; -- Raised if the database connection is not open. NOT_OPEN : exception; NOT_FOUND : exception; NO_DATABASE : exception; -- Raised when the connection URI is invalid. Connection_Error : exception; -- The database connection status type Connection_Status is (OPEN, CLOSED); type Object_Factory is tagged private; -- --------- -- Session -- --------- -- Read-only database connection (or slave connection). -- type Session is tagged private; -- Get the session status. function Get_Status (Database : in Session) return Connection_Status; -- Get the database driver which manages this connection. function Get_Driver (Database : in Session) return ADO.Drivers.Connections.Driver_Access; -- Close the session. procedure Close (Database : in out Session); -- Insert a new cache in the manager. The cache is identified by the given name. procedure Add_Cache (Database : in out Session; Name : in String; Cache : in ADO.Caches.Cache_Type_Access); -- Attach the object to the session. procedure Attach (Database : in out Session; Object : in ADO.Objects.Object_Ref'Class); -- Check if the session contains the object identified by the given key. function Contains (Database : in Session; Item : in ADO.Objects.Object_Key) return Boolean; -- Remove the object from the session cache. procedure Evict (Database : in out Session; Item : in ADO.Objects.Object_Key); -- Create a query statement. The statement is not prepared function Create_Statement (Database : in Session; Table : in ADO.Schemas.Class_Mapping_Access) return Query_Statement; -- Create a query statement. The statement is not prepared function Create_Statement (Database : in Session; Query : in String) return Query_Statement; -- Create a query statement. The statement is not prepared function Create_Statement (Database : in Session; Query : in ADO.Queries.Context'Class) return Query_Statement; -- Create a query statement and initialize the SQL statement with the query definition. function Create_Statement (Database : in Session; Query : in ADO.Queries.Query_Definition_Access) return Query_Statement; -- Create a query statement. The statement is not prepared function Create_Statement (Database : in Session; Query : in ADO.SQL.Query'Class; Table : in ADO.Schemas.Class_Mapping_Access) return Query_Statement; -- Load the database schema definition for the current database. procedure Load_Schema (Database : in Session; Schema : out ADO.Schemas.Schema_Definition); -- Internal method to get the session proxy associated with the given database session. -- The session proxy is associated with some ADO objects to be able to retrieve the database -- session for the implementation of lazy loading. The session proxy is kept until the -- session exist and at least one ADO object is refering to it. function Get_Session_Proxy (Database : in Session) return ADO.Objects.Session_Proxy_Access; -- --------- -- Master Session -- --------- -- Read-write session. -- type Master_Session is new Session with private; -- Start a transaction. procedure Begin_Transaction (Database : in out Master_Session); -- Commit the current transaction. procedure Commit (Database : in out Master_Session); -- Rollback the current transaction. procedure Rollback (Database : in out Master_Session); -- Allocate an identifier for the table. procedure Allocate (Database : in out Master_Session; Id : in out ADO.Objects.Object_Record'Class); -- Flush the objects that were modified. procedure Flush (Database : in out Master_Session); -- Create a delete statement function Create_Statement (Database : in Master_Session; Table : in ADO.Schemas.Class_Mapping_Access) return Delete_Statement; -- Create an update statement function Create_Statement (Database : in Master_Session; Table : in ADO.Schemas.Class_Mapping_Access) return Update_Statement; -- Create an insert statement function Create_Statement (Database : in Master_Session; Table : in ADO.Schemas.Class_Mapping_Access) return Insert_Statement; type Session_Record is limited private; type Session_Record_Access is access all Session_Record; private type Entity_Cache_Access is access ADO.Schemas.Entities.Entity_Cache; type Object_Factory is tagged record A : Integer; end record; type Object_Factory_Access is access all Object_Factory'Class; -- The <b>Session_Record</b> maintains the connection information to the database for -- the duration of the session. It also maintains a cache of application objects -- which is used when session objects are fetched (either through Load or a Find). -- The connection is released and the session record is deleted when the session -- is closed with <b>Close</b>. -- -- For the lazy loading support, each object is associated with a shared <b>Session_Proxy</b> -- object that allows to give access to the session record associated with the object. -- When a session is closed, the <b>Session_Proxy</b> is not deleted but it is simply -- unlinked from the session record. type Session_Record is limited record Counter : Util.Concurrent.Counters.Counter := Util.Concurrent.Counters.ONE; Database : ADO.Drivers.Connections.Ref.Ref; Proxy : ADO.Objects.Session_Proxy_Access; Cache : ADO.Objects.Cache.Object_Cache; Entities : Entity_Cache_Access; Values : ADO.Caches.Cache_Manager_Access; Queries : ADO.Queries.Query_Manager_Access; end record; type Session is new Ada.Finalization.Controlled with record Impl : Session_Record_Access := null; end record; overriding procedure Adjust (Object : in out Session); overriding procedure Finalize (Object : in out Session); type Factory_Access is access all ADO.Sequences.Factory; type Master_Session is new Session with record Sequences : Factory_Access; end record; procedure Check_Session (Database : in Session'Class; Message : in String := ""); pragma Inline (Check_Session); end ADO.Sessions;
----------------------------------------------------------------------- -- ADO Sessions -- Sessions Management -- Copyright (C) 2009, 2010, 2011, 2012, 2013, 2015, 2017, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Finalization; with ADO.Schemas; with ADO.Statements; with ADO.Objects; with ADO.Objects.Cache; with ADO.Drivers.Connections; with ADO.Queries; with ADO.SQL; with ADO.Caches; with Util.Concurrent.Counters; limited with ADO.Sequences; limited with ADO.Schemas.Entities; -- = Session = -- The `ADO.Sessions` package defines the control and management of database sessions. -- The database session is represented by the `Session` or `Master_Session` types. -- It provides operation to create a database statement that can be executed. -- The `Session` type is used to represent read-only database sessions. It provides -- operations to query the database but it does not allow to update or delete content. -- The `Master_Session` type extends the `Session` type to provide write -- access and it provides operations to get update or delete statements. The differentiation -- between the two sessions is provided for the support of database replications with -- databases such as MySQL. -- -- @include ado-sessions-sources.ads -- @include ado-sessions-factory.ads -- @include ado-caches.ads package ADO.Sessions is use ADO.Statements; -- Raised if the database connection is not open. Session_Error : exception; -- Raised when the connection URI is invalid. Connection_Error : exception renames ADO.Drivers.Connection_Error; -- The database connection status type Connection_Status is (OPEN, CLOSED); type Object_Factory is tagged private; -- --------- -- Session -- --------- -- Read-only database connection (or slave connection). -- type Session is tagged private; -- Get the session status. function Get_Status (Database : in Session) return Connection_Status; -- Get the database driver which manages this connection. function Get_Driver (Database : in Session) return ADO.Drivers.Connections.Driver_Access; -- Close the session. procedure Close (Database : in out Session); -- Insert a new cache in the manager. The cache is identified by the given name. procedure Add_Cache (Database : in out Session; Name : in String; Cache : in ADO.Caches.Cache_Type_Access); -- Attach the object to the session. procedure Attach (Database : in out Session; Object : in ADO.Objects.Object_Ref'Class); -- Check if the session contains the object identified by the given key. function Contains (Database : in Session; Item : in ADO.Objects.Object_Key) return Boolean; -- Remove the object from the session cache. procedure Evict (Database : in out Session; Item : in ADO.Objects.Object_Key); -- Create a query statement. The statement is not prepared function Create_Statement (Database : in Session; Table : in ADO.Schemas.Class_Mapping_Access) return Query_Statement; -- Create a query statement. The statement is not prepared function Create_Statement (Database : in Session; Query : in String) return Query_Statement; -- Create a query statement. The statement is not prepared function Create_Statement (Database : in Session; Query : in ADO.Queries.Context'Class) return Query_Statement; -- Create a query statement and initialize the SQL statement with the query definition. function Create_Statement (Database : in Session; Query : in ADO.Queries.Query_Definition_Access) return Query_Statement; -- Create a query statement. The statement is not prepared function Create_Statement (Database : in Session; Query : in ADO.SQL.Query'Class; Table : in ADO.Schemas.Class_Mapping_Access) return Query_Statement; -- Load the database schema definition for the current database. procedure Load_Schema (Database : in Session; Schema : out ADO.Schemas.Schema_Definition); -- Internal method to get the session proxy associated with the given database session. -- The session proxy is associated with some ADO objects to be able to retrieve the database -- session for the implementation of lazy loading. The session proxy is kept until the -- session exist and at least one ADO object is refering to it. function Get_Session_Proxy (Database : in Session) return ADO.Objects.Session_Proxy_Access; -- --------- -- Master Session -- --------- -- Read-write session. -- type Master_Session is new Session with private; -- Start a transaction. procedure Begin_Transaction (Database : in out Master_Session); -- Commit the current transaction. procedure Commit (Database : in out Master_Session); -- Rollback the current transaction. procedure Rollback (Database : in out Master_Session); -- Allocate an identifier for the table. procedure Allocate (Database : in out Master_Session; Id : in out ADO.Objects.Object_Record'Class); -- Flush the objects that were modified. procedure Flush (Database : in out Master_Session); -- Create a delete statement function Create_Statement (Database : in Master_Session; Table : in ADO.Schemas.Class_Mapping_Access) return Delete_Statement; -- Create an update statement function Create_Statement (Database : in Master_Session; Table : in ADO.Schemas.Class_Mapping_Access) return Update_Statement; -- Create an insert statement function Create_Statement (Database : in Master_Session; Table : in ADO.Schemas.Class_Mapping_Access) return Insert_Statement; type Session_Record is limited private; type Session_Record_Access is access all Session_Record; private type Entity_Cache_Access is access ADO.Schemas.Entities.Entity_Cache; type Object_Factory is tagged record A : Integer; end record; type Object_Factory_Access is access all Object_Factory'Class; -- The <b>Session_Record</b> maintains the connection information to the database for -- the duration of the session. It also maintains a cache of application objects -- which is used when session objects are fetched (either through Load or a Find). -- The connection is released and the session record is deleted when the session -- is closed with <b>Close</b>. -- -- For the lazy loading support, each object is associated with a shared <b>Session_Proxy</b> -- object that allows to give access to the session record associated with the object. -- When a session is closed, the <b>Session_Proxy</b> is not deleted but it is simply -- unlinked from the session record. type Session_Record is limited record Counter : Util.Concurrent.Counters.Counter := Util.Concurrent.Counters.ONE; Database : ADO.Drivers.Connections.Ref.Ref; Proxy : ADO.Objects.Session_Proxy_Access; Cache : ADO.Objects.Cache.Object_Cache; Entities : Entity_Cache_Access; Values : ADO.Caches.Cache_Manager_Access; Queries : ADO.Queries.Query_Manager_Access; end record; type Session is new Ada.Finalization.Controlled with record Impl : Session_Record_Access := null; end record; overriding procedure Adjust (Object : in out Session); overriding procedure Finalize (Object : in out Session); type Factory_Access is access all ADO.Sequences.Factory; type Master_Session is new Session with record Sequences : Factory_Access; end record; procedure Check_Session (Database : in Session'Class; Message : in String := ""); pragma Inline (Check_Session); end ADO.Sessions;
Declare Session_Error and Connection_Error exception and remove unused exceptions
Declare Session_Error and Connection_Error exception and remove unused exceptions
Ada
apache-2.0
stcarrez/ada-ado
2fdfae6c3b7a3c2fafe97e9dbd6a1a693c5a63bc
ARM/STM32/drivers/stm32-pwm.adb
ARM/STM32/drivers/stm32-pwm.adb
------------------------------------------------------------------------------ -- -- -- Copyright (C) 2015, AdaCore -- -- -- -- Redistribution and use in source and binary forms, with or without -- -- modification, are permitted provided that the following conditions are -- -- met: -- -- 1. Redistributions of source code must retain the above copyright -- -- notice, this list of conditions and the following disclaimer. -- -- 2. Redistributions in binary form must reproduce the above copyright -- -- notice, this list of conditions and the following disclaimer in -- -- the documentation and/or other materials provided with the -- -- distribution. -- -- 3. Neither the name of STMicroelectronics nor the names of its -- -- contributors may be used to endorse or promote products derived -- -- from this software without specific prior written permission. -- -- -- -- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -- -- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -- -- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -- -- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -- -- HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -- -- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -- -- LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -- -- DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -- -- THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -- -- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -- -- OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -- -- -- ------------------------------------------------------------------------------ with System; use System; with STM32_SVD; use STM32_SVD; with STM32.Device; use STM32.Device; package body STM32.PWM is subtype Hertz is Word; procedure Compute_Prescalar_and_Period (This : access Timer; Requested_Frequency : Hertz; Prescalar : out Word; Period : out Word) with Pre => Requested_Frequency > 0; -- Computes the minimum prescaler and thus the maximum resolution for the -- given timer, based on the system clocks and the requested frequency function Has_HCLOCK_Frequency (This : Timer) return Boolean; -- timers 1, 8, 9, 10, 11 function Has_PCLOCK2_Frequency (This : Timer) return Boolean; -- timers 3, 4, 6, 7, 12, 13, 14 procedure Configure_PWM_GPIO (Output : GPIO_Point; PWM_AF : GPIO_Alternate_Function); -------------------- -- Set_Duty_Cycle -- -------------------- procedure Set_Duty_Cycle (This : in out PWM_Modulator; Channel : Timer_Channel; Value : Percentage) is Pulse : Short; begin This.Outputs (Channel).Duty_Cycle := Value; if Value = 0 then Set_Compare_Value (This.Output_Timer.all, Channel, Short'(0)); else Pulse := Short ((This.Timer_Period + 1) * Word (Value) / 100) - 1; -- for a Value of 0, the computation of Pulse wraps around to -- 65535, so we only compute it when not zero Set_Compare_Value (This.Output_Timer.all, Channel, Pulse); end if; end Set_Duty_Cycle; ------------------- -- Set_Duty_Time -- ------------------- procedure Set_Duty_Time (This : in out PWM_Modulator; Channel : Timer_Channel; Value : Microseconds) is Pulse : Short; Period : constant Word := This.Timer_Period + 1; uS_Per_Period : constant Word := 1_000_000 / This.Frequency; begin if Value > uS_per_Period then raise Invalid_Request with "duty time too high"; end if; Pulse := Short ((Period * Value) / uS_per_Period) - 1; Set_Compare_Value (This.Output_Timer.all, Channel, Pulse); end Set_Duty_Time; ------------------------ -- Current_Duty_Cycle -- ------------------------ function Current_Duty_Cycle (This : PWM_Modulator; Channel : Timer_Channel) return Percentage is begin return This.Outputs (Channel).Duty_Cycle; end Current_Duty_Cycle; ------------------------------ -- Initialise_PWM_Modulator -- ------------------------------ procedure Initialise_PWM_Modulator (This : in out PWM_Modulator; Requested_Frequency : Float; PWM_Timer : not null access Timer; PWM_AF : GPIO_Alternate_Function) is Prescalar : Word; begin This.Output_Timer := PWM_Timer; This.AF := PWM_AF; Enable_Clock (PWM_Timer.all); Compute_Prescalar_and_Period (PWM_Timer, Requested_Frequency => Word (Requested_Frequency), Prescalar => Prescalar, Period => This.Timer_Period); This.Timer_Period := This.Timer_Period - 1; This.Frequency := Word (Requested_Frequency); Configure (PWM_Timer.all, Prescaler => Short (Prescalar), Period => This.Timer_Period, Clock_Divisor => Div1, Counter_Mode => Up); Set_Autoreload_Preload (PWM_Timer.all, True); Enable (PWM_Timer.all); for Channel in Timer_Channel loop This.Outputs (Channel).Attached := False; end loop; end Initialise_PWM_Modulator; ------------------------ -- Attach_PWM_Channel -- ------------------------ procedure Attach_PWM_Channel (This : in out PWM_Modulator; Channel : Timer_Channel; Point : GPIO_Point) is begin This.Outputs (Channel).Attached := True; Enable_CLock (Point); Configure_PWM_GPIO (Point, This.AF); Configure_Channel_Output (This.Output_Timer.all, Channel => Channel, Mode => PWM1, State => Disable, Pulse => 0, Polarity => High); Set_Compare_Value (This.Output_Timer.all, Channel, Short (0)); end Attach_PWM_Channel; procedure Enable_PWM_Channel (This : in out PWM_Modulator; Channel : Timer_Channel) is begin Enable_Channel (This.Output_Timer.all, Channel); end Enable_PWM_Channel; procedure Disable_PWM_Channel (This : in out PWM_Modulator; Channel : Timer_Channel) is begin Disable_Channel (This.Output_Timer.all, Channel); end Disable_PWM_Channel; -------------- -- Attached -- -------------- function Attached (This : PWM_Modulator; Channel : Timer_Channel) return Boolean is (This.Outputs (Channel).Attached); ------------------------ -- Configure_PWM_GPIO -- ------------------------ procedure Configure_PWM_GPIO (Output : GPIO_Point; PWM_AF : GPIO_Alternate_Function) is Configuration : GPIO_Port_Configuration; begin Configuration.Mode := Mode_AF; Configuration.Output_Type := Push_Pull; Configuration.Speed := Speed_100MHz; Configuration.Resistors := Pull_Down; Configure_IO (Point => Output, Config => Configuration); Configure_Alternate_Function (Output, AF => PWM_AF); Lock (Output); end Configure_PWM_GPIO; ---------------------------------- -- Compute_Prescalar_and_Period -- ---------------------------------- procedure Compute_Prescalar_And_Period (This : access Timer; Requested_Frequency : Hertz; Prescalar : out Word; Period : out Word) is Max_Prescalar : constant := 16#FFFF#; Max_Period : Word; Hardware_Frequency : Word; Clocks : constant RCC_System_Clocks := System_Clock_Frequencies; begin if Has_32bit_Counter (This.all) then -- timers 2 and 5 Hardware_Frequency := Clocks.PCLK2; Max_Period := 16#FFFF_FFFF#; elsif Has_HCLOCK_Frequency (This.all) then Hardware_Frequency := Clocks.HCLK; Max_Period := 16#FFFF#; elsif Has_PCLOCK2_Frequency (This.all) then Hardware_Frequency := Clocks.PCLK2; Max_Period := 16#FFFF#; else raise Unknown_Timer; end if; if Requested_Frequency > Hardware_Frequency then raise Invalid_Request with "Freq too high"; end if; Prescalar := 0; loop Period := Hardware_Frequency / (Prescalar + 1); Period := Period / Requested_Frequency; Prescalar := Prescalar + 1; exit when not ((Period > Max_Period) and (Prescalar <= Max_Prescalar + 1)); end loop; if Prescalar > Max_Prescalar + 1 then raise Invalid_Request with "Freq too low"; end if; end Compute_Prescalar_and_Period; -------------------------- -- Has_HCLOCK_Frequency -- -------------------------- function Has_HCLOCK_Frequency (This : Timer) return Boolean is (This'Address = STM32_SVD.TIM1_Base or This'Address = STM32_SVD.TIM8_Base or This'Address = STM32_SVD.TIM9_Base or This'Address = STM32_SVD.TIM10_Base or This'Address = STM32_SVD.TIM11_Base); --------------------------- -- Has_PCLOCK2_Frequency -- --------------------------- function Has_PCLOCK2_Frequency (This : Timer) return Boolean is (This'Address = STM32_SVD.TIM3_Base or This'Address = STM32_SVD.TIM4_Base or This'Address = STM32_SVD.TIM6_Base or This'Address = STM32_SVD.TIM7_Base or This'Address = STM32_SVD.TIM12_Base or This'Address = STM32_SVD.TIM13_Base or This'Address = STM32_SVD.TIM14_Base); end STM32.PWM;
------------------------------------------------------------------------------ -- -- -- Copyright (C) 2015, AdaCore -- -- -- -- Redistribution and use in source and binary forms, with or without -- -- modification, are permitted provided that the following conditions are -- -- met: -- -- 1. Redistributions of source code must retain the above copyright -- -- notice, this list of conditions and the following disclaimer. -- -- 2. Redistributions in binary form must reproduce the above copyright -- -- notice, this list of conditions and the following disclaimer in -- -- the documentation and/or other materials provided with the -- -- distribution. -- -- 3. Neither the name of STMicroelectronics nor the names of its -- -- contributors may be used to endorse or promote products derived -- -- from this software without specific prior written permission. -- -- -- -- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -- -- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -- -- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -- -- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -- -- HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -- -- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -- -- LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -- -- DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -- -- THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -- -- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -- -- OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -- -- -- ------------------------------------------------------------------------------ with System; use System; with STM32_SVD; use STM32_SVD; with STM32.Device; use STM32.Device; package body STM32.PWM is subtype Hertz is Word; procedure Compute_Prescalar_and_Period (This : access Timer; Requested_Frequency : Hertz; Prescalar : out Word; Period : out Word) with Pre => Requested_Frequency > 0; -- Computes the minimum prescaler and thus the maximum resolution for the -- given timer, based on the system clocks and the requested frequency function Has_APB2_Frequency (This : Timer) return Boolean; -- timers 1, 8, 9, 10, 11 function Has_APB1_Frequency (This : Timer) return Boolean; -- timers 3, 4, 6, 7, 12, 13, 14 procedure Configure_PWM_GPIO (Output : GPIO_Point; PWM_AF : GPIO_Alternate_Function); -------------------- -- Set_Duty_Cycle -- -------------------- procedure Set_Duty_Cycle (This : in out PWM_Modulator; Channel : Timer_Channel; Value : Percentage) is Pulse : Short; begin This.Outputs (Channel).Duty_Cycle := Value; if Value = 0 then Set_Compare_Value (This.Output_Timer.all, Channel, Short'(0)); else Pulse := Short ((This.Timer_Period + 1) * Word (Value) / 100) - 1; -- for a Value of 0, the computation of Pulse wraps around to -- 65535, so we only compute it when not zero Set_Compare_Value (This.Output_Timer.all, Channel, Pulse); end if; end Set_Duty_Cycle; ------------------- -- Set_Duty_Time -- ------------------- procedure Set_Duty_Time (This : in out PWM_Modulator; Channel : Timer_Channel; Value : Microseconds) is Pulse : Short; Period : constant Word := This.Timer_Period + 1; uS_Per_Period : constant Word := 1_000_000 / This.Frequency; begin if Value > uS_per_Period then raise Invalid_Request with "duty time too high"; end if; Pulse := Short ((Period * Value) / uS_per_Period) - 1; Set_Compare_Value (This.Output_Timer.all, Channel, Pulse); end Set_Duty_Time; ------------------------ -- Current_Duty_Cycle -- ------------------------ function Current_Duty_Cycle (This : PWM_Modulator; Channel : Timer_Channel) return Percentage is begin return This.Outputs (Channel).Duty_Cycle; end Current_Duty_Cycle; ------------------------------ -- Initialise_PWM_Modulator -- ------------------------------ procedure Initialise_PWM_Modulator (This : in out PWM_Modulator; Requested_Frequency : Float; PWM_Timer : not null access Timer; PWM_AF : GPIO_Alternate_Function) is Prescalar : Word; begin This.Output_Timer := PWM_Timer; This.AF := PWM_AF; Enable_Clock (PWM_Timer.all); Compute_Prescalar_and_Period (PWM_Timer, Requested_Frequency => Word (Requested_Frequency), Prescalar => Prescalar, Period => This.Timer_Period); This.Timer_Period := This.Timer_Period - 1; This.Frequency := Word (Requested_Frequency); Configure (PWM_Timer.all, Prescaler => Short (Prescalar), Period => This.Timer_Period, Clock_Divisor => Div1, Counter_Mode => Up); Set_Autoreload_Preload (PWM_Timer.all, True); Enable (PWM_Timer.all); for Channel in Timer_Channel loop This.Outputs (Channel).Attached := False; end loop; end Initialise_PWM_Modulator; ------------------------ -- Attach_PWM_Channel -- ------------------------ procedure Attach_PWM_Channel (This : in out PWM_Modulator; Channel : Timer_Channel; Point : GPIO_Point) is begin This.Outputs (Channel).Attached := True; Enable_CLock (Point); Configure_PWM_GPIO (Point, This.AF); Configure_Channel_Output (This.Output_Timer.all, Channel => Channel, Mode => PWM1, State => Disable, Pulse => 0, Polarity => High); Set_Compare_Value (This.Output_Timer.all, Channel, Short (0)); end Attach_PWM_Channel; procedure Enable_PWM_Channel (This : in out PWM_Modulator; Channel : Timer_Channel) is begin Enable_Channel (This.Output_Timer.all, Channel); end Enable_PWM_Channel; procedure Disable_PWM_Channel (This : in out PWM_Modulator; Channel : Timer_Channel) is begin Disable_Channel (This.Output_Timer.all, Channel); end Disable_PWM_Channel; -------------- -- Attached -- -------------- function Attached (This : PWM_Modulator; Channel : Timer_Channel) return Boolean is (This.Outputs (Channel).Attached); ------------------------ -- Configure_PWM_GPIO -- ------------------------ procedure Configure_PWM_GPIO (Output : GPIO_Point; PWM_AF : GPIO_Alternate_Function) is Configuration : GPIO_Port_Configuration; begin Configuration.Mode := Mode_AF; Configuration.Output_Type := Push_Pull; Configuration.Speed := Speed_100MHz; Configuration.Resistors := Floating; Configure_IO (Point => Output, Config => Configuration); Configure_Alternate_Function (Output, AF => PWM_AF); Lock (Output); end Configure_PWM_GPIO; ---------------------------------- -- Compute_Prescalar_and_Period -- ---------------------------------- procedure Compute_Prescalar_And_Period (This : access Timer; Requested_Frequency : Hertz; Prescalar : out Word; Period : out Word) is Max_Prescalar : constant := 16#FFFF#; Max_Period : Word; Hardware_Frequency : Word; Clocks : constant RCC_System_Clocks := System_Clock_Frequencies; begin if Has_APB1_Frequency (This.all) then Hardware_Frequency := Clocks.TIMCLK1; elsif Has_APB2_Frequency (This.all) then Hardware_Frequency := Clocks.TIMCLK2; else raise Unknown_Timer; end if; if Has_32bit_Counter (This.all) then Max_Period := 16#FFFF_FFFF#; else Max_Period := 16#FFFF#; end if; if Requested_Frequency > Hardware_Frequency then raise Invalid_Request with "Freq too high"; end if; Prescalar := 0; loop Period := Hardware_Frequency / (Prescalar + 1); Period := Period / Requested_Frequency; exit when not ((Period > Max_Period) and (Prescalar <= Max_Prescalar)); Prescalar := Prescalar + 1; end loop; if Prescalar > Max_Prescalar then raise Invalid_Request with "Freq too low"; end if; end Compute_Prescalar_and_Period; ------------------------ -- Has_APB2_Frequency -- ------------------------ function Has_APB2_Frequency (This : Timer) return Boolean is (This'Address = STM32_SVD.TIM1_Base or This'Address = STM32_SVD.TIM8_Base or This'Address = STM32_SVD.TIM9_Base or This'Address = STM32_SVD.TIM10_Base or This'Address = STM32_SVD.TIM11_Base); ------------------------ -- Has_APB1_Frequency -- ------------------------ function Has_APB1_Frequency (This : Timer) return Boolean is (This'Address = STM32_SVD.TIM3_Base or This'Address = STM32_SVD.TIM4_Base or This'Address = STM32_SVD.TIM6_Base or This'Address = STM32_SVD.TIM7_Base or This'Address = STM32_SVD.TIM12_Base or This'Address = STM32_SVD.TIM13_Base or This'Address = STM32_SVD.TIM14_Base); end STM32.PWM;
Fix Compute_Prescalar_And_Period
STM32.PWM: Fix Compute_Prescalar_And_Period - Timers were assigned to the wrong APB - APB clock value was used instead of timer clock - Prescalar was off by one
Ada
bsd-3-clause
Fabien-Chouteau/Ada_Drivers_Library,AdaCore/Ada_Drivers_Library,simonjwright/Ada_Drivers_Library,Fabien-Chouteau/Ada_Drivers_Library,AdaCore/Ada_Drivers_Library,simonjwright/Ada_Drivers_Library,ellamosi/Ada_BMP_Library,lambourg/Ada_Drivers_Library
528781c0fccb9281082614e08d519495d589b0e3
src/ado-drivers.ads
src/ado-drivers.ads
----------------------------------------------------------------------- -- ADO Drivers -- Database Drivers -- 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.Strings.Unbounded; with Ada.Finalization; with ADO.Statements; with ADO.Schemas; with Util.Properties; -- The <b>ADO.Drivers</b> package represents the database driver that will create -- database connections and provide the database specific implementation. package ADO.Drivers is use ADO.Statements; use Ada.Strings.Unbounded; -- Raised when the connection URI is invalid. Connection_Error : exception; -- Raised for all errors reported by the database DB_Error : exception; -- ------------------------------ -- Database connection implementation -- ------------------------------ -- type Database_Connection is abstract tagged limited record Count : Natural := 0; end record; type Database_Connection_Access is access all Database_Connection'Class; function Create_Statement (Database : in Database_Connection; Table : in ADO.Schemas.Class_Mapping_Access) return Query_Statement_Access is abstract; function Create_Statement (Database : in Database_Connection; Query : in String) return Query_Statement_Access is abstract; -- Create a delete statement. function Create_Statement (Database : in Database_Connection; Table : in ADO.Schemas.Class_Mapping_Access) return Delete_Statement_Access is abstract; -- Create an insert statement. function Create_Statement (Database : in Database_Connection; Table : in ADO.Schemas.Class_Mapping_Access) return Insert_Statement_Access is abstract; -- Create an update statement. function Create_Statement (Database : in Database_Connection; Table : in ADO.Schemas.Class_Mapping_Access) return Update_Statement_Access is abstract; -- Start a transaction. procedure Begin_Transaction (Database : in out Database_Connection) is abstract; -- Commit the current transaction. procedure Commit (Database : in out Database_Connection) is abstract; -- Rollback the current transaction. procedure Rollback (Database : in out Database_Connection) is abstract; procedure Execute (Database : in out Database_Connection; SQL : in Query_String) is abstract; procedure Execute (Database : in out Database_Connection; SQL : in Query_String; Id : out Identifier) is abstract; -- Load the database schema definition for the current database. procedure Load_Schema (Database : in Database_Connection; Schema : out ADO.Schemas.Schema_Definition) is abstract; -- Closes the database connection procedure Close (Database : in out Database_Connection) is abstract; -- Releases the connection and all resources used to maintain it. procedure Release (Database : access Database_Connection) is abstract; -- ------------------------------ -- The database configuration properties -- ------------------------------ type Configuration is new Ada.Finalization.Controlled with private; type Configuration_Access is access all Configuration'Class; -- Set the connection URL to connect to the database. -- The driver connection is a string of the form: -- -- driver://[host][:port]/[database][?property1][=value1]... -- -- If the string is invalid or if the driver cannot be found, -- the Connection_Error exception is raised. procedure Set_Connection (Controller : in out Configuration; URI : in String); -- Set a property on the datasource for the driver. -- The driver can retrieve the property to configure and open -- the database connection. procedure Set_Property (Controller : in out Configuration; Name : in String; Value : in String); -- Get a property from the data source configuration. -- If the property does not exist, an empty string is returned. function Get_Property (Controller : in Configuration; Name : in String) return String; -- Create a new connection using the configuration parameters. procedure Create_Connection (Config : in Configuration'Class; Result : out Database_Connection_Access); -- ------------------------------ -- Database Driver -- ------------------------------ type Driver is abstract tagged limited private; type Driver_Access is access all Driver'Class; -- Create a new connection using the configuration parameters. procedure Create_Connection (D : in out Driver; Config : in Configuration'Class; Result : out Database_Connection_Access) is abstract; -- Register a database driver. procedure Register (Driver : in Driver_Access); -- Get a database driver given its name. function Get_Driver (Name : in String) return Driver_Access; private type Driver is abstract new Ada.Finalization.Limited_Controlled with record Name : Unbounded_String; end record; type Configuration is new Ada.Finalization.Controlled with record URI : Unbounded_String := Null_Unbounded_String; Server : Unbounded_String := Null_Unbounded_String; Port : Integer := 0; Database : Unbounded_String := Null_Unbounded_String; Properties : Util.Properties.Manager; Driver : Driver_Access; end record; end ADO.Drivers;
----------------------------------------------------------------------- -- ADO Drivers -- Database Drivers -- 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.Strings.Unbounded; with Ada.Finalization; with ADO.Statements; with ADO.Schemas; with Util.Properties; -- The <b>ADO.Drivers</b> package represents the database driver that will create -- database connections and provide the database specific implementation. package ADO.Drivers is use ADO.Statements; use Ada.Strings.Unbounded; -- Raised when the connection URI is invalid. Connection_Error : exception; -- Raised for all errors reported by the database DB_Error : exception; -- ------------------------------ -- Database connection implementation -- ------------------------------ -- type Database_Connection is abstract new Ada.Finalization.Limited_Controlled with record Count : Natural := 0; end record; type Database_Connection_Access is access all Database_Connection'Class; function Create_Statement (Database : in Database_Connection; Table : in ADO.Schemas.Class_Mapping_Access) return Query_Statement_Access is abstract; function Create_Statement (Database : in Database_Connection; Query : in String) return Query_Statement_Access is abstract; -- Create a delete statement. function Create_Statement (Database : in Database_Connection; Table : in ADO.Schemas.Class_Mapping_Access) return Delete_Statement_Access is abstract; -- Create an insert statement. function Create_Statement (Database : in Database_Connection; Table : in ADO.Schemas.Class_Mapping_Access) return Insert_Statement_Access is abstract; -- Create an update statement. function Create_Statement (Database : in Database_Connection; Table : in ADO.Schemas.Class_Mapping_Access) return Update_Statement_Access is abstract; -- Start a transaction. procedure Begin_Transaction (Database : in out Database_Connection) is abstract; -- Commit the current transaction. procedure Commit (Database : in out Database_Connection) is abstract; -- Rollback the current transaction. procedure Rollback (Database : in out Database_Connection) is abstract; procedure Execute (Database : in out Database_Connection; SQL : in Query_String) is abstract; procedure Execute (Database : in out Database_Connection; SQL : in Query_String; Id : out Identifier) is abstract; -- Load the database schema definition for the current database. procedure Load_Schema (Database : in Database_Connection; Schema : out ADO.Schemas.Schema_Definition) is abstract; -- Closes the database connection procedure Close (Database : in out Database_Connection) is abstract; -- ------------------------------ -- The database configuration properties -- ------------------------------ type Configuration is new Ada.Finalization.Controlled with private; type Configuration_Access is access all Configuration'Class; -- Set the connection URL to connect to the database. -- The driver connection is a string of the form: -- -- driver://[host][:port]/[database][?property1][=value1]... -- -- If the string is invalid or if the driver cannot be found, -- the Connection_Error exception is raised. procedure Set_Connection (Controller : in out Configuration; URI : in String); -- Set a property on the datasource for the driver. -- The driver can retrieve the property to configure and open -- the database connection. procedure Set_Property (Controller : in out Configuration; Name : in String; Value : in String); -- Get a property from the data source configuration. -- If the property does not exist, an empty string is returned. function Get_Property (Controller : in Configuration; Name : in String) return String; -- Create a new connection using the configuration parameters. procedure Create_Connection (Config : in Configuration'Class; Result : out Database_Connection_Access); -- ------------------------------ -- Database Driver -- ------------------------------ type Driver is abstract tagged limited private; type Driver_Access is access all Driver'Class; -- Create a new connection using the configuration parameters. procedure Create_Connection (D : in out Driver; Config : in Configuration'Class; Result : out Database_Connection_Access) is abstract; -- Register a database driver. procedure Register (Driver : in Driver_Access); -- Get a database driver given its name. function Get_Driver (Name : in String) return Driver_Access; private type Driver is abstract new Ada.Finalization.Limited_Controlled with record Name : Unbounded_String; end record; type Configuration is new Ada.Finalization.Controlled with record URI : Unbounded_String := Null_Unbounded_String; Server : Unbounded_String := Null_Unbounded_String; Port : Integer := 0; Database : Unbounded_String := Null_Unbounded_String; Properties : Util.Properties.Manager; Driver : Driver_Access; end record; end ADO.Drivers;
Replace the Release by the Finalize method
Replace the Release by the Finalize method
Ada
apache-2.0
Letractively/ada-ado
61a831ba17b748f3923d4357c0e03b264bda89f7
src/util-streams.ads
src/util-streams.ads
----------------------------------------------------------------------- -- Util.Streams -- Stream utilities -- Copyright (C) 2010, 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Streams; package Util.Streams is pragma Preelaborate; -- ----------------------- -- Output stream -- ----------------------- -- The <b>Output_Stream</b> is an interface that accepts output bytes -- and sends them to a sink. type Output_Stream is limited interface; type Output_Stream_Access is access all Output_Stream'Class; -- Write the buffer array to the output stream. procedure Write (Stream : in out Output_Stream; Buffer : in Ada.Streams.Stream_Element_Array) is abstract; -- Flush the buffer (if any) to the sink. procedure Flush (Stream : in out Output_Stream) is null; -- Close the sink. procedure Close (Stream : in out Output_Stream) is null; -- ----------------------- -- Input stream -- ----------------------- -- The <b>Input_Stream</b> is the interface that reads input bytes -- from a source and returns them. type Input_Stream is limited interface; type Input_Stream_Access is access all Input_Stream'Class; -- Read into the buffer as many bytes as possible and return in -- <b>last</b> the position of the last byte read. procedure Read (Stream : in out Input_Stream; Into : out Ada.Streams.Stream_Element_Array; Last : out Ada.Streams.Stream_Element_Offset) is abstract; -- Copy the input stream to the output stream until the end of the input stream -- is reached. procedure Copy (From : in out Input_Stream'Class; Into : in out Output_Stream'Class); -- Copy the stream array to the string. -- The string must be large enough to hold the stream array -- or a Constraint_Error exception is raised. procedure Copy (From : in Ada.Streams.Stream_Element_Array; Into : in out String); -- Copy the string to the stream array. -- The stream array must be large enough to hold the string -- or a Constraint_Error exception is raised. procedure Copy (From : in String; Into : in out Ada.Streams.Stream_Element_Array); -- Notes: -- ------ -- The <b>Ada.Streams.Root_Stream_Type</b> implements the <b>Output_Stream</b> -- and <b>Input_Stream</b>. It is however not easy to use for composing various -- stream behaviors. end Util.Streams;
----------------------------------------------------------------------- -- util-streams -- Stream utilities -- Copyright (C) 2010, 2016, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Streams; -- == Streams == -- The <tt>Util.Streams</tt> package provides several types and operations to allow the -- composition of input and output streams. -- -- @include util-streams-buffered.ads -- @include util-streams-files.ads -- @include util-streams-pipes.ads -- @include util-streams-sockets.ads -- @include util-streams-raw.ads -- @include util-streams-texts.ads -- @include util-streams-buffered-encoders.ads package Util.Streams is pragma Preelaborate; -- ----------------------- -- Output stream -- ----------------------- -- The <b>Output_Stream</b> is an interface that accepts output bytes -- and sends them to a sink. type Output_Stream is limited interface; type Output_Stream_Access is access all Output_Stream'Class; -- Write the buffer array to the output stream. procedure Write (Stream : in out Output_Stream; Buffer : in Ada.Streams.Stream_Element_Array) is abstract; -- Flush the buffer (if any) to the sink. procedure Flush (Stream : in out Output_Stream) is null; -- Close the sink. procedure Close (Stream : in out Output_Stream) is null; -- ----------------------- -- Input stream -- ----------------------- -- The <b>Input_Stream</b> is the interface that reads input bytes -- from a source and returns them. type Input_Stream is limited interface; type Input_Stream_Access is access all Input_Stream'Class; -- Read into the buffer as many bytes as possible and return in -- <b>last</b> the position of the last byte read. procedure Read (Stream : in out Input_Stream; Into : out Ada.Streams.Stream_Element_Array; Last : out Ada.Streams.Stream_Element_Offset) is abstract; -- Copy the input stream to the output stream until the end of the input stream -- is reached. procedure Copy (From : in out Input_Stream'Class; Into : in out Output_Stream'Class); -- Copy the stream array to the string. -- The string must be large enough to hold the stream array -- or a Constraint_Error exception is raised. procedure Copy (From : in Ada.Streams.Stream_Element_Array; Into : in out String); -- Copy the string to the stream array. -- The stream array must be large enough to hold the string -- or a Constraint_Error exception is raised. procedure Copy (From : in String; Into : in out Ada.Streams.Stream_Element_Array); -- Notes: -- ------ -- The <b>Ada.Streams.Root_Stream_Type</b> implements the <b>Output_Stream</b> -- and <b>Input_Stream</b>. It is however not easy to use for composing various -- stream behaviors. end Util.Streams;
Document the streams framework
Document the streams framework
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
9ea684c21230eb6a3add486376e5aec38aef27e7
awa/plugins/awa-images/src/awa-images-modules.adb
awa/plugins/awa-images/src/awa-images-modules.adb
----------------------------------------------------------------------- -- awa-images-modules -- Image management module -- 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 AWA.Modules.Get; with AWA.Applications; with AWA.Storages.Modules; with Util.Strings; with Util.Log.Loggers; package body AWA.Images.Modules is Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("AWA.Images.Module"); -- ------------------------------ -- Initialize the image module. -- ------------------------------ overriding procedure Initialize (Plugin : in out Image_Module; App : in AWA.Modules.Application_Access; Props : in ASF.Applications.Config) is begin Log.Info ("Initializing the image module"); -- Setup the resource bundles. App.Register ("imageMsg", "images"); AWA.Modules.Module (Plugin).Initialize (App, Props); Plugin.Add_Listener (AWA.Storages.Modules.NAME, Plugin'Unchecked_Access); end Initialize; -- ------------------------------ -- Configures the module after its initialization and after having read its XML configuration. -- ------------------------------ overriding procedure Configure (Plugin : in out Image_Module; Props : in ASF.Applications.Config) is pragma Unreferenced (Props); begin -- Create the image manager when everything is initialized. Plugin.Manager := Plugin.Create_Image_Manager; end Configure; -- ------------------------------ -- Get the image manager. -- ------------------------------ function Get_Image_Manager (Plugin : in Image_Module) return Services.Image_Service_Access is begin return Plugin.Manager; end Get_Image_Manager; -- ------------------------------ -- Create an image manager. This operation can be overridden to provide another -- image service implementation. -- ------------------------------ function Create_Image_Manager (Plugin : in Image_Module) return Services.Image_Service_Access is Result : constant Services.Image_Service_Access := new Services.Image_Service; begin Result.Initialize (Plugin); return Result; end Create_Image_Manager; -- ------------------------------ -- Returns true if the storage file has an image mime type. -- ------------------------------ function Is_Image (File : in AWA.Storages.Models.Storage_Ref'Class) return Boolean is Mime : constant String := File.Get_Mime_Type; Pos : constant Natural := Util.Strings.Index (Mime, '/'); begin if Pos = 0 then return False; else return Mime (Mime'First .. Pos - 1) = "image"; end if; end Is_Image; -- ------------------------------ -- The `On_Create` procedure is called by `Notify_Create` to notify the creation of the item. -- ------------------------------ overriding procedure On_Create (Instance : in Image_Module; Item : in AWA.Storages.Models.Storage_Ref'Class) is begin if Is_Image (Item) then Instance.Manager.Create_Image (Item); end if; end On_Create; -- ------------------------------ -- The `On_Update` procedure is called by `Notify_Update` to notify the update of the item. -- ------------------------------ overriding procedure On_Update (Instance : in Image_Module; Item : in AWA.Storages.Models.Storage_Ref'Class) is begin if Is_Image (Item) then Instance.Manager.Create_Image (Item); else Instance.Manager.Delete_Image (Item); end if; end On_Update; -- ------------------------------ -- The `On_Delete` procedure is called by `Notify_Delete` to notify the deletion of the item. -- ------------------------------ overriding procedure On_Delete (Instance : in Image_Module; Item : in AWA.Storages.Models.Storage_Ref'Class) is begin Instance.Manager.Delete_Image (Item); end On_Delete; -- ------------------------------ -- Get the image module instance associated with the current application. -- ------------------------------ function Get_Image_Module return Image_Module_Access is function Get is new AWA.Modules.Get (Image_Module, Image_Module_Access, NAME); begin return Get; end Get_Image_Module; -- ------------------------------ -- Get the image manager instance associated with the current application. -- ------------------------------ function Get_Image_Manager return Services.Image_Service_Access is Module : constant Image_Module_Access := Get_Image_Module; begin if Module = null then Log.Error ("There is no active Storage_Module"); return null; else return Module.Get_Image_Manager; end if; end Get_Image_Manager; end AWA.Images.Modules;
----------------------------------------------------------------------- -- awa-images-modules -- Image management module -- 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 AWA.Modules.Get; with AWA.Applications; with AWA.Storages.Modules; with AWA.Services.Contexts; with ADO.Sessions; with Util.Strings; with Util.Log.Loggers; package body AWA.Images.Modules is Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("AWA.Images.Module"); -- ------------------------------ -- Job worker procedure to identify an image and generate its thumnbnail. -- ------------------------------ procedure Thumbnail_Worker (Job : in out AWA.Jobs.Services.Abstract_Job_Type'Class) is Module : constant Image_Module_Access := Get_Image_Module; begin Module.Do_Thumbnail_Job (Job); end Thumbnail_Worker; -- ------------------------------ -- Initialize the image module. -- ------------------------------ overriding procedure Initialize (Plugin : in out Image_Module; App : in AWA.Modules.Application_Access; Props : in ASF.Applications.Config) is begin Log.Info ("Initializing the image module"); -- Setup the resource bundles. App.Register ("imageMsg", "images"); AWA.Modules.Module (Plugin).Initialize (App, Props); Plugin.Add_Listener (AWA.Storages.Modules.NAME, Plugin'Unchecked_Access); end Initialize; -- ------------------------------ -- Configures the module after its initialization and after having read its XML configuration. -- ------------------------------ overriding procedure Configure (Plugin : in out Image_Module; Props : in ASF.Applications.Config) is pragma Unreferenced (Props); begin -- Create the image manager when everything is initialized. Plugin.Manager := Plugin.Create_Image_Manager; Plugin.Job_Module := AWA.Jobs.Modules.Get_Job_Module; Plugin.Job_Module.Register (Definition => Thumbnail_Job_Definition.Factory); end Configure; -- ------------------------------ -- Get the image manager. -- ------------------------------ function Get_Image_Manager (Plugin : in Image_Module) return Services.Image_Service_Access is begin return Plugin.Manager; end Get_Image_Manager; -- ------------------------------ -- Create an image manager. This operation can be overridden to provide another -- image service implementation. -- ------------------------------ function Create_Image_Manager (Plugin : in Image_Module) return Services.Image_Service_Access is Result : constant Services.Image_Service_Access := new Services.Image_Service; begin Result.Initialize (Plugin); return Result; end Create_Image_Manager; -- ------------------------------ -- Create a thumbnail job for the image. -- ------------------------------ procedure Make_Thumbnail_Job (Plugin : in Image_Module; Image : in AWA.Images.Models.Image_Ref'Class) is pragma Unreferenced (Plugin); J : AWA.Jobs.Services.Job_Type; begin J.Set_Parameter ("image_id", Image); J.Schedule (Thumbnail_Job_Definition.Factory.all); end Make_Thumbnail_Job; -- ------------------------------ -- Returns true if the storage file has an image mime type. -- ------------------------------ function Is_Image (File : in AWA.Storages.Models.Storage_Ref'Class) return Boolean is Mime : constant String := File.Get_Mime_Type; Pos : constant Natural := Util.Strings.Index (Mime, '/'); begin if Pos = 0 then return False; else return Mime (Mime'First .. Pos - 1) = "image"; end if; end Is_Image; -- ------------------------------ -- Create an image instance. -- ------------------------------ procedure Create_Image (Plugin : in Image_Module; 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 Img.Set_Width (0); Img.Set_Height (0); Img.Set_Thumb_Height (0); Img.Set_Thumb_Width (0); Img.Set_Storage (File); Img.Set_Folder (File.Get_Folder); Img.Set_Owner (File.Get_Owner); Img.Save (DB); Plugin.Make_Thumbnail_Job (Img); end Create_Image; -- ------------------------------ -- The `On_Create` procedure is called by `Notify_Create` to notify the creation of the item. -- ------------------------------ overriding procedure On_Create (Instance : in Image_Module; Item : in AWA.Storages.Models.Storage_Ref'Class) is begin if Is_Image (Item) then Instance.Create_Image (Item); end if; end On_Create; -- ------------------------------ -- The `On_Update` procedure is called by `Notify_Update` to notify the update of the item. -- ------------------------------ overriding procedure On_Update (Instance : in Image_Module; Item : in AWA.Storages.Models.Storage_Ref'Class) is begin if Is_Image (Item) then Instance.Create_Image (Item); else Instance.Manager.Delete_Image (Item); end if; end On_Update; -- ------------------------------ -- The `On_Delete` procedure is called by `Notify_Delete` to notify the deletion of the item. -- ------------------------------ overriding procedure On_Delete (Instance : in Image_Module; Item : in AWA.Storages.Models.Storage_Ref'Class) is begin Instance.Manager.Delete_Image (Item); end On_Delete; -- ------------------------------ -- Thumbnail job to identify the image dimension and produce a thumbnail. -- ------------------------------ procedure Do_Thumbnail_Job (Plugin : in Image_Module; Job : in out AWA.Jobs.Services.Abstract_Job_Type'Class) is Image_Id : constant ADO.Identifier := Job.Get_Parameter ("image_id"); begin Plugin.Manager.Build_Thumbnail (Image_Id); end Do_Thumbnail_Job; -- ------------------------------ -- Get the image module instance associated with the current application. -- ------------------------------ function Get_Image_Module return Image_Module_Access is function Get is new AWA.Modules.Get (Image_Module, Image_Module_Access, NAME); begin return Get; end Get_Image_Module; -- ------------------------------ -- Get the image manager instance associated with the current application. -- ------------------------------ function Get_Image_Manager return Services.Image_Service_Access is Module : constant Image_Module_Access := Get_Image_Module; begin if Module = null then Log.Error ("There is no active Storage_Module"); return null; else return Module.Get_Image_Manager; end if; end Get_Image_Manager; end AWA.Images.Modules;
Implement the thumnail job and related procedure to make a thumbnail of an image
Implement the thumnail job and related procedure to make a thumbnail of an image
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
9f18a08843b07dd3a43383b892b6c6c396cba83c
regtests/asf-applications-main-tests.adb
regtests/asf-applications-main-tests.adb
----------------------------------------------------------------------- -- asf-applications-main-tests - Unit tests for Applications -- Copyright (C) 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Test_Caller; with Util.Beans.Objects; with Ada.Unchecked_Deallocation; with EL.Contexts.Default; with ASF.Applications.Tests; with ASF.Applications.Main.Configs; with ASF.Requests.Mockup; package body ASF.Applications.Main.Tests is use Util.Tests; function Create_Form_Bean return Util.Beans.Basic.Readonly_Bean_Access; package Caller is new Util.Test_Caller (Test, "Applications.Main"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test ASF.Applications.Main.Read_Configuration", Test_Read_Configuration'Access); Caller.Add_Test (Suite, "Test ASF.Applications.Main.Create", Test_Create_Bean'Access); Caller.Add_Test (Suite, "Test ASF.Applications.Main.Load_Bundle", Test_Load_Bundle'Access); Caller.Add_Test (Suite, "Test ASF.Applications.Main.Register,Load_Bundle", Test_Bundle_Configuration'Access); Caller.Add_Test (Suite, "Test ASF.Applications.Main.Get_Supported_Locales", Test_Locales'Access); end Add_Tests; -- ------------------------------ -- Initialize the test application -- ------------------------------ procedure Set_Up (T : in out Test) is Fact : ASF.Applications.Main.Application_Factory; C : ASF.Applications.Config; begin T.App := new ASF.Applications.Main.Application; C.Copy (Util.Tests.Get_Properties); T.App.Initialize (C, Fact); T.App.Register ("layoutMsg", "layout"); end Set_Up; -- ------------------------------ -- Deletes the application object -- ------------------------------ overriding procedure Tear_Down (T : in out Test) is procedure Free is new Ada.Unchecked_Deallocation (Object => ASF.Applications.Main.Application'Class, Name => ASF.Applications.Main.Application_Access); begin Free (T.App); end Tear_Down; function Create_Form_Bean return Util.Beans.Basic.Readonly_Bean_Access is Result : constant Applications.Tests.Form_Bean_Access := new Applications.Tests.Form_Bean; begin return Result.all'Access; end Create_Form_Bean; -- ------------------------------ -- Test creation of module -- ------------------------------ procedure Test_Read_Configuration (T : in out Test) is Path : constant String := Util.Tests.Get_Test_Path ("config/empty.xml"); begin ASF.Applications.Main.Configs.Read_Configuration (T.App.all, Path); end Test_Read_Configuration; -- ------------------------------ -- Test creation of a module and registration in an application. -- ------------------------------ procedure Test_Create_Bean (T : in out Test) is use type Util.Beans.Basic.Readonly_Bean_Access; procedure Check (Name : in String; Kind : in ASF.Beans.Scope_Type); procedure Check (Name : in String; Kind : in ASF.Beans.Scope_Type) is Value : Util.Beans.Objects.Object; Bean : Util.Beans.Basic.Readonly_Bean_Access; Scope : ASF.Beans.Scope_Type; Context : EL.Contexts.Default.Default_Context; begin T.App.Create (Name => Ada.Strings.Unbounded.To_Unbounded_String (Name), Context => Context, Result => Bean, Scope => Scope); T.Assert (Kind = Scope, "Invalid scope for " & Name); T.Assert (Bean /= null, "Invalid bean object"); Value := Util.Beans.Objects.To_Object (Bean); T.Assert (not Util.Beans.Objects.Is_Null (Value), "Invalid bean"); -- Special test for the sessionForm bean which is initialized by configuration properties if Name = "sessionForm" then T.Assert_Equals ("[email protected]", Util.Beans.Objects.To_String (Bean.Get_Value ("email")), "Session form not initialized"); end if; end Check; Path : constant String := Util.Tests.Get_Test_Path ("regtests/config/test-module.xml"); begin T.App.Register_Class ("ASF.Applications.Tests.Form_Bean", Create_Form_Bean'Access); ASF.Applications.Main.Configs.Read_Configuration (T.App.all, Path); -- Check the 'regtests/config/test-module.xml' managed bean configuration. Check ("applicationForm", ASF.Beans.APPLICATION_SCOPE); Check ("sessionForm", ASF.Beans.SESSION_SCOPE); Check ("requestForm", ASF.Beans.REQUEST_SCOPE); end Test_Create_Bean; -- ------------------------------ -- Test loading a resource bundle through the application. -- ------------------------------ procedure Test_Load_Bundle (T : in out Test) is use type Util.Beans.Basic.Readonly_Bean_Access; Path : constant String := Util.Tests.Get_Test_Path ("regtests/config/test-bundle.xml"); Bundle : ASF.Locales.Bundle; begin ASF.Applications.Main.Configs.Read_Configuration (T.App.all, Path); T.App.Load_Bundle (Name => "samples", Locale => "en", Bundle => Bundle); Util.Tests.Assert_Equals (T, "Help", String '(Bundle.Get ("layout_help_label")), "Invalid bundle value"); T.App.Load_Bundle (Name => "asf", Locale => "en", Bundle => Bundle); Util.Tests.Assert_Matches (T, ".*greater than.*", String '(Bundle.Get ("validators.length.maximum")), "Invalid bundle value"); end Test_Load_Bundle; -- ------------------------------ -- Test application configuration and registration of resource bundles. -- ------------------------------ procedure Test_Bundle_Configuration (T : in out Test) is use type Util.Beans.Basic.Readonly_Bean_Access; Path : constant String := Util.Tests.Get_Test_Path ("regtests/config/test-bundle.xml"); Result : Util.Beans.Basic.Readonly_Bean_Access; Ctx : EL.Contexts.Default.Default_Context; Scope : Scope_Type; begin ASF.Applications.Main.Configs.Read_Configuration (T.App.all, Path); T.App.Create (Name => Ada.Strings.Unbounded.To_Unbounded_String ("samplesMsg"), Context => Ctx, Result => Result, Scope => Scope); T.Assert (Result /= null, "The samplesMsg bundle was not created"); T.App.Create (Name => Ada.Strings.Unbounded.To_Unbounded_String ("defaultMsg"), Context => Ctx, Result => Result, Scope => Scope); T.Assert (Result /= null, "The defaultMsg bundle was not created"); end Test_Bundle_Configuration; -- ------------------------------ -- Test locales. -- ------------------------------ procedure Test_Locales (T : in out Test) is use Util.Locales; Path : constant String := Util.Tests.Get_Test_Path ("regtests/config/test-locales.xml"); Req : aliased ASF.Requests.Mockup.Request; View : constant access Applications.Views.View_Handler'Class := T.App.Get_View_Handler; Context : aliased ASF.Contexts.Faces.Faces_Context; ELContext : aliased EL.Contexts.Default.Default_Context; Locale : Util.Locales.Locale; begin ASF.Applications.Main.Configs.Read_Configuration (T.App.all, Path); Util.Tests.Assert_Equals (T, To_String (Util.Locales.FRENCH), To_String (T.App.Get_Default_Locale), "Invalid default locale"); Context.Set_ELContext (ELContext'Unchecked_Access); Context.Set_Request (Req'Unchecked_Access); Req.Set_Header ("Accept-Language", "da, en-gb;q=0.3, fr;q=0.7"); T.App.Set_Context (Context'Unchecked_Access); Locale := View.Calculate_Locale (Context); Util.Tests.Assert_Equals (T, To_String (Util.Locales.FRENCH), To_String (Locale), "Invalid calculated locale"); Req.Set_Header ("Accept-Language", "da, en-gb, en;q=0.8, fr;q=0.7"); T.App.Set_Context (Context'Unchecked_Access); Locale := View.Calculate_Locale (Context); Util.Tests.Assert_Equals (T, "en_GB", To_String (Locale), "Invalid calculated locale"); Req.Set_Header ("Accept-Language", "da, fr;q=0.7, fr-fr;q=0.8"); T.App.Set_Context (Context'Unchecked_Access); Locale := View.Calculate_Locale (Context); Util.Tests.Assert_Equals (T, "fr_FR", To_String (Locale), "Invalid calculated locale"); Req.Set_Header ("Accept-Language", "da, ru, it;q=0.8, de;q=0.7"); T.App.Set_Context (Context'Unchecked_Access); Locale := View.Calculate_Locale (Context); Util.Tests.Assert_Equals (T, To_String (Util.Locales.FRENCH), To_String (Locale), "Invalid calculated locale"); end Test_Locales; end ASF.Applications.Main.Tests;
----------------------------------------------------------------------- -- asf-applications-main-tests - Unit tests for Applications -- Copyright (C) 2011, 2012, 2014 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Test_Caller; with Util.Beans.Objects; with Ada.Unchecked_Deallocation; with EL.Contexts.Default; with ASF.Applications.Tests; with ASF.Applications.Main.Configs; with ASF.Requests.Mockup; package body ASF.Applications.Main.Tests is use Util.Tests; function Create_Form_Bean return Util.Beans.Basic.Readonly_Bean_Access; package Caller is new Util.Test_Caller (Test, "Applications.Main"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test ASF.Applications.Main.Read_Configuration", Test_Read_Configuration'Access); Caller.Add_Test (Suite, "Test ASF.Applications.Main.Create", Test_Create_Bean'Access); Caller.Add_Test (Suite, "Test ASF.Applications.Main.Load_Bundle", Test_Load_Bundle'Access); Caller.Add_Test (Suite, "Test ASF.Applications.Main.Register,Load_Bundle", Test_Bundle_Configuration'Access); Caller.Add_Test (Suite, "Test ASF.Applications.Main.Get_Supported_Locales", Test_Locales'Access); end Add_Tests; -- ------------------------------ -- Initialize the test application -- ------------------------------ procedure Set_Up (T : in out Test) is Fact : ASF.Applications.Main.Application_Factory; C : ASF.Applications.Config; begin T.App := new ASF.Applications.Main.Application; C.Copy (Util.Tests.Get_Properties); T.App.Initialize (C, Fact); T.App.Register ("layoutMsg", "layout"); end Set_Up; -- ------------------------------ -- Deletes the application object -- ------------------------------ overriding procedure Tear_Down (T : in out Test) is procedure Free is new Ada.Unchecked_Deallocation (Object => ASF.Applications.Main.Application'Class, Name => ASF.Applications.Main.Application_Access); begin Free (T.App); end Tear_Down; function Create_Form_Bean return Util.Beans.Basic.Readonly_Bean_Access is Result : constant Applications.Tests.Form_Bean_Access := new Applications.Tests.Form_Bean; begin return Result.all'Access; end Create_Form_Bean; -- ------------------------------ -- Test creation of module -- ------------------------------ procedure Test_Read_Configuration (T : in out Test) is Path : constant String := Util.Tests.Get_Test_Path ("config/empty.xml"); begin ASF.Applications.Main.Configs.Read_Configuration (T.App.all, Path); end Test_Read_Configuration; -- ------------------------------ -- Test creation of a module and registration in an application. -- ------------------------------ procedure Test_Create_Bean (T : in out Test) is use type Util.Beans.Basic.Readonly_Bean_Access; procedure Check (Name : in String; Kind : in ASF.Beans.Scope_Type); procedure Check (Name : in String; Kind : in ASF.Beans.Scope_Type) is Value : Util.Beans.Objects.Object; Bean : Util.Beans.Basic.Readonly_Bean_Access; Scope : ASF.Beans.Scope_Type; Context : EL.Contexts.Default.Default_Context; begin T.App.Create (Name => Ada.Strings.Unbounded.To_Unbounded_String (Name), Context => Context, Result => Bean, Scope => Scope); T.Assert (Kind = Scope, "Invalid scope for " & Name); T.Assert (Bean /= null, "Invalid bean object"); Value := Util.Beans.Objects.To_Object (Bean); T.Assert (not Util.Beans.Objects.Is_Null (Value), "Invalid bean"); -- Special test for the sessionForm bean which is initialized by configuration properties if Name = "sessionForm" then T.Assert_Equals ("[email protected]", Util.Beans.Objects.To_String (Bean.Get_Value ("email")), "Session form not initialized"); end if; end Check; Path : constant String := Util.Tests.Get_Test_Path ("regtests/config/test-module.xml"); begin T.App.Register_Class ("ASF.Applications.Tests.Form_Bean", Create_Form_Bean'Access); ASF.Applications.Main.Configs.Read_Configuration (T.App.all, Path); -- Check the 'regtests/config/test-module.xml' managed bean configuration. Check ("applicationForm", ASF.Beans.APPLICATION_SCOPE); Check ("sessionForm", ASF.Beans.SESSION_SCOPE); Check ("requestForm", ASF.Beans.REQUEST_SCOPE); end Test_Create_Bean; -- ------------------------------ -- Test loading a resource bundle through the application. -- ------------------------------ procedure Test_Load_Bundle (T : in out Test) is use type Util.Beans.Basic.Readonly_Bean_Access; Path : constant String := Util.Tests.Get_Test_Path ("regtests/config/test-bundle.xml"); Bundle : ASF.Locales.Bundle; begin ASF.Applications.Main.Configs.Read_Configuration (T.App.all, Path); T.App.Load_Bundle (Name => "samples", Locale => "en", Bundle => Bundle); Util.Tests.Assert_Equals (T, "Help", String '(Bundle.Get ("layout_help_label")), "Invalid bundle value"); T.App.Load_Bundle (Name => "asf", Locale => "en", Bundle => Bundle); Util.Tests.Assert_Matches (T, ".*greater than.*", String '(Bundle.Get ("validators.length.maximum")), "Invalid bundle value"); end Test_Load_Bundle; -- ------------------------------ -- Test application configuration and registration of resource bundles. -- ------------------------------ procedure Test_Bundle_Configuration (T : in out Test) is use type Util.Beans.Basic.Readonly_Bean_Access; Path : constant String := Util.Tests.Get_Test_Path ("regtests/config/test-bundle.xml"); Result : Util.Beans.Basic.Readonly_Bean_Access; Context : aliased ASF.Contexts.Faces.Faces_Context; Ctx : aliased EL.Contexts.Default.Default_Context; Scope : Scope_Type; begin Context.Set_ELContext (Ctx'Unchecked_Access); ASF.Applications.Main.Configs.Read_Configuration (T.App.all, Path); T.App.Create (Name => Ada.Strings.Unbounded.To_Unbounded_String ("samplesMsg"), Context => Ctx, Result => Result, Scope => Scope); T.Assert (Result /= null, "The samplesMsg bundle was not created"); T.App.Create (Name => Ada.Strings.Unbounded.To_Unbounded_String ("defaultMsg"), Context => Ctx, Result => Result, Scope => Scope); T.Assert (Result /= null, "The defaultMsg bundle was not created"); end Test_Bundle_Configuration; -- ------------------------------ -- Test locales. -- ------------------------------ procedure Test_Locales (T : in out Test) is use Util.Locales; Path : constant String := Util.Tests.Get_Test_Path ("regtests/config/test-locales.xml"); Req : aliased ASF.Requests.Mockup.Request; View : constant access Applications.Views.View_Handler'Class := T.App.Get_View_Handler; Context : aliased ASF.Contexts.Faces.Faces_Context; ELContext : aliased EL.Contexts.Default.Default_Context; Locale : Util.Locales.Locale; begin ASF.Applications.Main.Configs.Read_Configuration (T.App.all, Path); Util.Tests.Assert_Equals (T, To_String (Util.Locales.FRENCH), To_String (T.App.Get_Default_Locale), "Invalid default locale"); Context.Set_ELContext (ELContext'Unchecked_Access); Context.Set_Request (Req'Unchecked_Access); Req.Set_Header ("Accept-Language", "da, en-gb;q=0.3, fr;q=0.7"); T.App.Set_Context (Context'Unchecked_Access); Locale := View.Calculate_Locale (Context); Util.Tests.Assert_Equals (T, To_String (Util.Locales.FRENCH), To_String (Locale), "Invalid calculated locale"); Req.Set_Header ("Accept-Language", "da, en-gb, en;q=0.8, fr;q=0.7"); T.App.Set_Context (Context'Unchecked_Access); Locale := View.Calculate_Locale (Context); Util.Tests.Assert_Equals (T, "en_GB", To_String (Locale), "Invalid calculated locale"); Req.Set_Header ("Accept-Language", "da, fr;q=0.7, fr-fr;q=0.8"); T.App.Set_Context (Context'Unchecked_Access); Locale := View.Calculate_Locale (Context); Util.Tests.Assert_Equals (T, "fr_FR", To_String (Locale), "Invalid calculated locale"); Req.Set_Header ("Accept-Language", "da, ru, it;q=0.8, de;q=0.7"); T.App.Set_Context (Context'Unchecked_Access); Locale := View.Calculate_Locale (Context); Util.Tests.Assert_Equals (T, To_String (Util.Locales.FRENCH), To_String (Locale), "Invalid calculated locale"); end Test_Locales; end ASF.Applications.Main.Tests;
Fix the Test_Bundle_Configuration that requires a faces context to be executed
Fix the Test_Bundle_Configuration that requires a faces context to be executed
Ada
apache-2.0
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
d87ab82f26940c486b70554aa63df43f997efdfe
awa/plugins/awa-images/regtests/awa-images-modules-tests.adb
awa/plugins/awa-images/regtests/awa-images-modules-tests.adb
----------------------------------------------------------------------- -- awa-storages-modules-tests -- Unit tests for storage service -- Copyright (C) 2012, 2013, 2016, 2019 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Test_Caller; with Security.Contexts; with AWA.Services.Contexts; with AWA.Tests.Helpers.Users; with AWA.Images.Modules; package body AWA.Images.Modules.Tests is package Caller is new Util.Test_Caller (Test, "Images.Services"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test AWA.Images.Create_Image", Test_Create_Image'Access); end Add_Tests; -- ------------------------------ -- Test creation of a storage object -- ------------------------------ procedure Test_Create_Image (T : in out Test) is Sec_Ctx : Security.Contexts.Security_Context; Context : AWA.Services.Contexts.Service_Context; Source : constant String := Util.Tests.Get_Path ("regtests/files/images/bast-12.jpg"); Thumb : constant String := Util.Tests.Get_Test_Path ("regtests/result/bast-12-thumb.jpg"); Width : Natural := 64; Height : Natural := 64; begin AWA.Tests.Helpers.Users.Login (Context, Sec_Ctx, "[email protected]"); T.Manager := AWA.Images.Modules.Get_Image_Module; T.Manager.Create_Thumbnail (Source, Thumb, Width, Height); Util.Tests.Assert_Equals (T, 1720, Width, "Invalid image width"); Util.Tests.Assert_Equals (T, 1098, Height, "Invalid image height"); end Test_Create_Image; end AWA.Images.Modules.Tests;
----------------------------------------------------------------------- -- awa-storages-modules-tests -- Unit tests for storage service -- Copyright (C) 2012, 2013, 2016, 2019, 2020 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Test_Caller; with Security.Contexts; with AWA.Services.Contexts; with AWA.Tests.Helpers.Users; with AWA.Images.Modules; package body AWA.Images.Modules.Tests is package Caller is new Util.Test_Caller (Test, "Images.Services"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test AWA.Images.Create_Image", Test_Create_Image'Access); Caller.Add_Test (Suite, "Test AWA.Images.Get_Sizes", Test_Get_Sizes'Access); end Add_Tests; -- ------------------------------ -- Test creation of a storage object -- ------------------------------ procedure Test_Create_Image (T : in out Test) is Sec_Ctx : Security.Contexts.Security_Context; Context : AWA.Services.Contexts.Service_Context; Source : constant String := Util.Tests.Get_Path ("regtests/files/images/bast-12.jpg"); Thumb : constant String := Util.Tests.Get_Test_Path ("regtests/result/bast-12-thumb.jpg"); Width : Natural := 64; Height : Natural := 64; begin AWA.Tests.Helpers.Users.Login (Context, Sec_Ctx, "[email protected]"); T.Manager := AWA.Images.Modules.Get_Image_Module; T.Manager.Create_Thumbnail (Source, Thumb, Width, Height); Util.Tests.Assert_Equals (T, 1720, Width, "Invalid image width"); Util.Tests.Assert_Equals (T, 1098, Height, "Invalid image height"); end Test_Create_Image; -- ------------------------------ -- Test the Get_Sizes operation. -- ------------------------------ procedure Test_Get_Sizes (T : in out TesT) is Width : Natural; Height : Natural; begin AWA.Images.Modules.Get_Sizes ("default", Width, Height); Util.Tests.Assert_Equals (T, 800, Width, "Default width should be 800"); Util.Tests.Assert_Equals (T, 0, Height, "Default height should be 0"); AWA.Images.Modules.Get_Sizes ("123x456", Width, Height); Util.Tests.Assert_Equals (T, 123, Width, "Invalid width"); Util.Tests.Assert_Equals (T, 456, Height, "Invalid height"); AWA.Images.Modules.Get_Sizes ("x56", Width, Height); Util.Tests.Assert_Equals (T, 0, Width, "Invalid width"); Util.Tests.Assert_Equals (T, 56, Height, "Invalid height"); AWA.Images.Modules.Get_Sizes ("123x", Width, Height); Util.Tests.Assert_Equals (T, 123, Width, "Invalid width"); Util.Tests.Assert_Equals (T, 0, Height, "Invalid height"); AWA.Images.Modules.Get_Sizes ("123xtoto", Width, Height); Util.Tests.Assert_Equals (T, 0, Width, "Invalid width"); Util.Tests.Assert_Equals (T, 0, Height, "Invalid height"); AWA.Images.Modules.Get_Sizes ("xtoto", Width, Height); Util.Tests.Assert_Equals (T, 0, Width, "Invalid width"); Util.Tests.Assert_Equals (T, 0, Height, "Invalid height"); AWA.Images.Modules.Get_Sizes ("original", Width, Height); Util.Tests.Assert_Equals (T, Natural'Last, Width, "Invalid width"); Util.Tests.Assert_Equals (T, Natural'Last, Height, "Invalid height"); end Test_Get_Sizes; end AWA.Images.Modules.Tests;
Implement the Test_Get_Sizes procedure and register it for execution
Implement the Test_Get_Sizes procedure and register it for execution
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
e3db2034ef10583aad8bb6cf86bb95ef51fabc95
src/sys/streams/util-streams-buffered.adb
src/sys/streams/util-streams-buffered.adb
----------------------------------------------------------------------- -- util-streams-buffered -- Buffered streams utilities -- Copyright (C) 2010, 2011, 2013, 2014, 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.IO_Exceptions; with Ada.Unchecked_Deallocation; package body Util.Streams.Buffered is procedure Free_Buffer is new Ada.Unchecked_Deallocation (Object => Stream_Element_Array, Name => Buffer_Access); -- ------------------------------ -- Initialize the stream to read or write on the given streams. -- An internal buffer is allocated for writing the stream. -- ------------------------------ procedure Initialize (Stream : in out Output_Buffer_Stream; Output : access Output_Stream'Class; Size : in Positive) is begin Free_Buffer (Stream.Buffer); Stream.Last := Stream_Element_Offset (Size); Stream.Buffer := new Stream_Element_Array (1 .. Stream.Last); Stream.Output := Output; Stream.Write_Pos := 1; Stream.Read_Pos := 1; Stream.No_Flush := False; end Initialize; -- ------------------------------ -- Initialize the stream to read from the string. -- ------------------------------ procedure Initialize (Stream : in out Input_Buffer_Stream; Content : in String) is begin Free_Buffer (Stream.Buffer); Stream.Last := Stream_Element_Offset (Content'Length); Stream.Buffer := new Stream_Element_Array (1 .. Content'Length); Stream.Input := null; Stream.Write_Pos := Stream.Last + 1; Stream.Read_Pos := 1; for I in Content'Range loop Stream.Buffer (Stream_Element_Offset (I - Content'First + 1)) := Character'Pos (Content (I)); end loop; end Initialize; -- ------------------------------ -- Initialize the stream with a buffer of <b>Size</b> bytes. -- ------------------------------ procedure Initialize (Stream : in out Output_Buffer_Stream; Size : in Positive) is begin Stream.Initialize (Output => null, Size => Size); Stream.No_Flush := True; Stream.Read_Pos := 1; end Initialize; -- ------------------------------ -- Initialize the stream to read or write on the given streams. -- An internal buffer is allocated for writing the stream. -- ------------------------------ procedure Initialize (Stream : in out Input_Buffer_Stream; Input : access Input_Stream'Class; Size : in Positive) is begin Free_Buffer (Stream.Buffer); Stream.Last := Stream_Element_Offset (Size); Stream.Buffer := new Stream_Element_Array (1 .. Stream.Last); Stream.Input := Input; Stream.Write_Pos := 1; Stream.Read_Pos := 1; end Initialize; -- ------------------------------ -- Initialize the stream from the buffer created for an output stream. -- ------------------------------ procedure Initialize (Stream : in out Input_Buffer_Stream; From : in out Output_Buffer_Stream'Class) is begin Free_Buffer (Stream.Buffer); Stream.Buffer := From.Buffer; From.Buffer := null; Stream.Input := null; Stream.Read_Pos := 1; Stream.Write_Pos := From.Write_Pos + 1; Stream.Last := From.Last; end Initialize; -- ------------------------------ -- Close the sink. -- ------------------------------ overriding procedure Close (Stream : in out Output_Buffer_Stream) is begin if Stream.Output /= null then Output_Buffer_Stream'Class (Stream).Flush; Stream.Output.Close; Free_Buffer (Stream.Buffer); end if; end Close; -- ------------------------------ -- Get the direct access to the buffer. -- ------------------------------ function Get_Buffer (Stream : in Output_Buffer_Stream) return Buffer_Access is begin return Stream.Buffer; end Get_Buffer; -- ------------------------------ -- Get the number of element in the stream. -- ------------------------------ function Get_Size (Stream : in Output_Buffer_Stream) return Natural is begin return Natural (Stream.Write_Pos - Stream.Read_Pos); end Get_Size; -- ------------------------------ -- Write the buffer array to the output stream. -- ------------------------------ overriding procedure Write (Stream : in out Output_Buffer_Stream; Buffer : in Ada.Streams.Stream_Element_Array) is Start : Stream_Element_Offset := Buffer'First; Pos : Stream_Element_Offset := Stream.Write_Pos; Avail : Stream_Element_Offset; Size : Stream_Element_Offset; begin while Start <= Buffer'Last loop Size := Buffer'Last - Start + 1; Avail := Stream.Last - Pos + 1; if Avail = 0 then if Stream.Output = null then raise Ada.IO_Exceptions.End_Error with "Buffer is full"; end if; Stream.Output.Write (Stream.Buffer (1 .. Pos - 1)); Stream.Write_Pos := 1; Pos := 1; Avail := Stream.Last - Pos + 1; end if; if Avail < Size then Size := Avail; end if; Stream.Buffer (Pos .. Pos + Size - 1) := Buffer (Start .. Start + Size - 1); Start := Start + Size; Pos := Pos + Size; Stream.Write_Pos := Pos; -- If we have still more data than the buffer size, flush and write -- the buffer directly. if Start < Buffer'Last and then Buffer'Last - Start > Stream.Buffer'Length then if Stream.Output = null then raise Ada.IO_Exceptions.End_Error with "Buffer is full"; end if; Stream.Output.Write (Stream.Buffer (1 .. Pos - 1)); Stream.Write_Pos := 1; Stream.Output.Write (Buffer (Start .. Buffer'Last)); return; end if; end loop; end Write; -- ------------------------------ -- Flush the stream. -- ------------------------------ overriding procedure Flush (Stream : in out Output_Buffer_Stream) is begin if not Stream.No_Flush then if Stream.Write_Pos > 1 then if Stream.Output /= null then Stream.Output.Write (Stream.Buffer (1 .. Stream.Write_Pos - 1)); end if; Stream.Write_Pos := 1; end if; if Stream.Output /= null then Stream.Output.Flush; end if; end if; end Flush; -- ------------------------------ -- Flush the buffer in the <tt>Into</tt> array and return the index of the -- last element (inclusive) in <tt>Last</tt>. -- ------------------------------ procedure Flush (Stream : in out Output_Buffer_Stream; Into : out Ada.Streams.Stream_Element_Array; Last : out Ada.Streams.Stream_Element_Offset) is begin if Stream.Write_Pos > 1 then Into (Into'First .. Into'First + Stream.Write_Pos - 1) := Stream.Buffer (Stream.Buffer'First .. Stream.Write_Pos - 1); Stream.Write_Pos := 1; Last := Into'First + Stream.Write_Pos - 1; else Last := Into'First - 1; end if; end Flush; -- ------------------------------ -- Flush the buffer stream to the unbounded string. -- ------------------------------ procedure Flush (Stream : in out Output_Buffer_Stream; Into : out Ada.Strings.Unbounded.Unbounded_String) is begin Ada.Strings.Unbounded.Set_Unbounded_String (Into, ""); if Stream.Write_Pos > 1 then for I in 1 .. Stream.Write_Pos - 1 loop Ada.Strings.Unbounded.Append (Into, Character'Val (Stream.Buffer (I))); end loop; Stream.Write_Pos := 1; end if; end Flush; -- ------------------------------ -- Fill the buffer by reading the input stream. -- Raises Data_Error if there is no input stream; -- ------------------------------ procedure Fill (Stream : in out Input_Buffer_Stream) is begin if Stream.Input = null then Stream.Eof := True; else Stream.Input.Read (Stream.Buffer (1 .. Stream.Last - 1), Stream.Write_Pos); Stream.Eof := Stream.Write_Pos < 1; if not Stream.Eof then Stream.Write_Pos := Stream.Write_Pos + 1; end if; Stream.Read_Pos := 1; end if; end Fill; -- ------------------------------ -- Read one character from the input stream. -- ------------------------------ procedure Read (Stream : in out Input_Buffer_Stream; Char : out Character) is begin if Stream.Read_Pos >= Stream.Write_Pos then Stream.Fill; if Stream.Eof then raise Ada.IO_Exceptions.Data_Error with "End of buffer"; end if; end if; Char := Character'Val (Stream.Buffer (Stream.Read_Pos)); Stream.Read_Pos := Stream.Read_Pos + 1; end Read; -- ------------------------------ -- Read into the buffer as many bytes as possible and return in -- <b>last</b> the position of the last byte read. -- ------------------------------ overriding procedure Read (Stream : in out Input_Buffer_Stream; Into : out Ada.Streams.Stream_Element_Array; Last : out Ada.Streams.Stream_Element_Offset) is Start : Stream_Element_Offset := Into'First; Pos : Stream_Element_Offset := Stream.Read_Pos; Avail : Stream_Element_Offset; Size : Stream_Element_Offset; Total : Stream_Element_Offset := 0; begin while Start <= Into'Last loop Size := Into'Last - Start + 1; Avail := Stream.Write_Pos - Pos; if Avail = 0 then Stream.Fill; Pos := Stream.Read_Pos; Avail := Stream.Write_Pos - Pos; exit when Avail <= 0; end if; if Avail < Size then Size := Avail; end if; Into (Start .. Start + Size - 1) := Stream.Buffer (Pos .. Pos + Size - 1); Start := Start + Size; Pos := Pos + Size; Total := Total + Size; Stream.Read_Pos := Pos; end loop; Last := Total; end Read; -- ------------------------------ -- Read into the buffer as many bytes as possible and return in -- <b>last</b> the position of the last byte read. -- ------------------------------ procedure Read (Stream : in out Input_Buffer_Stream; Into : in out Ada.Strings.Unbounded.Unbounded_String) is Pos : Stream_Element_Offset := Stream.Read_Pos; Avail : Stream_Element_Offset; begin loop Avail := Stream.Write_Pos - Pos; if Avail = 0 then Stream.Fill; if Stream.Eof then return; end if; Pos := Stream.Read_Pos; Avail := Stream.Write_Pos - Pos; end if; for I in 1 .. Avail loop Ada.Strings.Unbounded.Append (Into, Character'Val (Stream.Buffer (Pos))); Pos := Pos + 1; end loop; Stream.Read_Pos := Pos; end loop; end Read; -- ------------------------------ -- Flush the stream and release the buffer. -- ------------------------------ overriding procedure Finalize (Stream : in out Output_Buffer_Stream) is begin if Stream.Buffer /= null then if Stream.Output /= null then Stream.Flush; end if; Free_Buffer (Stream.Buffer); end if; end Finalize; -- ------------------------------ -- Returns True if the end of the stream is reached. -- ------------------------------ function Is_Eof (Stream : in Input_Buffer_Stream) return Boolean is begin return Stream.Eof; end Is_Eof; -- ------------------------------ -- Flush the stream and release the buffer. -- ------------------------------ overriding procedure Finalize (Object : in out Input_Buffer_Stream) is begin if Object.Buffer /= null then Free_Buffer (Object.Buffer); end if; end Finalize; end Util.Streams.Buffered;
----------------------------------------------------------------------- -- util-streams-buffered -- Buffered streams utilities -- Copyright (C) 2010, 2011, 2013, 2014, 2016, 2017, 2018, 2019, 2020 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Interfaces; with Ada.IO_Exceptions; with Ada.Unchecked_Deallocation; package body Util.Streams.Buffered is procedure Free_Buffer is new Ada.Unchecked_Deallocation (Object => Stream_Element_Array, Name => Buffer_Access); -- ------------------------------ -- Initialize the stream to read or write on the given streams. -- An internal buffer is allocated for writing the stream. -- ------------------------------ procedure Initialize (Stream : in out Output_Buffer_Stream; Output : access Output_Stream'Class; Size : in Positive) is begin Free_Buffer (Stream.Buffer); Stream.Last := Stream_Element_Offset (Size); Stream.Buffer := new Stream_Element_Array (1 .. Stream.Last); Stream.Output := Output; Stream.Write_Pos := 1; Stream.Read_Pos := 1; Stream.No_Flush := False; end Initialize; -- ------------------------------ -- Initialize the stream to read from the string. -- ------------------------------ procedure Initialize (Stream : in out Input_Buffer_Stream; Content : in String) is begin Free_Buffer (Stream.Buffer); Stream.Last := Stream_Element_Offset (Content'Length); Stream.Buffer := new Stream_Element_Array (1 .. Content'Length); Stream.Input := null; Stream.Write_Pos := Stream.Last + 1; Stream.Read_Pos := 1; for I in Content'Range loop Stream.Buffer (Stream_Element_Offset (I - Content'First + 1)) := Character'Pos (Content (I)); end loop; end Initialize; -- ------------------------------ -- Initialize the stream with a buffer of <b>Size</b> bytes. -- ------------------------------ procedure Initialize (Stream : in out Output_Buffer_Stream; Size : in Positive) is begin Stream.Initialize (Output => null, Size => Size); Stream.No_Flush := True; Stream.Read_Pos := 1; end Initialize; -- ------------------------------ -- Initialize the stream to read or write on the given streams. -- An internal buffer is allocated for writing the stream. -- ------------------------------ procedure Initialize (Stream : in out Input_Buffer_Stream; Input : access Input_Stream'Class; Size : in Positive) is begin Free_Buffer (Stream.Buffer); Stream.Last := Stream_Element_Offset (Size); Stream.Buffer := new Stream_Element_Array (1 .. Stream.Last); Stream.Input := Input; Stream.Write_Pos := 1; Stream.Read_Pos := 1; end Initialize; -- ------------------------------ -- Initialize the stream from the buffer created for an output stream. -- ------------------------------ procedure Initialize (Stream : in out Input_Buffer_Stream; From : in out Output_Buffer_Stream'Class) is begin Free_Buffer (Stream.Buffer); Stream.Buffer := From.Buffer; From.Buffer := null; Stream.Input := null; Stream.Read_Pos := 1; Stream.Write_Pos := From.Write_Pos + 1; Stream.Last := From.Last; end Initialize; -- ------------------------------ -- Close the sink. -- ------------------------------ overriding procedure Close (Stream : in out Output_Buffer_Stream) is begin if Stream.Output /= null then Output_Buffer_Stream'Class (Stream).Flush; Stream.Output.Close; Free_Buffer (Stream.Buffer); end if; end Close; -- ------------------------------ -- Get the direct access to the buffer. -- ------------------------------ function Get_Buffer (Stream : in Output_Buffer_Stream) return Buffer_Access is begin return Stream.Buffer; end Get_Buffer; -- ------------------------------ -- Get the number of element in the stream. -- ------------------------------ function Get_Size (Stream : in Output_Buffer_Stream) return Natural is begin return Natural (Stream.Write_Pos - Stream.Read_Pos); end Get_Size; -- ------------------------------ -- Write the buffer array to the output stream. -- ------------------------------ overriding procedure Write (Stream : in out Output_Buffer_Stream; Buffer : in Ada.Streams.Stream_Element_Array) is Start : Stream_Element_Offset := Buffer'First; Pos : Stream_Element_Offset := Stream.Write_Pos; Avail : Stream_Element_Offset; Size : Stream_Element_Offset; begin while Start <= Buffer'Last loop Size := Buffer'Last - Start + 1; Avail := Stream.Last - Pos + 1; if Avail = 0 then if Stream.Output = null then raise Ada.IO_Exceptions.End_Error with "Buffer is full"; end if; Stream.Output.Write (Stream.Buffer (1 .. Pos - 1)); Stream.Write_Pos := 1; Pos := 1; Avail := Stream.Last - Pos + 1; end if; if Avail < Size then Size := Avail; end if; Stream.Buffer (Pos .. Pos + Size - 1) := Buffer (Start .. Start + Size - 1); Start := Start + Size; Pos := Pos + Size; Stream.Write_Pos := Pos; -- If we have still more data than the buffer size, flush and write -- the buffer directly. if Start < Buffer'Last and then Buffer'Last - Start > Stream.Buffer'Length then if Stream.Output = null then raise Ada.IO_Exceptions.End_Error with "Buffer is full"; end if; Stream.Output.Write (Stream.Buffer (1 .. Pos - 1)); Stream.Write_Pos := 1; Stream.Output.Write (Buffer (Start .. Buffer'Last)); return; end if; end loop; end Write; -- ------------------------------ -- Flush the stream. -- ------------------------------ overriding procedure Flush (Stream : in out Output_Buffer_Stream) is begin if not Stream.No_Flush then if Stream.Write_Pos > 1 then if Stream.Output /= null then Stream.Output.Write (Stream.Buffer (1 .. Stream.Write_Pos - 1)); end if; Stream.Write_Pos := 1; end if; if Stream.Output /= null then Stream.Output.Flush; end if; end if; end Flush; -- ------------------------------ -- Flush the buffer in the <tt>Into</tt> array and return the index of the -- last element (inclusive) in <tt>Last</tt>. -- ------------------------------ procedure Flush (Stream : in out Output_Buffer_Stream; Into : out Ada.Streams.Stream_Element_Array; Last : out Ada.Streams.Stream_Element_Offset) is begin if Stream.Write_Pos > 1 then Into (Into'First .. Into'First + Stream.Write_Pos - 1) := Stream.Buffer (Stream.Buffer'First .. Stream.Write_Pos - 1); Stream.Write_Pos := 1; Last := Into'First + Stream.Write_Pos - 1; else Last := Into'First - 1; end if; end Flush; -- ------------------------------ -- Flush the buffer stream to the unbounded string. -- ------------------------------ procedure Flush (Stream : in out Output_Buffer_Stream; Into : out Ada.Strings.Unbounded.Unbounded_String) is begin Ada.Strings.Unbounded.Set_Unbounded_String (Into, ""); if Stream.Write_Pos > 1 then for I in 1 .. Stream.Write_Pos - 1 loop Ada.Strings.Unbounded.Append (Into, Character'Val (Stream.Buffer (I))); end loop; Stream.Write_Pos := 1; end if; end Flush; -- ------------------------------ -- Fill the buffer by reading the input stream. -- Raises Data_Error if there is no input stream; -- ------------------------------ procedure Fill (Stream : in out Input_Buffer_Stream) is begin if Stream.Input = null then Stream.Eof := True; else Stream.Input.Read (Stream.Buffer (1 .. Stream.Last - 1), Stream.Write_Pos); Stream.Eof := Stream.Write_Pos < 1; if not Stream.Eof then Stream.Write_Pos := Stream.Write_Pos + 1; end if; Stream.Read_Pos := 1; end if; end Fill; -- ------------------------------ -- Read one character from the input stream. -- ------------------------------ procedure Read (Stream : in out Input_Buffer_Stream; Char : out Character) is begin if Stream.Read_Pos >= Stream.Write_Pos then Stream.Fill; if Stream.Eof then raise Ada.IO_Exceptions.Data_Error with "End of buffer"; end if; end if; Char := Character'Val (Stream.Buffer (Stream.Read_Pos)); Stream.Read_Pos := Stream.Read_Pos + 1; end Read; procedure Read (Stream : in out Input_Buffer_Stream; Value : out Ada.Streams.Stream_Element) is begin if Stream.Read_Pos >= Stream.Write_Pos then Stream.Fill; if Stream.Eof then raise Ada.IO_Exceptions.Data_Error with "End of buffer"; end if; end if; Value := Stream.Buffer (Stream.Read_Pos); Stream.Read_Pos := Stream.Read_Pos + 1; end Read; -- ------------------------------ -- Read one character from the input stream. -- ------------------------------ procedure Read (Stream : in out Input_Buffer_Stream; Char : out Wide_Wide_Character) is use Interfaces; Val : Ada.Streams.Stream_Element; Result : Unsigned_32; begin Stream.Read (Val); -- UTF-8 conversion -- 7 U+0000 U+007F 1 0xxxxxxx if Val <= 16#7F# then Char := Wide_Wide_Character'Val (Val); -- 11 U+0080 U+07FF 2 110xxxxx 10xxxxxx elsif Val <= 16#DF# then Result := Shift_Left (Unsigned_32 (Val and 16#1F#), 6); Stream.Read (Val); Result := Result or Unsigned_32 (Val and 16#3F#); Char := Wide_Wide_Character'Val (Result); -- 16 U+0800 U+FFFF 3 1110xxxx 10xxxxxx 10xxxxxx elsif Val <= 16#EF# then Result := Shift_Left (Unsigned_32 (Val and 16#0F#), 12); Stream.Read (Val); Result := Result or Shift_Left (Unsigned_32 (Val and 16#3F#), 6); Stream.Read (Val); Result := Result or Unsigned_32 (Val and 16#3F#); Char := Wide_Wide_Character'Val (Result); -- 21 U+10000 U+1FFFFF 4 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx else Result := Shift_Left (Unsigned_32 (Val and 16#07#), 18); Stream.Read (Val); Result := Result or Shift_Left (Unsigned_32 (Val and 16#3F#), 12); Stream.Read (Val); Result := Result or Shift_Left (Unsigned_32 (Val and 16#3F#), 6); Stream.Read (Val); Result := Result or Unsigned_32 (Val and 16#3F#); Char := Wide_Wide_Character'Val (Result); end if; end Read; -- ------------------------------ -- Read into the buffer as many bytes as possible and return in -- <b>last</b> the position of the last byte read. -- ------------------------------ overriding procedure Read (Stream : in out Input_Buffer_Stream; Into : out Ada.Streams.Stream_Element_Array; Last : out Ada.Streams.Stream_Element_Offset) is Start : Stream_Element_Offset := Into'First; Pos : Stream_Element_Offset := Stream.Read_Pos; Avail : Stream_Element_Offset; Size : Stream_Element_Offset; Total : Stream_Element_Offset := 0; begin while Start <= Into'Last loop Size := Into'Last - Start + 1; Avail := Stream.Write_Pos - Pos; if Avail = 0 then Stream.Fill; Pos := Stream.Read_Pos; Avail := Stream.Write_Pos - Pos; exit when Avail <= 0; end if; if Avail < Size then Size := Avail; end if; Into (Start .. Start + Size - 1) := Stream.Buffer (Pos .. Pos + Size - 1); Start := Start + Size; Pos := Pos + Size; Total := Total + Size; Stream.Read_Pos := Pos; end loop; Last := Total; end Read; -- ------------------------------ -- Read into the buffer as many bytes as possible and return in -- <b>last</b> the position of the last byte read. -- ------------------------------ procedure Read (Stream : in out Input_Buffer_Stream; Into : in out Ada.Strings.Unbounded.Unbounded_String) is Pos : Stream_Element_Offset := Stream.Read_Pos; Avail : Stream_Element_Offset; begin loop Avail := Stream.Write_Pos - Pos; if Avail = 0 then Stream.Fill; if Stream.Eof then return; end if; Pos := Stream.Read_Pos; Avail := Stream.Write_Pos - Pos; end if; for I in 1 .. Avail loop Ada.Strings.Unbounded.Append (Into, Character'Val (Stream.Buffer (Pos))); Pos := Pos + 1; end loop; Stream.Read_Pos := Pos; end loop; end Read; procedure Read (Stream : in out Input_Buffer_Stream; Into : in out Ada.Strings.Wide_Wide_Unbounded.Unbounded_Wide_Wide_String) is Pos : Stream_Element_Offset; Avail : Stream_Element_Offset; C : Wide_Wide_Character; begin loop Pos := Stream.Read_Pos; Avail := Stream.Write_Pos - Pos; if Avail = 0 then Stream.Fill; if Stream.Eof then return; end if; Pos := Stream.Read_Pos; Avail := Stream.Write_Pos - Pos; end if; Stream.Read (C); Ada.Strings.Wide_Wide_Unbounded.Append (Into, C); end loop; end Read; -- ------------------------------ -- Flush the stream and release the buffer. -- ------------------------------ overriding procedure Finalize (Stream : in out Output_Buffer_Stream) is begin if Stream.Buffer /= null then if Stream.Output /= null then Stream.Flush; end if; Free_Buffer (Stream.Buffer); end if; end Finalize; -- ------------------------------ -- Returns True if the end of the stream is reached. -- ------------------------------ function Is_Eof (Stream : in Input_Buffer_Stream) return Boolean is begin return Stream.Eof; end Is_Eof; -- ------------------------------ -- Flush the stream and release the buffer. -- ------------------------------ overriding procedure Finalize (Object : in out Input_Buffer_Stream) is begin if Object.Buffer /= null then Free_Buffer (Object.Buffer); end if; end Finalize; end Util.Streams.Buffered;
Implement Read procedure to read Wide_Wide characters from UTF-8 sequences
Implement Read procedure to read Wide_Wide characters from UTF-8 sequences
Ada
apache-2.0
stcarrez/ada-util,stcarrez/ada-util
01625f977c27721afb71a838c845463c67958b77
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.Services.Contexts; package body AWA.Comments.Beans is package ASC renames AWA.Services.Contexts; -- ------------------------------ -- 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 => Ada.Strings.Unbounded.To_String (Bean.Permission), Entity_Type => Ada.Strings.Unbounded.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 begin null; end Save; -- ------------------------------ -- 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 = "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 begin null; 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;
Implement the Publish action in the comment bean
Implement the Publish action in the comment bean
Ada
apache-2.0
stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa,stcarrez/ada-awa
4cce17be592410634ac8a6fbe54ca2db9f39ed2c
src/asf-servlets-rest.adb
src/asf-servlets-rest.adb
----------------------------------------------------------------------- -- asf-servlets-rest -- REST servlet -- 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.Rest; with ASF.Applications; with ASF.Streams.JSON; with Util.Streams.Texts; with Util.Serialize.IO.JSON; with ASF.Routes.Servlets.Rest; package body ASF.Servlets.Rest is -- ------------------------------ -- Called by the servlet container to indicate to a servlet that the servlet -- is being placed into service. -- ------------------------------ procedure Initialize (Server : in out Rest_Servlet; Context : in Servlet_Registry'Class) is pragma Unreferenced (Context); Ctx : constant Servlet_Registry_Access := Server.Get_Servlet_Context; begin if Ctx.all in ASF.Applications.Main.Application'Class then Server.App := ASF.Applications.Main.Application'Class (Ctx.all)'Unchecked_Access; end if; end Initialize; -- ------------------------------ -- 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. -- ------------------------------ overriding procedure Service (Server : in Rest_Servlet; Request : in out Requests.Request'Class; Response : in out Responses.Response'Class) is Method : constant String := Request.Get_Method; begin if Method = "GET" then Rest_Servlet'Class (Server).Dispatch (ASF.Rest.GET, Request, Response); elsif Method = "POST" then Rest_Servlet'Class (Server).Dispatch (ASF.Rest.POST, Request, Response); elsif Method = "PUT" then Rest_Servlet'Class (Server).Dispatch (ASF.Rest.PUT, Request, Response); elsif Method = "DELETE" then Rest_Servlet'Class (Server).Dispatch (ASF.Rest.DELETE, Request, Response); elsif Method = "HEAD" then Rest_Servlet'Class (Server).Dispatch (ASF.Rest.POST, Request, Response); elsif Method = "OPTIONS" then Rest_Servlet'Class (Server).Dispatch (ASF.Rest.HEAD, Request, Response); elsif Method = "TRACE" then Rest_Servlet'Class (Server).Dispatch (ASF.Rest.TRACE, Request, Response); elsif Method = "CONNECT" then Rest_Servlet'Class (Server).Dispatch (ASF.Rest.CONNECT, Request, Response); else Response.Send_Error (Responses.SC_NOT_IMPLEMENTED); end if; end Service; procedure Dispatch (Server : in Rest_Servlet; Method : in ASF.Rest.Method_Type; Request : in out Requests.Request'Class; Response : in out Responses.Response'Class) is use type ASF.Routes.Route_Type_Access; use type ASF.Routes.Servlets.Rest.API_Route_Type; use type ASF.Rest.Descriptor_Access; Route : constant ASF.Routes.Route_Type_Access := Request.Get_Route; begin if Route = null or else not (Route.all in ASF.Routes.Servlets.Rest.API_Route_Type'Class) then Response.Set_Status (ASF.Responses.SC_INTERNAL_SERVER_ERROR); return; end if; declare Api : constant access ASF.Routes.Servlets.Rest.API_Route_Type := ASF.Routes.Servlets.Rest.API_Route_Type (Route.all)'Access; Output : ASF.Streams.Print_Stream := Response.Get_Output_Stream; Stream : ASF.Streams.JSON.Print_Stream; begin if Api.Descriptors (Method) = null then Response.Set_Status (ASF.Responses.SC_NOT_FOUND); return; end if; ASF.Streams.JSON.Initialize (Stream, Output); Api.Descriptors (Method).Dispatch (Request, Response, Stream); end; end Dispatch; function Create_Route (Registry : in ASF.Servlets.Servlet_Registry; Name : in String) return ASF.Routes.Servlets.Rest.API_Route_Type_Access is Pos : constant Servlet_Maps.Cursor := Registry.Servlets.Find (Name); Result : ASF.Routes.Servlets.Rest.API_Route_Type_Access; begin if not Servlet_Maps.Has_Element (Pos) then -- Log.Error ("No servlet {0}", Name); raise Servlet_Error with "No servlet " & Name; end if; Result := new ASF.Routes.Servlets.Rest.API_Route_Type; Result.Servlet := Servlet_Maps.Element (Pos); return Result; end Create_Route; end ASF.Servlets.Rest;
----------------------------------------------------------------------- -- asf-servlets-rest -- REST servlet -- 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.Rest; with ASF.Applications; with ASF.Streams.JSON; with Util.Streams.Texts; with Util.Serialize.IO.JSON; with ASF.Routes.Servlets.Rest; package body ASF.Servlets.Rest is -- ------------------------------ -- Called by the servlet container to indicate to a servlet that the servlet -- is being placed into service. -- ------------------------------ procedure Initialize (Server : in out Rest_Servlet; Context : in Servlet_Registry'Class) is pragma Unreferenced (Context); Ctx : constant Servlet_Registry_Access := Server.Get_Servlet_Context; begin if Ctx.all in ASF.Applications.Main.Application'Class then Server.App := ASF.Applications.Main.Application'Class (Ctx.all)'Unchecked_Access; end if; end Initialize; -- ------------------------------ -- 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. -- ------------------------------ overriding procedure Service (Server : in Rest_Servlet; Request : in out Requests.Request'Class; Response : in out Responses.Response'Class) is Method : constant String := Request.Get_Method; begin if Method = "GET" then Rest_Servlet'Class (Server).Dispatch (ASF.Rest.GET, Request, Response); elsif Method = "POST" then Rest_Servlet'Class (Server).Dispatch (ASF.Rest.POST, Request, Response); elsif Method = "PUT" then Rest_Servlet'Class (Server).Dispatch (ASF.Rest.PUT, Request, Response); elsif Method = "DELETE" then Rest_Servlet'Class (Server).Dispatch (ASF.Rest.DELETE, Request, Response); elsif Method = "HEAD" then Rest_Servlet'Class (Server).Dispatch (ASF.Rest.POST, Request, Response); elsif Method = "OPTIONS" then Rest_Servlet'Class (Server).Dispatch (ASF.Rest.HEAD, Request, Response); elsif Method = "TRACE" then Rest_Servlet'Class (Server).Dispatch (ASF.Rest.TRACE, Request, Response); elsif Method = "CONNECT" then Rest_Servlet'Class (Server).Dispatch (ASF.Rest.CONNECT, Request, Response); else Response.Send_Error (Responses.SC_NOT_IMPLEMENTED); end if; end Service; procedure Dispatch (Server : in Rest_Servlet; Method : in ASF.Rest.Method_Type; Request : in out Requests.Request'Class; Response : in out Responses.Response'Class) is use type ASF.Routes.Route_Type_Access; use type ASF.Routes.Servlets.Rest.API_Route_Type; use type ASF.Rest.Descriptor_Access; Route : constant ASF.Routes.Route_Type_Access := Request.Get_Route; begin if Route = null or else not (Route.all in ASF.Routes.Servlets.Rest.API_Route_Type'Class) then Response.Set_Status (ASF.Responses.SC_NOT_FOUND); return; end if; declare Api : constant access ASF.Routes.Servlets.Rest.API_Route_Type := ASF.Routes.Servlets.Rest.API_Route_Type (Route.all)'Access; Output : ASF.Streams.Print_Stream := Response.Get_Output_Stream; Stream : ASF.Streams.JSON.Print_Stream; begin if Api.Descriptors (Method) = null then Response.Set_Status (ASF.Responses.SC_NOT_FOUND); return; end if; ASF.Streams.JSON.Initialize (Stream, Output); Api.Descriptors (Method).Dispatch (Request, Response, Stream); end; end Dispatch; function Create_Route (Registry : in ASF.Servlets.Servlet_Registry; Name : in String) return ASF.Routes.Servlets.Rest.API_Route_Type_Access is Pos : constant Servlet_Maps.Cursor := Registry.Servlets.Find (Name); Result : ASF.Routes.Servlets.Rest.API_Route_Type_Access; begin if not Servlet_Maps.Has_Element (Pos) then -- Log.Error ("No servlet {0}", Name); raise Servlet_Error with "No servlet " & Name; end if; Result := new ASF.Routes.Servlets.Rest.API_Route_Type; Result.Servlet := Servlet_Maps.Element (Pos); return Result; end Create_Route; end ASF.Servlets.Rest;
Return a 404 error when there is no valid API rest descriptor
Return a 404 error when there is no valid API rest descriptor
Ada
apache-2.0
stcarrez/ada-asf,stcarrez/ada-asf,stcarrez/ada-asf
32f2312874b73d91aac817c5c3648f072cc3d8f0
components/src/printer/adafruit_thermal_printer/adafruit-thermal_printer.adb
components/src/printer/adafruit_thermal_printer/adafruit-thermal_printer.adb
with Ada.Unchecked_Conversion; with HAL.UART; use HAL.UART; with Interfaces; use Interfaces; package body AdaFruit.Thermal_Printer is function To_Char is new Ada.Unchecked_Conversion (Source => Byte, Target => Character); function To_Byte is new Ada.Unchecked_Conversion (Source => Character, Target => Byte); procedure Write (This : in out TP_Device; Cmd : String); procedure Read (This : in out TP_Device; Str : out String); ----------- -- Write -- ----------- procedure Write (This : in out TP_Device; Cmd : String) is Status : UART_Status; Data : UART_Data_8b (Cmd'Range); begin for Index in Cmd'Range loop Data (Index) := To_Byte (Cmd (Index)); end loop; This.Port.Transmit (Data, Status); if Status /= Ok then -- No error handling... raise Program_Error; end if; -- This.Time.Delay_Microseconds ((11 * 1000000 / 19_2000) + Cmd'Length); end Write; ---------- -- Read -- ---------- procedure Read (This : in out TP_Device; Str : out String) is Status : UART_Status; Data : UART_Data_8b (Str'Range); begin This.Port.Receive (Data, Status); if Status /= Ok then -- No error handling... raise Program_Error; end if; for Index in Str'Range loop Str (Index) := To_Char (Data (Index)); end loop; end Read; ---------------------- -- Set_Line_Spacing -- ---------------------- procedure Set_Line_Spacing (This : in out TP_Device; Spacing : Byte) is begin Write (This, ASCII.ESC & '3' & To_Char (Spacing)); end Set_Line_Spacing; --------------- -- Set_Align -- --------------- procedure Set_Align (This : in out TP_Device; Align : Text_Align) is Mode : Character; begin case Align is when Left => Mode := '0'; when Center => Mode := '1'; when Right => Mode := '2'; end case; Write (This, ASCII.ESC & 'a' & Mode); end Set_Align; ---------------------- -- Set_Font_Enlarge -- ---------------------- procedure Set_Font_Enlarge (This : in out TP_Device; Height, Width : Boolean) is Data : Byte := 0; begin if Height then Data := Data or 16#01#; end if; if Width then Data := Data or 16#10#; end if; Write (This, ASCII.GS & '!' & To_Char (Data)); end Set_Font_Enlarge; -------------- -- Set_Bold -- -------------- procedure Set_Bold (This : in out TP_Device; Bold : Boolean) is begin Write (This, ASCII.ESC & 'E' & To_Char (if Bold then 1 else 0)); end Set_Bold; ---------------------- -- Set_Double_Width -- ---------------------- procedure Set_Double_Width (This : in out TP_Device; Double : Boolean) is begin if Double then Write (This, ASCII.ESC & ASCII.SO); else Write (This, ASCII.ESC & ASCII.DC4); end if; end Set_Double_Width; ---------------- -- Set_UpDown -- ---------------- procedure Set_UpDown (This : in out TP_Device; UpDown : Boolean) is begin Write (This, ASCII.ESC & '{' & To_Char (if UpDown then 1 else 0)); end Set_UpDown; ------------------ -- Set_Reversed -- ------------------ procedure Set_Reversed (This : in out TP_Device; Reversed : Boolean) is begin Write (This, ASCII.GS & 'B' & To_Char (if Reversed then 1 else 0)); end Set_Reversed; -------------------------- -- Set_Underline_Height -- -------------------------- procedure Set_Underline_Height (This : in out TP_Device; Height : Underline_Height) is begin Write (This, ASCII.ESC & '-' & To_Char (Height)); end Set_Underline_Height; ----------------------- -- Set_Character_Set -- ----------------------- procedure Set_Character_Set (This : in out TP_Device; Set : Character_Set) is begin Write (This, ASCII.ESC & 't' & To_Char (Character_Set'Pos (Set))); end Set_Character_Set; ---------- -- Feed -- ---------- procedure Feed (This : in out TP_Device; Rows : Byte) is begin Write (This, ASCII.ESC & 'd' & To_Char (Rows)); end Feed; ------------------ -- Print_Bitmap -- ------------------ procedure Print_Bitmap (This : in out TP_Device; BM : Thermal_Printer_Bitmap) is Nbr_Of_Rows : constant Natural := BM'Length (2); Nbr_Of_Columns : constant Natural := BM'Length (1); Str : String (1 .. Nbr_Of_Columns / 8); begin Write (This, ASCII.DC2 & 'v' & To_Char (Byte (Nbr_Of_Rows rem 256)) & To_Char (Byte (Nbr_Of_Rows / 256))); for Row in 0 .. Nbr_Of_Rows - 1 loop for Colum in 0 .. (Nbr_Of_Columns / 8) - 1 loop declare BM_Index : constant Natural := BM'First (1) + Colum * 8; Str_Index : constant Natural := Str'First + Colum; B : Byte := 0; begin for X in 0 .. 7 loop B := B or (if BM (BM_Index + X, BM'First (2) + Row) then 2**X else 0); end loop; Str (Str_Index) := To_Char (B); end; end loop; Write (This, Str); -- delay until Clock + Microseconds (10000 * Str'Length); This.Time.Delay_Microseconds (800 * Str'Length); end loop; end Print_Bitmap; ---------- -- Wake -- ---------- procedure Wake (This : in out TP_Device) is begin Write (This, ASCII.ESC & '@'); end Wake; ----------- -- Reset -- ----------- procedure Reset (This : in out TP_Device) is begin Write (This, "" & To_Char (16#FF#)); This.Time.Delay_Milliseconds (50); Write (This, ASCII.ESC & '8' & ASCII.NUL & ASCII.NUL); for X in 1 .. 10 loop This.Time.Delay_Microseconds (10_000); Write (This, "" & ASCII.NUL); end loop; end Reset; ----------- -- Print -- ----------- procedure Print (This : in out TP_Device; Text : String) is begin Write (This, Text); end Print; ---------------- -- Get_Status -- ---------------- function Get_Status (This : in out TP_Device) return Printer_Status is Ret : Printer_Status; Status : String := "P1V72T30"; begin Ret.Paper := False; Ret.Voltage := 0; Ret.Temperature := 0; Write (This, ASCII.ESC & 'v'); Read (This, Status); -- Parse status here -- P<Paper>V<Voltage>T<Degree> -- Example: P1V72T30 Mean:Paper Ready,Current voltage 7.2V,Printer degree:30 return Ret; end Get_Status; -------------------------- -- Set_Printer_Settings -- -------------------------- procedure Set_Printer_Settings (This : in out TP_Device; Settings : Printer_Settings) is begin Write (This, ASCII.ESC & '7' & To_Char (Settings.Max_Printing_Dots) & To_Char (if Settings.Heating_Time < 3 then 3 else Settings.Heating_Time) & To_Char (Settings.Heating_Interval)); end Set_Printer_Settings; ----------------- -- Set_Density -- ----------------- procedure Set_Density (This : in out TP_Device; Density, Breaktime : Byte) is begin Write (This, ASCII.DC2 & '#' & To_Char (Shift_Left (Breaktime, 5) or Density)); end Set_Density; --------------------- -- Print_Test_Page -- --------------------- procedure Print_Test_Page (This : in out TP_Device) is begin Write (This, ASCII.DC2 & 'T'); end Print_Test_Page; end AdaFruit.Thermal_Printer;
with Ada.Unchecked_Conversion; with HAL.UART; use HAL.UART; with Interfaces; use Interfaces; package body AdaFruit.Thermal_Printer is function To_Char is new Ada.Unchecked_Conversion (Source => Byte, Target => Character); function To_Byte is new Ada.Unchecked_Conversion (Source => Character, Target => Byte); procedure Write (This : in out TP_Device; Cmd : String); procedure Read (This : in out TP_Device; Str : out String); ----------- -- Write -- ----------- procedure Write (This : in out TP_Device; Cmd : String) is Status : UART_Status; Data : UART_Data_8b (Cmd'Range); begin for Index in Cmd'Range loop Data (Index) := To_Byte (Cmd (Index)); end loop; This.Port.Transmit (Data, Status); if Status /= Ok then -- No error handling... raise Program_Error; end if; -- This.Time.Delay_Microseconds ((11 * 1000000 / 19_2000) + Cmd'Length); end Write; ---------- -- Read -- ---------- procedure Read (This : in out TP_Device; Str : out String) is Status : UART_Status; Data : UART_Data_8b (Str'Range); begin This.Port.Receive (Data, Status); if Status /= Ok then -- No error handling... raise Program_Error; end if; for Index in Str'Range loop Str (Index) := To_Char (Data (Index)); end loop; end Read; ---------------------- -- Set_Line_Spacing -- ---------------------- procedure Set_Line_Spacing (This : in out TP_Device; Spacing : Byte) is begin Write (This, ASCII.ESC & '3' & To_Char (Spacing)); end Set_Line_Spacing; --------------- -- Set_Align -- --------------- procedure Set_Align (This : in out TP_Device; Align : Text_Align) is Mode : Character; begin case Align is when Left => Mode := '0'; when Center => Mode := '1'; when Right => Mode := '2'; end case; Write (This, ASCII.ESC & 'a' & Mode); end Set_Align; ---------------------- -- Set_Font_Enlarge -- ---------------------- procedure Set_Font_Enlarge (This : in out TP_Device; Height, Width : Boolean) is Data : Byte := 0; begin if Height then Data := Data or 16#01#; end if; if Width then Data := Data or 16#10#; end if; Write (This, ASCII.GS & '!' & To_Char (Data)); end Set_Font_Enlarge; -------------- -- Set_Bold -- -------------- procedure Set_Bold (This : in out TP_Device; Bold : Boolean) is begin Write (This, ASCII.ESC & 'E' & To_Char (if Bold then 1 else 0)); end Set_Bold; ---------------------- -- Set_Double_Width -- ---------------------- procedure Set_Double_Width (This : in out TP_Device; Double : Boolean) is begin if Double then Write (This, ASCII.ESC & ASCII.SO); else Write (This, ASCII.ESC & ASCII.DC4); end if; end Set_Double_Width; ---------------- -- Set_UpDown -- ---------------- procedure Set_UpDown (This : in out TP_Device; UpDown : Boolean) is begin Write (This, ASCII.ESC & '{' & To_Char (if UpDown then 1 else 0)); end Set_UpDown; ------------------ -- Set_Reversed -- ------------------ procedure Set_Reversed (This : in out TP_Device; Reversed : Boolean) is begin Write (This, ASCII.GS & 'B' & To_Char (if Reversed then 1 else 0)); end Set_Reversed; -------------------------- -- Set_Underline_Height -- -------------------------- procedure Set_Underline_Height (This : in out TP_Device; Height : Underline_Height) is begin Write (This, ASCII.ESC & '-' & To_Char (Height)); end Set_Underline_Height; ----------------------- -- Set_Character_Set -- ----------------------- procedure Set_Character_Set (This : in out TP_Device; Set : Character_Set) is begin Write (This, ASCII.ESC & 't' & To_Char (Character_Set'Pos (Set))); end Set_Character_Set; ---------- -- Feed -- ---------- procedure Feed (This : in out TP_Device; Rows : Byte) is begin Write (This, ASCII.ESC & 'd' & To_Char (Rows)); end Feed; ------------------ -- Print_Bitmap -- ------------------ procedure Print_Bitmap (This : in out TP_Device; BM : Thermal_Printer_Bitmap) is Nbr_Of_Rows : constant Natural := BM'Length (2); Nbr_Of_Columns : constant Natural := BM'Length (1); Str : String (1 .. Nbr_Of_Columns / 8); begin Write (This, ASCII.DC2 & 'v' & To_Char (Byte (Nbr_Of_Rows rem 256)) & To_Char (Byte (Nbr_Of_Rows / 256))); for Row in 0 .. Nbr_Of_Rows - 1 loop for Colum in 0 .. (Nbr_Of_Columns / 8) - 1 loop declare BM_Index : constant Natural := BM'First (1) + Colum * 8; Str_Index : constant Natural := Str'First + Colum; B : Byte := 0; begin for X in 0 .. 7 loop B := B or (if BM (BM_Index + X, BM'First (2) + Row) then 2**X else 0); end loop; Str (Str_Index) := To_Char (B); end; end loop; Write (This, Str); -- delay until Clock + Microseconds (10000 * Str'Length); This.Time.Delay_Microseconds (600 * Str'Length); end loop; end Print_Bitmap; ---------- -- Wake -- ---------- procedure Wake (This : in out TP_Device) is begin Write (This, ASCII.ESC & '@'); end Wake; ----------- -- Reset -- ----------- procedure Reset (This : in out TP_Device) is begin Write (This, "" & To_Char (16#FF#)); This.Time.Delay_Milliseconds (50); Write (This, ASCII.ESC & '8' & ASCII.NUL & ASCII.NUL); for X in 1 .. 10 loop This.Time.Delay_Microseconds (10_000); Write (This, "" & ASCII.NUL); end loop; end Reset; ----------- -- Print -- ----------- procedure Print (This : in out TP_Device; Text : String) is begin Write (This, Text); end Print; ---------------- -- Get_Status -- ---------------- function Get_Status (This : in out TP_Device) return Printer_Status is Ret : Printer_Status; Status : String := "P1V72T30"; begin Ret.Paper := False; Ret.Voltage := 0; Ret.Temperature := 0; Write (This, ASCII.ESC & 'v'); Read (This, Status); -- Parse status here -- P<Paper>V<Voltage>T<Degree> -- Example: P1V72T30 Mean:Paper Ready,Current voltage 7.2V,Printer degree:30 return Ret; end Get_Status; -------------------------- -- Set_Printer_Settings -- -------------------------- procedure Set_Printer_Settings (This : in out TP_Device; Settings : Printer_Settings) is begin Write (This, ASCII.ESC & '7' & To_Char (Settings.Max_Printing_Dots) & To_Char (if Settings.Heating_Time < 3 then 3 else Settings.Heating_Time) & To_Char (Settings.Heating_Interval)); end Set_Printer_Settings; ----------------- -- Set_Density -- ----------------- procedure Set_Density (This : in out TP_Device; Density, Breaktime : Byte) is begin Write (This, ASCII.DC2 & '#' & To_Char (Shift_Left (Breaktime, 5) or Density)); end Set_Density; --------------------- -- Print_Test_Page -- --------------------- procedure Print_Test_Page (This : in out TP_Device) is begin Write (This, ASCII.DC2 & 'T'); end Print_Test_Page; end AdaFruit.Thermal_Printer;
Increase bitmap print speed
AdaFruit.Thermal_Printer: Increase bitmap print speed
Ada
bsd-3-clause
simonjwright/Ada_Drivers_Library,Fabien-Chouteau/Ada_Drivers_Library,lambourg/Ada_Drivers_Library,Fabien-Chouteau/Ada_Drivers_Library,simonjwright/Ada_Drivers_Library,AdaCore/Ada_Drivers_Library,ellamosi/Ada_BMP_Library,AdaCore/Ada_Drivers_Library
03a0acca7f70d116e4d45211400f635b20400c5a
matp/src/mat-expressions.adb
matp/src/mat-expressions.adb
----------------------------------------------------------------------- -- mat-expressions -- Expressions for memory slot selection -- Copyright (C) 2014, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Unchecked_Deallocation; with MAT.Expressions.Parser; package body MAT.Expressions is procedure Free is new Ada.Unchecked_Deallocation (Object => Node_Type, Name => Node_Type_Access); -- Destroy recursively the node, releasing the storage. procedure Destroy (Node : in out Node_Type_Access); -- ------------------------------ -- Create a NOT expression node. -- ------------------------------ function Create_Not (Expr : in Expression_Type) return Expression_Type is Result : Expression_Type; begin Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE, Kind => N_NOT, Expr => Expr.Node); Util.Concurrent.Counters.Increment (Expr.Node.Ref_Counter); return Result; end Create_Not; -- ------------------------------ -- Create a AND expression node. -- ------------------------------ function Create_And (Left : in Expression_Type; Right : in Expression_Type) return Expression_Type is Result : Expression_Type; begin Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE, Kind => N_AND, Left => Left.Node, Right => Right.Node); Util.Concurrent.Counters.Increment (Left.Node.Ref_Counter); Util.Concurrent.Counters.Increment (Right.Node.Ref_Counter); return Result; end Create_And; -- ------------------------------ -- Create a OR expression node. -- ------------------------------ function Create_Or (Left : in Expression_Type; Right : in Expression_Type) return Expression_Type is Result : Expression_Type; begin Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE, Kind => N_OR, Left => Left.Node, Right => Right.Node); Util.Concurrent.Counters.Increment (Left.Node.Ref_Counter); Util.Concurrent.Counters.Increment (Right.Node.Ref_Counter); return Result; end Create_Or; -- ------------------------------ -- Create an INSIDE expression node. -- ------------------------------ function Create_Inside (Name : in Ada.Strings.Unbounded.Unbounded_String; Kind : in Inside_Type) return Expression_Type is Result : Expression_Type; begin Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE, Kind => N_INSIDE, Name => Name, Inside => Kind); return Result; end Create_Inside; -- ------------------------------ -- Create an size range expression node. -- ------------------------------ function Create_Size (Min : in MAT.Types.Target_Size; Max : in MAT.Types.Target_Size) return Expression_Type is Result : Expression_Type; begin Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE, Kind => N_RANGE_SIZE, Min_Size => Min, Max_Size => Max); return Result; end Create_Size; -- ------------------------------ -- Create an addr range expression node. -- ------------------------------ function Create_Addr (Min : in MAT.Types.Target_Addr; Max : in MAT.Types.Target_Addr) return Expression_Type is Result : Expression_Type; begin Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE, Kind => N_RANGE_ADDR, Min_Addr => Min, Max_Addr => Max); return Result; end Create_Addr; -- ------------------------------ -- Create an time range expression node. -- ------------------------------ function Create_Time (Min : in MAT.Types.Target_Tick_Ref; Max : in MAT.Types.Target_Tick_Ref) return Expression_Type is Result : Expression_Type; begin Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE, Kind => N_RANGE_TIME, Min_Time => Min, Max_Time => Max); return Result; end Create_Time; -- ------------------------------ -- Create a thread ID range expression node. -- ------------------------------ function Create_Thread (Min : in MAT.Types.Target_Thread_Ref; Max : in MAT.Types.Target_Thread_Ref) return Expression_Type is Result : Expression_Type; begin Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE, Kind => N_THREAD, Min_Thread => Min, Max_Thread => Max); return Result; end Create_Thread; -- ------------------------------ -- Create a event type expression check. -- ------------------------------ function Create_Event_Type (Event_Kind : in MAT.Events.Targets.Probe_Index_Type) return Expression_Type is Result : Expression_Type; begin Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE, Kind => N_TYPE, Event_Kind => Event_Kind); return Result; end Create_Event_Type; -- ------------------------------ -- Create an event ID range expression node. -- ------------------------------ function Create_Event (Min : in MAT.Events.Targets.Event_Id_Type; Max : in MAT.Events.Targets.Event_Id_Type) return Expression_Type is Result : Expression_Type; begin Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE, Kind => N_EVENT, Min_Event => Min, Max_Event => Max); return Result; end Create_Event; -- ------------------------------ -- Evaluate the expression to check if the memory slot described by the -- context is selected. Returns True if the memory slot is selected. -- ------------------------------ function Is_Selected (Node : in Expression_Type; Addr : in MAT.Types.Target_Addr; Allocation : in MAT.Memory.Allocation) return Boolean is begin if Node.Node = null then return True; else return Is_Selected (Node.Node.all, Addr, Allocation); end if; end Is_Selected; -- ------------------------------ -- Evaluate the expression to check if the event described by the -- context is selected. Returns True if the event is selected. -- ------------------------------ function Is_Selected (Node : in Expression_Type; Event : in MAT.Events.Targets.Probe_Event_Type) return Boolean is begin return Is_Selected (Node.Node.all, Event); end Is_Selected; -- ------------------------------ -- Evaluate the node against the context. Returns True if the node expression -- selects the memory slot defined by the context. -- ------------------------------ function Is_Selected (Node : in Node_Type; Addr : in MAT.Types.Target_Addr; Allocation : in MAT.Memory.Allocation) return Boolean is use type MAT.Types.Target_Size; use type MAT.Types.Target_Tick_Ref; begin case Node.Kind is when N_NOT => return not Is_Selected (Node.Expr.all, Addr, Allocation); when N_AND => return Is_Selected (Node.Left.all, Addr, Allocation) and then Is_Selected (Node.Right.all, Addr, Allocation); when N_OR => return Is_Selected (Node.Left.all, Addr, Allocation) or else Is_Selected (Node.Right.all, Addr, Allocation); when N_RANGE_SIZE => return Allocation.Size >= Node.Min_Size and Allocation.Size <= Node.Max_Size; when N_RANGE_ADDR => return Addr >= Node.Min_Addr and Addr <= Node.Max_Addr; when N_RANGE_TIME => return Allocation.Time >= Node.Min_Time and Allocation.Time <= Node.Max_Time; when others => return False; end case; end Is_Selected; -- ------------------------------ -- Evaluate the expression to check if the event described by the -- context is selected. Returns True if the event is selected. -- ------------------------------ function Is_Selected (Node : in Node_Type; Event : in MAT.Events.Targets.Probe_Event_Type) return Boolean is use type MAT.Types.Target_Size; use type MAT.Types.Target_Tick_Ref; use type MAT.Types.Target_Thread_Ref; use type MAT.Events.Targets.Event_Id_Type; use type MAT.Events.Targets.Probe_Index_Type; begin case Node.Kind is when N_NOT => return not Is_Selected (Node.Expr.all, Event); when N_AND => return Is_Selected (Node.Left.all, Event) and then Is_Selected (Node.Right.all, Event); when N_OR => return Is_Selected (Node.Left.all, Event) or else Is_Selected (Node.Right.all, Event); when N_RANGE_SIZE => return Event.Size >= Node.Min_Size and Event.Size <= Node.Max_Size; when N_RANGE_ADDR => return Event.Addr >= Node.Min_Addr and Event.Addr <= Node.Max_Addr; when N_RANGE_TIME => return Event.Time >= Node.Min_Time and Event.Time <= Node.Max_Time; when N_EVENT => return Event.Id >= Node.Min_Event and Event.Id <= Node.Max_Event; when N_THREAD => return Event.Thread >= Node.Min_Thread and Event.Thread <= Node.Max_Thread; when N_TYPE => return Event.Index = Node.Event_Kind; when others => return False; end case; end Is_Selected; -- ------------------------------ -- Parse the string and return the expression tree. -- ------------------------------ function Parse (Expr : in String) return Expression_Type is begin return MAT.Expressions.Parser.Parse (Expr); end Parse; -- ------------------------------ -- Destroy recursively the node, releasing the storage. -- ------------------------------ procedure Destroy (Node : in out Node_Type_Access) is Release : Boolean; begin if Node /= null then Util.Concurrent.Counters.Decrement (Node.Ref_Counter, Release); if Release then case Node.Kind is when N_NOT => Destroy (Node.Expr); when N_AND | N_OR => Destroy (Node.Left); Destroy (Node.Right); when others => null; end case; Free (Node); else Node := null; end if; end if; end Destroy; -- ------------------------------ -- Release the reference and destroy the expression tree if it was the last reference. -- ------------------------------ overriding procedure Finalize (Obj : in out Expression_Type) is begin if Obj.Node /= null then Destroy (Obj.Node); end if; end Finalize; -- ------------------------------ -- Update the reference after an assignment. -- ------------------------------ overriding procedure Adjust (Obj : in out Expression_Type) is begin if Obj.Node /= null then Util.Concurrent.Counters.Increment (Obj.Node.Ref_Counter); end if; end Adjust; end MAT.Expressions;
----------------------------------------------------------------------- -- mat-expressions -- Expressions for event and memory slot selection -- Copyright (C) 2014, 2015 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Unchecked_Deallocation; with MAT.Expressions.Parser; package body MAT.Expressions is procedure Free is new Ada.Unchecked_Deallocation (Object => Node_Type, Name => Node_Type_Access); -- Destroy recursively the node, releasing the storage. procedure Destroy (Node : in out Node_Type_Access); -- ------------------------------ -- Create a NOT expression node. -- ------------------------------ function Create_Not (Expr : in Expression_Type) return Expression_Type is Result : Expression_Type; begin Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE, Kind => N_NOT, Expr => Expr.Node); Util.Concurrent.Counters.Increment (Expr.Node.Ref_Counter); return Result; end Create_Not; -- ------------------------------ -- Create a AND expression node. -- ------------------------------ function Create_And (Left : in Expression_Type; Right : in Expression_Type) return Expression_Type is Result : Expression_Type; begin Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE, Kind => N_AND, Left => Left.Node, Right => Right.Node); Util.Concurrent.Counters.Increment (Left.Node.Ref_Counter); Util.Concurrent.Counters.Increment (Right.Node.Ref_Counter); return Result; end Create_And; -- ------------------------------ -- Create a OR expression node. -- ------------------------------ function Create_Or (Left : in Expression_Type; Right : in Expression_Type) return Expression_Type is Result : Expression_Type; begin Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE, Kind => N_OR, Left => Left.Node, Right => Right.Node); Util.Concurrent.Counters.Increment (Left.Node.Ref_Counter); Util.Concurrent.Counters.Increment (Right.Node.Ref_Counter); return Result; end Create_Or; -- ------------------------------ -- Create an INSIDE expression node. -- ------------------------------ function Create_Inside (Name : in Ada.Strings.Unbounded.Unbounded_String; Kind : in Inside_Type) return Expression_Type is Result : Expression_Type; begin Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE, Kind => N_INSIDE, Name => Name, Inside => Kind); return Result; end Create_Inside; -- ------------------------------ -- Create an size range expression node. -- ------------------------------ function Create_Size (Min : in MAT.Types.Target_Size; Max : in MAT.Types.Target_Size) return Expression_Type is Result : Expression_Type; begin Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE, Kind => N_RANGE_SIZE, Min_Size => Min, Max_Size => Max); return Result; end Create_Size; -- ------------------------------ -- Create an addr range expression node. -- ------------------------------ function Create_Addr (Min : in MAT.Types.Target_Addr; Max : in MAT.Types.Target_Addr) return Expression_Type is Result : Expression_Type; begin Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE, Kind => N_RANGE_ADDR, Min_Addr => Min, Max_Addr => Max); return Result; end Create_Addr; -- ------------------------------ -- Create an time range expression node. -- ------------------------------ function Create_Time (Min : in MAT.Types.Target_Tick_Ref; Max : in MAT.Types.Target_Tick_Ref) return Expression_Type is Result : Expression_Type; begin Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE, Kind => N_RANGE_TIME, Min_Time => Min, Max_Time => Max); return Result; end Create_Time; -- ------------------------------ -- Create a thread ID range expression node. -- ------------------------------ function Create_Thread (Min : in MAT.Types.Target_Thread_Ref; Max : in MAT.Types.Target_Thread_Ref) return Expression_Type is Result : Expression_Type; begin Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE, Kind => N_THREAD, Min_Thread => Min, Max_Thread => Max); return Result; end Create_Thread; -- ------------------------------ -- Create a event type expression check. -- ------------------------------ function Create_Event_Type (Event_Kind : in MAT.Events.Targets.Probe_Index_Type) return Expression_Type is Result : Expression_Type; begin Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE, Kind => N_TYPE, Event_Kind => Event_Kind); return Result; end Create_Event_Type; -- ------------------------------ -- Create an event ID range expression node. -- ------------------------------ function Create_Event (Min : in MAT.Events.Targets.Event_Id_Type; Max : in MAT.Events.Targets.Event_Id_Type) return Expression_Type is Result : Expression_Type; begin Result.Node := new Node_Type'(Ref_Counter => Util.Concurrent.Counters.ONE, Kind => N_EVENT, Min_Event => Min, Max_Event => Max); return Result; end Create_Event; -- ------------------------------ -- Evaluate the expression to check if the memory slot described by the -- context is selected. Returns True if the memory slot is selected. -- ------------------------------ function Is_Selected (Node : in Expression_Type; Addr : in MAT.Types.Target_Addr; Allocation : in MAT.Memory.Allocation) return Boolean is begin if Node.Node = null then return True; else return Is_Selected (Node.Node.all, Addr, Allocation); end if; end Is_Selected; -- ------------------------------ -- Evaluate the expression to check if the event described by the -- context is selected. Returns True if the event is selected. -- ------------------------------ function Is_Selected (Node : in Expression_Type; Event : in MAT.Events.Targets.Probe_Event_Type) return Boolean is begin return Is_Selected (Node.Node.all, Event); end Is_Selected; -- ------------------------------ -- Evaluate the node against the context. Returns True if the node expression -- selects the memory slot defined by the context. -- ------------------------------ function Is_Selected (Node : in Node_Type; Addr : in MAT.Types.Target_Addr; Allocation : in MAT.Memory.Allocation) return Boolean is use type MAT.Types.Target_Size; use type MAT.Types.Target_Tick_Ref; begin case Node.Kind is when N_NOT => return not Is_Selected (Node.Expr.all, Addr, Allocation); when N_AND => return Is_Selected (Node.Left.all, Addr, Allocation) and then Is_Selected (Node.Right.all, Addr, Allocation); when N_OR => return Is_Selected (Node.Left.all, Addr, Allocation) or else Is_Selected (Node.Right.all, Addr, Allocation); when N_RANGE_SIZE => return Allocation.Size >= Node.Min_Size and Allocation.Size <= Node.Max_Size; when N_RANGE_ADDR => return Addr >= Node.Min_Addr and Addr <= Node.Max_Addr; when N_RANGE_TIME => return Allocation.Time >= Node.Min_Time and Allocation.Time <= Node.Max_Time; when others => return False; end case; end Is_Selected; -- ------------------------------ -- Evaluate the expression to check if the event described by the -- context is selected. Returns True if the event is selected. -- ------------------------------ function Is_Selected (Node : in Node_Type; Event : in MAT.Events.Targets.Probe_Event_Type) return Boolean is use type MAT.Types.Target_Size; use type MAT.Types.Target_Tick_Ref; use type MAT.Types.Target_Thread_Ref; use type MAT.Events.Targets.Event_Id_Type; use type MAT.Events.Targets.Probe_Index_Type; begin case Node.Kind is when N_NOT => return not Is_Selected (Node.Expr.all, Event); when N_AND => return Is_Selected (Node.Left.all, Event) and then Is_Selected (Node.Right.all, Event); when N_OR => return Is_Selected (Node.Left.all, Event) or else Is_Selected (Node.Right.all, Event); when N_RANGE_SIZE => return Event.Size >= Node.Min_Size and Event.Size <= Node.Max_Size; when N_RANGE_ADDR => return Event.Addr >= Node.Min_Addr and Event.Addr <= Node.Max_Addr; when N_RANGE_TIME => return Event.Time >= Node.Min_Time and Event.Time <= Node.Max_Time; when N_EVENT => return Event.Id >= Node.Min_Event and Event.Id <= Node.Max_Event; when N_THREAD => return Event.Thread >= Node.Min_Thread and Event.Thread <= Node.Max_Thread; when N_TYPE => return Event.Index = Node.Event_Kind; when others => return False; end case; end Is_Selected; -- ------------------------------ -- Parse the string and return the expression tree. -- ------------------------------ function Parse (Expr : in String) return Expression_Type is begin return MAT.Expressions.Parser.Parse (Expr); end Parse; -- ------------------------------ -- Destroy recursively the node, releasing the storage. -- ------------------------------ procedure Destroy (Node : in out Node_Type_Access) is Release : Boolean; begin if Node /= null then Util.Concurrent.Counters.Decrement (Node.Ref_Counter, Release); if Release then case Node.Kind is when N_NOT => Destroy (Node.Expr); when N_AND | N_OR => Destroy (Node.Left); Destroy (Node.Right); when others => null; end case; Free (Node); else Node := null; end if; end if; end Destroy; -- ------------------------------ -- Release the reference and destroy the expression tree if it was the last reference. -- ------------------------------ overriding procedure Finalize (Obj : in out Expression_Type) is begin if Obj.Node /= null then Destroy (Obj.Node); end if; end Finalize; -- ------------------------------ -- Update the reference after an assignment. -- ------------------------------ overriding procedure Adjust (Obj : in out Expression_Type) is begin if Obj.Node /= null then Util.Concurrent.Counters.Increment (Obj.Node.Ref_Counter); end if; end Adjust; end MAT.Expressions;
Update the title comment
Update the title comment
Ada
apache-2.0
stcarrez/mat,stcarrez/mat,stcarrez/mat
17d06483aee8768d9ad23d27c018d1f875bff74c
orka/src/orka/implementation/orka-loops.adb
orka/src/orka/implementation/orka-loops.adb
-- SPDX-License-Identifier: Apache-2.0 -- -- Copyright (c) 2017 onox <[email protected]> -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. with System.Multiprocessors.Dispatching_Domains; with Ada.Unchecked_Conversion; with Ada.Unchecked_Deallocation; with Ada.Exceptions; with Orka.Futures; with Orka.Loggers; with Orka.Logging; with Orka.Simulation; with Orka.Simulation_Jobs; package body Orka.Loops is use all type Orka.Logging.Source; use all type Orka.Logging.Severity; use Orka.Logging; package Messages is new Orka.Logging.Messages (Game_Loop); function "+" (Value : Ada.Real_Time.Time_Span) return Duration renames Ada.Real_Time.To_Duration; procedure Free is new Ada.Unchecked_Deallocation (Behaviors.Behavior_Array, Behaviors.Behavior_Array_Access); function "<" (Left, Right : Behaviors.Behavior_Ptr) return Boolean is function Convert is new Ada.Unchecked_Conversion (Source => System.Address, Target => Long_Integer); begin return Convert (Left.all'Address) < Convert (Right.all'Address); end "<"; protected body Handler is procedure Stop is begin Stop_Flag := True; end Stop; procedure Set_Frame_Limit (Value : Time_Span) is begin Limit := Value; end Set_Frame_Limit; function Frame_Limit return Time_Span is (Limit); procedure Enable_Limit (Enable : Boolean) is begin Limit_Flag := Enable; end Enable_Limit; function Limit_Enabled return Boolean is (Limit_Flag); function Should_Stop return Boolean is (Stop_Flag); end Handler; protected body Scene is procedure Add (Object : Behaviors.Behavior_Ptr) is begin Behaviors_Set.Insert (Object); Modified_Flag := True; end Add; procedure Remove (Object : Behaviors.Behavior_Ptr) is begin Behaviors_Set.Delete (Object); Modified_Flag := True; end Remove; procedure Replace_Array (Target : in out Behaviors.Behavior_Array_Access) is pragma Assert (Modified); Index : Positive := 1; Count : constant Positive := Positive (Behaviors_Set.Length); begin Free (Target); Target := new Behaviors.Behavior_Array'(1 .. Count => Behaviors.Null_Behavior); -- Copy the elements from the set to the array -- for faster iteration by the game loop for Element of Behaviors_Set loop Target (Index) := Element; Index := Index + 1; end loop; Modified_Flag := False; end Replace_Array; function Modified return Boolean is (Modified_Flag); procedure Set_Camera (Camera : Cameras.Camera_Ptr) is begin Scene_Camera := Camera; end Set_Camera; function Camera return Cameras.Camera_Ptr is (Scene_Camera); end Scene; package SJ renames Simulation_Jobs; procedure Stop_Loop is begin Handler.Stop; end Stop_Loop; procedure Run_Game_Loop (Fence : not null access SJ.Fences.Buffer_Fence; Render : Simulation.Render_Ptr) is Previous_Time : Time := Clock; Next_Time : Time := Previous_Time; Lag : Time_Span := Time_Span_Zero; Scene_Array : not null Behaviors.Behavior_Array_Access := Behaviors.Empty_Behavior_Array; Batch_Length : constant := 10; One_Second : constant Time_Span := Seconds (1); Frame_Counter : Natural := 0; Exceeded_Frame_Counter : Natural := 0; Clock_FPS_Start : Time := Clock; Stat_Sum : Time_Span := Time_Span_Zero; Stat_Min : Duration := To_Duration (One_Second); Stat_Max : Duration := To_Duration (-One_Second); begin Scene.Replace_Array (Scene_Array); Messages.Log (Debug, "Simulation tick resolution: " & Trim (Image (+Tick))); -- Based on http://gameprogrammingpatterns.com/game-loop.html loop declare Current_Time : constant Time := Clock; Elapsed : constant Time_Span := Current_Time - Previous_Time; begin Previous_Time := Current_Time; Lag := Lag + Elapsed; exit when Handler.Should_Stop; declare Iterations : constant Natural := Lag / Time_Step; begin Lag := Lag - Iterations * Time_Step; Scene.Camera.Update (To_Duration (Lag)); declare Fixed_Update_Job : constant Jobs.Job_Ptr := Jobs.Parallelize (SJ.Create_Fixed_Update_Job (Scene_Array, Time_Step, Iterations), SJ.Clone_Fixed_Update_Job'Access, Scene_Array'Length, Batch_Length); Finished_Job : constant Jobs.Job_Ptr := SJ.Create_Finished_Job (Scene_Array, Time_Step, Scene.Camera.View_Position, Batch_Length); Render_Scene_Job : constant Jobs.Job_Ptr := SJ.Create_Scene_Render_Job (Render, Scene_Array, Scene.Camera); Render_Start_Job : constant Jobs.Job_Ptr := SJ.Create_Start_Render_Job (Fence); Render_Finish_Job : constant Jobs.Job_Ptr := SJ.Create_Finish_Render_Job (Fence); Handle : Futures.Pointers.Mutable_Pointer; Status : Futures.Status; begin Orka.Jobs.Chain ((Render_Start_Job, Fixed_Update_Job, Finished_Job, Render_Scene_Job, Render_Finish_Job)); Job_Manager.Queue.Enqueue (Render_Start_Job, Handle); declare Frame_Future : constant Orka.Futures.Future_Access := Handle.Get.Value; begin select Frame_Future.Wait_Until_Done (Status); or delay until Current_Time + Maximum_Frame_Time; raise Program_Error with "Maximum frame time of " & Trim (Image (+Maximum_Frame_Time)) & " exceeded"; end select; end; end; end; if Scene.Modified then Scene.Replace_Array (Scene_Array); end if; declare Total_Elapsed : constant Time_Span := Clock - Clock_FPS_Start; Limit_Exceeded : constant Time_Span := Elapsed - Handler.Frame_Limit; begin Frame_Counter := Frame_Counter + 1; if Limit_Exceeded > Time_Span_Zero then Stat_Sum := Stat_Sum + Limit_Exceeded; Stat_Min := Duration'Min (Stat_Min, To_Duration (Limit_Exceeded)); Stat_Max := Duration'Max (Stat_Max, To_Duration (Limit_Exceeded)); Exceeded_Frame_Counter := Exceeded_Frame_Counter + 1; end if; if Total_Elapsed > One_Second then declare Frame_Time : constant Time_Span := Total_Elapsed / Frame_Counter; FPS : constant Integer := Integer (1.0 / To_Duration (Frame_Time)); begin Messages.Log (Debug, Trim (FPS'Image) & " FPS, frame time: " & Trim (Image (+Frame_Time))); end; if Exceeded_Frame_Counter > 0 then declare Stat_Avg : constant Duration := +(Stat_Sum / Exceeded_Frame_Counter); begin Messages.Log (Debug, " deadline missed: " & Trim (Exceeded_Frame_Counter'Image) & " (limit is " & Trim (Image (+Handler.Frame_Limit)) & ")"); Messages.Log (Debug, " avg/min/max: " & Image (Stat_Avg) & Image (Stat_Min) & Image (Stat_Max)); end; end if; Clock_FPS_Start := Clock; Frame_Counter := 0; Exceeded_Frame_Counter := 0; Stat_Sum := Time_Span_Zero; Stat_Min := To_Duration (One_Second); Stat_Max := To_Duration (Time_Span_Zero); end if; end; if Handler.Limit_Enabled then -- Do not sleep if Next_Time fell behind more than one frame -- due to high workload (FPS dropping below limit), otherwise -- the FPS will be exceeded during a subsequent low workload -- until Next_Time has catched up if Next_Time < Current_Time - Handler.Frame_Limit then Next_Time := Current_Time; else Next_Time := Next_Time + Handler.Frame_Limit; delay until Next_Time; end if; end if; end; end loop; Job_Manager.Shutdown; exception when others => Job_Manager.Shutdown; raise; end Run_Game_Loop; procedure Run_Loop (Render : not null access procedure (Scene : not null Behaviors.Behavior_Array_Access; Camera : Cameras.Camera_Ptr)) is Fence : aliased SJ.Fences.Buffer_Fence := SJ.Fences.Create_Buffer_Fence; begin declare -- Create a separate task for the game loop. The current task -- will be used to dequeue and execute GPU jobs. task Simulation; task body Simulation is begin System.Multiprocessors.Dispatching_Domains.Set_CPU (1); Run_Game_Loop (Fence'Unchecked_Access, Render); exception when Error : others => Messages.Log (Loggers.Error, Ada.Exceptions.Exception_Information (Error)); end Simulation; begin System.Multiprocessors.Dispatching_Domains.Set_CPU (1); -- Execute GPU jobs in the current task Job_Manager.Execute_GPU_Jobs; end; end Run_Loop; end Orka.Loops;
-- SPDX-License-Identifier: Apache-2.0 -- -- Copyright (c) 2017 onox <[email protected]> -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. with System.Multiprocessors.Dispatching_Domains; with Ada.Unchecked_Conversion; with Ada.Unchecked_Deallocation; with Ada.Exceptions; with Orka.Futures; with Orka.Loggers; with Orka.Logging; with Orka.Simulation; with Orka.Simulation_Jobs; package body Orka.Loops is use all type Orka.Logging.Source; use all type Orka.Logging.Severity; use Orka.Logging; package Messages is new Orka.Logging.Messages (Game_Loop); function "+" (Value : Ada.Real_Time.Time_Span) return Duration renames Ada.Real_Time.To_Duration; procedure Free is new Ada.Unchecked_Deallocation (Behaviors.Behavior_Array, Behaviors.Behavior_Array_Access); function "<" (Left, Right : Behaviors.Behavior_Ptr) return Boolean is function Convert is new Ada.Unchecked_Conversion (Source => System.Address, Target => Long_Integer); begin return Convert (Left.all'Address) < Convert (Right.all'Address); end "<"; protected body Handler is procedure Stop is begin Stop_Flag := True; end Stop; procedure Set_Frame_Limit (Value : Time_Span) is begin Limit := Value; end Set_Frame_Limit; function Frame_Limit return Time_Span is (Limit); procedure Enable_Limit (Enable : Boolean) is begin Limit_Flag := Enable; end Enable_Limit; function Limit_Enabled return Boolean is (Limit_Flag); function Should_Stop return Boolean is (Stop_Flag); end Handler; protected body Scene is procedure Add (Object : Behaviors.Behavior_Ptr) is begin Behaviors_Set.Insert (Object); Modified_Flag := True; end Add; procedure Remove (Object : Behaviors.Behavior_Ptr) is begin Behaviors_Set.Delete (Object); Modified_Flag := True; end Remove; procedure Replace_Array (Target : in out Behaviors.Behavior_Array_Access) is pragma Assert (Modified); Index : Positive := 1; Count : constant Positive := Positive (Behaviors_Set.Length); begin Free (Target); Target := new Behaviors.Behavior_Array'(1 .. Count => Behaviors.Null_Behavior); -- Copy the elements from the set to the array -- for faster iteration by the game loop for Element of Behaviors_Set loop Target (Index) := Element; Index := Index + 1; end loop; Modified_Flag := False; end Replace_Array; function Modified return Boolean is (Modified_Flag); procedure Set_Camera (Camera : Cameras.Camera_Ptr) is begin Scene_Camera := Camera; end Set_Camera; function Camera return Cameras.Camera_Ptr is (Scene_Camera); end Scene; package SJ renames Simulation_Jobs; procedure Stop_Loop is begin Handler.Stop; end Stop_Loop; procedure Run_Game_Loop (Fence : not null access SJ.Fences.Buffer_Fence; Render : Simulation.Render_Ptr) is subtype Time is Ada.Real_Time.Time; Previous_Time : Time := Clock; Next_Time : Time := Previous_Time; Lag : Time_Span := Time_Span_Zero; Scene_Array : not null Behaviors.Behavior_Array_Access := Behaviors.Empty_Behavior_Array; Batch_Length : constant := 10; One_Second : constant Time_Span := Seconds (1); Frame_Counter : Natural := 0; Exceeded_Frame_Counter : Natural := 0; Clock_FPS_Start : Time := Clock; Stat_Sum : Time_Span := Time_Span_Zero; Stat_Min : Duration := To_Duration (One_Second); Stat_Max : Duration := To_Duration (-One_Second); begin Scene.Replace_Array (Scene_Array); Messages.Log (Debug, "Simulation tick resolution: " & Trim (Image (+Tick))); -- Based on http://gameprogrammingpatterns.com/game-loop.html loop declare Current_Time : constant Time := Clock; Elapsed : constant Time_Span := Current_Time - Previous_Time; begin Previous_Time := Current_Time; Lag := Lag + Elapsed; exit when Handler.Should_Stop; declare Iterations : constant Natural := Lag / Time_Step; begin Lag := Lag - Iterations * Time_Step; Scene.Camera.Update (To_Duration (Lag)); declare Fixed_Update_Job : constant Jobs.Job_Ptr := Jobs.Parallelize (SJ.Create_Fixed_Update_Job (Scene_Array, Time_Step, Iterations), SJ.Clone_Fixed_Update_Job'Access, Scene_Array'Length, Batch_Length); Finished_Job : constant Jobs.Job_Ptr := SJ.Create_Finished_Job (Scene_Array, Time_Step, Scene.Camera.View_Position, Batch_Length); Render_Scene_Job : constant Jobs.Job_Ptr := SJ.Create_Scene_Render_Job (Render, Scene_Array, Scene.Camera); Render_Start_Job : constant Jobs.Job_Ptr := SJ.Create_Start_Render_Job (Fence); Render_Finish_Job : constant Jobs.Job_Ptr := SJ.Create_Finish_Render_Job (Fence); Handle : Futures.Pointers.Mutable_Pointer; Status : Futures.Status; begin Orka.Jobs.Chain ((Render_Start_Job, Fixed_Update_Job, Finished_Job, Render_Scene_Job, Render_Finish_Job)); Job_Manager.Queue.Enqueue (Render_Start_Job, Handle); declare Frame_Future : constant Orka.Futures.Future_Access := Handle.Get.Value; begin select Frame_Future.Wait_Until_Done (Status); or delay until Current_Time + Maximum_Frame_Time; raise Program_Error with "Maximum frame time of " & Trim (Image (+Maximum_Frame_Time)) & " exceeded"; end select; end; end; end; if Scene.Modified then Scene.Replace_Array (Scene_Array); end if; declare Total_Elapsed : constant Time_Span := Clock - Clock_FPS_Start; Limit_Exceeded : constant Time_Span := Elapsed - Handler.Frame_Limit; begin Frame_Counter := Frame_Counter + 1; if Limit_Exceeded > Time_Span_Zero then Stat_Sum := Stat_Sum + Limit_Exceeded; Stat_Min := Duration'Min (Stat_Min, To_Duration (Limit_Exceeded)); Stat_Max := Duration'Max (Stat_Max, To_Duration (Limit_Exceeded)); Exceeded_Frame_Counter := Exceeded_Frame_Counter + 1; end if; if Total_Elapsed > One_Second then declare Frame_Time : constant Time_Span := Total_Elapsed / Frame_Counter; FPS : constant Integer := Integer (1.0 / To_Duration (Frame_Time)); begin Messages.Log (Debug, Trim (FPS'Image) & " FPS, frame time: " & Trim (Image (+Frame_Time))); end; if Exceeded_Frame_Counter > 0 then declare Stat_Avg : constant Duration := +(Stat_Sum / Exceeded_Frame_Counter); begin Messages.Log (Debug, " deadline missed: " & Trim (Exceeded_Frame_Counter'Image) & " (limit is " & Trim (Image (+Handler.Frame_Limit)) & ")"); Messages.Log (Debug, " avg/min/max: " & Image (Stat_Avg) & Image (Stat_Min) & Image (Stat_Max)); end; end if; Clock_FPS_Start := Clock; Frame_Counter := 0; Exceeded_Frame_Counter := 0; Stat_Sum := Time_Span_Zero; Stat_Min := To_Duration (One_Second); Stat_Max := To_Duration (Time_Span_Zero); end if; end; if Handler.Limit_Enabled then -- Do not sleep if Next_Time fell behind more than one frame -- due to high workload (FPS dropping below limit), otherwise -- the FPS will be exceeded during a subsequent low workload -- until Next_Time has catched up if Next_Time < Current_Time - Handler.Frame_Limit then Next_Time := Current_Time; else Next_Time := Next_Time + Handler.Frame_Limit; delay until Next_Time; end if; end if; end; end loop; Job_Manager.Shutdown; exception when others => Job_Manager.Shutdown; raise; end Run_Game_Loop; procedure Run_Loop (Render : not null access procedure (Scene : not null Behaviors.Behavior_Array_Access; Camera : Cameras.Camera_Ptr)) is Fence : aliased SJ.Fences.Buffer_Fence := SJ.Fences.Create_Buffer_Fence; begin declare -- Create a separate task for the game loop. The current task -- will be used to dequeue and execute GPU jobs. task Simulation; task body Simulation is begin System.Multiprocessors.Dispatching_Domains.Set_CPU (1); Run_Game_Loop (Fence'Unchecked_Access, Render); exception when Error : others => Messages.Log (Loggers.Error, Ada.Exceptions.Exception_Information (Error)); end Simulation; begin System.Multiprocessors.Dispatching_Domains.Set_CPU (1); -- Execute GPU jobs in the current task Job_Manager.Execute_GPU_Jobs; end; end Run_Loop; end Orka.Loops;
Fix compilation of package Orka.Loops
orka: Fix compilation of package Orka.Loops Signed-off-by: onox <[email protected]>
Ada
apache-2.0
onox/orka
f15f688de37dd67075ab8c3530354db52d7422ea
src/security-contexts.adb
src/security-contexts.adb
----------------------------------------------------------------------- -- security-contexts -- Context to provide security information and verify permissions -- Copyright (C) 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Task_Attributes; with Ada.Unchecked_Deallocation; package body Security.Contexts is use type Security.Policies.Policy_Context_Array_Access; use type Security.Policies.Policy_Access; use type Security.Policies.Policy_Context_Access; package Task_Context is new Ada.Task_Attributes (Security_Context_Access, null); procedure Free is new Ada.Unchecked_Deallocation (Object => Security.Policies.Policy_Context'Class, Name => Security.Policies.Policy_Context_Access); -- ------------------------------ -- Get the application associated with the current service operation. -- ------------------------------ function Get_User_Principal (Context : in Security_Context'Class) return Security.Principal_Access is begin return Context.Principal; end Get_User_Principal; -- ------------------------------ -- Get the permission manager. -- ------------------------------ function Get_Permission_Manager (Context : in Security_Context'Class) return Security.Policies.Policy_Manager_Access is begin return Context.Manager; end Get_Permission_Manager; -- ------------------------------ -- Get the policy with the name <b>Name</b> registered in the policy manager. -- Returns null if there is no such policy. -- ------------------------------ function Get_Policy (Context : in Security_Context'Class; Name : in String) return Security.Policies.Policy_Access is use type Security.Policies.Policy_Manager_Access; begin if Context.Manager = null then return null; else return Context.Manager.Get_Policy (Name); end if; end Get_Policy; -- ------------------------------ -- Check if the permission identified by <b>Permission</b> is allowed according to -- the current security context. The result is cached in the security context and -- returned in <b>Result</b>. -- ------------------------------ procedure Has_Permission (Context : in out Security_Context; Permission : in Security.Permissions.Permission_Index; Result : out Boolean) is use type Security.Policies.Policy_Manager_Access; begin if Context.Manager = null then Result := False; return; end if; declare Perm : Security.Permissions.Permission (Permission); begin Result := Context.Manager.Has_Permission (Context, Perm); end; end Has_Permission; -- ------------------------------ -- Check if the permission identified by <b>Permission</b> is allowed according to -- the current security context. The result is cached in the security context and -- returned in <b>Result</b>. -- ------------------------------ procedure Has_Permission (Context : in out Security_Context; Permission : in String; Result : out Boolean) is Index : constant Permissions.Permission_Index := Permissions.Get_Permission_Index (Permission); begin Security_Context'Class (Context).Has_Permission (Index, Result); end Has_Permission; -- ------------------------------ -- Initializes the service context. By creating the <b>Security_Context</b> variable, -- the instance will be associated with the current task attribute. If the current task -- already has a security context, the new security context is installed, the old one -- being kept. -- ------------------------------ overriding procedure Initialize (Context : in out Security_Context) is begin Context.Previous := Task_Context.Value; Task_Context.Set_Value (Context'Unchecked_Access); end Initialize; -- ------------------------------ -- Finalize the security context releases any object. The previous security context is -- restored to the current task attribute. -- ------------------------------ overriding procedure Finalize (Context : in out Security_Context) is procedure Free is new Ada.Unchecked_Deallocation (Object => Security.Policies.Policy_Context_Array, Name => Security.Policies.Policy_Context_Array_Access); begin Task_Context.Set_Value (Context.Previous); if Context.Contexts /= null then for I in Context.Contexts'Range loop Free (Context.Contexts (I)); end loop; Free (Context.Contexts); end if; end Finalize; -- ------------------------------ -- Set a policy context information represented by <b>Value</b> and associated with -- the policy index <b>Policy</b>. -- ------------------------------ procedure Set_Policy_Context (Context : in out Security_Context; Policy : in Security.Policies.Policy_Access; Value : in Security.Policies.Policy_Context_Access) is begin if Context.Contexts = null then Context.Contexts := Context.Manager.Create_Policy_Contexts; end if; Free (Context.Contexts (Policy.Get_Policy_Index)); Context.Contexts (Policy.Get_Policy_Index) := Value; end Set_Policy_Context; -- ------------------------------ -- Get the policy context information registered for the given security policy in the security -- context <b>Context</b>. -- Raises <b>Invalid_Context</b> if there is no such information. -- Raises <b>Invalid_Policy</b> if the policy was not set. -- ------------------------------ function Get_Policy_Context (Context : in Security_Context; Policy : in Security.Policies.Policy_Access) return Security.Policies.Policy_Context_Access is Result : Security.Policies.Policy_Context_Access; begin if Policy = null then raise Invalid_Policy; end if; if Context.Contexts = null then raise Invalid_Context; end if; Result := Context.Contexts (Policy.Get_Policy_Index); return Result; end Get_Policy_Context; -- ------------------------------ -- Returns True if a context information was registered for the security policy. -- ------------------------------ function Has_Policy_Context (Context : in Security_Context; Policy : in Security.Policies.Policy_Access) return Boolean is begin return Policy /= null and then Context.Contexts /= null and then Context.Contexts (Policy.Get_Policy_Index) /= null; end Has_Policy_Context; -- ------------------------------ -- Set the current application and user context. -- ------------------------------ procedure Set_Context (Context : in out Security_Context; Manager : in Security.Policies.Policy_Manager_Access; Principal : in Security.Principal_Access) is begin Context.Manager := Manager; Context.Principal := Principal; end Set_Context; -- ------------------------------ -- Get the current security context. -- Returns null if the current thread is not associated with any security context. -- ------------------------------ function Current return Security_Context_Access is begin return Task_Context.Value; end Current; -- ------------------------------ -- Check if the permission identified by <b>Permission</b> is allowed according to -- the current security context. The result is cached in the security context and -- returned in <b>Result</b>. -- ------------------------------ function Has_Permission (Permission : in Permissions.Permission_Index) return Boolean is Result : Boolean; Context : constant Security_Context_Access := Current; begin if Context = null then return False; else Context.Has_Permission (Permission, Result); return Result; end if; end Has_Permission; -- ------------------------------ -- Check if the permission identified by <b>Permission</b> is allowed according to -- the current security context. The result is cached in the security context and -- returned in <b>Result</b>. -- ------------------------------ function Has_Permission (Permission : in String) return Boolean is Result : Boolean; Context : constant Security_Context_Access := Current; begin if Context = null then return False; else Context.Has_Permission (Permission, Result); return Result; end if; end Has_Permission; end Security.Contexts;
----------------------------------------------------------------------- -- security-contexts -- Context to provide security information and verify permissions -- Copyright (C) 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Task_Attributes; with Ada.Unchecked_Deallocation; package body Security.Contexts is use type Security.Policies.Policy_Context_Array_Access; use type Security.Policies.Policy_Access; use type Security.Policies.Policy_Context_Access; package Task_Context is new Ada.Task_Attributes (Security_Context_Access, null); procedure Free is new Ada.Unchecked_Deallocation (Object => Security.Policies.Policy_Context'Class, Name => Security.Policies.Policy_Context_Access); -- ------------------------------ -- Get the application associated with the current service operation. -- ------------------------------ function Get_User_Principal (Context : in Security_Context'Class) return Security.Principal_Access is begin return Context.Principal; end Get_User_Principal; -- ------------------------------ -- Get the permission manager. -- ------------------------------ function Get_Permission_Manager (Context : in Security_Context'Class) return Security.Policies.Policy_Manager_Access is begin return Context.Manager; end Get_Permission_Manager; -- ------------------------------ -- Get the policy with the name <b>Name</b> registered in the policy manager. -- Returns null if there is no such policy. -- ------------------------------ function Get_Policy (Context : in Security_Context'Class; Name : in String) return Security.Policies.Policy_Access is use type Security.Policies.Policy_Manager_Access; begin if Context.Manager = null then return null; else return Context.Manager.Get_Policy (Name); end if; end Get_Policy; -- ------------------------------ -- Check if the permission identified by <b>Permission</b> is allowed according to -- the current security context. The result is cached in the security context and -- returned in <b>Result</b>. -- ------------------------------ procedure Has_Permission (Context : in out Security_Context; Permission : in Security.Permissions.Permission_Index; Result : out Boolean) is use type Security.Policies.Policy_Manager_Access; begin if Context.Manager = null then Result := False; return; end if; declare Perm : Security.Permissions.Permission (Permission); begin Result := Context.Manager.Has_Permission (Context, Perm); end; end Has_Permission; -- ------------------------------ -- Check if the permission identified by <b>Permission</b> is allowed according to -- the current security context. The result is cached in the security context and -- returned in <b>Result</b>. -- ------------------------------ procedure Has_Permission (Context : in out Security_Context; Permission : in String; Result : out Boolean) is Index : constant Permissions.Permission_Index := Permissions.Get_Permission_Index (Permission); begin Security_Context'Class (Context).Has_Permission (Index, Result); end Has_Permission; -- ------------------------------ -- Check if the permission identified by <b>Permission</b> is allowed according to -- the current security context. The result is cached in the security context and -- returned in <b>Result</b>. -- ------------------------------ procedure Has_Permission (Context : in out Security_Context; Permission : in Security.Permissions.Permission'Class; Result : out Boolean) is use type Security.Policies.Policy_Manager_Access; begin if Context.Manager = null then Result := False; return; end if; Result := Context.Manager.Has_Permission (Context, Permission); end Has_Permission; -- ------------------------------ -- Initializes the service context. By creating the <b>Security_Context</b> variable, -- the instance will be associated with the current task attribute. If the current task -- already has a security context, the new security context is installed, the old one -- being kept. -- ------------------------------ overriding procedure Initialize (Context : in out Security_Context) is begin Context.Previous := Task_Context.Value; Task_Context.Set_Value (Context'Unchecked_Access); end Initialize; -- ------------------------------ -- Finalize the security context releases any object. The previous security context is -- restored to the current task attribute. -- ------------------------------ overriding procedure Finalize (Context : in out Security_Context) is procedure Free is new Ada.Unchecked_Deallocation (Object => Security.Policies.Policy_Context_Array, Name => Security.Policies.Policy_Context_Array_Access); begin Task_Context.Set_Value (Context.Previous); if Context.Contexts /= null then for I in Context.Contexts'Range loop Free (Context.Contexts (I)); end loop; Free (Context.Contexts); end if; end Finalize; -- ------------------------------ -- Set a policy context information represented by <b>Value</b> and associated with -- the policy index <b>Policy</b>. -- ------------------------------ procedure Set_Policy_Context (Context : in out Security_Context; Policy : in Security.Policies.Policy_Access; Value : in Security.Policies.Policy_Context_Access) is begin if Context.Contexts = null then Context.Contexts := Context.Manager.Create_Policy_Contexts; end if; Free (Context.Contexts (Policy.Get_Policy_Index)); Context.Contexts (Policy.Get_Policy_Index) := Value; end Set_Policy_Context; -- ------------------------------ -- Get the policy context information registered for the given security policy in the security -- context <b>Context</b>. -- Raises <b>Invalid_Context</b> if there is no such information. -- Raises <b>Invalid_Policy</b> if the policy was not set. -- ------------------------------ function Get_Policy_Context (Context : in Security_Context; Policy : in Security.Policies.Policy_Access) return Security.Policies.Policy_Context_Access is Result : Security.Policies.Policy_Context_Access; begin if Policy = null then raise Invalid_Policy; end if; if Context.Contexts = null then raise Invalid_Context; end if; Result := Context.Contexts (Policy.Get_Policy_Index); return Result; end Get_Policy_Context; -- ------------------------------ -- Returns True if a context information was registered for the security policy. -- ------------------------------ function Has_Policy_Context (Context : in Security_Context; Policy : in Security.Policies.Policy_Access) return Boolean is begin return Policy /= null and then Context.Contexts /= null and then Context.Contexts (Policy.Get_Policy_Index) /= null; end Has_Policy_Context; -- ------------------------------ -- Set the current application and user context. -- ------------------------------ procedure Set_Context (Context : in out Security_Context; Manager : in Security.Policies.Policy_Manager_Access; Principal : in Security.Principal_Access) is begin Context.Manager := Manager; Context.Principal := Principal; end Set_Context; -- ------------------------------ -- Get the current security context. -- Returns null if the current thread is not associated with any security context. -- ------------------------------ function Current return Security_Context_Access is begin return Task_Context.Value; end Current; -- ------------------------------ -- Check if the permission identified by <b>Permission</b> is allowed according to -- the current security context. The result is cached in the security context and -- returned in <b>Result</b>. -- ------------------------------ function Has_Permission (Permission : in Permissions.Permission_Index) return Boolean is Result : Boolean; Context : constant Security_Context_Access := Current; begin if Context = null then return False; else Context.Has_Permission (Permission, Result); return Result; end if; end Has_Permission; -- ------------------------------ -- Check if the permission identified by <b>Permission</b> is allowed according to -- the current security context. The result is cached in the security context and -- returned in <b>Result</b>. -- ------------------------------ function Has_Permission (Permission : in String) return Boolean is Result : Boolean; Context : constant Security_Context_Access := Current; begin if Context = null then return False; else Context.Has_Permission (Permission, Result); return Result; end if; end Has_Permission; end Security.Contexts;
Implement the new Has_Permission procedure
Implement the new Has_Permission procedure
Ada
apache-2.0
stcarrez/ada-security
b3252712548772b6ebe5144e69eac3d3e48ba34d
src/security-policies.ads
src/security-policies.ads
----------------------------------------------------------------------- -- security-policies -- Security Policies -- Copyright (C) 2010, 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Finalization; with Util.Beans.Objects; with Util.Beans.Objects.Vectors; with Util.Serialize.IO.XML; with Security.Permissions; limited with Security.Controllers; limited with Security.Contexts; -- == Security Policies == -- -- @include security-policies-roles.ads -- @include security-policies-urls.ads package Security.Policies is type Security_Context_Access is access all Contexts.Security_Context'Class; type Controller_Access is access all Security.Controllers.Controller'Class; type Controller_Access_Array is array (Permissions.Permission_Index range <>) of Controller_Access; type Policy_Index is new Positive; type Policy_Context is limited interface; type Policy_Context_Access is access all Policy_Context'Class; type Policy_Context_Array is array (Policy_Index range <>) of Policy_Context_Access; type Policy_Context_Array_Access is access Policy_Context_Array; -- ------------------------------ -- Security policy -- ------------------------------ type Policy is abstract new Ada.Finalization.Limited_Controlled with private; type Policy_Access is access all Policy'Class; -- Get the policy name. function Get_Name (From : in Policy) return String is abstract; -- Get the policy index. function Get_Policy_Index (From : in Policy'Class) return Policy_Index; pragma Inline (Get_Policy_Index); -- Prepare the XML parser to read the policy configuration. procedure Prepare_Config (Pol : in out Policy; Reader : in out Util.Serialize.IO.XML.Parser) is null; -- Finish reading the XML policy configuration. The security policy implementation can use -- this procedure to perform any configuration setup after the configuration is parsed. procedure Finish_Config (Into : in out Policy; Reader : in out Util.Serialize.IO.XML.Parser) is null; -- Add a permission under the given permission name and associated with the controller. -- To verify the permission, the controller will be called. procedure Add_Permission (Manager : in out Policy; Name : in String; Permission : in Controller_Access); Invalid_Name : exception; Policy_Error : exception; -- ------------------------------ -- Permission Manager -- ------------------------------ -- The <b>Permission_Manager</b> verifies through some policy that a permission -- is granted to a user. type Policy_Manager (Max_Policies : Policy_Index) is new Ada.Finalization.Limited_Controlled with private; type Policy_Manager_Access is access all Policy_Manager'Class; -- Get the policy with the name <b>Name</b> registered in the policy manager. -- Returns null if there is no such policy. function Get_Policy (Manager : in Policy_Manager; Name : in String) return Policy_Access; -- Add the policy to the policy manager. After a policy is added in the manager, -- it can participate in the security policy. -- Raises Policy_Error if the policy table is full. procedure Add_Policy (Manager : in out Policy_Manager; Policy : in Policy_Access); -- Add a permission under the given permission name and associated with the controller. -- To verify the permission, the controller will be called. procedure Add_Permission (Manager : in out Policy_Manager; Name : in String; Permission : in Controller_Access); -- Checks whether the permission defined by the <b>Permission</b> controller data is granted -- by the security context passed in <b>Context</b>. -- Returns true if such permission is granted. function Has_Permission (Manager : in Policy_Manager; Context : in Security.Contexts.Security_Context'Class; Permission : in Security.Permissions.Permission'Class) return Boolean; -- Create the policy contexts to be associated with the security context. function Create_Policy_Contexts (Manager : in Policy_Manager) return Policy_Context_Array_Access; -- Read the policy file procedure Read_Policy (Manager : in out Policy_Manager; File : in String); -- Initialize the permission manager. overriding procedure Initialize (Manager : in out Policy_Manager); -- Finalize the permission manager. overriding procedure Finalize (Manager : in out Policy_Manager); -- ------------------------------ -- Policy Configuration -- ------------------------------ type Policy_Config is record Id : Natural := 0; Permissions : Util.Beans.Objects.Vectors.Vector; Patterns : Util.Beans.Objects.Vectors.Vector; Manager : Policy_Manager_Access; end record; type Policy_Config_Access is access all Policy_Config; -- Setup the XML parser to read the <b>policy</b> description. For example: -- -- <policy id='1'> -- <permission>create-workspace</permission> -- <permission>admin</permission> -- <url-pattern>/workspace/create</url-pattern> -- <url-pattern>/workspace/setup/*</url-pattern> -- </policy> -- -- This policy gives access to the URL that match one of the URL pattern if the -- security context has the permission <b>create-workspace</b> or <b>admin</b>. generic Reader : in out Util.Serialize.IO.XML.Parser; Manager : in Policy_Manager_Access; package Reader_Config is Config : aliased Policy_Config; end Reader_Config; private subtype Permission_Index is Permissions.Permission_Index; type Permission_Index_Array is array (Positive range <>) of Permissions.Permission_Index; type Controller_Access_Array_Access is access all Controller_Access_Array; type Policy_Access_Array is array (Policy_Index range <>) of Policy_Access; type Policy is abstract new Ada.Finalization.Limited_Controlled with record Manager : Policy_Manager_Access; Index : Policy_Index; end record; type Policy_Manager (Max_Policies : Policy_Index) is new Ada.Finalization.Limited_Controlled with record Permissions : Controller_Access_Array_Access; Last_Index : Permission_Index := Permission_Index'First; -- The security policies. Policies : Policy_Access_Array (1 .. Max_Policies); end record; end Security.Policies;
----------------------------------------------------------------------- -- security-policies -- Security Policies -- Copyright (C) 2010, 2011, 2012 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Finalization; with Util.Beans.Objects; with Util.Beans.Objects.Vectors; with Util.Serialize.IO.XML; with Security.Permissions; limited with Security.Controllers; limited with Security.Contexts; -- == Security Policies == -- The Security Policy 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. These policies are registered when an application starts -- and before reading the policy configuration files. -- -- [http://ada-security.googlecode.com/svn/wiki/PolicyModel.png] -- -- While the policy configuration files are processed, the policy instances that have been -- registered will create a security controller and bind it to a given permission. After -- successful initialization, the <tt>Policy_Manager</tt> contains a list of securiy -- controllers which are associated with each permission defined by the application. -- -- @include security-policies-roles.ads -- @include security-policies-urls.ads -- @include security-controllers.ads package Security.Policies is type Security_Context_Access is access all Contexts.Security_Context'Class; type Controller_Access is access all Security.Controllers.Controller'Class; type Controller_Access_Array is array (Permissions.Permission_Index range <>) of Controller_Access; type Policy_Index is new Positive; type Policy_Context is limited interface; type Policy_Context_Access is access all Policy_Context'Class; type Policy_Context_Array is array (Policy_Index range <>) of Policy_Context_Access; type Policy_Context_Array_Access is access Policy_Context_Array; -- ------------------------------ -- Security policy -- ------------------------------ type Policy is abstract new Ada.Finalization.Limited_Controlled with private; type Policy_Access is access all Policy'Class; -- Get the policy name. function Get_Name (From : in Policy) return String is abstract; -- Get the policy index. function Get_Policy_Index (From : in Policy'Class) return Policy_Index; pragma Inline (Get_Policy_Index); -- Prepare the XML parser to read the policy configuration. procedure Prepare_Config (Pol : in out Policy; Reader : in out Util.Serialize.IO.XML.Parser) is null; -- Finish reading the XML policy configuration. The security policy implementation can use -- this procedure to perform any configuration setup after the configuration is parsed. procedure Finish_Config (Into : in out Policy; Reader : in out Util.Serialize.IO.XML.Parser) is null; -- Add a permission under the given permission name and associated with the controller. -- To verify the permission, the controller will be called. procedure Add_Permission (Manager : in out Policy; Name : in String; Permission : in Controller_Access); Invalid_Name : exception; Policy_Error : exception; -- ------------------------------ -- Permission Manager -- ------------------------------ -- The <b>Permission_Manager</b> verifies through some policy that a permission -- is granted to a user. type Policy_Manager (Max_Policies : Policy_Index) is new Ada.Finalization.Limited_Controlled with private; type Policy_Manager_Access is access all Policy_Manager'Class; -- Get the policy with the name <b>Name</b> registered in the policy manager. -- Returns null if there is no such policy. function Get_Policy (Manager : in Policy_Manager; Name : in String) return Policy_Access; -- Add the policy to the policy manager. After a policy is added in the manager, -- it can participate in the security policy. -- Raises Policy_Error if the policy table is full. procedure Add_Policy (Manager : in out Policy_Manager; Policy : in Policy_Access); -- Add a permission under the given permission name and associated with the controller. -- To verify the permission, the controller will be called. procedure Add_Permission (Manager : in out Policy_Manager; Name : in String; Permission : in Controller_Access); -- Checks whether the permission defined by the <b>Permission</b> controller data is granted -- by the security context passed in <b>Context</b>. -- Returns true if such permission is granted. function Has_Permission (Manager : in Policy_Manager; Context : in Security.Contexts.Security_Context'Class; Permission : in Security.Permissions.Permission'Class) return Boolean; -- Create the policy contexts to be associated with the security context. function Create_Policy_Contexts (Manager : in Policy_Manager) return Policy_Context_Array_Access; -- Read the policy file procedure Read_Policy (Manager : in out Policy_Manager; File : in String); -- Initialize the permission manager. overriding procedure Initialize (Manager : in out Policy_Manager); -- Finalize the permission manager. overriding procedure Finalize (Manager : in out Policy_Manager); -- ------------------------------ -- Policy Configuration -- ------------------------------ type Policy_Config is record Id : Natural := 0; Permissions : Util.Beans.Objects.Vectors.Vector; Patterns : Util.Beans.Objects.Vectors.Vector; Manager : Policy_Manager_Access; end record; type Policy_Config_Access is access all Policy_Config; -- Setup the XML parser to read the <b>policy</b> description. For example: -- -- <policy id='1'> -- <permission>create-workspace</permission> -- <permission>admin</permission> -- <url-pattern>/workspace/create</url-pattern> -- <url-pattern>/workspace/setup/*</url-pattern> -- </policy> -- -- This policy gives access to the URL that match one of the URL pattern if the -- security context has the permission <b>create-workspace</b> or <b>admin</b>. generic Reader : in out Util.Serialize.IO.XML.Parser; Manager : in Policy_Manager_Access; package Reader_Config is Config : aliased Policy_Config; end Reader_Config; private subtype Permission_Index is Permissions.Permission_Index; type Permission_Index_Array is array (Positive range <>) of Permissions.Permission_Index; type Controller_Access_Array_Access is access all Controller_Access_Array; type Policy_Access_Array is array (Policy_Index range <>) of Policy_Access; type Policy is abstract new Ada.Finalization.Limited_Controlled with record Manager : Policy_Manager_Access; Index : Policy_Index; end record; type Policy_Manager (Max_Policies : Policy_Index) is new Ada.Finalization.Limited_Controlled with record Permissions : Controller_Access_Array_Access; Last_Index : Permission_Index := Permission_Index'First; -- The security policies. Policies : Policy_Access_Array (1 .. Max_Policies); end record; end Security.Policies;
Document the security policy
Document the security policy
Ada
apache-2.0
Letractively/ada-security